From 449672077205a4d664bb4197752e623ff24ef8ff Mon Sep 17 00:00:00 2001 From: John Lewin Date: Mon, 18 Apr 2016 11:31:31 -0700 Subject: [PATCH] Json Profiles --- ActionBar/ActionBarBaseControls.cs | 437 -------- ActionBar/ActionBarPlus.cs | 31 +- .../ActionRowBase.cs | 39 +- ActionBar/PrintActionRow.cs | 35 +- ActionBar/PrintStatusRow.cs | 14 +- ActionBar/PrinterActionRow.cs | 49 +- ActionBar/PrinterSelector.cs | 60 ++ ...nelTabView.cs => AdvancedControlsPanel.cs} | 149 ++- ApplicationView/CompactSlidePanel.cs | 82 +- ApplicationView/CompactTabView.cs | 32 +- ApplicationView/MainApplicationWidget.cs | 99 +- ApplicationView/MenuRow/MenuBase.cs | 6 +- ApplicationView/MenuRow/MenuOptionFile.cs | 139 +-- ApplicationView/MenuRow/MenuOptionHelp.cs | 85 +- ApplicationView/MenuRow/MenuOptionSettings.cs | 41 +- ApplicationView/WidescreenPanel.cs | 47 +- .../ApplicationSettingsView.cs | 17 +- .../CalibrationSettingsView.cs | 12 +- .../PrintLeveling/InstructionsPage.cs | 4 +- .../PrintLeveling/LevelWizard13PointRadial.cs | 12 +- .../PrintLeveling/LevelWizard2Point.cs | 12 +- .../PrintLeveling/LevelWizard3Point.cs | 4 +- .../PrintLeveling/LevelWizard7PointRadial.cs | 10 +- .../PrintLeveling/LevelWizardBase.cs | 15 +- .../PrintLeveling/PrintLevelPages.cs | 34 +- .../PrintLeveling/PrintLevelingData.cs | 74 +- ConfigurationPage/PrinterConfigurationPage.cs | 2 +- .../PrinterSettings/PrinterSettingsView.cs | 4 +- CustomWidgets/DropDownMenuWidget.cs | 59 +- CustomWidgets/ExportPrintItemWindow.cs | 12 +- CustomWidgets/SlidePanelWidget.cs | 2 +- .../Classic/ClassicSqlitePrinterProfiles.cs | 218 ++++ DataStorage/Datastore.cs | 14 +- DataStorage/GenerateSampleData.cs | 22 - MatterControl.csproj | 17 +- MatterControlApplication.cs | 51 +- .../BaseClasses/PartPreview3DWidget.cs | 2 +- PartPreviewWindow/PartPreviewContent.cs | 21 +- PartPreviewWindow/View3D/View3DWidget.cs | 6 +- PartPreviewWindow/ViewGcodeBasic.cs | 2 +- PrinterCommunication/ActivePrinterProfile.cs | 341 ------- .../Io/PrintLevelingStream.cs | 3 +- .../Io/ResumePrintingStream.cs | 14 +- .../PrinterConnectionAndCommunication.cs | 68 +- .../ControlWidgets/MacroControls.cs | 6 +- .../ControlWidgets/MovementControls.cs | 14 +- .../ControlWidgets/TemperatureControls.cs | 7 +- PrinterControls/EditLevelingSettingsWindow.cs | 14 +- PrinterControls/EditMacrosWindow.cs | 9 +- PrinterControls/ManualPrinterControls.cs | 2 +- .../BaseConnectionWidget.cs | 66 +- .../ChooseConnectionWidget.cs | 232 ----- .../PrinterConnections/ConnectionWindow.cs | 146 +-- .../EditConnectionWidget.cs | 40 +- .../PrinterConnections/PrinterListItems.cs | 232 ----- .../PrinterConnections/PrinterSetupStatus.cs | 331 +----- .../SetupConnectionWidgetBase.cs | 64 +- .../PrinterConnections/SetupStepBaudRate.cs | 37 +- .../SetupStepComPortManual.cs | 148 +-- .../PrinterConnections/SetupStepComPortOne.cs | 40 +- .../PrinterConnections/SetupStepComPortTwo.cs | 97 +- .../SetupStepConfigureConnection.cs | 78 +- .../SetupStepInstallDriver.cs | 74 +- .../SetupStepMakeModelName.cs | 233 ++--- PrinterControls/TemperatureIndicator.cs | 4 +- Queue/OptionsMenu/ExportToFolderProcess.cs | 4 +- Queue/OptionsMenu/QueueOptionsMenu.cs | 4 +- Queue/PrintItemWrapper.cs | 10 +- Queue/QueueDataWidget.cs | 4 +- SettingsManagement/PrinterSettings.cs | 27 +- SlicerConfiguration/CuraEngineInfo.cs | 4 +- SlicerConfiguration/MatterSliceInfo.cs | 4 +- .../Settings/ActiveSliceSettings.cs | 281 ++++++ .../Settings/LayeredProfile.cs | 306 ++++++ .../Settings/SettingsDiagram.cd | 77 ++ .../SettingsProfile.cs} | 950 ++++++++++-------- SlicerConfiguration/SettingsControlBar.cs | 29 +- .../SettingsControlSelectors.cs | 140 ++- SlicerConfiguration/Slic3rInfo.cs | 4 +- SlicerConfiguration/SliceEngineInfo.cs | 2 +- .../SlicePresetDetailWidget.cs | 86 +- .../SlicePresetListWidget.cs | 21 +- .../SlicePresetsWindow/SlicePresetsWindow.cs | 28 +- .../SliceSettingsDetailControl.cs | 10 +- SlicerConfiguration/SliceSettingsWidget.cs | 820 ++++++++------- .../SlicerMapping/MappingClasses.cs | 16 +- SlicerConfiguration/SlicingQueue.cs | 16 +- StaticData/Translations/Master.txt | 52 +- Submodules/agg-sharp | 2 +- .../MatterControl.Tests.csproj | 1 - .../Slicing/SliceMappingCLassesTets.cs | 15 +- .../MatterControl/TranslationsTests.cs | 1 - VersionManagement/WebRequestHandler.cs | 4 +- 93 files changed, 3069 insertions(+), 4120 deletions(-) delete mode 100644 ActionBar/ActionBarBaseControls.cs rename CustomWidgets/LibrarySelector/LibraryProviderEventArgs.cs => ActionBar/ActionRowBase.cs (71%) create mode 100644 ActionBar/PrinterSelector.cs rename ApplicationView/{ThirdPanelTabView.cs => AdvancedControlsPanel.cs} (51%) create mode 100644 DataStorage/Classic/ClassicSqlitePrinterProfiles.cs delete mode 100644 DataStorage/GenerateSampleData.cs delete mode 100644 PrinterCommunication/ActivePrinterProfile.cs delete mode 100644 PrinterControls/PrinterConnections/ChooseConnectionWidget.cs delete mode 100644 PrinterControls/PrinterConnections/PrinterListItems.cs create mode 100644 SlicerConfiguration/Settings/ActiveSliceSettings.cs create mode 100644 SlicerConfiguration/Settings/LayeredProfile.cs create mode 100644 SlicerConfiguration/Settings/SettingsDiagram.cd rename SlicerConfiguration/{ActiveSliceSettings.cs => Settings/SettingsProfile.cs} (57%) diff --git a/ActionBar/ActionBarBaseControls.cs b/ActionBar/ActionBarBaseControls.cs deleted file mode 100644 index 3a6f96d88..000000000 --- a/ActionBar/ActionBarBaseControls.cs +++ /dev/null @@ -1,437 +0,0 @@ -using MatterHackers.Agg; -using MatterHackers.Agg.UI; -using MatterHackers.Agg.VertexSource; -using MatterHackers.Localizations; -using MatterHackers.MatterControl.DataStorage; -using MatterHackers.MatterControl.PrinterCommunication; -using MatterHackers.VectorMath; -using System; - -namespace MatterHackers.MatterControl.ActionBar -{ - //Base widget for ActionBarRows - public abstract class ActionRowBase : FlowLayoutWidget - { - public ActionRowBase() - : base(FlowDirection.LeftToRight) - { - Initialize(); - SetDisplayAttributes(); - AddChildElements(); - AddHandlers(); - } - - protected virtual void Initialize() - { - //Placeholder for row-specific initialization - } - - protected void SetDisplayAttributes() - { - this.HAnchor = HAnchor.ParentLeftRight; - } - - protected abstract void AddChildElements(); - - protected virtual void AddHandlers() - { - //Placeholder for row-specific handlers - } - } - - //Base widget for use in ButtonViewStates - public class ControlButtonViewBase : GuiWidget - { - protected RGBA_Bytes fillColor; - protected RGBA_Bytes borderColor; - protected double borderWidth; - protected double borderRadius; - protected double padding; - - public ControlButtonViewBase(string label, - double width, - double height, - double textHeight, - double borderWidth, - double borderRadius, - double padding, - RGBA_Bytes textColor, - RGBA_Bytes fillColor, - RGBA_Bytes borderColor) - : base(width, height) - { - this.borderRadius = borderRadius; - this.borderWidth = borderWidth; - this.fillColor = fillColor; - this.borderColor = borderColor; - this.padding = padding; - - TextWidget buttonText = new TextWidget(label, textHeight); - buttonText.VAnchor = VAnchor.ParentCenter; - buttonText.HAnchor = HAnchor.ParentCenter; - buttonText.TextColor = textColor; - - //this.AnchorAll(); - this.AddChild(buttonText); - } - - public override void OnDraw(Graphics2D graphics2D) - { - RectangleDouble Bounds = LocalBounds; - RoundedRect rectBorder = new RoundedRect(Bounds, this.borderRadius); - - graphics2D.Render(rectBorder, borderColor); - - RectangleDouble insideBounds = Bounds; - insideBounds.Inflate(-this.borderWidth); - RoundedRect rectInside = new RoundedRect(insideBounds, Math.Max(this.borderRadius - this.borderWidth, 0)); - - graphics2D.Render(rectInside, this.fillColor); - - base.OnDraw(graphics2D); - } - } - - //Base widget for use in ButtonViewStates - public class PrinterSelectViewBase : GuiWidget - { - protected RGBA_Bytes fillColor; - protected RGBA_Bytes borderColor; - protected double borderWidth; - protected double borderRadius; - protected double padding; - protected double statusTextHeight = 8; - private TextWidget printerStatusText; - private TextWidget printerNameText; - - private event EventHandler unregisterEvents; - - public PrinterSelectViewBase( - double width, - double height, - double textHeight, - double borderWidth, - double borderRadius, - double padding, - RGBA_Bytes textColor, - RGBA_Bytes fillColor, - RGBA_Bytes borderColor) - : base(width, height) - { - this.borderRadius = borderRadius; - this.borderWidth = borderWidth; - this.fillColor = fillColor; - this.borderColor = borderColor; - this.padding = padding; - this.Padding = new BorderDouble(10, 5); - this.HAnchor = HAnchor.ParentLeftRight; - - FlowLayoutWidget textContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - textContainer.VAnchor = VAnchor.ParentBottomTop; - textContainer.HAnchor = HAnchor.ParentLeftRight; - - printerNameText = new TextWidget("", pointSize: textHeight); - printerNameText.AutoExpandBoundsToText = true; - printerNameText.HAnchor = HAnchor.ParentCenter; - printerNameText.TextColor = textColor; - - string printerStatusTextBeg = LocalizedString.Get("Status"); - string printerStatusTextEnd = LocalizedString.Get("Connected"); - string printerStatusTextFull = string.Format("{0}: {1}", printerStatusTextBeg, printerStatusTextEnd); - printerStatusText = new TextWidget(printerStatusTextFull, pointSize: statusTextHeight); - printerStatusText.AutoExpandBoundsToText = true; - printerStatusText.HAnchor = HAnchor.ParentCenter; - printerStatusText.TextColor = textColor; - - textContainer.AddChild(printerNameText); - textContainer.AddChild(printerStatusText); - - SetButtonText(); - - //this.AnchorAll(); - this.AddChild(textContainer); - - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents); - PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents); - } - - public override void OnClosed(EventArgs e) - { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } - base.OnClosed(e); - } - - private void onActivePrinterChanged(object sender, EventArgs e) - { - UiThread.RunOnIdle(SetButtonText); - } - - private int GetPrinterRecordCount() - { - return Datastore.Instance.RecordCount("Printer"); - } - - private void SetButtonText() - { - if (PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.FailedToConnect && PrinterConnectionAndCommunication.Instance.ConnectionFailureMessage != "") - { - printerStatusText.Text = "Status: " + PrinterConnectionAndCommunication.Instance.ConnectionFailureMessage; - } - else - { - string statusStringBeg = LocalizedString.Get("Status").ToUpper(); - string statusString = string.Format("{1}: {0}", PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose, statusStringBeg); - printerStatusText.Text = string.Format(statusString, PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose); - } - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - printerNameText.Text = ActivePrinterProfile.Instance.ActivePrinter.Name; - } - else - { - if (GetPrinterRecordCount() > 0) - { - string printerNameLabel = LocalizedString.Get("Select Printer"); - string printerNameLabelFull = string.Format("- {0} -", printerNameLabel); - printerNameText.Text = (printerNameLabelFull); - } - else - { - string addPrinterLabel = LocalizedString.Get("Add Printer"); - string addPrinterLabelFull = string.Format("- {0} -", addPrinterLabel); - printerNameText.Text = (addPrinterLabelFull); - } - } - } - - public override void OnDraw(Graphics2D graphics2D) - { - RectangleDouble Bounds = LocalBounds; - RoundedRect rectBorder = new RoundedRect(Bounds, this.borderRadius); - - graphics2D.Render(rectBorder, borderColor); - - RectangleDouble insideBounds = Bounds; - insideBounds.Inflate(-this.borderWidth); - RoundedRect rectInside = new RoundedRect(insideBounds, Math.Max(this.borderRadius - this.borderWidth, 0)); - - graphics2D.Render(rectInside, this.fillColor); - base.OnDraw(graphics2D); - } - } - - public class PrinterSelectButton : Button - { - private double width = 180; - private double height = 40; - private double borderRadius = 0; - private double borderWidth = 1; - private double fontSize = 14; - private double padding = 3; - private BorderDouble margin = new BorderDouble(0, 0); - - public PrinterSelectButton() - { - this.HAnchor = HAnchor.ParentLeftRight; - - //Widgets to show during the four button states - PrinterSelectViewBase buttonWidgetPressed = getButtonWidgetNormal(); - PrinterSelectViewBase buttonWidgetHover = getButtonWidgetHover(); - PrinterSelectViewBase buttonWidgetNormal = getButtonWidgetNormal(); - PrinterSelectViewBase buttonWidgetDisabled = getButtonWidgetNormal(); - - //Create container for the three state widgets for the button - ButtonViewStates buttonView = new ButtonViewStates(buttonWidgetNormal, buttonWidgetHover, buttonWidgetPressed, buttonWidgetDisabled); - buttonView.HAnchor = HAnchor.ParentLeftRight; - - this.ToolTipText = "Select a printer".Localize(); - this.Name = "Select a Printer Button"; - - Margin = DefaultMargin; - - OriginRelativeParent = new Vector2(0, 0); - - if (buttonView != null) - { - buttonView.Selectable = false; - - AddChild(buttonView); - - HAnchor = HAnchor.FitToChildren; - VAnchor = VAnchor.FitToChildren; - - if (LocalBounds.Left != 0 || LocalBounds.Bottom != 0) - { - // let's make sure that a button has 0, 0 at the lower left - // move the children so they will fit with 0, 0 at the lower left - foreach (GuiWidget child in Children) - { - child.OriginRelativeParent = child.OriginRelativeParent + new Vector2(-LocalBounds.Left, -LocalBounds.Bottom); - } - - HAnchor = HAnchor.FitToChildren; - VAnchor = VAnchor.FitToChildren; - } - - MinimumSize = new Vector2(Width, Height); - } - } - - private PrinterSelectViewBase getButtonWidgetHover() - { - RGBA_Bytes borderColor; - RGBA_Bytes fillColor = ActiveTheme.Instance.PrimaryBackgroundColor; - if (ActiveTheme.Instance.IsDarkTheme) - { - borderColor = new RGBA_Bytes(128, 128, 128); - } - else - { - borderColor = new RGBA_Bytes(128, 128, 128); - } - RGBA_Bytes textColor = ActiveTheme.Instance.PrimaryTextColor; - PrinterSelectViewBase widget = new PrinterSelectViewBase( - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - - public PrinterSelectViewBase getButtonWidgetNormal() - { - RGBA_Bytes fillColor = ActiveTheme.Instance.PrimaryBackgroundColor; - RGBA_Bytes borderColor; - if (ActiveTheme.Instance.IsDarkTheme) - { - borderColor = new RGBA_Bytes(77, 77, 77); - } - else - { - borderColor = new RGBA_Bytes(190, 190, 190); - } - - RGBA_Bytes textColor = ActiveTheme.Instance.PrimaryTextColor; - PrinterSelectViewBase widget = new PrinterSelectViewBase( - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - } - - public class ActionBarControlButtonFactory - { - private double width = 75; - private double height = 30; - private double borderRadius = 3; - private double borderWidth = 1; - private double fontSize = 14; - private double padding = 3; - private BorderDouble margin = new BorderDouble(5, 0); - - public Button Generate(string buttonText) - { - //Widgets to show during the four button states - ControlButtonViewBase buttonWidgetPressed = getButtonWidgetPressed(buttonText); - ControlButtonViewBase buttonWidgetHover = getButtonWidgetHover(buttonText); - ControlButtonViewBase buttonWidgetNormal = getButtonWidgetNormal(buttonText); - ControlButtonViewBase buttonWidgetDisabled = getButtonWidgetDisabled(buttonText); - - //Create container for the three state widgets for the button - ButtonViewStates buttonViewWidget = new ButtonViewStates(buttonWidgetNormal, buttonWidgetHover, buttonWidgetPressed, buttonWidgetDisabled); - - //Create button based on view container widget - Button controlButton = new Button(0, 0, buttonViewWidget); - controlButton.Margin = margin; - - return controlButton; - } - - private ControlButtonViewBase getButtonWidgetPressed(string buttonText) - { - RGBA_Bytes fillColor = new RGBA_Bytes(63, 63, 70); - RGBA_Bytes borderColor = new RGBA_Bytes(37, 37, 38); - RGBA_Bytes textColor = new RGBA_Bytes(230, 230, 230); - ControlButtonViewBase widget = new ControlButtonViewBase(buttonText, - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - - private ControlButtonViewBase getButtonWidgetHover(string buttonText) - { - RGBA_Bytes fillColor = new RGBA_Bytes(63, 63, 70); - RGBA_Bytes borderColor = RGBA_Bytes.LightGray; - RGBA_Bytes textColor = new RGBA_Bytes(230, 230, 230); - ControlButtonViewBase widget = new ControlButtonViewBase(buttonText, - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - - public ControlButtonViewBase getButtonWidgetNormal(string buttonText) - { - RGBA_Bytes fillColor = new RGBA_Bytes(245, 245, 245); - RGBA_Bytes borderColor = new RGBA_Bytes(204, 204, 204); - RGBA_Bytes textColor = new RGBA_Bytes(69, 69, 69); - ControlButtonViewBase widget = new ControlButtonViewBase(buttonText, - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - - private ControlButtonViewBase getButtonWidgetDisabled(string buttonText) - { - RGBA_Bytes fillColor = new RGBA_Bytes(245, 245, 245); - RGBA_Bytes borderColor = new RGBA_Bytes(204, 204, 204); - RGBA_Bytes textColor = new RGBA_Bytes(153, 153, 153); - ControlButtonViewBase widget = new ControlButtonViewBase(buttonText, - this.width, - this.height, - this.fontSize, - this.borderWidth, - this.borderRadius, - this.padding, - textColor, - fillColor, - borderColor); - return widget; - } - } -} \ No newline at end of file diff --git a/ActionBar/ActionBarPlus.cs b/ActionBar/ActionBarPlus.cs index 5d22eaf6b..f83954021 100644 --- a/ActionBar/ActionBarPlus.cs +++ b/ActionBar/ActionBarPlus.cs @@ -1,4 +1,33 @@ -using MatterHackers.Agg; +/* +Copyright (c) 2016, 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 MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.MatterControl.ActionBar; using MatterHackers.MatterControl.PrintQueue; diff --git a/CustomWidgets/LibrarySelector/LibraryProviderEventArgs.cs b/ActionBar/ActionRowBase.cs similarity index 71% rename from CustomWidgets/LibrarySelector/LibraryProviderEventArgs.cs rename to ActionBar/ActionRowBase.cs index 3215932c8..3c7096d05 100644 --- a/CustomWidgets/LibrarySelector/LibraryProviderEventArgs.cs +++ b/ActionBar/ActionRowBase.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Kevin Pope +Copyright (c) 2016, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without @@ -30,22 +30,37 @@ either expressed or implied, of the FreeBSD Project. using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Agg.VertexSource; -using MatterHackers.MatterControl.PrintLibrary; -using MatterHackers.MatterControl.PrintLibrary.Provider; -using MatterHackers.VectorMath; using System; -using System.Globalization; -using System.Threading.Tasks; -namespace MatterHackers.MatterControl.CustomWidgets.LibrarySelector +namespace MatterHackers.MatterControl.ActionBar { - public class LibraryDataViewEventArgs : EventArgs + //Base widget for ActionBarRows + public abstract class ActionRowBase : FlowLayoutWidget { - public LibraryProvider LibraryProvider { get; set; } - - public LibraryDataViewEventArgs(LibraryProvider libraryProvider) + public ActionRowBase() + : base(FlowDirection.LeftToRight) { - this.LibraryProvider = libraryProvider; + Initialize(); + SetDisplayAttributes(); + AddChildElements(); + AddHandlers(); + } + + protected virtual void Initialize() + { + //Placeholder for row-specific initialization + } + + protected void SetDisplayAttributes() + { + this.HAnchor = HAnchor.ParentLeftRight; + } + + protected abstract void AddChildElements(); + + protected virtual void AddHandlers() + { + //Placeholder for row-specific handlers } } } \ No newline at end of file diff --git a/ActionBar/PrintActionRow.cs b/ActionBar/PrintActionRow.cs index f7e17b887..cdf79f162 100644 --- a/ActionBar/PrintActionRow.cs +++ b/ActionBar/PrintActionRow.cs @@ -1,4 +1,33 @@ -using MatterHackers.Agg; +/* +Copyright (c) 2016, 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 MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.ConfigurationPage.PrintLeveling; @@ -256,7 +285,7 @@ namespace MatterHackers.MatterControl.ActionBar break; case PrinterConnectionAndCommunication.CommunicationStates.Connected: - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (levelingData != null && ActiveSliceSettings.Instance.LevelingRequiredToPrint && !levelingData.HasBeenRun()) { @@ -393,7 +422,7 @@ namespace MatterHackers.MatterControl.ActionBar private void onConnectButton_Click(object sender, EventArgs mouseEvent) { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { #if __ANDROID__ SetupWizardWindow.Show(); diff --git a/ActionBar/PrintStatusRow.cs b/ActionBar/PrintStatusRow.cs index d7955c625..75faf8ee6 100644 --- a/ActionBar/PrintStatusRow.cs +++ b/ActionBar/PrintStatusRow.cs @@ -238,16 +238,16 @@ namespace MatterHackers.MatterControl.ActionBar autoLevelButton.Cursor = Cursors.Hand; autoLevelButton.Margin = new Agg.BorderDouble(top: 3); autoLevelButton.ToolTipText = "Print leveling is enabled.".Localize(); - autoLevelButton.Visible = ActivePrinterProfile.Instance.DoPrintLeveling; + autoLevelButton.Visible = ActiveSliceSettings.Instance.DoPrintLeveling; - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent((sender, e) => + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((sender, e) => { - autoLevelButton.Visible = ActivePrinterProfile.Instance.DoPrintLeveling; + autoLevelButton.Visible = ActiveSliceSettings.Instance.DoPrintLeveling; }, ref unregisterEvents); - ActivePrinterProfile.Instance.DoPrintLevelingChanged.RegisterEvent((sender, e) => + ActiveSliceSettings.Instance.DoPrintLevelingChanged.RegisterEvent((sender, e) => { - autoLevelButton.Visible = ActivePrinterProfile.Instance.DoPrintLeveling; + autoLevelButton.Visible = ActiveSliceSettings.Instance.DoPrintLeveling; }, ref unregisterEvents); return autoLevelButton; @@ -255,7 +255,7 @@ namespace MatterHackers.MatterControl.ActionBar private string getConnectionMessage() { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { return LocalizedString.Get("Press 'Connect' to select a printer."); } @@ -339,7 +339,7 @@ namespace MatterHackers.MatterControl.ActionBar } private void SetVisibleStatus() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { if (ActiveSliceSettings.Instance.HasHeatedBed()) { diff --git a/ActionBar/PrinterActionRow.cs b/ActionBar/PrinterActionRow.cs index 1474bc363..6887125b1 100644 --- a/ActionBar/PrinterActionRow.cs +++ b/ActionBar/PrinterActionRow.cs @@ -1,4 +1,33 @@ -using MatterHackers.Agg; +/* +Copyright (c) 2016, 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 MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; @@ -10,7 +39,7 @@ namespace MatterHackers.MatterControl.ActionBar { public class PrinterActionRow : ActionRowBase { - static private ConnectionWindow connectionWindow; + static private ConnectionWizard connectionWindow; private TextImageButtonFactory actionBarButtonFactory = new TextImageButtonFactory(); private Button connectPrinterButton; private string disconnectAndCancelMessage = "Disconnect and cancel the current print?".Localize(); @@ -26,12 +55,12 @@ namespace MatterHackers.MatterControl.ActionBar { if (connectAfterSelection) { - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(ConnectToActivePrinter, ref staticUnregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent(ConnectToActivePrinter, ref staticUnregisterEvents); } if (connectionWindow == null) { - connectionWindow = new ConnectionWindow(); + connectionWindow = new ConnectionWizard(); connectionWindow.Closed += new EventHandler(ConnectionWindow_Closed); } @@ -46,10 +75,7 @@ namespace MatterHackers.MatterControl.ActionBar public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -95,7 +121,7 @@ namespace MatterHackers.MatterControl.ActionBar disconnectPrinterButton.VAnchor = VAnchor.ParentTop; disconnectPrinterButton.Cursor = Cursors.Hand; - selectActivePrinterButton = new PrinterSelectButton(); + selectActivePrinterButton = new PrinterSelector(); selectActivePrinterButton.HAnchor = HAnchor.ParentLeftRight; selectActivePrinterButton.Cursor = Cursors.Hand; if (ApplicationController.Instance.WidescreenMode) @@ -132,11 +158,10 @@ namespace MatterHackers.MatterControl.ActionBar protected override void AddHandlers() { - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents); PrinterConnectionAndCommunication.Instance.EnableChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); - selectActivePrinterButton.Click += new EventHandler(onSelectActivePrinterButton_Click); connectPrinterButton.Click += new EventHandler(onConnectButton_Click); disconnectPrinterButton.Click += new EventHandler(onDisconnectButtonClick); resetConnectionButton.Click += new EventHandler(resetConnectionButton_Click); @@ -196,7 +221,7 @@ namespace MatterHackers.MatterControl.ActionBar Button buttonClicked = ((Button)sender); if (buttonClicked.Enabled) { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { OpenConnectionWindow(true); } diff --git a/ActionBar/PrinterSelector.cs b/ActionBar/PrinterSelector.cs new file mode 100644 index 000000000..1ce8a94b7 --- /dev/null +++ b/ActionBar/PrinterSelector.cs @@ -0,0 +1,60 @@ +/* +Copyright (c) 2016, John Lewin +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 MatterHackers.Localizations; +using MatterHackers.MatterControl.SlicerConfiguration; + +namespace MatterHackers.MatterControl +{ + public class PrinterSelector : StyledDropDownList + { + public PrinterSelector() : base("Printers".Localize() + "... ") + { + //Add the menu items to the menu itself + foreach (var printer in ActiveSliceSettings.ProfileData.Profiles) + { + this.AddItem(printer.Name, printer.Id.ToString()); + } + + if (!string.IsNullOrEmpty(ActiveSliceSettings.ProfileData.ActiveProfileID)) + { + this.SelectedValue = ActiveSliceSettings.ProfileData.ActiveProfileID; + } + + this.SelectionChanged += (s, e) => + { + int printerID; + if (int.TryParse(this.SelectedValue, out printerID)) + { + ActiveSliceSettings.SwitchToProfile(printerID); + } + }; + } + } +} \ No newline at end of file diff --git a/ApplicationView/ThirdPanelTabView.cs b/ApplicationView/AdvancedControlsPanel.cs similarity index 51% rename from ApplicationView/ThirdPanelTabView.cs rename to ApplicationView/AdvancedControlsPanel.cs index 8fa6d1027..a4e540ba6 100644 --- a/ApplicationView/ThirdPanelTabView.cs +++ b/ApplicationView/AdvancedControlsPanel.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Kevin Pope +Copyright (c) 2016, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -37,46 +37,52 @@ using System; namespace MatterHackers.MatterControl { - public class ThirdPanelTabView : GuiWidget + public class AdvancedControlsPanel : GuiWidget { + private static readonly string ThirdPanelTabView_AdvancedControls_CurrentTab = "ThirdPanelTabView_AdvancedControls_CurrentTab"; + private event EventHandler unregisterEvents; - private Button advancedControlsBackButton; - private SliceSettingsWidget sliceSettingsWidget; - private EventHandler AdvancedControlsButton_Click; + private Button backButton; + private GuiWidget sliceSettingsWidget; - private TabControl advancedControls2; + public event EventHandler BackClicked; - public ThirdPanelTabView(EventHandler AdvancedControlsButton_Click = null) + private TabControl advancedTab; + + public AdvancedControlsPanel() { - this.AdvancedControlsButton_Click = AdvancedControlsButton_Click; - - advancedControls2 = CreateNewAdvancedControls(AdvancedControlsButton_Click); - - AddChild(advancedControls2); - - ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent(ReloadAdvancedControlsPanelTrigger, ref unregisterEvents); - + advancedTab = CreateAdvancedControlsTab(); + AddChild(advancedTab); AnchorAll(); + + ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent((s, e) => UiThread.RunOnIdle(ReloadSliceSettings), ref unregisterEvents); + } + + public static string SliceSettingsTabName { get; } = "Slice Settings Tab"; + + public static string ControlsTabName { get; } = "Controls Tab"; + + public void ReloadSliceSettings() + { + WidescreenPanel.PreChangePanels.CallEvents(null, null); + + // remove the advance control and replace it with new ones built for the selected printer + int advancedControlsIndex = GetChildIndex(advancedTab); + RemoveChild(advancedControlsIndex); + advancedTab.Close(); + + advancedTab = CreateAdvancedControlsTab(); + AddChild(advancedTab, advancedControlsIndex); } public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } - public void ReloadAdvancedControlsPanelTrigger(object sender, EventArgs e) - { - UiThread.RunOnIdle(ReloadSliceSettings); - } - - private static readonly string ThirdPanelTabView_AdvancedControls_CurrentTab = "ThirdPanelTabView_AdvancedControls_CurrentTab"; - - private TabControl CreateNewAdvancedControls(EventHandler AdvancedControlsButton_Click) + private TabControl CreateAdvancedControlsTab() { TabControl advancedControls = new TabControl(); @@ -87,44 +93,46 @@ namespace MatterHackers.MatterControl int textSize = 16; - if (AdvancedControlsButton_Click != null) - { - // this means we are in compact view and so we will make the tabs text a bit smaller - textSize = 14; - TextImageButtonFactory advancedControlsButtonFactory = new TextImageButtonFactory(); - advancedControlsButtonFactory.fontSize = 14; - advancedControlsButtonFactory.invertImageLocation = false; - advancedControlsBackButton = advancedControlsButtonFactory.Generate(LocalizedString.Get("Back"), "icon_arrow_left_32x32.png"); - advancedControlsBackButton.ToolTipText = "Switch to Queue, Library and History".Localize(); - advancedControlsBackButton.Margin = new BorderDouble(right: 3); - advancedControlsBackButton.VAnchor = VAnchor.ParentBottom; - advancedControlsBackButton.Cursor = Cursors.Hand; - advancedControlsBackButton.Click += new EventHandler(AdvancedControlsButton_Click); + // this means we are in compact view and so we will make the tabs text a bit smaller + textSize = 14; + TextImageButtonFactory advancedControlsButtonFactory = new TextImageButtonFactory(); + advancedControlsButtonFactory.fontSize = 14; + advancedControlsButtonFactory.invertImageLocation = false; + backButton = advancedControlsButtonFactory.Generate(LocalizedString.Get("Back"), "icon_arrow_left_32x32.png"); + backButton.ToolTipText = "Switch to Queue, Library and History".Localize(); + backButton.Margin = new BorderDouble(right: 3); + backButton.VAnchor = VAnchor.ParentBottom; + backButton.Cursor = Cursors.Hand; + backButton.Click += (s, e) => BackClicked?.Invoke(this, null); - advancedControls.TabBar.AddChild(advancedControlsBackButton); - } + advancedControls.TabBar.AddChild(backButton); advancedControls.TabBar.AddChild(new HorizontalSpacer()); GuiWidget manualPrinterControls = new ManualPrinterControls(); + ScrollableWidget manualPrinterControlsScrollArea = new ScrollableWidget(true); - manualPrinterControlsScrollArea.ScrollArea.HAnchor |= Agg.UI.HAnchor.ParentLeftRight; + manualPrinterControlsScrollArea.ScrollArea.HAnchor |= HAnchor.ParentLeftRight; manualPrinterControlsScrollArea.AnchorAll(); manualPrinterControlsScrollArea.AddChild(manualPrinterControls); RGBA_Bytes unselectedTextColor = ActiveTheme.Instance.TabLabelUnselected; - //Add the tab contents for 'Advanced Controls' - string sliceSettingsLabel = LocalizedString.Get("Settings").ToUpper(); - string printerControlsLabel = LocalizedString.Get("Controls").ToUpper(); - sliceSettingsWidget = new SliceSettingsWidget(); + if (ActiveSliceSettings.Instance.PrinterSelected) + { + sliceSettingsWidget = new SliceSettingsWidget(); + } + else + { + sliceSettingsWidget = new NoSettingsWidget(); + } - TabPage sliceSettingsTabPage = new TabPage(sliceSettingsWidget, sliceSettingsLabel); - PopOutTextTabWidget sliceSettingPopOut = new PopOutTextTabWidget(sliceSettingsTabPage, SliceSettingsTabName, new Vector2(590, 400), textSize); + var sliceSettingsTabPage = new TabPage(sliceSettingsWidget, "Settings".Localize().ToUpper()); + var sliceSettingPopOut = new PopOutTextTabWidget(sliceSettingsTabPage, SliceSettingsTabName, new Vector2(590, 400), textSize); advancedControls.AddTab(sliceSettingPopOut); - TabPage controlsTabPage = new TabPage(manualPrinterControlsScrollArea, printerControlsLabel); - PopOutTextTabWidget controlsPopOut = new PopOutTextTabWidget(controlsTabPage, ControlsTabName, new Vector2(400, 300), textSize); + var controlsTabPage = new TabPage(manualPrinterControlsScrollArea, "Controls".Localize().ToUpper()); + var controlsPopOut = new PopOutTextTabWidget(controlsTabPage, ControlsTabName, new Vector2(400, 300), textSize); advancedControls.AddTab(controlsPopOut); #if !__ANDROID__ @@ -132,9 +140,8 @@ namespace MatterHackers.MatterControl MenuOptionSettings.controlsPopOut = controlsPopOut; #endif - string optionsLabel = LocalizedString.Get("Options").ToUpper(); - ScrollableWidget optionsControls = new PrinterConfigurationScrollWidget(); - advancedControls.AddTab(new SimpleTextTabWidget(new TabPage(optionsControls, optionsLabel), "Options Tab", textSize, + var optionsControls = new PrinterConfigurationScrollWidget(); + advancedControls.AddTab(new SimpleTextTabWidget(new TabPage(optionsControls, "Options".Localize().ToUpper()), "Options Tab", textSize, ActiveTheme.Instance.PrimaryTextColor, new RGBA_Bytes(), unselectedTextColor, new RGBA_Bytes())); // Make sure we are on the right tab when we create this view @@ -142,7 +149,7 @@ namespace MatterHackers.MatterControl string selectedTab = UserSettings.Instance.get(ThirdPanelTabView_AdvancedControls_CurrentTab); advancedControls.SelectTab(selectedTab); - advancedControls.TabBar.TabIndexChanged += (object sender, EventArgs e) => + advancedControls.TabBar.TabIndexChanged += (sender, e) => { UserSettings.Instance.set(ThirdPanelTabView_AdvancedControls_CurrentTab, advancedControls.TabBar.SelectedTabName); }; @@ -150,37 +157,5 @@ namespace MatterHackers.MatterControl return advancedControls; } - - public static string SliceSettingsTabName - { - get { return "Slice Settings Tab"; } - } - - public static string ControlsTabName - { - get { return "Controls Tab"; } - } - - public void ReloadSliceSettings() - { - WidescreenPanel.PreChangePanels.CallEvents(null, null); - - // remove the advance control and replace it with new ones built for the selected printer - int advancedControlsIndex = GetChildIndex(advancedControls2); - RemoveChild(advancedControlsIndex); - advancedControls2.Close(); - - if (advancedControlsBackButton != null) - { - advancedControlsBackButton.Click -= new EventHandler(AdvancedControlsButton_Click); - } - - advancedControls2 = CreateNewAdvancedControls(AdvancedControlsButton_Click); - AddChild(advancedControls2, advancedControlsIndex); - - // This is a hack to make the panel remain on the screen. It would be great to debug it and understand - // why it does not work without this code in here. - //currentParent.Parent.Width = currentParent.Parent.Width + 1; - } } } \ No newline at end of file diff --git a/ApplicationView/CompactSlidePanel.cs b/ApplicationView/CompactSlidePanel.cs index 5a8467bfc..9f674bf17 100644 --- a/ApplicationView/CompactSlidePanel.cs +++ b/ApplicationView/CompactSlidePanel.cs @@ -46,22 +46,18 @@ namespace MatterHackers.MatterControl private QueueDataView queueDataView; - private GuiWidget LeftPanel - { - get { return GetPanel(0); } - } + const int StandardControlsPanelIndex = 0; + const int AdvancedControlsPanelIndex = 1; - private GuiWidget RightPanel - { - get { return GetPanel(1); } - } + private GuiWidget LeftPanel => GetPanel(0); - public double TabBarWidth { get { return mainControlsTabControl.Width; } } + private GuiWidget RightPanel => GetPanel(1); + + public double TabBarWidth => mainControlsTabControl.Width; private static int lastPanelIndexBeforeReload = 0; - public CompactSlidePanel(QueueDataView queueDataView) - : base(2) + public CompactSlidePanel(QueueDataView queueDataView) : base(2) { this.queueDataView = queueDataView; @@ -73,24 +69,27 @@ namespace MatterHackers.MatterControl // construct the main controls tab control mainControlsTabControl = new FirstPanelTabView(queueDataView); - TextImageButtonFactory advancedControlsButtonFactory = new TextImageButtonFactory(); - advancedControlsButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor; - advancedControlsButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor; - advancedControlsButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor; - advancedControlsButtonFactory.fontSize = 10; + var advancedControlsButtonFactory = new TextImageButtonFactory() + { + normalTextColor = ActiveTheme.Instance.PrimaryTextColor, + hoverTextColor = ActiveTheme.Instance.PrimaryTextColor, + pressedTextColor = ActiveTheme.Instance.PrimaryTextColor, + fontSize = 10, - advancedControlsButtonFactory.disabledTextColor = RGBA_Bytes.LightGray; - advancedControlsButtonFactory.disabledFillColor = ActiveTheme.Instance.PrimaryBackgroundColor; - advancedControlsButtonFactory.disabledBorderColor = ActiveTheme.Instance.PrimaryBackgroundColor; + disabledTextColor = RGBA_Bytes.LightGray, + disabledFillColor = ActiveTheme.Instance.PrimaryBackgroundColor, + disabledBorderColor = ActiveTheme.Instance.PrimaryBackgroundColor, + + invertImageLocation = true + }; - advancedControlsButtonFactory.invertImageLocation = true; Button advancedControlsLinkButton = advancedControlsButtonFactory.Generate(LocalizedString.Get("Settings\n& Controls"), "icon_arrow_right_32x32.png"); - advancedControlsLinkButton.Name = "SettingsAndControls"; - advancedControlsLinkButton.ToolTipText = "Switch to Settings, Controls and Options".Localize(); - advancedControlsLinkButton.Margin = new BorderDouble(right: 3); + advancedControlsLinkButton.Name = "SettingsAndControls"; + advancedControlsLinkButton.ToolTipText = "Switch to Settings, Controls and Options".Localize(); + advancedControlsLinkButton.Margin = new BorderDouble(right: 3); advancedControlsLinkButton.VAnchor = VAnchor.ParentBottom; advancedControlsLinkButton.Cursor = Cursors.Hand; - advancedControlsLinkButton.Click += new EventHandler(AdvancedControlsButton_Click); + advancedControlsLinkButton.Click += ToggleActivePanel_Click; mainControlsTabControl.TabBar.AddChild(new HorizontalSpacer()); mainControlsTabControl.TabBar.AddChild(advancedControlsLinkButton); @@ -100,17 +99,20 @@ namespace MatterHackers.MatterControl this.LeftPanel.AddChild(mainControlsTabControl); } - // do the right panel + // Right panel + this.RightPanel.AddChild(new PrintProgressBar()); + + var advancedControlsPanel = new AdvancedControlsPanel() { - this.RightPanel.AddChild(new PrintProgressBar()); - ThirdPanelTabView thirdPanelTabView = new ThirdPanelTabView(AdvancedControlsButton_Click); - thirdPanelTabView.Name = "For - CompactSlidePanel"; - this.RightPanel.AddChild(thirdPanelTabView); - } + Name = "For - CompactSlidePanel" + }; + advancedControlsPanel.BackClicked += ToggleActivePanel_Click; + + this.RightPanel.AddChild(advancedControlsPanel); WidescreenPanel.PreChangePanels.RegisterEvent(SaveCurrentPanelIndex, ref unregisterEvents); - SetPanelIndexImediate(lastPanelIndexBeforeReload); + SetPanelIndexImmediate(lastPanelIndexBeforeReload); } private void SaveCurrentPanelIndex(object sender, EventArgs e) @@ -118,30 +120,22 @@ namespace MatterHackers.MatterControl lastPanelIndexBeforeReload = PanelIndex; } - private void AdvancedControlsButton_Click(object sender, EventArgs mouseEvent) + private void ToggleActivePanel_Click(object sender, EventArgs mouseEvent) { - if (this.PanelIndex == 0) + if (this.PanelIndex == StandardControlsPanelIndex) { - this.PanelIndex = 1; + this.PanelIndex = AdvancedControlsPanelIndex; } else { - this.PanelIndex = 0; + this.PanelIndex = StandardControlsPanelIndex; } } public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } - - private void DoNotChangePanel() - { - //Empty function used as placeholder - } } } \ No newline at end of file diff --git a/ApplicationView/CompactTabView.cs b/ApplicationView/CompactTabView.cs index f2dda2f00..fbc05c26a 100644 --- a/ApplicationView/CompactTabView.cs +++ b/ApplicationView/CompactTabView.cs @@ -207,9 +207,9 @@ namespace MatterHackers.MatterControl QueueData.Instance.ItemAdded.RegisterEvent(NumQueueItemsChanged, ref unregisterEvents); QueueData.Instance.ItemRemoved.RegisterEvent(NumQueueItemsChanged, ref unregisterEvents); - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(LoadSettingsOnPrinterChanged, ref unregisterEvents); - PrinterConnectionAndCommunication.Instance.ActivePrintItemChanged.RegisterEvent(OnActivePrintItemChanged, ref unregisterEvents); - ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent(ReloadAdvancedControlsPanelTrigger, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((s, e) => ApplicationController.Instance.ReloadAdvancedControlsPanel(), ref unregisterEvents); + PrinterConnectionAndCommunication.Instance.ActivePrintItemChanged.RegisterEvent((s, e) => UiThread.RunOnIdle(ReloadPartPreview, null, 1), ref unregisterEvents); + ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent((s, e) => UiThread.RunOnIdle(LoadAdvancedControls), ref unregisterEvents); UpdateControlData.Instance.UpdateStatusChanged.RegisterEvent(SetUpdateNotification, ref unregisterEvents); // Make sure we are on the right tab when we create this view @@ -225,28 +225,9 @@ namespace MatterHackers.MatterControl } private event EventHandler unregisterEvents; - public void LoadSettingsOnPrinterChanged(object sender, EventArgs e) - { - ActiveSliceSettings.Instance.LoadAllSettings(); - ApplicationController.Instance.ReloadAdvancedControlsPanel(); - } - public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } - } - - public void ReloadAdvancedControlsPanel() - { - UiThread.RunOnIdle(LoadAdvancedControls); - } - - public void ReloadAdvancedControlsPanelTrigger(object sender, EventArgs e) - { - UiThread.RunOnIdle(ReloadAdvancedControlsPanel); + unregisterEvents?.Invoke(this, null); } public void SetUpdateNotification(object sender, EventArgs widgetEvent) @@ -294,11 +275,6 @@ namespace MatterHackers.MatterControl QueueTabPage.Text = string.Format(queueString, QueueData.Instance.Count); } - private void OnActivePrintItemChanged(object sender, EventArgs e) - { - UiThread.RunOnIdle(ReloadPartPreview, null, 1); - } - private void ReloadConfigurationWidget() { optionsPage.RemoveAllChildren(); diff --git a/ApplicationView/MainApplicationWidget.cs b/ApplicationView/MainApplicationWidget.cs index ae7317632..9b30d0bfd 100644 --- a/ApplicationView/MainApplicationWidget.cs +++ b/ApplicationView/MainApplicationWidget.cs @@ -36,13 +36,14 @@ using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.VectorMath; using System; using System.Diagnostics; +using System.Linq; using System.Threading.Tasks; namespace MatterHackers.MatterControl { public abstract class ApplicationView : GuiWidget { - public TopContainerWidget TopContainer; + public FlowLayoutWidget TopContainer; public abstract void AddElements(); @@ -57,14 +58,14 @@ namespace MatterHackers.MatterControl private QueueDataView queueDataView; private GuiWidget menuSeparator; private PrintProgressBar progressBar; + private bool topIsHidden = false; public CompactApplicationView() { AddElements(); - Initialize(); - } - private bool topIsHidden = false; + this.AnchorAll(); + } public override void HideTopContainer() { @@ -98,7 +99,7 @@ namespace MatterHackers.MatterControl FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); container.AnchorAll(); - TopContainer = new TopContainerWidget(); + TopContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); TopContainer.HAnchor = HAnchor.ParentLeftRight; ApplicationMenuRow menuRow = new ApplicationMenuRow(); @@ -114,7 +115,6 @@ namespace MatterHackers.MatterControl queueDataView = new QueueDataView(); TopContainer.AddChild(new ActionBarPlus(queueDataView)); - TopContainer.SetOriginalHeight(); container.AddChild(TopContainer); @@ -124,47 +124,7 @@ namespace MatterHackers.MatterControl container.AddChild(menuSeparator); compactTabView = new CompactTabView(queueDataView); - BottomOverlay bottomOverlay = new BottomOverlay(); - bottomOverlay.AddChild(compactTabView); - - container.AddChild(bottomOverlay); - - this.AddChild(container); - } - - private void Initialize() - { - this.AnchorAll(); - } - } - - public class TopContainerWidget : FlowLayoutWidget - { - private double originalHeight; - - public TopContainerWidget() - : base(FlowDirection.TopToBottom) - { - } - - public void SetOriginalHeight() - { - originalHeight = this.Height; - } - } - - internal class BottomOverlay : GuiWidget - { - public BottomOverlay() - : base() - { - this.AnchorAll(); - } - - public override void OnMouseDown(MouseEventArgs mouseEvent) - { - base.OnMouseDown(mouseEvent); - //ApplicationController.Instance.MainView.HideTopContainer(); + this.AddChild(compactTabView); } } @@ -188,36 +148,31 @@ namespace MatterHackers.MatterControl public override void AddElements() { - Stopwatch timer = Stopwatch.StartNew(); - timer.Start(); + this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); - + var container = new FlowLayoutWidget(FlowDirection.TopToBottom); container.AnchorAll(); - ApplicationMenuRow menuRow = new ApplicationMenuRow(); + var menuRow = new ApplicationMenuRow(); container.AddChild(menuRow); - GuiWidget menuSeparator = new GuiWidget(); - menuSeparator.BackgroundColor = new RGBA_Bytes(200, 200, 200); - menuSeparator.Height = 2; - menuSeparator.HAnchor = HAnchor.ParentLeftRight; - menuSeparator.Margin = new BorderDouble(3, 6, 3, 3); - + var menuSeparator = new GuiWidget() + { + BackgroundColor = new RGBA_Bytes(200, 200, 200), + Height = 2, + HAnchor = HAnchor.ParentLeftRight, + Margin = new BorderDouble(3, 6, 3, 3) + }; container.AddChild(menuSeparator); - Console.WriteLine("{0} ms 1".FormatWith(timer.ElapsedMilliseconds)); timer.Restart(); + widescreenPanel = new WidescreenPanel(); container.AddChild(widescreenPanel); - Console.WriteLine("{0} ms 2".FormatWith(timer.ElapsedMilliseconds)); timer.Restart(); - - Console.WriteLine("{0} ms 3".FormatWith(timer.ElapsedMilliseconds)); timer.Restart(); using (new PerformanceTimer("ReloadAll", "AddChild")) { this.AddChild(container); } - Console.WriteLine("{0} ms 4".FormatWith(timer.ElapsedMilliseconds)); timer.Restart(); } private void Initialize() @@ -267,18 +222,12 @@ namespace MatterHackers.MatterControl public void StartLogin() { - if (privateStartLogin != null) - { - privateStartLogin(null, null); - } + privateStartLogin?.Invoke(null, null); } public void StartLogout() { - if (privateStartLogout != null) - { - privateStartLogout(null, null); - } + privateStartLogout?.Invoke(null, null); } public string GetSessionUsername() @@ -301,13 +250,12 @@ namespace MatterHackers.MatterControl { // give the widget a chance to hear about the close before they are actually closed. PopOutManager.SaveIfClosed = false; - WidescreenPanel.PreChangePanels.CallEvents(this, null); + WidescreenPanel.PreChangePanels.CallEvents(this, null); MainView.CloseAllChildren(); using (new PerformanceTimer("ReloadAll", "AddElements")) { MainView.AddElements(); } - DoneReloadingAll.CallEvents(null, null); PopOutManager.SaveIfClosed = true; } }); @@ -315,10 +263,7 @@ namespace MatterHackers.MatterControl public void OnApplicationClosed() { - if (ApplicationClosed != null) - { - ApplicationClosed(null, null); - } + ApplicationClosed?.Invoke(null, null); } public static ApplicationController Instance diff --git a/ApplicationView/MenuRow/MenuBase.cs b/ApplicationView/MenuRow/MenuBase.cs index a519c6d95..2bdfeaa4e 100644 --- a/ApplicationView/MenuRow/MenuBase.cs +++ b/ApplicationView/MenuRow/MenuBase.cs @@ -55,7 +55,7 @@ namespace MatterHackers.MatterControl this.Margin = new BorderDouble(0); this.Padding = new BorderDouble(0); this.VAnchor = Agg.UI.VAnchor.ParentCenter; - this.MenuDropList.SelectionChanged += new EventHandler(MenuDropList_SelectionChanged); + this.MenuDropList.SelectionChanged += MenuDropList_SelectionChanged; this.MenuDropList.OpenOffset = new Vector2(0, 0); } @@ -64,9 +64,9 @@ namespace MatterHackers.MatterControl string menuSelection = ((DropDownMenu)sender).SelectedValue; foreach (MenuItemAction item in menuItems) { - if (item.Title == menuSelection) + if (item.Title == menuSelection && item.Action != null) { - item.Action?.Invoke(); + UiThread.RunOnIdle(item.Action); } } } diff --git a/ApplicationView/MenuRow/MenuOptionFile.cs b/ApplicationView/MenuRow/MenuOptionFile.cs index 4ef629f1f..dec64192d 100644 --- a/ApplicationView/MenuRow/MenuOptionFile.cs +++ b/ApplicationView/MenuRow/MenuOptionFile.cs @@ -9,6 +9,7 @@ using System.Collections.Generic; using MatterHackers.VectorMath; using System; using System.IO; +using System.Linq; namespace MatterHackers.MatterControl { @@ -18,127 +19,69 @@ namespace MatterHackers.MatterControl public static MenuOptionFile CurrentMenuOptionFile = null; - public event EventHandler AddLocalFolderToLibrary; public EventHandler RedeemDesignCode; - public EventHandler EnterShareCode; + public EventHandler EnterShareCode; public MenuOptionFile() : base("File".Localize()) { Name = "File Menu"; CurrentMenuOptionFile = this; + } - override protected IEnumerable GetMenuItems() + protected override IEnumerable GetMenuItems() { return new List { - new MenuItemAction("Add Printer".Localize(), addPrinter_Click), - new MenuItemAction("Add File To Queue".Localize(), importFile_Click), - //new MenuItemAction("Add Folder To Library".Localize(), addFolderToLibrar_Click), - new MenuItemAction("Redeem Design Code".Localize(), redeemDesignCode_Click), - new MenuItemAction("Enter Share Code".Localize(), enterShareCode_Click), + new MenuItemAction("Add Printer".Localize(), () => ConnectionWizard.Show()), + new MenuItemAction("Add File To Queue".Localize(), importFile_Click), + new MenuItemAction("Redeem Design Code".Localize(), () => RedeemDesignCode?.Invoke(this, null)), + new MenuItemAction("Enter Share Code".Localize(), () => EnterShareCode?.Invoke(this, null)), new MenuItemAction("------------------------", null), - new MenuItemAction("Exit".Localize(), exit_Click), - }; - } - - private void redeemDesignCode_Click() - { - if (RedeemDesignCode != null) - { - RedeemDesignCode(this, null); - } - } - - private void enterShareCode_Click() - { - if (EnterShareCode != null) - { - UiThread.RunOnIdle(() => EnterShareCode(this, null)); - } - } - - private void addFolderToLibrar_Click() - { - if (AddLocalFolderToLibrary != null) - { - if (createFolderWindow == null) + new MenuItemAction("Exit".Localize(), () => { - UiThread.RunOnIdle(() => - { - createFolderWindow = new CreateFolderWindow((returnInfo) => - { - AddLocalFolderToLibrary(this, new StringEventArgs(returnInfo.newName)); - }); - createFolderWindow.Closed += (sender2, e2) => { createFolderWindow = null; }; - }); - } - else - { - createFolderWindow.BringToFront(); - } - } - } - - private void addPrinter_Click() - { - UiThread.RunOnIdle(ConnectionWindow.Show); + MatterControlApplication app = this.Parents().FirstOrDefault(); + app.RestartOnClose = false; + app.Close(); + }) + }; } private void importFile_Click() { - UiThread.RunOnIdle(() => - { - FileDialog.OpenFileDialog( - new OpenFileDialogParams(ApplicationSettings.OpenPrintableFileParams) + FileDialog.OpenFileDialog( + new OpenFileDialogParams(ApplicationSettings.OpenPrintableFileParams) + { + MultiSelect = true, + ActionButtonLabel = "Add to Queue", + Title = "MatterControl: Select A File" + }, + (openParams) => + { + if (openParams.FileNames != null) { - MultiSelect = true, - ActionButtonLabel = "Add to Queue", - Title = "MatterControl: Select A File" - }, - (openParams) => - { - if (openParams.FileNames != null) + foreach (string loadedFileName in openParams.FileNames) { - foreach (string loadedFileName in openParams.FileNames) + if (Path.GetExtension(loadedFileName).ToUpper() == ".ZIP") { - if (Path.GetExtension(loadedFileName).ToUpper() == ".ZIP") - { - ProjectFileHandler project = new ProjectFileHandler(null); - List partFiles = project.ImportFromProjectArchive(loadedFileName); - if (partFiles != null) - { - foreach (PrintItem part in partFiles) - { - QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(part.Name, part.FileLocation))); - } - } - } - else - { - QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileNameWithoutExtension(loadedFileName), Path.GetFullPath(loadedFileName)))); - } + ProjectFileHandler project = new ProjectFileHandler(null); + List partFiles = project.ImportFromProjectArchive(loadedFileName); + if (partFiles != null) + { + foreach (PrintItem part in partFiles) + { + QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(part.Name, part.FileLocation))); + } + } + } + else + { + QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileNameWithoutExtension(loadedFileName), Path.GetFullPath(loadedFileName)))); } } - }); - }); - } - - private void exit_Click() - { - UiThread.RunOnIdle(() => - { - GuiWidget parent = this; - while (parent as MatterControlApplication == null) - { - parent = parent.Parent; - } - - MatterControlApplication app = parent as MatterControlApplication; - app.RestartOnClose = false; - app.Close(); - }); + } + }); } } } \ No newline at end of file diff --git a/ApplicationView/MenuRow/MenuOptionHelp.cs b/ApplicationView/MenuRow/MenuOptionHelp.cs index 32936bc4b..a423c0832 100644 --- a/ApplicationView/MenuRow/MenuOptionHelp.cs +++ b/ApplicationView/MenuRow/MenuOptionHelp.cs @@ -11,81 +11,30 @@ namespace MatterHackers.MatterControl { public class MenuOptionHelp : MenuBase { - public MenuOptionHelp() - : base("Help".Localize()) + public MenuOptionHelp() : base("Help".Localize()) { Name = "Help Menu"; } - override protected IEnumerable GetMenuItems() + protected override IEnumerable GetMenuItems() { return new List - { - new MenuItemAction("Getting Started".Localize(), gettingStarted_Click), - new MenuItemAction("View Help".Localize(), help_Click), - new MenuItemAction("Release Notes".Localize(), notes_Click), - new MenuItemAction("User Manual".Localize(), manual_Click), - new MenuItemAction("------------------------", null), - new MenuItemAction("Report a Bug".Localize(), bug_Click), - new MenuItemAction("Check For Update".Localize(), checkForUpdate_Click), + { + new MenuItemAction("Getting Started".Localize(), () => MatterControlApplication.Instance.LaunchBrowser("http://www.mattercontrol.com/articles/mattercontrol-getting-started")), + new MenuItemAction("View Help".Localize(), () => MatterControlApplication.Instance.LaunchBrowser("http://www.mattercontrol.com/articles")), + new MenuItemAction("Release Notes".Localize(), () => MatterControlApplication.Instance.LaunchBrowser("http://wiki.mattercontrol.com/Release_Notes")), + new MenuItemAction("User Manual".Localize(), () => MatterControlApplication.Instance.LaunchBrowser("http://wiki.mattercontrol.com")), new MenuItemAction("------------------------", null), - new MenuItemAction("About MatterControl".Localize(), about_Click), - }; - } - - private void bug_Click() - { - UiThread.RunOnIdle(() => - { - ContactFormWindow.Open(); - }); - } - - private void help_Click() - { - UiThread.RunOnIdle(() => - { - MatterControlApplication.Instance.LaunchBrowser("http://www.mattercontrol.com/articles"); - }); - } - - private void checkForUpdate_Click() - { - UiThread.RunOnIdle(() => - { - ApplicationMenuRow.AlwaysShowUpdateStatus = true; - UpdateControlData.Instance.CheckForUpdateUserRequested(); - CheckForUpdateWindow.Show(); - }); - } - - private void about_Click() - { - UiThread.RunOnIdle(AboutWindow.Show); - } - - private void notes_Click() - { - UiThread.RunOnIdle(() => + new MenuItemAction("Report a Bug".Localize(), () => ContactFormWindow.Open()), + new MenuItemAction("Check For Update".Localize(), () => { - MatterControlApplication.Instance.LaunchBrowser("http://wiki.mattercontrol.com/Release_Notes"); - }); + ApplicationMenuRow.AlwaysShowUpdateStatus = true; + UpdateControlData.Instance.CheckForUpdateUserRequested(); + CheckForUpdateWindow.Show(); + }), + new MenuItemAction("------------------------", null), + new MenuItemAction("About MatterControl".Localize(), () => AboutWindow.Show()), + }; } - - private void gettingStarted_Click() - { - UiThread.RunOnIdle(() => - { - MatterControlApplication.Instance.LaunchBrowser("http://www.mattercontrol.com/articles/mattercontrol-getting-started"); - }); - } - - private void manual_Click() - { - UiThread.RunOnIdle(() => - { - MatterControlApplication.Instance.LaunchBrowser("http://wiki.mattercontrol.com"); - }); - } - } + } } \ No newline at end of file diff --git a/ApplicationView/MenuRow/MenuOptionSettings.cs b/ApplicationView/MenuRow/MenuOptionSettings.cs index a4074f88e..78334e50e 100644 --- a/ApplicationView/MenuRow/MenuOptionSettings.cs +++ b/ApplicationView/MenuRow/MenuOptionSettings.cs @@ -17,47 +17,18 @@ namespace MatterHackers.MatterControl static public PopOutTextTabWidget sliceSettingsPopOut = null; static public PopOutTextTabWidget controlsPopOut = null; - public MenuOptionSettings() - : base("View".Localize()) + public MenuOptionSettings() : base("View".Localize()) { - } - override protected IEnumerable GetMenuItems() + protected override IEnumerable GetMenuItems() { return new List - { - new MenuItemAction("Settings".Localize(), openPrintingPanel_Click), - new MenuItemAction("Controls".Localize(), openControlsPanel_Click), - new MenuItemAction("Terminal".Localize(), openTermanialPanel_Click), - }; - } - - private void openPrintingPanel_Click() - { - UiThread.RunOnIdle(() => { - if (sliceSettingsPopOut != null) - { - sliceSettingsPopOut.ShowInWindow(); - } - }); - } - - private void openControlsPanel_Click() - { - UiThread.RunOnIdle(() => - { - if (controlsPopOut != null) - { - controlsPopOut.ShowInWindow(); - } - }); - } - - private void openTermanialPanel_Click() - { - UiThread.RunOnIdle(TerminalWindow.Show); + new MenuItemAction("Settings".Localize(), () => sliceSettingsPopOut?.ShowInWindow()), + new MenuItemAction("Controls".Localize(), () => controlsPopOut?.ShowInWindow()), + new MenuItemAction("Terminal".Localize(), () => UiThread.RunOnIdle(TerminalWindow.Show)), + }; } } } \ No newline at end of file diff --git a/ApplicationView/WidescreenPanel.cs b/ApplicationView/WidescreenPanel.cs index 1c5900ba7..59aa14fca 100644 --- a/ApplicationView/WidescreenPanel.cs +++ b/ApplicationView/WidescreenPanel.cs @@ -1,12 +1,4 @@ -using MatterHackers.Agg; -using MatterHackers.Agg.UI; -using MatterHackers.MatterControl.PartPreviewWindow; -using MatterHackers.MatterControl.PrinterCommunication; -using MatterHackers.MatterControl.PrintQueue; -using MatterHackers.MatterControl.SlicerConfiguration; -using MatterHackers.VectorMath; - -/* +/* Copyright (c) 2014, Kevin Pope All rights reserved. @@ -37,6 +29,14 @@ either expressed or implied, of the FreeBSD Project. using System; +using MatterHackers.Agg; +using MatterHackers.Agg.UI; +using MatterHackers.MatterControl.PartPreviewWindow; +using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.PrintQueue; +using MatterHackers.MatterControl.SlicerConfiguration; +using MatterHackers.VectorMath; + namespace MatterHackers.MatterControl { public class WidescreenPanel : FlowLayoutWidget @@ -68,15 +68,12 @@ namespace MatterHackers.MatterControl BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; Padding = new BorderDouble(4); - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(LoadSettingsOnPrinterChanged, ref unregisterEvents); - PrinterConnectionAndCommunication.Instance.ActivePrintItemChanged.RegisterEvent(onActivePrintItemChanged, ref unregisterEvents); - ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent(ReloadAdvancedControlsPanelTrigger, ref unregisterEvents); - this.BoundsChanged += new EventHandler(onBoundsChanges); - } + // TODO: This hooks seems to invalidate most of the other ActivePrinterChanged subscribers as this destroys and recreates everything + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((s, e) => ApplicationController.Instance.ReloadAll(null, null), ref unregisterEvents); - public void ReloadAdvancedControlsPanelTrigger(object sender, EventArgs e) - { - UiThread.RunOnIdle(ReloadAdvancedControlsPanel); + PrinterConnectionAndCommunication.Instance.ActivePrintItemChanged.RegisterEvent(onActivePrintItemChanged, ref unregisterEvents); + ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent((s, e) => UiThread.RunOnIdle(ReloadAdvancedControlsPanel), ref unregisterEvents); + this.BoundsChanged += onBoundsChanges; } public override void OnParentChanged(EventArgs e) @@ -96,10 +93,7 @@ namespace MatterHackers.MatterControl public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -207,11 +201,6 @@ namespace MatterHackers.MatterControl } } - public override void OnDraw(Graphics2D graphics2D) - { - base.OnDraw(graphics2D); - } - private void RemovePanelsAndCreateEmpties() { CloseAllChildren(); @@ -237,12 +226,6 @@ namespace MatterHackers.MatterControl { PreChangePanels.CallEvents(this, null); } - - public void LoadSettingsOnPrinterChanged(object sender, EventArgs e) - { - ActiveSliceSettings.Instance.LoadAllSettings(); - ApplicationController.Instance.ReloadAll(null, null); - } } public class UpdateNotificationMark : GuiWidget diff --git a/ConfigurationPage/ApplicationSettings/ApplicationSettingsView.cs b/ConfigurationPage/ApplicationSettings/ApplicationSettingsView.cs index c95667c81..964f51568 100644 --- a/ConfigurationPage/ApplicationSettings/ApplicationSettingsView.cs +++ b/ConfigurationPage/ApplicationSettings/ApplicationSettingsView.cs @@ -70,7 +70,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage mainContainer.AddChild(GetLanguageControl()); mainContainer.AddChild(new HorizontalLine(separatorLineColor)); GuiWidget sliceEngineControl = GetSliceEngineControl(); - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { mainContainer.AddChild(sliceEngineControl); mainContainer.AddChild(new HorizontalLine(separatorLineColor)); @@ -399,15 +399,14 @@ namespace MatterHackers.MatterControl.ConfigurationPage FlowLayoutWidget optionsContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); optionsContainer.Margin = new BorderDouble(bottom: 6); - if (ActiveSliceSettings.Instance.ExtruderCount > 1) + var settings = ActiveSliceSettings.Instance; + + // Reset active slicer to MatterSlice when multi-extruder is detected and MatterSlice is not already set + if (settings?.ExtruderCount > 1 && settings.ActiveSliceEngineType != SlicingEngineTypes.MatterSlice) { - // Reset active slicer to MatterSlice when multi-extruder is detected and MatterSlice is not already set - if (ActivePrinterProfile.Instance.ActiveSliceEngineType != ActivePrinterProfile.SlicingEngineTypes.MatterSlice) - { - ActivePrinterProfile.Instance.ActiveSliceEngineType = ActivePrinterProfile.SlicingEngineTypes.MatterSlice; - ApplicationController.Instance.ReloadAll(null, null); - } - } + settings.ActiveSliceEngineType = SlicingEngineTypes.MatterSlice; + ApplicationController.Instance.ReloadAll(null, null); + } optionsContainer.AddChild(new SliceEngineSelector("Slice Engine".Localize())); optionsContainer.Width = 200; diff --git a/ConfigurationPage/CalibrationSettings/CalibrationSettingsView.cs b/ConfigurationPage/CalibrationSettings/CalibrationSettingsView.cs index 5214a9b93..5b167364d 100644 --- a/ConfigurationPage/CalibrationSettings/CalibrationSettingsView.cs +++ b/ConfigurationPage/CalibrationSettings/CalibrationSettingsView.cs @@ -92,12 +92,12 @@ namespace MatterHackers.MatterControl.ConfigurationPage ImageWidget levelingIcon = new ImageWidget(levelingImage); levelingIcon.Margin = new BorderDouble(right: 6); - CheckBox printLevelingSwitch = ImageButtonFactory.CreateToggleSwitch(ActivePrinterProfile.Instance.DoPrintLeveling); + CheckBox printLevelingSwitch = ImageButtonFactory.CreateToggleSwitch(ActiveSliceSettings.Instance.DoPrintLeveling); printLevelingSwitch.VAnchor = VAnchor.ParentCenter; printLevelingSwitch.Margin = new BorderDouble(left: 16); printLevelingSwitch.CheckedStateChanged += (sender, e) => { - ActivePrinterProfile.Instance.DoPrintLeveling = printLevelingSwitch.Checked; + ActiveSliceSettings.Instance.DoPrintLeveling = printLevelingSwitch.Checked; }; printLevelingStatusLabel = new TextWidget(""); @@ -105,10 +105,10 @@ namespace MatterHackers.MatterControl.ConfigurationPage printLevelingStatusLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor; printLevelingStatusLabel.VAnchor = VAnchor.ParentCenter; - ActivePrinterProfile.Instance.DoPrintLevelingChanged.RegisterEvent((sender, e) => + ActiveSliceSettings.Instance.DoPrintLevelingChanged.RegisterEvent((sender, e) => { SetPrintLevelButtonVisiblity(); - printLevelingSwitch.Checked = ActivePrinterProfile.Instance.DoPrintLeveling; + printLevelingSwitch.Checked = ActiveSliceSettings.Instance.DoPrintLeveling; }, ref unregisterEvents); buttonRow.AddChild(levelingIcon); @@ -284,7 +284,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage private void SetPrintLevelButtonVisiblity() { - if (ActivePrinterProfile.Instance.DoPrintLeveling) + if (ActiveSliceSettings.Instance.DoPrintLeveling) { printLevelingStatusLabel.Text = "Software Print Leveling (enabled)".Localize(); } @@ -302,7 +302,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage currentStatus == PrinterConnectionAndCommunication.CommunicationStates.Connected || currentStatus == PrinterConnectionAndCommunication.CommunicationStates.FinishedPrint; - if (ActivePrinterProfile.Instance.ActivePrinter == null || !connected) + if (ActiveSliceSettings.Instance == null || !connected) { printLevelingContainer.SetEnableLevel(DisableableWidget.EnableLevel.Disabled); } diff --git a/ConfigurationPage/PrintLeveling/InstructionsPage.cs b/ConfigurationPage/PrintLeveling/InstructionsPage.cs index 8fba44aea..b7bd0f261 100644 --- a/ConfigurationPage/PrintLeveling/InstructionsPage.cs +++ b/ConfigurationPage/PrintLeveling/InstructionsPage.cs @@ -30,6 +30,7 @@ either expressed or implied, of the FreeBSD Project. using MatterHackers.Agg; using MatterHackers.Agg.Font; using MatterHackers.Agg.UI; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl @@ -62,7 +63,8 @@ namespace MatterHackers.MatterControl public static Vector3 ManualControlsFeedRate() { Vector3 feedRate = new Vector3(3000, 3000, 315); - string savedSettings = ActivePrinterProfile.Instance.ActivePrinter.ManualMovementSpeeds; + + string savedSettings = ActiveSliceSettings.Instance.ManualMovementSpeeds; if (savedSettings != null && savedSettings != "") { feedRate.x = double.Parse(savedSettings.Split(',')[1]); diff --git a/ConfigurationPage/PrintLeveling/LevelWizard13PointRadial.cs b/ConfigurationPage/PrintLeveling/LevelWizard13PointRadial.cs index a87c72952..d1b3a7a1a 100644 --- a/ConfigurationPage/PrintLeveling/LevelWizard13PointRadial.cs +++ b/ConfigurationPage/PrintLeveling/LevelWizard13PointRadial.cs @@ -51,15 +51,14 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { - Printer activePrinter = PrinterConnectionAndCommunication.Instance.ActivePrinter; - if (activePrinter != null - && activePrinter.DoPrintLeveling + + var settings = ActiveSliceSettings.Instance; + if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(activePrinter); - return GetLevelingFunctions(numberOfRadialSamples, levelingData, ActiveSliceSettings.Instance.BedCenter) + return GetLevelingFunctions(numberOfRadialSamples, settings.PrintLevelingData, ActiveSliceSettings.Instance.BedCenter) .DoApplyLeveling(lineBeingSent, currentDestination, movementMode); } @@ -68,8 +67,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override Vector2 GetPrintLevelPositionToSample(int index, double radius) { - Printer activePrinter = PrinterConnectionAndCommunication.Instance.ActivePrinter; - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(activePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; return GetLevelingFunctions(numberOfRadialSamples, levelingData, ActiveSliceSettings.Instance.BedCenter) .GetPrintLevelPositionToSample(index, radius); } diff --git a/ConfigurationPage/PrintLeveling/LevelWizard2Point.cs b/ConfigurationPage/PrintLeveling/LevelWizard2Point.cs index 910a3c833..9c94bfed1 100644 --- a/ConfigurationPage/PrintLeveling/LevelWizard2Point.cs +++ b/ConfigurationPage/PrintLeveling/LevelWizard2Point.cs @@ -32,6 +32,7 @@ using MatterHackers.Agg.UI; using MatterHackers.GCodeVisualizer; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.VectorMath; using System; using System.Collections.Generic; @@ -115,8 +116,8 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { - if (PrinterConnectionAndCommunication.Instance.ActivePrinter != null - && PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling + var settings = ActiveSliceSettings.Instance; + if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 "))) { lineBeingSent = PrintLevelingPlane.Instance.ApplyLeveling(currentDestination, movementMode, lineBeingSent); @@ -153,7 +154,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling } if (PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Printing) { - ActivePrinterProfile.Instance.DoPrintLeveling = false; + ActiveSliceSettings.Instance.DoPrintLeveling = false; } probeIndex = 0; @@ -248,14 +249,15 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling private static void SetEquations() { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; // position 0 does not change as it is the distance from the switch trigger to the extruder tip. //levelingData.sampledPosition0 = levelingData.sampledPosition0; levelingData.SampledPosition1 = levelingData.SampledPosition0 + probeRead1; levelingData.SampledPosition2 = levelingData.SampledPosition0 + probeRead2; - ActivePrinterProfile.Instance.DoPrintLeveling = true; + ActiveSliceSettings.Instance.PrintLevelingData = levelingData; + ActiveSliceSettings.Instance.DoPrintLeveling = true; } } } \ No newline at end of file diff --git a/ConfigurationPage/PrintLeveling/LevelWizard3Point.cs b/ConfigurationPage/PrintLeveling/LevelWizard3Point.cs index 47ab8b18c..494f3e0de 100644 --- a/ConfigurationPage/PrintLeveling/LevelWizard3Point.cs +++ b/ConfigurationPage/PrintLeveling/LevelWizard3Point.cs @@ -101,8 +101,8 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { - if (PrinterConnectionAndCommunication.Instance.ActivePrinter != null - && PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling + var settings = ActiveSliceSettings.Instance; + if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 "))) { lineBeingSent = PrintLevelingPlane.Instance.ApplyLeveling(currentDestination, movementMode, lineBeingSent); diff --git a/ConfigurationPage/PrintLeveling/LevelWizard7PointRadial.cs b/ConfigurationPage/PrintLeveling/LevelWizard7PointRadial.cs index 768ef8fad..a87051bf7 100644 --- a/ConfigurationPage/PrintLeveling/LevelWizard7PointRadial.cs +++ b/ConfigurationPage/PrintLeveling/LevelWizard7PointRadial.cs @@ -260,14 +260,13 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { - Printer activePrinter = PrinterConnectionAndCommunication.Instance.ActivePrinter; - if (activePrinter != null - && activePrinter.DoPrintLeveling + var settings = ActiveSliceSettings.Instance; + if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(activePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; return GetLevelingFunctions(numberOfRadialSamples, levelingData, ActiveSliceSettings.Instance.BedCenter) .DoApplyLeveling(lineBeingSent, currentDestination, movementMode); } @@ -277,8 +276,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override Vector2 GetPrintLevelPositionToSample(int index, double radius) { - Printer activePrinter = PrinterConnectionAndCommunication.Instance.ActivePrinter; - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(activePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; return GetLevelingFunctions(numberOfRadialSamples, levelingData, ActiveSliceSettings.Instance.BedCenter) .GetPrintLevelPositionToSample(index, radius); } diff --git a/ConfigurationPage/PrintLeveling/LevelWizardBase.cs b/ConfigurationPage/PrintLeveling/LevelWizardBase.cs index c13a80902..b19e18313 100644 --- a/ConfigurationPage/PrintLeveling/LevelWizardBase.cs +++ b/ConfigurationPage/PrintLeveling/LevelWizardBase.cs @@ -122,6 +122,19 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling private static SystemWindow printLevelWizardWindow; + public static void ShowPrintLevelWizard() + { + LevelWizardBase.RuningState runningState = LevelWizardBase.RuningState.UserRequestedCalibration; + + if (ActiveSliceSettings.Instance.LevelingRequiredToPrint) + { + // run in the first run state + runningState = LevelWizardBase.RuningState.InitialStartupCalibration; + } + + ShowPrintLevelWizard(runningState); + } + public static void ShowPrintLevelWizard(LevelWizardBase.RuningState runningState) { if (printLevelWizardWindow == null) @@ -140,7 +153,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling private static LevelWizardBase CreateAndShowWizard(LevelWizardBase.RuningState runningState) { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; LevelWizardBase printLevelWizardWindow; switch (levelingData.CurrentPrinterLevelingSystem) diff --git a/ConfigurationPage/PrintLeveling/PrintLevelPages.cs b/ConfigurationPage/PrintLeveling/PrintLevelPages.cs index e1bb812b8..dbd24d314 100644 --- a/ConfigurationPage/PrintLeveling/PrintLevelPages.cs +++ b/ConfigurationPage/PrintLeveling/PrintLevelPages.cs @@ -46,7 +46,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void PageIsBecomingActive() { - ActivePrinterProfile.Instance.DoPrintLeveling = false; + ActiveSliceSettings.Instance.DoPrintLeveling = false; base.PageIsBecomingActive(); } } @@ -63,13 +63,18 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void PageIsBecomingActive() { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); Vector3 paperWidth = new Vector3(0, 0, ActiveSliceSettings.Instance.ProbePaperWidth); + + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; levelingData.SampledPosition0 = probePositions[0].position - paperWidth; levelingData.SampledPosition1 = probePositions[1].position - paperWidth; levelingData.SampledPosition2 = probePositions[2].position - paperWidth; - ActivePrinterProfile.Instance.DoPrintLeveling = true; + // Invoke setter forcing persistence of leveling data + ActiveSliceSettings.Instance.PrintLevelingData = levelingData; + + ActiveSliceSettings.Instance.DoPrintLeveling = true; + base.PageIsBecomingActive(); } } @@ -86,7 +91,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void PageIsBecomingActive() { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; levelingData.SampledPositions.Clear(); Vector3 paperWidth = new Vector3(0, 0, ActiveSliceSettings.Instance.ProbePaperWidth); for (int i = 0; i < probePositions.Length; i++) @@ -94,10 +99,10 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling levelingData.SampledPositions.Add(probePositions[i].position - paperWidth); } - levelingData.Commit(); + // Invoke setter forcing persistence of leveling data + ActiveSliceSettings.Instance.PrintLevelingData = levelingData; - - ActivePrinterProfile.Instance.DoPrintLeveling = true; + ActiveSliceSettings.Instance.DoPrintLeveling = true; base.PageIsBecomingActive(); } } @@ -120,10 +125,8 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); + base.OnClosed(e); } @@ -178,7 +181,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling // This data is currently the offset from the probe to the extruder tip. We need to translate them // into bed offsets and store them. - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); // The first point is the user assisted offset to the bed Vector3 userBedSample0 = probePositions[0].position; // The first point sample offset at the limit switch @@ -193,6 +195,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling Vector3 paperWidth = new Vector3(0, 0, ActiveSliceSettings.Instance.ProbePaperWidth); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; levelingData.SampledPosition0 = userBedSample0 - paperWidth; levelingData.SampledPosition1 = userBedSample1 - paperWidth; levelingData.SampledPosition2 = probeOffset2 - probeOffset0 + userBedSample0 - paperWidth; @@ -200,7 +203,10 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling levelingData.ProbeOffset0 = probeOffset0 - paperWidth; levelingData.ProbeOffset1 = probeOffset1 - paperWidth; - ActivePrinterProfile.Instance.DoPrintLeveling = true; + // Invoke setter forcing persistence of leveling data + ActiveSliceSettings.Instance.PrintLevelingData = levelingData; + + ActiveSliceSettings.Instance.DoPrintLeveling = true; base.PageIsBecomingActive(); } } @@ -270,7 +276,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void PageIsBecomingActive() { // always make sure we don't have print leveling turned on - ActivePrinterProfile.Instance.DoPrintLeveling = false; + ActiveSliceSettings.Instance.DoPrintLeveling = false; base.PageIsBecomingActive(); } diff --git a/ConfigurationPage/PrintLeveling/PrintLevelingData.cs b/ConfigurationPage/PrintLeveling/PrintLevelingData.cs index f00971fce..1af915a4f 100644 --- a/ConfigurationPage/PrintLeveling/PrintLevelingData.cs +++ b/ConfigurationPage/PrintLeveling/PrintLevelingData.cs @@ -11,11 +11,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public class PrintLevelingData { public List SampledPositions = new List(); - private static bool activelyLoading = false; - - private static Printer activePrinter = null; - - private static PrintLevelingData instance = null; private Vector3 probeOffset0Private; @@ -60,7 +55,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling if (probeOffset0Private != value) { probeOffset0Private = value; - Commit(); } } } @@ -73,7 +67,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling if (probeOffset1Private != value) { probeOffset1Private = value; - Commit(); } } } @@ -86,9 +79,8 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling if (sampledPosition0Private != value) { sampledPosition0Private = value; - Commit(); } - } + } } public Vector3 SampledPosition1 @@ -99,7 +91,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling if (sampledPosition1Private != value) { sampledPosition1Private = value; - Commit(); } } } @@ -112,54 +103,25 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling if (sampledPosition2Private != value) { sampledPosition2Private = value; - Commit(); } } } - public static PrintLevelingData GetForPrinter(Printer printer) + internal static PrintLevelingData Create(string jsonData, string depricatedPositionsCsv3ByXYZ) { - if (printer != null) + if (!string.IsNullOrEmpty(jsonData)) { - if (activePrinter != printer) - { - CreateFromJsonOrLegacy(printer.PrintLevelingJsonData, printer.PrintLevelingProbePositions); - activePrinter = printer; - } + return JsonConvert.DeserializeObject(jsonData); } - return instance; - } - - public void Commit() - { - if (!activelyLoading) + else if (!string.IsNullOrEmpty(depricatedPositionsCsv3ByXYZ)) { - string newLevelingInfo = Newtonsoft.Json.JsonConvert.SerializeObject(this); - - // clear the legacy value - activePrinter.PrintLevelingProbePositions = ""; - // set the new value - activePrinter.PrintLevelingJsonData = newLevelingInfo; - activePrinter.Commit(); - } - } - - private static void CreateFromJsonOrLegacy(string jsonData, string depricatedPositionsCsv3ByXYZ) - { - if (jsonData != null) - { - activelyLoading = true; - instance = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonData); - activelyLoading = false; - } - else if (depricatedPositionsCsv3ByXYZ != null) - { - instance = new PrintLevelingData(); - instance.ParseDepricatedPrintLevelingMeasuredPositions(depricatedPositionsCsv3ByXYZ); + var item = new PrintLevelingData(); + item.ParseDepricatedPrintLevelingMeasuredPositions(depricatedPositionsCsv3ByXYZ); + return item; } else { - instance = new PrintLevelingData(); + return new PrintLevelingData(); } } @@ -176,9 +138,9 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { for (int i = 0; i < 3; i++) { - sampledPosition0Private[i % 3] = double.Parse(lines[0 * 3 + i]); - sampledPosition1Private[i % 3] = double.Parse(lines[1 * 3 + i]); - sampledPosition2Private[i % 3] = double.Parse(lines[2 * 3 + i]); + sampledPosition0Private[i] = double.Parse(lines[0 * 3 + i]); + sampledPosition1Private[i] = double.Parse(lines[1 * 3 + i]); + sampledPosition2Private[i] = double.Parse(lines[2 * 3 + i]); } } } @@ -218,17 +180,5 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling return true; } - - public void RunLevelingWizard() - { - LevelWizardBase.RuningState runningState = LevelWizardBase.RuningState.UserRequestedCalibration; - if (ActiveSliceSettings.Instance.LevelingRequiredToPrint) - { - // run in the first run state - runningState = LevelWizardBase.RuningState.InitialStartupCalibration; - } - - LevelWizardBase.ShowPrintLevelWizard(runningState); - } } } \ No newline at end of file diff --git a/ConfigurationPage/PrinterConfigurationPage.cs b/ConfigurationPage/PrinterConfigurationPage.cs index b4e22f955..35735c6ae 100644 --- a/ConfigurationPage/PrinterConfigurationPage.cs +++ b/ConfigurationPage/PrinterConfigurationPage.cs @@ -70,7 +70,7 @@ namespace MatterHackers.MatterControl mainLayoutContainer.VAnchor = Agg.UI.VAnchor.FitToChildren; mainLayoutContainer.Padding = new BorderDouble(top: 10); - if (!ActiveSliceSettings.Instance.HasHardwareLeveling()) + if (!ActiveSliceSettings.Instance.HasHardwareLeveling() == true) { mainLayoutContainer.AddChild(new CalibrationSettingsWidget()); } diff --git a/ConfigurationPage/PrinterSettings/PrinterSettingsView.cs b/ConfigurationPage/PrinterSettings/PrinterSettingsView.cs index c7ce430fa..4ee93bac8 100644 --- a/ConfigurationPage/PrinterSettings/PrinterSettingsView.cs +++ b/ConfigurationPage/PrinterSettings/PrinterSettingsView.cs @@ -251,7 +251,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage private void SetPrintLevelButtonVisiblity() { - if (ActivePrinterProfile.Instance.DoPrintLeveling) + if (ActiveSliceSettings.Instance.DoPrintLeveling) { printLevelingStatusLabel.Text = "Software Print Leveling (enabled)".Localize(); } @@ -263,7 +263,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage private void SetVisibleControls() { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { // no printer selected eePromControlsContainer.SetEnableLevel(DisableableWidget.EnableLevel.Disabled); diff --git a/CustomWidgets/DropDownMenuWidget.cs b/CustomWidgets/DropDownMenuWidget.cs index aab1c8c63..fe7d7c292 100644 --- a/CustomWidgets/DropDownMenuWidget.cs +++ b/CustomWidgets/DropDownMenuWidget.cs @@ -12,11 +12,6 @@ namespace MatterHackers.Agg.UI private TextWidget mainControlText; - public DropDownMenu(GuiWidget topMenuWidget, Direction direction = Direction.Down) - : base(direction) - { - } - public DropDownMenu(string topMenuText, Direction direction = Direction.Down, double pointSize = 12) : base(direction) { @@ -29,41 +24,11 @@ namespace MatterHackers.Agg.UI SetStates(topMenuText, pointSize); } - bool menuAsWideAsItems = true; - public bool MenuAsWideAsItems - { - get - { - return menuAsWideAsItems; - } + public bool MenuAsWideAsItems { get; set; } = true; - set - { - menuAsWideAsItems = value; - } - } + public bool DrawDirectionalArrow { get; set; } = true; - private int borderWidth = 1; - - bool drawDirectionalArrow = true; - public bool DrawDirectionalArrow - { - get - { - return drawDirectionalArrow; - } - - set - { - drawDirectionalArrow = value; - } - } - - public int BorderWidth - { - get { return borderWidth; } - set { borderWidth = value; } - } + public int BorderWidth { get; set; } = 1; public RGBA_Bytes BorderColor { get; set; } @@ -75,17 +40,7 @@ namespace MatterHackers.Agg.UI public RGBA_Bytes HoverColor { get; set; } - private RGBA_Bytes textColor = RGBA_Bytes.Black; - - public RGBA_Bytes TextColor - { - get { return textColor; } - set - { - textColor = value; - //mainControlText.TextColor = TextColor; - } - } + public RGBA_Bytes TextColor { get; set; } = RGBA_Bytes.Black; private int selectedIndex = -1; @@ -261,16 +216,16 @@ namespace MatterHackers.Agg.UI private void DrawBorder(Graphics2D graphics2D) { RectangleDouble Bounds = LocalBounds; - if (borderWidth > 0) + if (BorderWidth > 0) { - if (borderWidth == 1) + if (BorderWidth == 1) { graphics2D.Rectangle(Bounds, BorderColor); } else { RoundedRect borderRect = new RoundedRect(this.LocalBounds, 0); - Stroke strokeRect = new Stroke(borderRect, borderWidth); + Stroke strokeRect = new Stroke(borderRect, BorderWidth); graphics2D.Render(strokeRect, BorderColor); } } diff --git a/CustomWidgets/ExportPrintItemWindow.cs b/CustomWidgets/ExportPrintItemWindow.cs index a07887696..c78d5b17e 100644 --- a/CustomWidgets/ExportPrintItemWindow.cs +++ b/CustomWidgets/ExportPrintItemWindow.cs @@ -49,8 +49,8 @@ namespace MatterHackers.MatterControl this.Name = "Export Item Window"; CreateWindowContent(); - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(ReloadAfterPrinterProfileChanged, ref unregisterEvents); - ActivePrinterProfile.Instance.DoPrintLevelingChanged.RegisterEvent(ReloadAfterPrinterProfileChanged, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent(ReloadAfterPrinterProfileChanged, ref unregisterEvents); + ActiveSliceSettings.Instance.DoPrintLevelingChanged.RegisterEvent(ReloadAfterPrinterProfileChanged, ref unregisterEvents); } private string applyLevelingDuringExportString = "Apply leveling to G-Code during export".Localize(); @@ -114,7 +114,7 @@ namespace MatterHackers.MatterControl middleRowContainer.AddChild(exportAsAmfButton); } - bool showExportGCodeButton = ActivePrinterProfile.Instance.ActivePrinter != null || partIsGCode; + bool showExportGCodeButton = ActiveSliceSettings.Instance != null || partIsGCode; if (showExportGCodeButton) { string exportGCodeTextFull = string.Format("{0} G-Code", "Export as".Localize()); @@ -191,7 +191,7 @@ namespace MatterHackers.MatterControl middleRowContainer.AddChild(new VerticalSpacer()); // If print leveling is enabled then add in a check box 'Apply Leveling During Export' and default checked. - if (showExportGCodeButton && ActivePrinterProfile.Instance.DoPrintLeveling) + if (showExportGCodeButton && ActiveSliceSettings.Instance.DoPrintLeveling) { applyLeveling = new CheckBox(LocalizedString.Get(applyLevelingDuringExportString), ActiveTheme.Instance.PrimaryTextColor, 10); applyLeveling.Checked = true; @@ -308,12 +308,12 @@ namespace MatterHackers.MatterControl { try { - if (ActivePrinterProfile.Instance.DoPrintLeveling) + if (ActiveSliceSettings.Instance.DoPrintLeveling) { GCodeFileLoaded unleveledGCode = new GCodeFileLoaded(source); if (applyLeveling.Checked) { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (levelingData != null) { for (int lineIndex = 0; lineIndex < unleveledGCode.LineCount; lineIndex++) diff --git a/CustomWidgets/SlidePanelWidget.cs b/CustomWidgets/SlidePanelWidget.cs index e98759c59..b06c05858 100644 --- a/CustomWidgets/SlidePanelWidget.cs +++ b/CustomWidgets/SlidePanelWidget.cs @@ -45,7 +45,7 @@ namespace MatterHackers.MatterControl } } - public void SetPanelIndexImediate(int index) + public void SetPanelIndexImmediate(int index) { desiredPanelIndex = index; SetSlidePosition(); diff --git a/DataStorage/Classic/ClassicSqlitePrinterProfiles.cs b/DataStorage/Classic/ClassicSqlitePrinterProfiles.cs new file mode 100644 index 000000000..59e3c4e3f --- /dev/null +++ b/DataStorage/Classic/ClassicSqlitePrinterProfiles.cs @@ -0,0 +1,218 @@ +/* +Copyright (c) 2016, Lars Brubaker, John Lewin +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 MatterHackers.Agg; +using MatterHackers.Agg.PlatformAbstract; +using MatterHackers.Agg.UI; +using MatterHackers.Localizations; +using MatterHackers.MatterControl.ConfigurationPage.PrintLeveling; +using MatterHackers.MatterControl.ContactForm; +using MatterHackers.MatterControl.DataStorage; +using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; +using MatterHackers.VectorMath; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; + +namespace MatterHackers.MatterControl.DataStorage.ClassicDB +{ + public class ClassicSqlitePrinterProfiles + { + + public class ClassicSettingsLayer + { + //Container class representing a collection of setting along with the meta info for that collection + public Dictionary settingsDictionary; + + public SliceSettingsCollection settingsCollectionData; + + public ClassicSettingsLayer(SliceSettingsCollection settingsCollection, Dictionary settingsDictionary) + { + this.settingsCollectionData = settingsCollection; + this.settingsDictionary = settingsDictionary; + } + } + + public static void ImportPrinters(ProfileData profileData, string profilePath) + { + foreach (Printer printer in Datastore.Instance.dbSQLite.Query("SELECT * FROM Printer;")) + { + ImportPrinter(printer, profileData, profilePath); + } + } + + public static void ImportPrinter(Printer printer, ProfileData profileData, string profilePath) + { + var printerInfo = new PrinterInfo() + { + Name = printer.Name, + Id = printer.Id.ToString() + }; + profileData.Profiles.Add(printerInfo); + + var layeredProfile = ActiveSliceSettings.LoadEmptyProfile(); + + //Load printer settings from database as second layer + + layeredProfile.OemProfile = new OemProfile(LoadOemLayer(printer)); + + //Ordering matters - Material presets trump Quality + LoadQualitySettings(layeredProfile, printer); + LoadMaterialSettings(layeredProfile, printer); + + string fullProfilePath = Path.Combine(profilePath, printer.Id + ".json"); + + File.WriteAllText(fullProfilePath, JsonConvert.SerializeObject(layeredProfile, Formatting.Indented)); + + //GET LEVELING DATA from DB + + //PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(printer); + + /* + PrintLevelingPlane.Instance.SetPrintLevelingEquation( + levelingData.SampledPosition0, + levelingData.SampledPosition1, + levelingData.SampledPosition2, + ActiveSliceSettings.Instance.PrintCenter); */ + + } + + private static void LoadMaterialSettings(LayeredProfile layeredProfile, Printer printer) + { + var materialAssignments = printer.MaterialCollectionIds.Split(','); + + var collections = Datastore.Instance.dbSQLite.Table().Where(v => v.PrinterId == printer.Id && v.Tag == "material"); + foreach (var collection in collections) + { + var settingsDictionary = LoadSettings(collection); + layeredProfile.MaterialLayers[collection.Name] = new SettingsLayer(settingsDictionary); + } + } + + public static void LoadQualitySettings(LayeredProfile layeredProfile, Printer printer) + { + var collections = Datastore.Instance.dbSQLite.Table().Where(v => v.PrinterId == printer.Id && v.Tag == "quality"); + foreach (var collection in collections) + { + var settingsDictionary = LoadSettings(collection); + layeredProfile.QualityLayers[collection.Name] = new SettingsLayer(settingsDictionary); + } + } + + public static Dictionary LoadOemLayer(Printer printer) + { + SliceSettingsCollection collection; + if (printer.DefaultSettingsCollectionId != 0) + { + int activePrinterSettingsID = printer.DefaultSettingsCollectionId; + collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == activePrinterSettingsID).Take(1).FirstOrDefault(); + } + else + { + collection = new SliceSettingsCollection(); + collection.Name = printer.Name; + collection.Commit(); + + printer.DefaultSettingsCollectionId = collection.Id; + } + + return LoadSettings(collection); + } + + private static Dictionary LoadSettings(SliceSettingsCollection collection) + { + var settings = Datastore.Instance.dbSQLite.Query( + string.Format("SELECT * FROM SliceSetting WHERE SettingsCollectionID = " + collection.Id)); + + //return settings.ToDictionary(s => s.Name, s => s.Value); + + var dictionary = new Dictionary(); + foreach(var setting in settings) + { + // Not distinct on .Name; last value wins + dictionary[setting.Name] = setting.Value; + } + + return dictionary; + } + + private static void LoadDefaultConfigrationSettings(List settings) + { + SliceSettingsCollection defaultCollection = new SliceSettingsCollection(); + defaultCollection.Name = "__default__"; + ClassicSettingsLayer defaultSettingsLayer = LoadConfigurationSettingsFromFile(Path.Combine("PrinterSettings", "config.ini"), defaultCollection); + + settings.Add(defaultSettingsLayer); + } + + + private static ClassicSettingsLayer LoadConfigurationSettingsFromFile(string pathAndFileName, SliceSettingsCollection collection) + { + Dictionary settingsDictionary = new Dictionary(); + ClassicSettingsLayer activeCollection; + try + { + if (StaticData.Instance.FileExists(pathAndFileName)) + { + foreach (string line in StaticData.Instance.ReadAllLines(pathAndFileName)) + { + //Ignore commented lines + if (!line.StartsWith("#")) + { + string[] settingLine = line.Split('='); + string keyName = settingLine[0].Trim(); + string settingDefaultValue = settingLine[1].Trim(); + + SliceSetting sliceSetting = new SliceSetting(); + sliceSetting.Name = keyName; + sliceSetting.Value = settingDefaultValue; + + settingsDictionary.Add(keyName, sliceSetting); + } + } + activeCollection = new ClassicSettingsLayer(collection, settingsDictionary); + return activeCollection; + } + return null; + } + catch (Exception e) + { + Debug.Print(e.Message); + GuiWidget.BreakInDebugger(); + Debug.WriteLine(string.Format("Error loading configuration: {0}", e)); + return null; + } + } + } +} \ No newline at end of file diff --git a/DataStorage/Datastore.cs b/DataStorage/Datastore.cs index 382b7b421..a70067f45 100644 --- a/DataStorage/Datastore.cs +++ b/DataStorage/Datastore.cs @@ -328,7 +328,7 @@ namespace MatterHackers.MatterControl.DataStorage if (TEST_FLAG) { ValidateSchema(); - GenerateSampleData sampleData = new GenerateSampleData(); + GenerateSampleData(); } else { @@ -352,6 +352,18 @@ namespace MatterHackers.MatterControl.DataStorage dbSQLite.Insert(activeSession); } + private void GenerateSampleData() + { + for (int index = 1; index <= 5; index++) + { + Printer printer = new Printer(); + printer.ComPort = string.Format("COM{0}", index); + printer.BaudRate = "250000"; + printer.Name = string.Format("Printer {0}", index); + Datastore.Instance.dbSQLite.Insert(printer); + } + } + // Checks if the datastore contains the appropriate tables - adds them if necessary private void ValidateSchema() { diff --git a/DataStorage/GenerateSampleData.cs b/DataStorage/GenerateSampleData.cs deleted file mode 100644 index 3b68d6c8c..000000000 --- a/DataStorage/GenerateSampleData.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace MatterHackers.MatterControl.DataStorage -{ - internal class GenerateSampleData - { - public GenerateSampleData() - { - AddPrinters(); - } - - private void AddPrinters() - { - for (int index = 1; index <= 5; index++) - { - Printer printer = new Printer(); - printer.ComPort = string.Format("COM{0}", index); - printer.BaudRate = "250000"; - printer.Name = string.Format("Printer {0}", index); - Datastore.Instance.dbSQLite.Insert(printer); - } - } - } -} \ No newline at end of file diff --git a/MatterControl.csproj b/MatterControl.csproj index 9dc70d419..41990672f 100644 --- a/MatterControl.csproj +++ b/MatterControl.csproj @@ -127,8 +127,9 @@ - + + @@ -142,7 +143,7 @@ - + @@ -163,7 +164,6 @@ - @@ -202,7 +202,6 @@ - @@ -246,6 +245,10 @@ + + + + @@ -303,7 +306,6 @@ - @@ -322,7 +324,6 @@ - @@ -332,10 +333,8 @@ - - @@ -355,7 +354,6 @@ - @@ -444,6 +442,7 @@ + diff --git a/MatterControlApplication.cs b/MatterControlApplication.cs index ba717c45c..1cd727307 100644 --- a/MatterControlApplication.cs +++ b/MatterControlApplication.cs @@ -146,32 +146,32 @@ namespace MatterHackers.MatterControl DoCGCollectEveryDraw = true; break; - case "CREATE_AND_SELECT_PRINTER": - if (currentCommandIndex + 1 <= commandLineArgs.Length) - { - currentCommandIndex++; - string argument = commandLineArgs[currentCommandIndex]; - string[] printerData = argument.Split(','); - if (printerData.Length >= 2) - { - Printer ActivePrinter = new Printer(); + //case "CREATE_AND_SELECT_PRINTER": + // if (currentCommandIndex + 1 <= commandLineArgs.Length) + // { + // currentCommandIndex++; + // string argument = commandLineArgs[currentCommandIndex]; + // string[] printerData = argument.Split(','); + // if (printerData.Length >= 2) + // { + // Printer ActivePrinter = new Printer(); - ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); - ActivePrinter.Make = printerData[0]; - ActivePrinter.Model = printerData[1]; + // ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); + // ActivePrinter.Make = printerData[0]; + // ActivePrinter.Model = printerData[1]; - if (printerData.Length == 3) - { - ActivePrinter.ComPort = printerData[2]; - } + // if (printerData.Length == 3) + // { + // ActivePrinter.ComPort = printerData[2]; + // } - PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); - test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model); - ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter; - } - } + // PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); + // test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model); + // ActiveSliceSettings.Instance = ActivePrinter; + // } + // } - break; + // break; case "CONNECT_TO_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) @@ -484,11 +484,6 @@ namespace MatterHackers.MatterControl } } - public void DoAutoConnectIfRequired() - { - ActivePrinterProfile.CheckForAndDoAutoConnect(); - } - public void LaunchBrowser(string targetUri) { UiThread.RunOnIdle(() => @@ -590,7 +585,7 @@ namespace MatterHackers.MatterControl if (firstDraw) { - UiThread.RunOnIdle(DoAutoConnectIfRequired); + UiThread.RunOnIdle(ActiveSliceSettings.CheckForAndDoAutoConnect); firstDraw = false; foreach (string arg in commandLineArgs) diff --git a/PartPreviewWindow/BaseClasses/PartPreview3DWidget.cs b/PartPreviewWindow/BaseClasses/PartPreview3DWidget.cs index 915469439..148d0ab5d 100644 --- a/PartPreviewWindow/BaseClasses/PartPreview3DWidget.cs +++ b/PartPreviewWindow/BaseClasses/PartPreview3DWidget.cs @@ -69,7 +69,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow "extruder_offset", #endif - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent((s, e) => needToRecretaeBed = true, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((s, e) => needToRecretaeBed = true, ref unregisterEvents); } private void CheckSettingChanged(object sender, EventArgs e) diff --git a/PartPreviewWindow/PartPreviewContent.cs b/PartPreviewWindow/PartPreviewContent.cs index deec65f74..c168392a1 100644 --- a/PartPreviewWindow/PartPreviewContent.cs +++ b/PartPreviewWindow/PartPreviewContent.cs @@ -98,8 +98,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow double buildHeight = ActiveSliceSettings.Instance.BuildHeight; // put in the 3D view - string part3DViewLabelFull = string.Format("{0} {1} ", "3D", "View".Localize()).ToUpper(); - partPreviewView = new View3DWidget(printItem, new Vector3(ActiveSliceSettings.Instance.BedSize, buildHeight), ActiveSliceSettings.Instance.BedCenter, @@ -108,7 +106,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow autoRotate3DView, openMode); - TabPage partPreview3DView = new TabPage(partPreviewView, part3DViewLabelFull); + TabPage partPreview3DView = new TabPage(partPreviewView, string.Format("3D {0} ", "View".Localize()).ToUpper()); // put in the gcode view ViewGcodeBasic.WindowMode gcodeWindowMode = ViewGcodeBasic.WindowMode.Embeded; @@ -124,20 +122,14 @@ namespace MatterHackers.MatterControl.PartPreviewWindow if (windowMode == View3DWidget.WindowMode.StandAlone) { - partPreviewView.Closed += (sender, e) => - { - Close(); - }; - viewGcodeBasic.Closed += (sender, e) => - { - Close(); - }; + partPreviewView.Closed += (s, e) => Close(); + viewGcodeBasic.Closed += (s, e) => Close(); } layerView = new TabPage(viewGcodeBasic, LocalizedString.Get("Layer View").ToUpper()); int tabPointSize = 16; - // add the correct tabs based on wether we are stand alone or embeded + // add the correct tabs based on whether we are stand alone or embedded Tab threeDViewTab; Tab layerViewTab; if (windowMode == View3DWidget.WindowMode.StandAlone || OsInformation.OperatingSystem == OSType.Android) @@ -171,10 +163,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } } diff --git a/PartPreviewWindow/View3D/View3DWidget.cs b/PartPreviewWindow/View3D/View3DWidget.cs index 0c33325bb..e83918f8a 100644 --- a/PartPreviewWindow/View3D/View3DWidget.cs +++ b/PartPreviewWindow/View3D/View3DWidget.cs @@ -1065,7 +1065,8 @@ namespace MatterHackers.MatterControl.PartPreviewWindow colorSelectionContainer.HAnchor = HAnchor.ParentLeftRight; colorSelectionContainer.Padding = new BorderDouble(5); - string colorLabelText = "Material {0}".Localize().FormatWith(extruderIndex + 1); + string colorLabelText = string.Format("{0} {1}", "Material".Localize(), extruderIndex + 1); + RadioButton extruderSelection = new RadioButton(colorLabelText, textColor: ActiveTheme.Instance.PrimaryTextColor); extruderButtons.Add(extruderSelection); extruderSelection.SiblingRadioButtonList = extruderButtons; @@ -2101,8 +2102,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow private bool PartsAreInPrintVolume() { if (ActiveSliceSettings.Instance != null - && !ActiveSliceSettings.Instance.CenterOnBed() - && ActivePrinterProfile.Instance.ActivePrinter != null) + && !ActiveSliceSettings.Instance.CenterOnBed()) { AxisAlignedBoundingBox allBounds = MeshViewerWidget.GetAxisAlignedBoundingBox(MeshGroups); bool onBed = allBounds.minXYZ.z > -.001 && allBounds.minXYZ.z < .001; // really close to the bed diff --git a/PartPreviewWindow/ViewGcodeBasic.cs b/PartPreviewWindow/ViewGcodeBasic.cs index 3154cb5c4..2eb0cff87 100644 --- a/PartPreviewWindow/ViewGcodeBasic.cs +++ b/PartPreviewWindow/ViewGcodeBasic.cs @@ -110,7 +110,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow SliceSettingsWidget.SettingChanged.RegisterEvent(CheckSettingChanged, ref unregisterEvents); ApplicationController.Instance.ReloadAdvancedControlsPanelTrigger.RegisterEvent((s, e) => ClearGCode(), ref unregisterEvents); - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(CheckSettingChanged, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent(CheckSettingChanged, ref unregisterEvents); } private void CheckSettingChanged(object sender, EventArgs e) diff --git a/PrinterCommunication/ActivePrinterProfile.cs b/PrinterCommunication/ActivePrinterProfile.cs deleted file mode 100644 index 4a624e810..000000000 --- a/PrinterCommunication/ActivePrinterProfile.cs +++ /dev/null @@ -1,341 +0,0 @@ -/* -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 MatterHackers.Agg; -using MatterHackers.MatterControl.ConfigurationPage.PrintLeveling; -using MatterHackers.MatterControl.DataStorage; -using MatterHackers.MatterControl.PrinterCommunication; -using MatterHackers.MatterControl.SettingsManagement; -using MatterHackers.MatterControl.SlicerConfiguration; -using MatterHackers.SerialPortCommunication.FrostedSerial; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace MatterHackers.MatterControl -{ - public class ActivePrinterProfile - { - public enum SlicingEngineTypes { Slic3r, CuraEngine, MatterSlice }; - - private static readonly SlicingEngineTypes defaultEngineType = SlicingEngineTypes.MatterSlice; - private static ActivePrinterProfile globalInstance = null; - - public RootedObjectEventHandler ActivePrinterChanged = new RootedObjectEventHandler(); - public RootedObjectEventHandler DoPrintLevelingChanged = new RootedObjectEventHandler(); - - // private so that it can only be gotten through the Instance - private ActivePrinterProfile() - { - } - - private Printer activePrinter = null; - - public Printer ActivePrinter - { - get { return activePrinter; } - set - { - if (activePrinter != value) - { - // If we have an active printer, run Disable otherwise skip to prevent empty ActiveSliceSettings due to null ActivePrinter - if (activePrinter != null) - { - PrinterConnectionAndCommunication.Instance.Disable(); - } - - activePrinter = value; - ValidateMaterialSettings(); - ValidateQualitySettings(); - - if (activePrinter != null) - { - BedSettings.SetMakeAndModel(activePrinter.Make, activePrinter.Model); - } - - globalInstance.OnActivePrinterChanged(null); - } - } - } - - public static ActivePrinterProfile Instance - { - get - { - if (globalInstance == null) - { - globalInstance = new ActivePrinterProfile(); - } - - return globalInstance; - } - } - - private void ValidateQualitySettings() - { - if (activePrinter != null) - { - int index = activePrinter.QualityCollectionId; - SliceSettingsCollection collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == index).Take(1).FirstOrDefault(); - if (collection == null) - { - ActivePrinterProfile.Instance.ActiveQualitySettingsID = 0; - } - } - } - - private void ValidateMaterialSettings() - { - if (activePrinter != null && activePrinter.MaterialCollectionIds != null) - { - string[] activeMaterialPresets = activePrinter.MaterialCollectionIds.Split(','); - for (int i = 0; i < activeMaterialPresets.Count(); i++) - { - int index = 0; - Int32.TryParse(activeMaterialPresets[i], out index); - if (index != 0) - { - SliceSettingsCollection collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == index).Take(1).FirstOrDefault(); - if (collection == null) - { - ActivePrinterProfile.Instance.SetMaterialSetting(i + 1, 0); - } - } - } - } - } - - public int GetMaterialSetting(int extruderNumber1Based) - { - int i = 0; - if (extruderNumber1Based > 0 - && ActivePrinter != null) - { - string materialSettings = ActivePrinter.MaterialCollectionIds; - string[] materialSettingsList; - if (materialSettings != null) - { - materialSettingsList = materialSettings.Split(','); - if (materialSettingsList.Count() >= extruderNumber1Based) - { - Int32.TryParse(materialSettingsList[extruderNumber1Based - 1], out i); - } - } - } - return i; - } - - public void SetMaterialSetting(int extruderPosition, int settingId) - { - string[] newMaterialSettingsArray; - string[] currentMaterialSettingsArray; - - string materialSettings = ActivePrinter.MaterialCollectionIds; - - if (materialSettings != null) - { - currentMaterialSettingsArray = materialSettings.Split(','); - } - else - { - currentMaterialSettingsArray = new string[extruderPosition]; - } - - //Resize the array of material settings if necessary - if (currentMaterialSettingsArray.Count() < extruderPosition) - { - newMaterialSettingsArray = new string[extruderPosition]; - for (int i = 0; i < currentMaterialSettingsArray.Length; i++) - { - newMaterialSettingsArray[i] = currentMaterialSettingsArray[i]; - } - } - else - { - newMaterialSettingsArray = currentMaterialSettingsArray; - } - newMaterialSettingsArray[extruderPosition - 1] = settingId.ToString(); - - ActivePrinter.MaterialCollectionIds = String.Join(",", newMaterialSettingsArray); - ActivePrinter.Commit(); - } - - public int ActiveQualitySettingsID - { - get - { - if (ActivePrinter != null) - { - return ActivePrinter.QualityCollectionId; - } - return 0; - } - - set - { - if (ActiveQualitySettingsID != value) - { - ActivePrinter.QualityCollectionId = value; - ActivePrinter.Commit(); - } - } - } - - public SlicingEngineTypes ActiveSliceEngineType - { - get - { - if (ActivePrinter != null) - { - foreach (SlicingEngineTypes engine in SlicingEngineTypes.GetValues(typeof(SlicingEngineTypes))) - { - if (ActivePrinter.CurrentSlicingEngine == engine.ToString()) - { - return engine; - } - } - - // It is not set in the slice settings, so set it and save it. - ActivePrinter.CurrentSlicingEngine = defaultEngineType.ToString(); - ActivePrinter.Commit(); - } - return defaultEngineType; - } - - set - { - if (ActiveSliceEngineType != value) - { - ActivePrinter.CurrentSlicingEngine = value.ToString(); - ActivePrinter.Commit(); - } - } - } - - public SliceEngineMapping ActiveSliceEngine - { - get - { - switch (ActiveSliceEngineType) - { - case SlicingEngineTypes.CuraEngine: - return EngineMappingCura.Instance; - - case SlicingEngineTypes.MatterSlice: - return EngineMappingsMatterSlice.Instance; - - case SlicingEngineTypes.Slic3r: - return Slic3rEngineMappings.Instance; - - default: - return null; - } - } - } - - public void OnActivePrinterChanged(EventArgs e) - { - ActivePrinterChanged.CallEvents(this, e); - } - - public bool DoPrintLeveling - { - get - { - if (ActivePrinter != null) - { - return ActivePrinter.DoPrintLeveling; - } - return false; - } - - set - { - if (ActivePrinter != null && ActivePrinter.DoPrintLeveling != value) - { - ActivePrinter.DoPrintLeveling = value; - DoPrintLevelingChanged.CallEvents(this, null); - ActivePrinter.Commit(); - - if (DoPrintLeveling) - { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); - PrintLevelingPlane.Instance.SetPrintLevelingEquation( - levelingData.SampledPosition0, - levelingData.SampledPosition1, - levelingData.SampledPosition2, - ActiveSliceSettings.Instance.PrintCenter); - } - } - } - } - - public static void CheckForAndDoAutoConnect() - { - bool connectionAvailable; - Printer autoConnectProfile = ActivePrinterProfile.GetAutoConnectProfile(out connectionAvailable); - if (autoConnectProfile != null) - { - ActivePrinterProfile.Instance.ActivePrinter = autoConnectProfile; - if (connectionAvailable) - { - PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); - PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); - } - } - } - - public static Printer GetAutoConnectProfile(out bool connectionAvailable) - { - string[] comportNames = FrostedSerialPort.GetPortNames(); - - Printer printerToSelect = null; - connectionAvailable = false; - - foreach (Printer printer in Datastore.Instance.dbSQLite.Query("SELECT * FROM Printer;")) - { - if (printer.AutoConnectFlag) - { - printerToSelect = printer; - bool portIsAvailable = comportNames.Contains(printer.ComPort); - if (portIsAvailable) - { - // We found a printer that we can select and connect to. - connectionAvailable = true; - return printer; - } - } - } - - // return a printer we can connect to even though we can't connect - return printerToSelect; - } - } -} \ No newline at end of file diff --git a/PrinterCommunication/Io/PrintLevelingStream.cs b/PrinterCommunication/Io/PrintLevelingStream.cs index c4c331be6..2a17549d9 100644 --- a/PrinterCommunication/Io/PrintLevelingStream.cs +++ b/PrinterCommunication/Io/PrintLevelingStream.cs @@ -34,6 +34,7 @@ using MatterHackers.VectorMath; using System.Text; using System.Collections.Generic; using MatterHackers.MatterControl.ConfigurationPage.PrintLeveling; +using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.PrinterCommunication.Io { @@ -90,7 +91,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication.Io private string RunPrintLevelingTranslations(string lineBeingSent, PrinterMove currentDestination) { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (levelingData != null) { switch (levelingData.CurrentPrinterLevelingSystem) diff --git a/PrinterCommunication/Io/ResumePrintingStream.cs b/PrinterCommunication/Io/ResumePrintingStream.cs index 511b5825f..a403be201 100644 --- a/PrinterCommunication/Io/ResumePrintingStream.cs +++ b/PrinterCommunication/Io/ResumePrintingStream.cs @@ -83,7 +83,8 @@ namespace MatterHackers.MatterControl.PrinterCommunication.Io queuedCommands.Add("G90; use absolute coordinates"); queuedCommands.Add("G92 E0; reset the expected extruder position"); queuedCommands.Add("M82; use absolute distance for extrusion"); - queuedCommands.Add("M109 S{0}".FormatWith(ActiveSliceSettings.Instance.GetMaterialValue("temperature", 1))); + queuedCommands.Add("M109 S{0}".FormatWith(ActiveSliceSettings.Instance.GetExtruderTemperature(1))); + resumeState = ResumeState.Raising; return ""; @@ -194,7 +195,16 @@ namespace MatterHackers.MatterControl.PrinterCommunication.Io { PrinterMove currentMove = GetPosition(lineToSend, lastDestination); PrinterMove moveToSend = currentMove; - double feedRate = ActiveSliceSettings.Instance.GetActiveValueAsDouble("resume_first_layer_speed", 10) * 60; + + double feedRate; + + string firstLayerSpeed = ActiveSliceSettings.Instance.GetActiveValue("resume_first_layer_speed"); + if (!double.TryParse(firstLayerSpeed, out feedRate)) + { + feedRate = 10; + } + feedRate *= 60; + moveToSend.feedRate = feedRate; lineToSend = CreateMovementLine(moveToSend, lastDestination); diff --git a/PrinterCommunication/PrinterConnectionAndCommunication.cs b/PrinterCommunication/PrinterConnectionAndCommunication.cs index 90ee6cfc0..6bc3e6e8c 100644 --- a/PrinterCommunication/PrinterConnectionAndCommunication.cs +++ b/PrinterCommunication/PrinterConnectionAndCommunication.cs @@ -110,7 +110,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication private bool atxPowerIsOn = false; - private const int MAX_EXTRUDERS = 16; + internal const int MAX_EXTRUDERS = 16; private const int MAX_INVALID_CONNECTION_CHARS = 3; @@ -954,17 +954,8 @@ namespace MatterHackers.MatterControl.PrinterCommunication } } - public Printer ActivePrinter - { - get - { - return ActivePrinterProfile.Instance.ActivePrinter; - } - private set - { - ActivePrinterProfile.Instance.ActivePrinter = value; - } - } + // TODO: Consider having callers use the source rather than this proxy? Maybe better to change after arriving on a final type and location for printer settings + public SettingsProfile ActivePrinter => ActiveSliceSettings.Instance; private int NumberOfLinesInCurrentPrint { @@ -1056,7 +1047,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication return; } - ConnectToPrinter(PrinterConnectionAndCommunication.Instance.ActivePrinter); + ConnectToPrinter(); } } @@ -1173,14 +1164,13 @@ namespace MatterHackers.MatterControl.PrinterCommunication public double GetActualExtruderTemperature(int extruderIndex0Based) { extruderIndex0Based = Math.Min(extruderIndex0Based, MAX_EXTRUDERS - 1); - return actualExtruderTemperature[extruderIndex0Based]; } + public double GetTargetExtruderTemperature(int extruderIndex0Based) { extruderIndex0Based = Math.Min(extruderIndex0Based, MAX_EXTRUDERS - 1); - return targetExtruderTemperature[extruderIndex0Based]; } @@ -1332,23 +1322,22 @@ namespace MatterHackers.MatterControl.PrinterCommunication { PrintFinished.CallEvents(this, new PrintItemWrapperEventArgs(this.ActivePrintItem)); - bool resetValue = false; - foreach (KeyValuePair currentSetting in ActiveSliceSettings.Instance.DefaultSettings) + // TODO: Shouldn't this logic be in the UI layer where the controls are owned and hooked in via PrintFinished? + bool oneOrMoreValuesReset = false; + foreach (var kvp in ActiveSliceSettings.Instance.BaseLayer) { - string currentValue = ActiveSliceSettings.Instance.GetActiveValue(currentSetting.Key); + string currentValue = ActiveSliceSettings.Instance.GetActiveValue(kvp.Key); bool valueIsClear = currentValue == "0" | currentValue == ""; - OrganizerSettingsData data = SliceSettingsOrganizer.Instance.GetSettingsData(currentSetting.Key); - if (data != null - && data.ResetAtEndOfPrint - && !valueIsClear) + OrganizerSettingsData data = SliceSettingsOrganizer.Instance.GetSettingsData(kvp.Key); + if (data?.ResetAtEndOfPrint == true && !valueIsClear) { - resetValue = true; - ActiveSliceSettings.Instance.SaveValue(currentSetting.Key, "", RequestedSettingsLayer.User); + oneOrMoreValuesReset = true; + ActiveSliceSettings.Instance.ClearValue(kvp.Key); } } - if(resetValue) + if(oneOrMoreValuesReset) { ApplicationController.Instance.ReloadAdvancedControlsPanel(); } @@ -1360,12 +1349,12 @@ namespace MatterHackers.MatterControl.PrinterCommunication { // If leveling is required or is currently on if (ActiveSliceSettings.Instance.LevelingRequiredToPrint - || ActivePrinterProfile.Instance.DoPrintLeveling) + || ActiveSliceSettings.Instance.DoPrintLeveling) { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); - if(!levelingData.HasBeenRun()) + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; + if(levelingData?.HasBeenRun() != true) { - levelingData.RunLevelingWizard(); + LevelWizardBase.ShowPrintLevelWizard(); return; } } @@ -1548,7 +1537,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication // current approach results in unpredictable behavior if the caller fails to close the connection if (serialPort == null && this.ActivePrinter != null) { - IFrostedSerialPort resetSerialPort = FrostedSerialPortFactory.GetAppropriateFactory(ActivePrinterProfile.Instance.ActivePrinter.DriverType).Create(this.ActivePrinter.ComPort); + IFrostedSerialPort resetSerialPort = FrostedSerialPortFactory.GetAppropriateFactory(this.ActivePrinter.DriverType).Create(this.ActivePrinter.ComPort); resetSerialPort.Open(); Thread.Sleep(500); @@ -1658,12 +1647,12 @@ namespace MatterHackers.MatterControl.PrinterCommunication // run the print leveling wizard if we need to for this printer if (ActiveSliceSettings.Instance.LevelingRequiredToPrint - || ActivePrinterProfile.Instance.DoPrintLeveling) + || ActiveSliceSettings.Instance.DoPrintLeveling) { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); - if (!levelingData.HasBeenRun()) + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; + if (levelingData?.HasBeenRun() != true) { - UiThread.RunOnIdle(() => levelingData.RunLevelingWizard() ); + UiThread.RunOnIdle(LevelWizardBase.ShowPrintLevelWizard); } } } @@ -1840,7 +1829,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication { // We reset the board while attempting to connect, so now we don't have a serial port. // Create one and do the DTR to reset - var resetSerialPort = FrostedSerialPortFactory.GetAppropriateFactory(ActivePrinterProfile.Instance.ActivePrinter.DriverType).Create(this.ActivePrinter.ComPort); + var resetSerialPort = FrostedSerialPortFactory.GetAppropriateFactory(this.ActivePrinter.DriverType).Create(this.ActivePrinter.ComPort); resetSerialPort.Open(); Thread.Sleep(500); @@ -2202,7 +2191,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication } bool serialPortIsAvailable = SerialPortIsAvailable(serialPortName); - bool serialPortIsAlreadyOpen = FrostedSerialPortFactory.GetAppropriateFactory(ActivePrinterProfile.Instance.ActivePrinter.DriverType).SerialPortAlreadyOpen(serialPortName); + bool serialPortIsAlreadyOpen = FrostedSerialPortFactory.GetAppropriateFactory(this.ActivePrinter.DriverType).SerialPortAlreadyOpen(serialPortName); if (serialPortIsAvailable && !serialPortIsAlreadyOpen) { @@ -2210,7 +2199,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication { try { - serialPort = FrostedSerialPortFactory.GetAppropriateFactory(ActivePrinterProfile.Instance.ActivePrinter.DriverType).CreateAndOpen(serialPortName, baudRate, true); + serialPort = FrostedSerialPortFactory.GetAppropriateFactory(this.ActivePrinter.DriverType).CreateAndOpen(serialPortName, baudRate, true); #if __ANDROID__ ToggleHighLowHeigh(serialPort); #endif @@ -2299,7 +2288,7 @@ namespace MatterHackers.MatterControl.PrinterCommunication } } - private void ConnectToPrinter(Printer printerRecord) + private void ConnectToPrinter() { PrinterOutputCache.Instance.Clear(); LinesToWriteQueue.Clear(); @@ -2504,9 +2493,10 @@ namespace MatterHackers.MatterControl.PrinterCommunication if (activePrintTask == null) { + // TODO: Fix printerItemID int requirement activePrintTask = new PrintTask(); activePrintTask.PrintStart = DateTime.Now; - activePrintTask.PrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + activePrintTask.PrinterId = this.ActivePrinter.Id.GetHashCode(); activePrintTask.PrintName = ActivePrintItem.PrintItem.Name; activePrintTask.PrintItemId = ActivePrintItem.PrintItem.Id; activePrintTask.PrintingGCodeFileName = ActivePrintItem.GetGCodePathAndFileName(); diff --git a/PrinterControls/ControlWidgets/MacroControls.cs b/PrinterControls/ControlWidgets/MacroControls.cs index f27ed2c03..7db308ef4 100644 --- a/PrinterControls/ControlWidgets/MacroControls.cs +++ b/PrinterControls/ControlWidgets/MacroControls.cs @@ -166,10 +166,12 @@ namespace MatterHackers.MatterControl.PrinterControls internal static IEnumerable GetMacros() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (!string.IsNullOrEmpty(ActiveSliceSettings.Instance?.Id)) { + // TODO: Hook macros into new settings system + //Retrieve a list of macros from the database - string query = string.Format("SELECT * FROM CustomCommands WHERE PrinterId = {0};", ActivePrinterProfile.Instance.ActivePrinter.Id); + string query = string.Format("SELECT * FROM CustomCommands WHERE PrinterId = {0};", ActiveSliceSettings.Instance.Id); return Datastore.Instance.dbSQLite.Query(query); } diff --git a/PrinterControls/ControlWidgets/MovementControls.cs b/PrinterControls/ControlWidgets/MovementControls.cs index 39f1ef431..4b48f7d62 100644 --- a/PrinterControls/ControlWidgets/MovementControls.cs +++ b/PrinterControls/ControlWidgets/MovementControls.cs @@ -34,6 +34,7 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.MatterControl.Utilities; using MatterHackers.VectorMath; using System; @@ -88,10 +89,8 @@ namespace MatterHackers.MatterControl.PrinterControls { PrinterConnectionAndCommunication.Instance.OffsetStreamChanged -= OffsetStreamChanged; - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); + base.OnClosed(e); } @@ -171,9 +170,9 @@ namespace MatterHackers.MatterControl.PrinterControls private static string GetMovementSpeedsString() { string presets = "x,3000,y,3000,z,315,e0,150"; // stored x,value,y,value,z,value,e1,value,e2,value,e3,value,... - if (PrinterConnectionAndCommunication.Instance != null && ActivePrinterProfile.Instance.ActivePrinter != null) + if (PrinterConnectionAndCommunication.Instance != null && ActiveSliceSettings.Instance != null) { - string savedSettings = ActivePrinterProfile.Instance.ActivePrinter.ManualMovementSpeeds; + string savedSettings = ActiveSliceSettings.Instance.ManualMovementSpeeds; if (savedSettings != null && savedSettings != "") { presets = savedSettings; @@ -188,8 +187,7 @@ namespace MatterHackers.MatterControl.PrinterControls StringEventArgs stringEvent = e as StringEventArgs; if (stringEvent != null && stringEvent.Data != null) { - ActivePrinterProfile.Instance.ActivePrinter.ManualMovementSpeeds = stringEvent.Data; - ActivePrinterProfile.Instance.ActivePrinter.Commit(); + ActiveSliceSettings.Instance.ManualMovementSpeeds = stringEvent.Data; ApplicationController.Instance.ReloadAdvancedControlsPanel(); } } diff --git a/PrinterControls/ControlWidgets/TemperatureControls.cs b/PrinterControls/ControlWidgets/TemperatureControls.cs index 3af0b4b4d..c62c00bd0 100644 --- a/PrinterControls/ControlWidgets/TemperatureControls.cs +++ b/PrinterControls/ControlWidgets/TemperatureControls.cs @@ -24,12 +24,7 @@ namespace MatterHackers.MatterControl.PrinterControls temperatureGroupBox.AddChild(mainContainer); RGBA_Bytes separatorLineColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 100); - int numberOfHeatedExtruders = 1; - if (!ActiveSliceSettings.Instance.ExtrudersShareTemperature) - { - numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount; - } - + int numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount; if (numberOfHeatedExtruders > 1) { for (int i = 0; i < numberOfHeatedExtruders; i++) diff --git a/PrinterControls/EditLevelingSettingsWindow.cs b/PrinterControls/EditLevelingSettingsWindow.cs index 94489e28a..04e38d8c7 100644 --- a/PrinterControls/EditLevelingSettingsWindow.cs +++ b/PrinterControls/EditLevelingSettingsWindow.cs @@ -88,7 +88,7 @@ namespace MatterHackers.MatterControl textImageButtonFactory.FixedHeight = 30 * TextWidget.GlobalPointSizeScaleRatio; // put in the movement edit controls - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (EditSamplePositionList(levelingData)) { for (int i = 0; i < levelingData.SampledPositions.Count; i++) @@ -201,7 +201,7 @@ namespace MatterHackers.MatterControl private void DoSave_Click() { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (EditSamplePositionList(levelingData)) { @@ -209,22 +209,16 @@ namespace MatterHackers.MatterControl { levelingData.SampledPositions[i] = positions[i]; } - - levelingData.Commit(); } else { levelingData.SampledPosition0 = positions[0]; levelingData.SampledPosition1 = positions[1]; levelingData.SampledPosition2 = positions[2]; - - PrintLevelingPlane.Instance.SetPrintLevelingEquation( - levelingData.SampledPosition0, - levelingData.SampledPosition1, - levelingData.SampledPosition2, - ActiveSliceSettings.Instance.PrintCenter); } + ActiveSliceSettings.Instance.PrintLevelingData = levelingData; + Close(); } } diff --git a/PrinterControls/EditMacrosWindow.cs b/PrinterControls/EditMacrosWindow.cs index 5299ba0d6..7e8f5f753 100644 --- a/PrinterControls/EditMacrosWindow.cs +++ b/PrinterControls/EditMacrosWindow.cs @@ -34,6 +34,7 @@ using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.FieldValidation; using MatterHackers.MatterControl.PrinterControls; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.VectorMath; using System; using System.Collections.Generic; @@ -212,10 +213,14 @@ namespace MatterHackers.MatterControl private void initMacro() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { + // TODO: Review bindings to int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + windowController.ActiveMacro = new CustomCommands(); - windowController.ActiveMacro.PrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + windowController.ActiveMacro.PrinterId = printerID; windowController.ActiveMacro.Name = "Home All"; windowController.ActiveMacro.Value = "G28 ; Home All Axes"; } diff --git a/PrinterControls/ManualPrinterControls.cs b/PrinterControls/ManualPrinterControls.cs index 2e26c03ef..7333e8bfd 100644 --- a/PrinterControls/ManualPrinterControls.cs +++ b/PrinterControls/ManualPrinterControls.cs @@ -180,7 +180,7 @@ namespace MatterHackers.MatterControl private void SetVisibleControls() { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { // no printer selected foreach (DisableableWidget extruderTemperatureControlWidget in temperatureControlsContainer.ExtruderWidgetContainers) diff --git a/PrinterControls/PrinterConnections/BaseConnectionWidget.cs b/PrinterControls/PrinterConnections/BaseConnectionWidget.cs index 7ddd20c4c..65c0895ff 100644 --- a/PrinterControls/PrinterConnections/BaseConnectionWidget.cs +++ b/PrinterControls/PrinterConnections/BaseConnectionWidget.cs @@ -4,6 +4,7 @@ using MatterHackers.Agg.UI; using MatterHackers.Agg.VertexSource; using MatterHackers.Localizations; using MatterHackers.MatterControl.DataStorage; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.SerialPortCommunication.FrostedSerial; using System; @@ -49,9 +50,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections public class PrinterSelectRadioButton : RadioButton { - public Printer printer; + public PrinterInfo printer; - public PrinterSelectRadioButton(Printer printer) + public PrinterSelectRadioButton(PrinterInfo printer) : base(printer.Name) { this.printer = printer; @@ -131,9 +132,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections public class PrinterActionLink : ActionLink { - public Printer LinkedPrinter; + public PrinterInfo LinkedPrinter; - public PrinterActionLink(string text, Printer printer, int fontSize = 10) + public PrinterActionLink(string text, PrinterInfo printer, int fontSize = 10) : base(text, fontSize) { this.LinkedPrinter = printer; @@ -247,23 +248,37 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections protected List SerialPortButtonsList = new List(); private bool printerComPortIsAvailable = false; - protected GuiWidget containerWindowToClose; - protected RGBA_Bytes defaultTextColor = ActiveTheme.Instance.PrimaryTextColor; - protected RGBA_Bytes defaultBackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - protected RGBA_Bytes subContainerTextColor = ActiveTheme.Instance.PrimaryTextColor; - protected RGBA_Bytes labelBackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - protected RGBA_Bytes linkTextColor = ActiveTheme.Instance.SecondaryAccentColor; - protected ConnectionWindow windowController; - public ActionLinkFactory actionLinkFactory = new ActionLinkFactory(); - private event EventHandler unregisterEvents; - public ConnectionWidgetBase(ConnectionWindow windowController, GuiWidget containerWindowToClose) - : base() + private PrinterInfo activePrinter = null; + protected PrinterInfo ActivePrinter { - this.windowController = windowController; - this.containerWindowToClose = containerWindowToClose; - ActiveTheme.Instance.ThemeChanged.RegisterEvent(ThemeChanged, ref unregisterEvents); + get + { + if(activePrinter == null) + { + var settings = ActiveSliceSettings.Instance; + activePrinter = new PrinterInfo + { + AutoConnectFlag = settings.AutoConnectFlag, + BaudRate = settings.BaudRate, + ComPort = settings.ComPort, + DriverType = settings.DriverType, + Id = settings.Id, + Name = settings.Name + }; + } + + return activePrinter; + } + } + + protected ConnectionWizard connectionWizard; + + public ConnectionWidgetBase(ConnectionWizard wizard) + { + this.connectionWizard = wizard; + ActiveTheme.Instance.ThemeChanged.RegisterEvent((s,e) => this.Invalidate(), ref unregisterEvents); } public int GetPrinterRecordCount() @@ -271,18 +286,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return Datastore.Instance.RecordCount("Printer"); } - public void ThemeChanged(object sender, EventArgs e) - { - this.linkTextColor = ActiveTheme.Instance.PrimaryAccentColor; - this.Invalidate(); - } - public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -292,7 +298,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { HAnchor = HAnchor.ParentLeft, Margin = new BorderDouble(3, 3, 5, 3), - TextColor = this.subContainerTextColor, + TextColor = ActiveTheme.Instance.PrimaryTextColor, Checked = isActivePrinterPort }; return comPortOption; @@ -361,7 +367,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { TextWidget comPortOption = new TextWidget(LocalizedString.Get("No COM ports available")); comPortOption.Margin = new BorderDouble(3, 6, 5, 6); - comPortOption.TextColor = this.subContainerTextColor; + comPortOption.TextColor = ActiveTheme.Instance.PrimaryTextColor; comPortContainer.AddChild(comPortOption); } } diff --git a/PrinterControls/PrinterConnections/ChooseConnectionWidget.cs b/PrinterControls/PrinterConnections/ChooseConnectionWidget.cs deleted file mode 100644 index 50a259347..000000000 --- a/PrinterControls/PrinterConnections/ChooseConnectionWidget.cs +++ /dev/null @@ -1,232 +0,0 @@ -/* -Copyright (c) 2014, Kevin Pope -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 MatterHackers.Agg; -using MatterHackers.Agg.UI; -using MatterHackers.Localizations; -using MatterHackers.MatterControl.CustomWidgets; -using MatterHackers.MatterControl.DataStorage; -using System; -using System.Collections.Generic; - -namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections -{ - public class ChooseConnectionWidget : ConnectionWidgetBase - { - private FlowLayoutWidget ConnectionControlContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - - private List radioButtonsOfKnownPrinters = new List(); - private TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory(); - private TextImageButtonFactory editButtonFactory = new TextImageButtonFactory(); - private Button closeButton; - - private bool editMode; - - public ChooseConnectionWidget(ConnectionWindow windowController, SystemWindow container, bool editMode = false) - : base(windowController, container) - { - { - this.editMode = editMode; - - textImageButtonFactory.normalTextColor = ActiveTheme.Instance.PrimaryTextColor; - textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor; - textImageButtonFactory.disabledTextColor = ActiveTheme.Instance.PrimaryTextColor; - textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor; - textImageButtonFactory.borderWidth = 0; - - editButtonFactory.normalTextColor = ActiveTheme.Instance.SecondaryAccentColor; - editButtonFactory.hoverTextColor = RGBA_Bytes.White; - editButtonFactory.disabledTextColor = ActiveTheme.Instance.SecondaryAccentColor; - editButtonFactory.pressedTextColor = RGBA_Bytes.White; - editButtonFactory.borderWidth = 0; - editButtonFactory.FixedWidth = 60 * TextWidget.GlobalPointSizeScaleRatio; - - this.AnchorAll(); - this.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor; - this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off - - - GuiWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - mainContainer.AnchorAll(); - mainContainer.Padding = new BorderDouble(3, 0, 3, 5); - mainContainer.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - - FlowLayoutWidget headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight); - headerRow.HAnchor = HAnchor.ParentLeftRight; - headerRow.Margin = new BorderDouble(0, 3, 0, 0); - headerRow.Padding = new BorderDouble(0, 3, 0, 0); - - { - string chooseThreeDPrinterConfigLabel = LocalizedString.Get("Choose a 3D Printer Configuration"); - string chooseThreeDPrinterConfigFull = string.Format("{0}:", chooseThreeDPrinterConfigLabel); - - TextWidget elementHeader = new TextWidget(string.Format(chooseThreeDPrinterConfigFull), pointSize: 14); - elementHeader.TextColor = this.defaultTextColor; - elementHeader.HAnchor = HAnchor.ParentLeftRight; - elementHeader.VAnchor = Agg.UI.VAnchor.ParentCenter; - - headerRow.AddChild(elementHeader); - } - - FlowLayoutWidget editButtonRow = new FlowLayoutWidget(FlowDirection.LeftToRight); - editButtonRow.BackgroundColor = ActiveTheme.Instance.TransparentDarkOverlay; - editButtonRow.HAnchor = HAnchor.ParentLeftRight; - editButtonRow.Margin = new BorderDouble(0, 3, 0, 0); - editButtonRow.Padding = new BorderDouble(0, 3, 0, 0); - - Button enterLeaveEditModeButton; - if (!this.editMode) - { - enterLeaveEditModeButton = editButtonFactory.Generate(LocalizedString.Get("Edit"), centerText: true); - enterLeaveEditModeButton.Click += EditModeOnLink_Click; - } - else - { - enterLeaveEditModeButton = editButtonFactory.Generate(LocalizedString.Get("Done"), centerText: true); - enterLeaveEditModeButton.Click += EditModeOffLink_Click; - } - - editButtonRow.AddChild(enterLeaveEditModeButton); - - //To do - replace with scrollable widget - FlowLayoutWidget printerListContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - //ListBox printerListContainer = new ListBox(); - { - printerListContainer.HAnchor = HAnchor.ParentLeftRight; - printerListContainer.VAnchor = VAnchor.FitToChildren; - printerListContainer.Padding = new BorderDouble(3); - printerListContainer.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor; - - - //Get a list of printer records and add them to radio button list - foreach (Printer printer in GetAllPrinters()) - { - PrinterListItem printerListItem; - if (this.editMode) - { - printerListItem = new PrinterListItemEdit(printer, this.windowController); - } - else - { - printerListItem = new PrinterListItemView(printer, this.windowController); - } - - printerListContainer.AddChild(printerListItem); - } - } - - FlowLayoutWidget buttonContainer = new FlowLayoutWidget(FlowDirection.LeftToRight); - buttonContainer.HAnchor = HAnchor.ParentLeft | HAnchor.ParentRight; - buttonContainer.Margin = new BorderDouble(0, 3); - { - closeButton = textImageButtonFactory.Generate(LocalizedString.Get("Close")); - - Button addPrinterButton = textImageButtonFactory.Generate(LocalizedString.Get("Add"), "icon_circle_plus.png"); - addPrinterButton.Name = "Add new printer button"; - addPrinterButton.ToolTipText = "Add a new Printer Profile".Localize(); - addPrinterButton.Click += new EventHandler(AddConnectionLink_Click); - - Button refreshListButton = textImageButtonFactory.Generate(LocalizedString.Get("Refresh")); - refreshListButton.Click += new EventHandler(EditModeOffLink_Click); - - //Add buttons to ButtonContainer - buttonContainer.AddChild(addPrinterButton); - - if (!this.editMode) - { - buttonContainer.AddChild(refreshListButton); - } - - buttonContainer.AddChild(new HorizontalSpacer()); - buttonContainer.AddChild(closeButton); - } - - ScrollableWidget printerListScrollArea = new ScrollableWidget(true); - printerListScrollArea.ScrollArea.HAnchor |= Agg.UI.HAnchor.ParentLeftRight; - printerListScrollArea.AnchorAll(); - printerListScrollArea.AddChild(printerListContainer); - - FlowLayoutWidget printerListScrollContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - printerListScrollContainer.HAnchor = HAnchor.ParentLeftRight; - printerListScrollContainer.VAnchor = VAnchor.ParentBottomTop; - printerListScrollContainer.Padding = new BorderDouble(3); - printerListScrollContainer.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor; - - mainContainer.AddChild(headerRow); - mainContainer.AddChild(editButtonRow); - mainContainer.AddChild(printerListScrollContainer); - printerListScrollContainer.AddChild(printerListScrollArea); - mainContainer.AddChild(buttonContainer); - - this.AddChild(mainContainer); - - BindCloseButtonClick(); - } - } - - private void BindCloseButtonClick() - { - closeButton.UnbindClickEvents(); - closeButton.Click += new EventHandler(CloseWindow); - } - - private void EditModeOnLink_Click(object sender, EventArgs mouseEvent) - { - this.windowController.ChangeToChoosePrinter(true); - } - - private void EditModeOffLink_Click(object sender, EventArgs mouseEvent) - { - this.windowController.ChangeToChoosePrinter(false); - } - - private void AddConnectionLink_Click(object sender, EventArgs mouseEvent) - { - this.windowController.ChangeToAddPrinter(); - } - - private void EditConnectionLink_Click(object sender, EventArgs mouseEvent) - { - PrinterActionLink actionLink = (PrinterActionLink)sender; - this.windowController.ChangedToEditPrinter(actionLink.LinkedPrinter); - } - - private void CloseWindow(object o, EventArgs e) - { - //Stop listening for connection events (if set) and close window - UiThread.RunOnIdle(containerWindowToClose.Close); - } - - private IEnumerable GetAllPrinters() - { - //Retrieve a list of saved printers from the Datastore - return Datastore.Instance.dbSQLite.Query("SELECT * FROM Printer;"); - } - } -} \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/ConnectionWindow.cs b/PrinterControls/PrinterConnections/ConnectionWindow.cs index 65339048a..790bedc5e 100644 --- a/PrinterControls/PrinterConnections/ConnectionWindow.cs +++ b/PrinterControls/PrinterConnections/ConnectionWindow.cs @@ -1,16 +1,21 @@ -using MatterHackers.Agg.UI; +using System; +using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.DataStorage; using MatterHackers.VectorMath; +using System.Collections.Generic; +using MatterHackers.Agg.PlatformAbstract; +using System.IO; +using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { - public class ConnectionWindow : SystemWindow + public class ConnectionWizard : SystemWindow { - private Printer activePrinter; + protected PrinterInfo activePrinter; private bool editMode = false; - public ConnectionWindow() + public ConnectionWizard() : base(350 * TextWidget.GlobalPointSizeScaleRatio, 500 * TextWidget.GlobalPointSizeScaleRatio) { AlwaysOnTopOfMain = true; @@ -19,14 +24,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections Title = string.Format("{0} - {1}", connectToPrinterTitle, connectToPrinterTitleEnd); Name = "Printer Connection Window"; - if (GetPrinterRecordCount() > 0) - { - ChangeToChoosePrinter(); - } - else - { - ChangeToAddPrinter(); - } + ChangeToAddPrinter(); BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; @@ -34,85 +32,89 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections MinimumSize = new Vector2(350 * TextWidget.GlobalPointSizeScaleRatio, 400 * TextWidget.GlobalPointSizeScaleRatio); } - private static ConnectionWindow connectionWindow = null; - private static bool connectionWindowIsOpen = false; + private static ConnectionWizard connectionWindow = null; public static void Show() { - if (connectionWindowIsOpen == false) + if (connectionWindow != null) { - connectionWindow = new ConnectionWindow(); - connectionWindowIsOpen = true; - connectionWindow.Closed += (parentSender, e) => - { - connectionWindowIsOpen = false; - connectionWindow = null; - }; + connectionWindow.BringToFront(); } else - { - if (connectionWindow != null) - { - connectionWindow.BringToFront(); - } + { + connectionWindow = new ConnectionWizard(); + connectionWindow.Closed += (s, e) => connectionWindow = null; } } - public override void OnMouseUp(MouseEventArgs mouseEvent) - { - base.OnMouseUp(mouseEvent); - } - - private void DoNotChangeWindow() - { - //Empty function used as default callback for changeToWindowCallback - } - - public void ChangeToAddPrinter() + internal void ChangeToAddPrinter() { this.activePrinter = null; - UiThread.RunOnIdle(DoChangeToAddPrinter); + ChangeToStep(new SetupStepMakeModelName(this)); } - private void DoChangeToAddPrinter() + private void ChangeToStep(GuiWidget nextStep) { - GuiWidget addConnectionWidget = new SetupStepMakeModelName(this, this); - this.RemoveAllChildren(); - this.AddChild(addConnectionWidget); - this.Invalidate(); - } - - public void ChangedToEditPrinter(Printer activePrinter, object state = null) - { - this.activePrinter = activePrinter; - UiThread.RunOnIdle(DoChangeToEditPrinter, state); - } - - private void DoChangeToEditPrinter(object state) - { - GuiWidget addConnectionWidget = new EditConnectionWidget(this, this, activePrinter, state); - this.RemoveAllChildren(); - this.AddChild(addConnectionWidget); - this.Invalidate(); - } - - public void ChangeToChoosePrinter(bool editMode = false) - { - this.editMode = editMode; - UiThread.RunOnIdle(DoChangeToChoosePrinter); - } - - public void DoChangeToChoosePrinter() - { - GuiWidget chooseConnectionWidget = new ChooseConnectionWidget(this, this, this.editMode); - this.RemoveAllChildren(); - this.AddChild(chooseConnectionWidget); - this.Invalidate(); + UiThread.RunOnIdle(() => + { + this.RemoveAllChildren(); + this.AddChild(nextStep); + this.Invalidate(); + }); } private int GetPrinterRecordCount() { return Datastore.Instance.RecordCount("Printer"); } + + internal void ChangeToSetupBaudRate() + { + ChangeToStep(new SetupStepBaudRate(this)); + } + + internal void ChangeToInstallDriver() + { + ChangeToStep(new SetupStepInstallDriver(this)); + } + + internal void ChangeToSetupComPortOne() + { + ChangeToStep(new SetupStepComPortOne(this)); + } + + internal void ChangeToSetupCompPortTwo() + { + ChangeToStep(new SetupStepComPortTwo(this)); + } + + internal void ChangeToSetupComPortManual() + { + ChangeToStep(new SetupStepComPortManual(this)); + } + + internal void ChangeToInstallDriverOrComPortOne() + { + if (ActiveSliceSettings.Instance.PrinterDrivers().Count > 0) + { + ChangeToInstallDriver(); + } + else + { + ChangeToSetupComPortOne(); + } + } + + internal void ChangeToSetupBaudOrComPortOne() + { + if (string.IsNullOrEmpty(activePrinter.BaudRate)) + { + ChangeToSetupBaudRate(); + } + else + { + ChangeToSetupComPortOne(); + } + } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/EditConnectionWidget.cs b/PrinterControls/PrinterConnections/EditConnectionWidget.cs index 7de37e4e2..9f0f28cc6 100644 --- a/PrinterControls/PrinterConnections/EditConnectionWidget.cs +++ b/PrinterControls/PrinterConnections/EditConnectionWidget.cs @@ -4,6 +4,7 @@ using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.SerialPortCommunication.FrostedSerial; using System; using System.Collections.Generic; @@ -16,7 +17,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { private List BaudRateButtonsList = new List(); private FlowLayoutWidget ConnectionControlContainer; - private Printer ActivePrinter; + private SettingsProfile ActivePrinter; private MHTextEditWidget printerNameInput; private MHTextEditWidget otherBaudRateInput; private MHTextEditWidget printerModelInput; @@ -366,11 +367,15 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private void RefreshComPorts(object sender, EventArgs mouseEvent) { + // TODO: Why would refresh change the active state and why would it need to destroy and recreate + // the control rather than just refreshing the content? try { - this.ActivePrinter.Name = printerNameInput.Text; - this.ActivePrinter.BaudRate = GetSelectedBaudRate(); - this.ActivePrinter.ComPort = GetSelectedSerialPort(); + var settings = ActiveSliceSettings.Instance; + + settings.Name = printerNameInput.Text; + settings.BaudRate = GetSelectedBaudRate(); + settings.ComPort = GetSelectedSerialPort(); } catch { @@ -378,18 +383,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections this.windowController.ChangedToEditPrinter(this.ActivePrinter, new StateBeforeRefresh(enableAutoconnect.Checked)); } - private void ReloadCurrentWidget(object sender, EventArgs mouseEvent) - { - if (this.addNewPrinterFlag == true) - { - this.windowController.ChangeToAddPrinter(); - } - else - { - this.windowController.ChangedToEditPrinter(this.ActivePrinter); - } - } - private void BindSaveButtonHandlers() { saveButton.UnbindClickEvents(); @@ -426,23 +419,16 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { this.ActivePrinter.BaudRate = GetSelectedBaudRate(); this.ActivePrinter.ComPort = GetSelectedSerialPort(); - this.ActivePrinter.Make = printerMakeInput.Text; - this.ActivePrinter.Model = printerModelInput.Text; + + // TODO: These should be read only properties that describe what OEM definition your settings came from + //this.ActivePrinter.Make = printerMakeInput.Text; + //this.ActivePrinter.Model = printerModelInput.Text; this.ActivePrinter.AutoConnectFlag = enableAutoconnect.Checked; } catch { //Unable to retrieve Baud or Port, possibly because they weren't shown as options - needs better handling } - this.ActivePrinter.Commit(); - - // If the printer we're updating is also the currently active printer or if the ActivePrinter is unassigned, - // then we need to update the instance variable to match the new data - the old instance is bound to sql - // data that is no longer valid - if (ActivePrinterProfile.Instance.ActivePrinter == null || ActivePrinterProfile.Instance.ActivePrinter.Id == this.ActivePrinter.Id) - { - ActivePrinterProfile.Instance.ActivePrinter = this.ActivePrinter; - } this.windowController.ChangeToChoosePrinter(); } diff --git a/PrinterControls/PrinterConnections/PrinterListItems.cs b/PrinterControls/PrinterConnections/PrinterListItems.cs deleted file mode 100644 index d01a73866..000000000 --- a/PrinterControls/PrinterConnections/PrinterListItems.cs +++ /dev/null @@ -1,232 +0,0 @@ -using MatterHackers.Agg; -using MatterHackers.Agg.UI; -using MatterHackers.Localizations; -using MatterHackers.MatterControl.DataStorage; -using MatterHackers.MatterControl.PrinterCommunication; -using MatterHackers.SerialPortCommunication.FrostedSerial; -using System; -using System.Linq; - -namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections -{ - //Empty base class for selectable printer list - public class PrinterListItem : FlowLayoutWidget - { - protected ConnectionWindow windowController; - protected Printer printerRecord; - - public PrinterListItem(Printer printerRecord, ConnectionWindow windowController) - { - this.printerRecord = printerRecord; - this.windowController = windowController; - } - } - - internal class PrinterListItemView : PrinterListItem - { - private TextWidget printerName; - - private RGBA_Bytes defaultBackgroundColor = new RGBA_Bytes(250, 250, 250); - private RGBA_Bytes hoverBackgroundColor = new RGBA_Bytes(204, 204, 204); - - private RGBA_Bytes defaultTextColor = new RGBA_Bytes(34, 34, 34); - private RGBA_Bytes hoverTextColor = new RGBA_Bytes(34, 34, 34); - - public PrinterListItemView(Printer printerRecord, ConnectionWindow windowController) - : base(printerRecord, windowController) - { - this.Margin = new BorderDouble(1); - this.BackgroundColor = this.defaultBackgroundColor; - this.Padding = new BorderDouble(0); - this.Name = this.printerRecord.Name + " Profile"; - - string[] comportNames = FrostedSerialPort.GetPortNames(); - bool portIsAvailable = comportNames.Contains(printerRecord.ComPort); - - printerName = new TextWidget(this.printerRecord.Name); - printerName.TextColor = this.defaultTextColor; - printerName.HAnchor = HAnchor.ParentLeftRight; - printerName.Margin = new BorderDouble(5, 10, 5, 10); - - string availableText = LocalizedString.Get("Unavailable"); - RGBA_Bytes availableColor = new RGBA_Bytes(158, 18, 0); - if (portIsAvailable) - { - availableText = ""; - } - - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - int connectedPrinterHash = ActivePrinterProfile.Instance.ActivePrinter.GetHashCode(); - int printerOptionHash = printerRecord.GetHashCode(); - if (connectedPrinterHash == printerOptionHash) - { - availableText = PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose; - availableColor = new RGBA_Bytes(0, 95, 107); - } - } - - TextWidget availableIndicator = new TextWidget(availableText, pointSize: 10); - availableIndicator.TextColor = availableColor; - availableIndicator.Padding = new BorderDouble(3, 0, 0, 3); - availableIndicator.Margin = new BorderDouble(right: 5); - availableIndicator.VAnchor = Agg.UI.VAnchor.ParentCenter; - - this.AddChild(printerName); - this.AddChild(availableIndicator); - this.HAnchor = HAnchor.ParentLeftRight; - - BindHandlers(); - } - - public void BindHandlers() - { - this.MouseEnter += new EventHandler(onMouse_Enter); - this.MouseLeave += new EventHandler(onMouse_Leave); - this.MouseUp += (sender, e) => - { - UiThread.RunOnIdle(onMouse_Up, e); - }; - } - - private void onMouse_Up(object state) - { - MouseEventArgs mouseEvent = state as MouseEventArgs; - //Turns this into a standard 'click' event - if (this.PositionWithinLocalBounds(mouseEvent.X, mouseEvent.Y)) - { - // Changing ordering around so that CloseOnIdle is called after ActivePrinter is set - ActivePrinterProfile.Instance.ActivePrinter = this.printerRecord; - - UiThread.RunOnIdle(this.windowController.Close); - } - } - - private void onMouse_Enter(object sender, EventArgs args) - { - this.BackgroundColor = this.hoverBackgroundColor; - this.printerName.TextColor = this.hoverTextColor; - } - - private void onMouse_Leave(object sender, EventArgs args) - { - this.BackgroundColor = this.defaultBackgroundColor; - this.printerName.TextColor = this.defaultTextColor; - } - } - - internal class PrinterListItemEdit : PrinterListItem - { - private TextWidget printerName; - - private RGBA_Bytes defaultBackgroundColor = new RGBA_Bytes(250, 250, 250); - private RGBA_Bytes hoverBackgroundColor = ActiveTheme.Instance.PrimaryAccentColor; - - private RGBA_Bytes defaultTextColor = new RGBA_Bytes(34, 34, 34); - private RGBA_Bytes hoverTextColor = new RGBA_Bytes(250, 250, 250); - private SlideWidget rightButtonOverlay; - - public PrinterListItemEdit(Printer printerRecord, ConnectionWindow windowController) - : base(printerRecord, windowController) - { - this.printerRecord = printerRecord; - this.Margin = new BorderDouble(1); - this.BackgroundColor = this.defaultBackgroundColor; - this.Padding = new BorderDouble(0); - this.HAnchor = HAnchor.ParentLeftRight; - - FlowLayoutWidget printerNameContainer = new FlowLayoutWidget(); - printerNameContainer.HAnchor = HAnchor.ParentLeftRight; - - printerName = new TextWidget(this.printerRecord.Name); - printerName.TextColor = this.defaultTextColor; - printerName.Margin = new BorderDouble(5, 10, 0, 10); - printerName.HAnchor = HAnchor.ParentLeftRight; - - printerNameContainer.AddChild(printerName); - - FlowLayoutWidget rightButtonOverlayContainer = new FlowLayoutWidget(FlowDirection.RightToLeft); - rightButtonOverlayContainer.HAnchor = HAnchor.ParentLeftRight; - rightButtonOverlayContainer.VAnchor = VAnchor.ParentBottomTop; - - this.rightButtonOverlay = getItemActionButtons(); - this.rightButtonOverlay.Padding = new BorderDouble(0); - this.rightButtonOverlay.Visible = true; - rightButtonOverlayContainer.AddChild(rightButtonOverlay); - - this.AddChild(printerNameContainer); - this.AddChild(rightButtonOverlayContainer); - } - - private SlideWidget getItemActionButtons() - { - int buttonWidth; - if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen) - { - buttonWidth = 120; - } - else - { - buttonWidth = 80;//80 - } - - SlideWidget buttonContainer = new SlideWidget(); - buttonContainer.VAnchor = VAnchor.ParentBottomTop; - - FlowLayoutWidget buttonFlowContainer = new FlowLayoutWidget(FlowDirection.LeftToRight); - buttonFlowContainer.VAnchor = VAnchor.ParentBottomTop; - - TextWidget printLabel = new TextWidget("Remove".Localize()); - printLabel.TextColor = RGBA_Bytes.White; - printLabel.VAnchor = VAnchor.ParentCenter; - printLabel.HAnchor = HAnchor.ParentCenter; - - FatFlatClickWidget removeButton = new FatFlatClickWidget(printLabel); - removeButton.VAnchor = VAnchor.ParentBottomTop; - removeButton.BackgroundColor = ActiveTheme.Instance.PrimaryAccentColor; - removeButton.Width = buttonWidth; - removeButton.Click += RemoveConnectionLink_Click; - - TextWidget editLabel = new TextWidget("Edit".Localize()); - editLabel.TextColor = RGBA_Bytes.White; - editLabel.VAnchor = VAnchor.ParentCenter; - editLabel.HAnchor = HAnchor.ParentCenter; - - FatFlatClickWidget editButton = new FatFlatClickWidget(editLabel); - editButton.VAnchor = VAnchor.ParentBottomTop; - editButton.BackgroundColor = ActiveTheme.Instance.SecondaryAccentColor; - editButton.Width = buttonWidth; - - editButton.Click += EditConnectionLink_Click; - - buttonFlowContainer.AddChild(editButton); - buttonFlowContainer.AddChild(removeButton); - - buttonContainer.AddChild(buttonFlowContainer); - buttonContainer.Width = buttonWidth * 2; - - return buttonContainer; - } - - private void EditConnectionLink_Click(object sender, EventArgs mouseEvent) - { - this.windowController.ChangedToEditPrinter(this.printerRecord); - } - - private void RemoveConnectionLink_Click(object sender, EventArgs mouseEvent) - { - //Disconnect printer if the printer being removed is currently connected - if (ActivePrinterProfile.Instance.ActivePrinter != null && this.printerRecord.Id == ActivePrinterProfile.Instance.ActivePrinter.Id) - { - UiThread.RunOnIdle((state) => - { - PrinterConnectionAndCommunication.Instance.Disable(); - ActivePrinterProfile.Instance.ActivePrinter = null; - }, null, 0.5); - } - - this.printerRecord.Delete(); - this.windowController.ChangeToChoosePrinter(true); - } - } -} \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/PrinterSetupStatus.cs b/PrinterControls/PrinterConnections/PrinterSetupStatus.cs index a0914935b..0162bd3c6 100644 --- a/PrinterControls/PrinterConnections/PrinterSetupStatus.cs +++ b/PrinterControls/PrinterConnections/PrinterSetupStatus.cs @@ -5,6 +5,7 @@ using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrintLibrary; using MatterHackers.MatterControl.PrintLibrary.Provider; using MatterHackers.MatterControl.PrintQueue; +using MatterHackers.MatterControl.SlicerConfiguration; using System; using System.Collections.Generic; using System.IO; @@ -16,20 +17,18 @@ namespace MatterHackers.MatterControl //Wraps the printer record. Includes temporary information that we don't need in the DB. public class PrinterSetupStatus { - public Printer ActivePrinter; - public List DriversToInstall = new List(); + public PrinterInfo ActivePrinter; + public Type PreviousSetupWidget; public Type NextSetupWidget; - private List printerCustomCommands; - private string defaultMaterialPreset; - private string defaultQualityPreset; - private string defaultMovementSpeeds; - public PrinterSetupStatus(Printer printer = null) + private List printerCustomCommands; + + public PrinterSetupStatus(PrinterInfo printer = null) { if (printer == null) { - this.ActivePrinter = new Printer(); + this.ActivePrinter = new PrinterInfo(); this.ActivePrinter.Make = null; this.ActivePrinter.Model = null; this.ActivePrinter.Name = "Default Printer ({0})".FormatWith(ExistingPrinterCount() + 1); @@ -47,326 +46,18 @@ namespace MatterHackers.MatterControl return Datastore.Instance.RecordCount("Printer"); } - public void LoadCalibrationPrints() - { - if (this.ActivePrinter.Make != null && this.ActivePrinter.Model != null) - { - // Load the calibration file names - List calibrationPrintFileNames = LoadCalibrationPartNamesForPrinter(this.ActivePrinter.Make, this.ActivePrinter.Model); - - var libraryProvider = new LibraryProviderSQLite(null, null, null, "Local Library"); - libraryProvider.EnsureSamplePartsExist(calibrationPrintFileNames); - - var queueItems = QueueData.Instance.GetItemNames(); - - // Finally, ensure missing calibration parts are added to the queue if missing - var filenamesWithoutExtensions = calibrationPrintFileNames.Select(f => Path.GetFileNameWithoutExtension(f)); - foreach (string nameOnly in filenamesWithoutExtensions) - { - if (queueItems.Contains(nameOnly)) - { - continue; - } - - // Find the first library item with the given name and add it to the queue - PrintItem libraryItem = libraryProvider.GetLibraryItems(nameOnly).FirstOrDefault(); - if (libraryItem != null) - { - QueueData.Instance.AddItem(new PrintItemWrapper(libraryItem)); - } - } - - libraryProvider.Dispose(); - } - } - - private List LoadCalibrationPartNamesForPrinter(string make, string model) - { - string filePath = Path.Combine("PrinterSettings", make, model, "calibration.ini"); - if (StaticData.Instance.FileExists(filePath)) - { - try - { - return StaticData.Instance.ReadAllLines(filePath).Where(l => !l.StartsWith("#")).Select(l => l.Trim()).ToList(); - } - catch - { - } - } - - return new List(); - } - - public void LoadSetupSettings(string make, string model) - { - Dictionary settingsDict = LoadPrinterSetupFromFile(make, model); - Dictionary macroDict = new Dictionary(); - macroDict["Lights On"] = "M42 P6 S255"; - macroDict["Lights Off"] = "M42 P6 S0"; - macroDict["Offset 0.8"] = "M565 Z0.8;\nM500"; - macroDict["Offset 0.9"] = "M565 Z0.9;\nM500"; - macroDict["Offset 1"] = "M565 Z1;\nM500"; - macroDict["Offset 1.1"] = "M565 Z1.1;\nM500"; - macroDict["Offset 1.2"] = "M565 Z1.2;\nM500"; - macroDict["Z Offset"] = "G1 Z10;\nG28;\nG29;\nG1 Z10;\nG1 X5 Y5 F4000;\nM117;"; - - //Determine if baud rate is needed and show controls if required - string baudRate; - if (settingsDict.TryGetValue("baud_rate", out baudRate)) - { - ActivePrinter.BaudRate = baudRate; - } - - string defaultSliceEngine; - if (settingsDict.TryGetValue("default_slice_engine", out defaultSliceEngine)) - { - if (Enum.IsDefined(typeof(ActivePrinterProfile.SlicingEngineTypes), defaultSliceEngine)) - { - ActivePrinter.CurrentSlicingEngine = defaultSliceEngine; - } - } - - string defaultPrinterDriver; - if (settingsDict.TryGetValue("driver_type", out defaultPrinterDriver)) - { - ActivePrinter.DriverType = defaultPrinterDriver; - } - - settingsDict.TryGetValue("default_material_presets", out defaultMaterialPreset); - settingsDict.TryGetValue("default_quality_preset", out defaultQualityPreset); - settingsDict.TryGetValue("default_movement_speeds", out defaultMovementSpeeds); - - string defaultMacros; - printerCustomCommands = new List(); - if (settingsDict.TryGetValue("default_macros", out defaultMacros)) - { - string[] macroList = defaultMacros.Split(','); - foreach (string macroName in macroList) - { - string macroValue; - if (macroDict.TryGetValue(macroName.Trim(), out macroValue)) - { - CustomCommands customMacro = new CustomCommands(); - customMacro.Name = macroName.Trim(); - customMacro.Value = macroValue; - - printerCustomCommands.Add(customMacro); - } - } - } - - //Determine what if any drivers are needed - string infFileNames; - if (settingsDict.TryGetValue("windows_driver", out infFileNames)) - { - string[] fileNames = infFileNames.Split(','); - foreach (string fileName in fileNames) - { - switch (OsInformation.OperatingSystem) - { - case OSType.Windows: - - string pathForInf = Path.GetFileNameWithoutExtension(fileName); - - // TODO: It's really unexpected that the driver gets copied to the temp folder everytime a printer is setup. I'd think this only needs - // to happen when the infinstaller is run (More specifically - move this to *after* the user clicks Install Driver) - - string infPath = Path.Combine("Drivers", pathForInf); - string infPathAndFileToInstall = Path.Combine(infPath, fileName); - - if (StaticData.Instance.FileExists(infPathAndFileToInstall)) - { - // Ensure the output directory exists - string destTempPath = Path.GetFullPath(Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "inf", pathForInf)); - if (!Directory.Exists(destTempPath)) - { - Directory.CreateDirectory(destTempPath); - } - - string destTempInf = Path.GetFullPath(Path.Combine(destTempPath, fileName)); - - // Sync each file from StaticData to the location on disk for serial drivers - foreach (string file in StaticData.Instance.GetFiles(infPath)) - { - using (Stream outstream = File.OpenWrite(Path.Combine(destTempPath, Path.GetFileName(file)))) - using (Stream instream = StaticData.Instance.OpenSteam(file)) - { - instream.CopyTo(outstream); - } - } - - DriversToInstall.Add(destTempInf); - } - break; - - default: - break; - } - } - } - } - - private Dictionary LoadPrinterSetupFromFile(string make, string model) - { - string setupSettingsPathAndFile = Path.Combine("PrinterSettings", make, model, "setup.ini"); - Dictionary settingsDict = new Dictionary(); - - if (StaticData.Instance.FileExists(setupSettingsPathAndFile)) - { - try - { - foreach (string lineIn in StaticData.Instance.ReadAllLines(setupSettingsPathAndFile)) - { - string line = lineIn.Trim(); - //Ignore commented lines - if (line.Length > 0 - && !line.StartsWith("#")) - { - string[] settingLine = line.Split('='); - if (settingLine.Length > 1) - { - string keyName = settingLine[0].Trim(); - string settingDefaultValue = settingLine[1].Trim(); - - settingsDict.Add(keyName, settingDefaultValue); - } - } - } - } - catch - { - } - } - return settingsDict; - } - - /// - /// Loads a SliceSettingsCollection from StaticData PrinterSettings - /// - /// The make to load - /// The model to load - public SliceSettingsCollection LoadSettingsFromConfigFile(string make, string model) - { - Dictionary settingsDict = LoadSliceSettingsFromFile(Path.Combine("PrinterSettings", make, model, "config.ini")); - if (settingsDict.Count > 0) - { - SliceSettingsCollection collection = new SliceSettingsCollection(); - collection.Name = this.ActivePrinter.Name; - collection.Commit(); - - this.ActivePrinter.DefaultSettingsCollectionId = collection.Id; - - CommitSliceSettings(settingsDict, collection.Id); - - return collection; - } - - // Return null if the loaded settings dictionary was empty - return null; - } - - public void LoadSlicePresets(string make, string model, string tag) - { - foreach (string filePath in GetSlicePresets(make, model, tag)) - { - Dictionary settingsDict = LoadSliceSettingsFromFile(filePath); - - if (settingsDict.Count > 0) - { - SliceSettingsCollection collection = new SliceSettingsCollection(); - collection.Name = Path.GetFileNameWithoutExtension(filePath); - collection.PrinterId = ActivePrinter.Id; - collection.Tag = tag; - collection.Commit(); - - if (tag == "material" && defaultMaterialPreset != null && collection.Name == defaultMaterialPreset) - { - ActivePrinter.MaterialCollectionIds = collection.Id.ToString(); - ActivePrinter.Commit(); - } - else if (tag == "quality" && defaultQualityPreset != null && collection.Name == defaultQualityPreset) - { - ActivePrinter.QualityCollectionId = collection.Id; - ActivePrinter.Commit(); - } - CommitSliceSettings(settingsDict, collection.Id); - } - } - } - - private void CommitSliceSettings(Dictionary settingsDict, int collectionId) - { - foreach (KeyValuePair item in settingsDict) - { - SliceSetting sliceSetting = new SliceSetting(); - sliceSetting.Name = item.Key; - sliceSetting.Value = item.Value; - sliceSetting.SettingsCollectionId = collectionId; - sliceSetting.Commit(); - } - } - - private string[] GetSlicePresets(string make, string model, string tag) - { - string[] presetPaths = new string[] { }; - string folderPath = Path.Combine("PrinterSettings", make, model, tag); - if (StaticData.Instance.DirectoryExists(folderPath)) - { - presetPaths = StaticData.Instance.GetFiles(folderPath).ToArray(); - } - return presetPaths; - } - - private Dictionary LoadSliceSettingsFromFile(string setupSettingsPathAndFile) - { - Dictionary settingsDict = new Dictionary(); - if (StaticData.Instance.FileExists(setupSettingsPathAndFile)) - { - try - { - foreach (string line in StaticData.Instance.ReadAllLines(setupSettingsPathAndFile)) - { - //Ignore commented lines - if (!line.StartsWith("#") && line.Length > 0) - { - string[] settingLine = line.Split('='); - if (settingLine.Length == 2) - { - string keyName = settingLine[0].Trim(); - string settingDefaultValue = settingLine[1].Trim(); - - settingsDict.Add(keyName, settingDefaultValue); - } - } - } - } - catch - { - } - } - return settingsDict; - } - public void Save() { - //Load the default slice settings for the make and model combination - if they exist - SliceSettingsCollection collection = LoadSettingsFromConfigFile(this.ActivePrinter.Make, this.ActivePrinter.Model); - - if (defaultMovementSpeeds != null) - { - this.ActivePrinter.ManualMovementSpeeds = defaultMovementSpeeds; - } - //Ordering matters - need to get Id for printer prior to loading slice presets this.ActivePrinter.AutoConnectFlag = true; - this.ActivePrinter.Commit(); - LoadSlicePresets(this.ActivePrinter.Make, this.ActivePrinter.Model, "material"); - LoadSlicePresets(this.ActivePrinter.Make, this.ActivePrinter.Model, "quality"); + // TODO: Review printerID int requirement + int printerID; + int.TryParse(ActivePrinter.Id, out printerID); foreach (CustomCommands customCommand in printerCustomCommands) { - customCommand.PrinterId = ActivePrinter.Id; + customCommand.PrinterId = printerID; customCommand.Commit(); } } diff --git a/PrinterControls/PrinterConnections/SetupConnectionWidgetBase.cs b/PrinterControls/PrinterConnections/SetupConnectionWidgetBase.cs index 78decdce8..78de5d784 100644 --- a/PrinterControls/PrinterConnections/SetupConnectionWidgetBase.cs +++ b/PrinterControls/PrinterConnections/SetupConnectionWidgetBase.cs @@ -3,14 +3,13 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; using System; namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { public class SetupConnectionWidgetBase : ConnectionWidgetBase { - public PrinterSetupStatus currentPrinterSetupStatus; - //private GuiWidget mainContainer; protected FlowLayoutWidget headerRow; @@ -21,28 +20,13 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections protected TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory(); protected LinkButtonFactory linkButtonFactory = new LinkButtonFactory(); - public Printer ActivePrinter - { - get { return currentPrinterSetupStatus.ActivePrinter; } - } - - public SetupConnectionWidgetBase(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus printerSetupStatus = null) - : base(windowController, containerWindowToClose) + public SetupConnectionWidgetBase(ConnectionWizard wizard) : base(wizard) { SetDisplayAttributes(); - - if (printerSetupStatus == null) - { - this.currentPrinterSetupStatus = new PrinterSetupStatus(); - } - else - { - this.currentPrinterSetupStatus = printerSetupStatus; - } - - cancelButton = textImageButtonFactory.Generate(LocalizedString.Get("Cancel")); + + cancelButton = textImageButtonFactory.Generate("Cancel".Localize()); cancelButton.Name = "Setup Connection Cancel Button"; - cancelButton.Click += new EventHandler(CancelButton_Click); + cancelButton.Click += CancelButton_Click; //Create the main container GuiWidget mainContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); @@ -56,10 +40,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections headerRow.Padding = new BorderDouble(0, 3, 0, 3); headerRow.HAnchor = HAnchor.ParentLeftRight; { - string defaultHeaderTitle = LocalizedString.Get("3D Printer Setup"); - headerLabel = new TextWidget(defaultHeaderTitle, pointSize: 14); + headerLabel = new TextWidget("3D Printer Setup".Localize(), pointSize: 14); headerLabel.AutoExpandBoundsToText = true; - headerLabel.TextColor = this.defaultTextColor; + headerLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor; headerRow.AddChild(headerLabel); } @@ -83,9 +66,18 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections protected void SaveAndExit() { - this.ActivePrinter.Commit(); - ActivePrinterProfile.Instance.ActivePrinter = this.ActivePrinter; - this.containerWindowToClose.Close(); + ActiveSliceSettings.Instance.RunInTransaction(settings => + { + settings.AutoConnectFlag = ActivePrinter.AutoConnectFlag; + settings.BaudRate = ActivePrinter.BaudRate; + settings.ComPort = ActivePrinter.ComPort; + settings.SlicingEngine = ActivePrinter.CurrentSlicingEngine; + settings.DriverType = ActivePrinter.DriverType; + settings.Id = ActivePrinter.Id; + settings.Name = ActivePrinter.Name; + }); + + UiThread.RunOnIdle(connectionWizard.Close); } private void SetDisplayAttributes() @@ -104,26 +96,10 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off } - private void CloseWindow(object o, EventArgs e) - { - PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); - this.containerWindowToClose.Close(); - } - private void CancelButton_Click(object sender, EventArgs mouseEvent) { PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); - if (GetPrinterRecordCount() > 0) - { - this.windowController.ChangeToChoosePrinter(); - } - else - { - UiThread.RunOnIdle(() => - { - Parent.Close(); - }); - } + UiThread.RunOnIdle(connectionWizard.Close); } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/SetupStepBaudRate.cs b/PrinterControls/PrinterConnections/SetupStepBaudRate.cs index bbff5ad14..f23416df8 100644 --- a/PrinterControls/PrinterConnections/SetupStepBaudRate.cs +++ b/PrinterControls/PrinterConnections/SetupStepBaudRate.cs @@ -19,8 +19,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private Button printerBaudRateHelpLink; private TextWidget printerBaudRateHelpMessage; - public SetupStepBaudRate(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinterStatus) - : base(windowController, containerWindowToClose, setupPrinterStatus) + public SetupStepBaudRate(ConnectionWizard connectionWizard) : base(connectionWizard) { linkButtonFactory.fontSize = 8; @@ -49,7 +48,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections string baudRateLabelTextFull = string.Format("{0}:", baudRateLabelText); TextWidget baudRateLabel = new TextWidget(baudRateLabelTextFull, 0, 0, 12); - baudRateLabel.TextColor = this.defaultTextColor; + baudRateLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor; baudRateLabel.Margin = new BorderDouble(0, 0, 0, 10); baudRateLabel.HAnchor = HAnchor.ParentLeftRight; @@ -104,7 +103,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections BaudRateRadioButton baudOption = new BaudRateRadioButton(baudRate); BaudRateButtonsList.Add(baudOption); baudOption.Margin = baudRateMargin; - baudOption.TextColor = this.subContainerTextColor; + baudOption.TextColor = ActiveTheme.Instance.PrimaryTextColor; if (this.ActivePrinter.BaudRate == baudRate) { baudOption.Checked = true; @@ -114,7 +113,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections otherBaudRateRadioButton = new RadioButton(LocalizedString.Get("Other")); otherBaudRateRadioButton.Margin = baudRateMargin; - otherBaudRateRadioButton.TextColor = this.subContainerTextColor; + otherBaudRateRadioButton.TextColor = ActiveTheme.Instance.PrimaryTextColor; baudRateContainer.AddChild(otherBaudRateRadioButton); @@ -160,35 +159,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections } } - private void RecreateCurrentWidget() - { - // you can call this like this - // AfterUiEvents.AddAction(new AfterUIAction(RecreateCurrentWidget)); - - Parent.AddChild(new EditConnectionWidget((ConnectionWindow)Parent, Parent, ActivePrinter)); - Parent.RemoveChild(this); - } - - private void ReloadCurrentWidget(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(RecreateCurrentWidget); - } - private void MoveToNextWidget() { - // you can call this like this - // AfterUiEvents.AddAction(new AfterUIAction(MoveToNextWidget)); - - if (this.currentPrinterSetupStatus.DriversToInstall.Count > 0) - { - Parent.AddChild(new SetupStepInstallDriver((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else - { - Parent.AddChild(new SetupStepComPortOne((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } + connectionWizard.ChangeToInstallDriverOrComPortOne(); } private void NextButton_Click(object sender, EventArgs mouseEvent) diff --git a/PrinterControls/PrinterConnections/SetupStepComPortManual.cs b/PrinterControls/PrinterConnections/SetupStepComPortManual.cs index b2568cd63..51c17eb71 100644 --- a/PrinterControls/PrinterConnections/SetupStepComPortManual.cs +++ b/PrinterControls/PrinterConnections/SetupStepComPortManual.cs @@ -3,61 +3,54 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.PrinterCommunication; - +using MatterHackers.MatterControl.SlicerConfiguration; using System; namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { public class SetupStepComPortManual : SetupConnectionWidgetBase { - private TextWidget printerComPortError; - - //GuiWidget comPortWidget; private Button nextButton; - private Button connectButton; private Button refreshButton; private Button printerComPortHelpLink; - private TextWidget printerComPortHelpMessage; - public SetupStepComPortManual(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinterStatus) - : base(windowController, containerWindowToClose, setupPrinterStatus) + private TextWidget printerComPortHelpMessage; + private TextWidget printerComPortError; + + private event EventHandler unregisterEvents; + + public SetupStepComPortManual(ConnectionWizard connectionWizard) : base(connectionWizard) { linkButtonFactory.fontSize = 8; FlowLayoutWidget printerComPortContainer = createComPortContainer(); contentRow.AddChild(printerComPortContainer); - { - //Construct buttons - nextButton = textImageButtonFactory.Generate(LocalizedString.Get("Done")); - nextButton.Click += new EventHandler(NextButton_Click); - nextButton.Visible = false; - connectButton = textImageButtonFactory.Generate(LocalizedString.Get("Connect")); - connectButton.Click += new EventHandler(ConnectButton_Click); + //Construct buttons + nextButton = textImageButtonFactory.Generate("Done".Localize()); + nextButton.Click += (s, e) => UiThread.RunOnIdle(Parent.Close); + nextButton.Visible = false; - PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); + connectButton = textImageButtonFactory.Generate("Connect".Localize()); + connectButton.Click += ConnectButton_Click; - refreshButton = textImageButtonFactory.Generate(LocalizedString.Get("Refresh")); - refreshButton.Click += new EventHandler(RefreshButton_Click); + refreshButton = textImageButtonFactory.Generate("Refresh".Localize()); + refreshButton.Click += (s, e) => connectionWizard.ChangeToSetupComPortManual(); - //Add buttons to buttonContainer - footerRow.AddChild(nextButton); - footerRow.AddChild(connectButton); - footerRow.AddChild(refreshButton); - footerRow.AddChild(new HorizontalSpacer()); - footerRow.AddChild(cancelButton); - } + //Add buttons to buttonContainer + footerRow.AddChild(nextButton); + footerRow.AddChild(connectButton); + footerRow.AddChild(refreshButton); + footerRow.AddChild(new HorizontalSpacer()); + footerRow.AddChild(cancelButton); + + PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); } - private event EventHandler unregisterEvents; - public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -72,7 +65,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections string serialPortLabelFull = string.Format("{0}:", serialPortLabel); TextWidget comPortLabel = new TextWidget(serialPortLabelFull, 0, 0, 12); - comPortLabel.TextColor = this.defaultTextColor; + comPortLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor; comPortLabel.Margin = new BorderDouble(0, 0, 0, 10); comPortLabel.HAnchor = HAnchor.ParentLeftRight; @@ -83,16 +76,16 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections comPortMessageContainer.Margin = elementMargin; comPortMessageContainer.HAnchor = HAnchor.ParentLeftRight; - printerComPortError = new TextWidget(LocalizedString.Get("Currently available serial ports."), 0, 0, 10); + printerComPortError = new TextWidget("Currently available serial ports.".Localize(), 0, 0, 10); printerComPortError.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerComPortError.AutoExpandBoundsToText = true; - printerComPortHelpLink = linkButtonFactory.Generate(LocalizedString.Get("What's this?")); + printerComPortHelpLink = linkButtonFactory.Generate("What's this?".Localize()); printerComPortHelpLink.Margin = new BorderDouble(left: 5); printerComPortHelpLink.VAnchor = VAnchor.ParentBottom; - printerComPortHelpLink.Click += new EventHandler(printerComPortHelp_Click); + printerComPortHelpLink.Click += (s, e) => printerComPortHelpMessage.Visible = !printerComPortHelpMessage.Visible; - printerComPortHelpMessage = new TextWidget(LocalizedString.Get("The 'Serial Port' identifies which connected device is\nyour printer. Changing which usb plug you use may\nchange the associated serial port.\n\nTip: If you are uncertain, plug-in in your printer and hit\nrefresh. The new port that appears should be your\nprinter."), 0, 0, 10); + printerComPortHelpMessage = new TextWidget("The 'Serial Port' identifies which connected device is\nyour printer. Changing which usb plug you use may\nchange the associated serial port.\n\nTip: If you are uncertain, plug-in in your printer and hit\nrefresh. The new port that appears should be your\nprinter.".Localize(), 0, 0, 10); printerComPortHelpMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerComPortHelpMessage.Margin = new BorderDouble(top: 10); printerComPortHelpMessage.Visible = false; @@ -113,83 +106,41 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { if (PrinterConnectionAndCommunication.Instance.PrinterIsConnected) { - onConnectionSuccess(); + printerComPortHelpLink.Visible = false; + printerComPortError.TextColor = ActiveTheme.Instance.PrimaryTextColor; + printerComPortError.Text = "Connection succeeded".Localize() + "!"; + nextButton.Visible = true; + connectButton.Visible = false; + UiThread.RunOnIdle(Parent.Close); } else if (PrinterConnectionAndCommunication.Instance.CommunicationState != PrinterConnectionAndCommunication.CommunicationStates.AttemptingToConnect) { - onConnectionFailed(); + printerComPortHelpLink.Visible = false; + printerComPortError.TextColor = RGBA_Bytes.Red; + printerComPortError.Text = "Uh-oh! Could not connect to printer.".Localize(); + connectButton.Visible = true; + nextButton.Visible = false; } } - private void onConnectionFailed() - { - printerComPortHelpLink.Visible = false; - printerComPortError.TextColor = RGBA_Bytes.Red; - printerComPortError.Text = LocalizedString.Get("Uh-oh! Could not connect to printer."); - connectButton.Visible = true; - nextButton.Visible = false; - } - - private void onConnectionSuccess() - { - printerComPortHelpLink.Visible = false; - printerComPortError.TextColor = this.subContainerTextColor; - printerComPortError.Text = LocalizedString.Get("Connection succeeded!"); - nextButton.Visible = true; - connectButton.Visible = false; - UiThread.RunOnIdle(Parent.Close); - } - - private void printerComPortHelp_Click(object sender, EventArgs mouseEvent) - { - printerComPortHelpMessage.Visible = !printerComPortHelpMessage.Visible; - } - private void MoveToNextWidget(object state) { - // you can call this like this - // AfterUiEvents.AddAction(new AfterUIAction(MoveToNextWidget)); - - if (this.currentPrinterSetupStatus.DriversToInstall.Count > 0) - { - Parent.AddChild(new SetupStepInstallDriver((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else - { - Parent.AddChild(new SetupStepComPortOne((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - } - - private void RecreateCurrentWidget() - { - Parent.AddChild(new SetupStepComPortManual((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - - private void RefreshButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(RecreateCurrentWidget); + connectionWizard.ChangeToInstallDriverOrComPortOne(); } private void ConnectButton_Click(object sender, EventArgs mouseEvent) { - string serialPort; try { - serialPort = GetSelectedSerialPort(); - this.ActivePrinter.ComPort = serialPort; - this.ActivePrinter.Commit(); printerComPortHelpLink.Visible = false; - printerComPortError.TextColor = this.subContainerTextColor; - string printerComPortErrorLabel = LocalizedString.Get("Attempting to connect"); - string printerComPortErrorLabelFull = string.Format("{0}...", printerComPortErrorLabel); - printerComPortError.Text = printerComPortErrorLabelFull; printerComPortError.TextColor = ActiveTheme.Instance.PrimaryTextColor; - ActivePrinterProfile.Instance.ActivePrinter = this.ActivePrinter; + printerComPortError.Text = "Attempting to connect".Localize() + "..."; + printerComPortError.TextColor = ActiveTheme.Instance.PrimaryTextColor; + + ActiveSliceSettings.Instance.ComPort = GetSelectedSerialPort(); PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); + connectButton.Visible = false; refreshButton.Visible = false; } @@ -197,13 +148,8 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { printerComPortHelpLink.Visible = false; printerComPortError.TextColor = RGBA_Bytes.Red; - printerComPortError.Text = LocalizedString.Get("Oops! Please select a serial port."); + printerComPortError.Text = "Oops! Please select a serial port.".Localize(); } } - - private void NextButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(Parent.Close); - } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/SetupStepComPortOne.cs b/PrinterControls/PrinterConnections/SetupStepComPortOne.cs index 5094e24ad..5fef29bb7 100644 --- a/PrinterControls/PrinterConnections/SetupStepComPortOne.cs +++ b/PrinterControls/PrinterConnections/SetupStepComPortOne.cs @@ -11,14 +11,13 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { private Button nextButton; - public SetupStepComPortOne(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinter) - : base(windowController, containerWindowToClose, setupPrinter) + public SetupStepComPortOne(ConnectionWizard connectionWizard) : base(connectionWizard) { contentRow.AddChild(createPrinterConnectionMessageContainer()); { //Construct buttons - nextButton = textImageButtonFactory.Generate(LocalizedString.Get("Continue")); - nextButton.Click += new EventHandler(NextButton_Click); + nextButton = textImageButtonFactory.Generate("Continue".Localize()); + nextButton.Click += (s, e) => connectionWizard.ChangeToSetupCompPortTwo(); //Add buttons to buttonContainer footerRow.AddChild(nextButton); @@ -68,7 +67,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections Button manualLink = linkButtonFactory.Generate(LocalizedString.Get("Manually Configure Connection")); manualLink.Margin = new BorderDouble(0, 5); - manualLink.Click += new EventHandler(ManualLink_Click); + manualLink.Click += (s, e) => connectionWizard.ChangeToSetupComPortManual(); string printerMessageFourText = LocalizedString.Get("or"); TextWidget printerMessageFour = new TextWidget(printerMessageFourText, 0, 0, 10); @@ -93,39 +92,10 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return container; } - private void ManualLink_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(MoveToManualConfiguration); - } - - private void MoveToManualConfiguration() - { - Parent.AddChild(new SetupStepComPortManual((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - - private void NextButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(MoveToNextWidget); - } - - private void MoveToNextWidget() - { - Parent.AddChild(new SetupStepComPortTwo((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - private void SkipConnectionLink_Click(object sender, EventArgs mouseEvent) { PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); - if (GetPrinterRecordCount() > 0) - { - this.windowController.ChangeToChoosePrinter(); - } - else - { - Parent.Close(); - } + Parent.Close(); } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs b/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs index c00561499..7d2b8c561 100644 --- a/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs +++ b/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs @@ -3,6 +3,7 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.PrinterCommunication; +using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.SerialPortCommunication.FrostedSerial; using System; using System.Linq; @@ -19,19 +20,18 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private event EventHandler unregisterEvents; - public SetupStepComPortTwo(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinterStatus) - : base(windowController, containerWindowToClose, setupPrinterStatus) + public SetupStepComPortTwo(ConnectionWizard windowController) : base(windowController) { startingPortNames = FrostedSerialPort.GetPortNames(); contentRow.AddChild(createPrinterConnectionMessageContainer()); { //Construct buttons - nextButton = textImageButtonFactory.Generate(LocalizedString.Get("Done")); - nextButton.Click += new EventHandler(NextButton_Click); + nextButton = textImageButtonFactory.Generate("Done".Localize()); + nextButton.Click += (s, e) => UiThread.RunOnIdle(Parent.Close); nextButton.Visible = false; - connectButton = textImageButtonFactory.Generate(LocalizedString.Get("Connect")); - connectButton.Click += new EventHandler(ConnectButton_Click); + connectButton = textImageButtonFactory.Generate("Connect".Localize()); + connectButton.Click += ConnectButton_Click; PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); @@ -45,10 +45,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -59,38 +56,36 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections container.Margin = new BorderDouble(5); BorderDouble elementMargin = new BorderDouble(top: 5); - string printerMessageOneText = LocalizedString.Get("MatterControl will now attempt to auto-detect printer."); + string printerMessageOneText = "MatterControl will now attempt to auto-detect printer.".Localize(); TextWidget printerMessageOne = new TextWidget(printerMessageOneText, 0, 0, 10); printerMessageOne.Margin = new BorderDouble(0, 10, 0, 5); printerMessageOne.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerMessageOne.HAnchor = HAnchor.ParentLeftRight; printerMessageOne.Margin = elementMargin; - string printerMessageTwoTxtBeg = LocalizedString.Get("Disconnect printer"); - string printerMessageTwoTxtEnd = LocalizedString.Get("if currently connected"); - string printerMessageTwoTxtFull = string.Format("1.) {0} ({1}).", printerMessageTwoTxtBeg, printerMessageTwoTxtEnd); - TextWidget printerMessageTwo = new TextWidget(printerMessageTwoTxtFull, 0, 0, 12); + string disconnectMessage = string.Format("1.) {0} ({1}).", "Disconnect printer".Localize(), "if currently connected".Localize()); + TextWidget printerMessageTwo = new TextWidget(disconnectMessage, 0, 0, 12); printerMessageTwo.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerMessageTwo.HAnchor = HAnchor.ParentLeftRight; printerMessageTwo.Margin = elementMargin; - string printerMessageThreeTxtBeg = LocalizedString.Get("Press"); - string printerMessageThreeTxtEnd = LocalizedString.Get("Continue"); + string printerMessageThreeTxtBeg = "Press".Localize(); + string printerMessageThreeTxtEnd = "Continue".Localize(); string printerMessageThreeTxtFull = string.Format("2.) {0} '{1}'.", printerMessageThreeTxtBeg, printerMessageThreeTxtEnd); TextWidget printerMessageThree = new TextWidget(printerMessageThreeTxtFull, 0, 0, 12); printerMessageThree.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerMessageThree.HAnchor = HAnchor.ParentLeftRight; printerMessageThree.Margin = elementMargin; - string printerMessageFourBeg = LocalizedString.Get("Power on and connect printer"); + string printerMessageFourBeg = "Power on and connect printer".Localize(); string printerMessageFourFull = string.Format("3.) {0}.", printerMessageFourBeg); TextWidget printerMessageFour = new TextWidget(printerMessageFourFull, 0, 0, 12); printerMessageFour.TextColor = ActiveTheme.Instance.PrimaryTextColor; printerMessageFour.HAnchor = HAnchor.ParentLeftRight; printerMessageFour.Margin = elementMargin; - string printerMessageFiveTxtBeg = LocalizedString.Get("Press"); - string printerMessageFiveTxtEnd = LocalizedString.Get("Connect"); + string printerMessageFiveTxtBeg = "Press".Localize(); + string printerMessageFiveTxtEnd = "Connect".Localize(); string printerMessageFiveTxtFull = string.Format("4.) {0} '{1}'.", printerMessageFiveTxtBeg, printerMessageFiveTxtEnd); TextWidget printerMessageFive = new TextWidget(printerMessageFiveTxtFull, 0, 0, 12); printerMessageFive.TextColor = ActiveTheme.Instance.PrimaryTextColor; @@ -100,9 +95,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections GuiWidget vSpacer = new GuiWidget(); vSpacer.VAnchor = VAnchor.ParentBottomTop; - Button manualLink = linkButtonFactory.Generate(LocalizedString.Get("Manual Configuration")); + Button manualLink = linkButtonFactory.Generate("Manual Configuration".Localize()); manualLink.Margin = new BorderDouble(0, 5); - manualLink.Click += new EventHandler(ManualLink_Click); + manualLink.Click += (s, e) => connectionWizard.ChangeToSetupComPortManual(); printerErrorMessage = new TextWidget("", 0, 0, 10); printerErrorMessage.AutoExpandBoundsToText = true; @@ -123,17 +118,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return container; } - private void ManualLink_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(MoveToManualConfiguration); - } - - private void MoveToManualConfiguration() - { - Parent.AddChild(new SetupStepComPortManual((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - private void ConnectButton_Click(object sender, EventArgs mouseEvent) { // Select the first port that's in GetPortNames() but not in startingPortNames @@ -141,18 +125,14 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections if (candidatePort == null) { printerErrorMessage.TextColor = RGBA_Bytes.Red; - string printerErrorMessageLabelFull = LocalizedString.Get("Oops! Printer could not be detected "); - printerErrorMessage.Text = printerErrorMessageLabelFull; + printerErrorMessage.Text = "Oops! Printer could not be detected ".Localize(); } else { - ActivePrinter.ComPort = candidatePort; printerErrorMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; - string printerErrorMessageLabelTwo = LocalizedString.Get("Attempting to connect"); - string printerErrorMessageLabelTwoFull = string.Format("{0}...", printerErrorMessageLabelTwo); - printerErrorMessage.Text = printerErrorMessageLabelTwoFull; - this.ActivePrinter.Commit(); - ActivePrinterProfile.Instance.ActivePrinter = this.ActivePrinter; + printerErrorMessage.Text = "Attempting to connect".Localize() + "..."; + + ActiveSliceSettings.Instance.ComPort = candidatePort; PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); connectButton.Visible = false; } @@ -162,36 +142,19 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { if (PrinterConnectionAndCommunication.Instance.PrinterIsConnected) { - onConnectionSuccess(); + printerErrorMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; + printerErrorMessage.Text = "Connection succeeded".Localize() + "!"; + nextButton.Visible = true; + connectButton.Visible = false; + UiThread.RunOnIdle(Parent.Close); } else if (PrinterConnectionAndCommunication.Instance.CommunicationState != PrinterConnectionAndCommunication.CommunicationStates.AttemptingToConnect) { - onConnectionFailed(); + printerErrorMessage.TextColor = RGBA_Bytes.Red; + printerErrorMessage.Text = "Uh-oh! Could not connect to printer.".Localize(); + connectButton.Visible = true; + nextButton.Visible = false; } } - - private void onConnectionFailed() - { - printerErrorMessage.TextColor = RGBA_Bytes.Red; - printerErrorMessage.Text = LocalizedString.Get("Uh-oh! Could not connect to printer."); - connectButton.Visible = true; - nextButton.Visible = false; - } - - private void onConnectionSuccess() - { - printerErrorMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; - string printerErrorMessageLabelThree = LocalizedString.Get("Connection succeeded"); - string printerErrorMessageLabelThreeFull = string.Format("{0}!", printerErrorMessageLabelThree); - printerErrorMessage.Text = printerErrorMessageLabelThreeFull; - nextButton.Visible = true; - connectButton.Visible = false; - UiThread.RunOnIdle(Parent.Close); - } - - private void NextButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(Parent.Close); - } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/SetupStepConfigureConnection.cs b/PrinterControls/PrinterConnections/SetupStepConfigureConnection.cs index 6830cf8a7..e6ad997b8 100644 --- a/PrinterControls/PrinterConnections/SetupStepConfigureConnection.cs +++ b/PrinterControls/PrinterConnections/SetupStepConfigureConnection.cs @@ -36,93 +36,47 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { public class SetupStepConfigureConnection : SetupConnectionWidgetBase { - private Button nextButton; - private Button skipButton; - private TextWidget printerErrorMessage; - - public SetupStepConfigureConnection(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinter) - : base(windowController, containerWindowToClose, setupPrinter) + public SetupStepConfigureConnection(ConnectionWizard connectionWizard) : base(connectionWizard) { - contentRow.AddChild(createPrinterConnectionMessageContainer()); - { - //Construct buttons - nextButton = textImageButtonFactory.Generate("Connect"); - nextButton.Click += new EventHandler(NextButton_Click); - - skipButton = textImageButtonFactory.Generate("Skip"); - skipButton.Click += new EventHandler(SkipButton_Click); - - //Add buttons to buttonContainer - footerRow.AddChild(nextButton); - footerRow.AddChild(skipButton); - footerRow.AddChild(new HorizontalSpacer()); - footerRow.AddChild(cancelButton); - } - } - - public FlowLayoutWidget createPrinterConnectionMessageContainer() - { - FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); - container.Margin = new BorderDouble(5); BorderDouble elementMargin = new BorderDouble(top: 5); - TextWidget continueMessage = new TextWidget("Would you like to connect to this printer now?", 0, 0, 12); + var continueMessage = new TextWidget("Would you like to connect to this printer now?", 0, 0, 12); continueMessage.AutoExpandBoundsToText = true; continueMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; continueMessage.HAnchor = HAnchor.ParentLeftRight; continueMessage.Margin = elementMargin; - TextWidget continueMessageTwo = new TextWidget("You can always configure this later.", 0, 0, 10); + var continueMessageTwo = new TextWidget("You can always configure this later.", 0, 0, 10); continueMessageTwo.AutoExpandBoundsToText = true; continueMessageTwo.TextColor = ActiveTheme.Instance.PrimaryTextColor; continueMessageTwo.HAnchor = HAnchor.ParentLeftRight; continueMessageTwo.Margin = elementMargin; - printerErrorMessage = new TextWidget("", 0, 0, 10); + var printerErrorMessage = new TextWidget("", 0, 0, 10); printerErrorMessage.AutoExpandBoundsToText = true; printerErrorMessage.TextColor = RGBA_Bytes.Red; printerErrorMessage.HAnchor = HAnchor.ParentLeftRight; printerErrorMessage.Margin = elementMargin; + var container = new FlowLayoutWidget(FlowDirection.TopToBottom); + container.Margin = new BorderDouble(5); container.AddChild(continueMessage); container.AddChild(continueMessageTwo); container.AddChild(printerErrorMessage); - container.HAnchor = HAnchor.ParentLeftRight; - return container; - } - private void SkipButton_Click(object sender, EventArgs e) - { - //Save the printer info to the datastore and exit the setup process - this.ActivePrinter.Commit(); - SaveAndExit(); - } + //Construct buttons + var nextButton = textImageButtonFactory.Generate("Connect"); + nextButton.Click += (s, e) => base.connectionWizard.ChangeToSetupBaudOrComPortOne(); - private void MoveToNextWidget() - { - // you can call this like this - // AfterUiEvents.AddAction(new AfterUIAction(MoveToNextWidget)); - if (this.ActivePrinter.BaudRate == null) - { - Parent.AddChild(new SetupStepBaudRate((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else if (this.currentPrinterSetupStatus.DriversToInstall.Count > 0) - { - Parent.AddChild(new SetupStepInstallDriver((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else - { - Parent.AddChild(new SetupStepComPortOne((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - } + var skipButton = textImageButtonFactory.Generate("Skip"); + skipButton.Click += (s, e) => SaveAndExit(); - private void NextButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(MoveToNextWidget); + //Add buttons to buttonContainer + footerRow.AddChild(nextButton); + footerRow.AddChild(skipButton); + footerRow.AddChild(new HorizontalSpacer()); + footerRow.AddChild(cancelButton); } } } \ No newline at end of file diff --git a/PrinterControls/PrinterConnections/SetupStepInstallDriver.cs b/PrinterControls/PrinterConnections/SetupStepInstallDriver.cs index 7f0f28e88..e5b288515 100644 --- a/PrinterControls/PrinterConnections/SetupStepInstallDriver.cs +++ b/PrinterControls/PrinterConnections/SetupStepInstallDriver.cs @@ -3,6 +3,7 @@ using MatterHackers.Agg.PlatformAbstract; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; +using MatterHackers.MatterControl.SlicerConfiguration; using System; using System.Collections.Generic; using System.Diagnostics; @@ -14,18 +15,13 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { private FlowLayoutWidget printerDriverContainer; private TextWidget printerDriverMessage; - private List driversToInstall; - - //bool driverInstallFinished; private Button installButton; private Button skipButton; - public SetupStepInstallDriver(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus setupPrinterStatus) - : base(windowController, containerWindowToClose, setupPrinterStatus) + public SetupStepInstallDriver(ConnectionWizard windowController) + : base(windowController) { - this.driversToInstall = this.currentPrinterSetupStatus.DriversToInstall; - headerLabel.Text = string.Format(LocalizedString.Get("Install Communication Driver")); printerDriverContainer = createPrinterDriverContainer(); contentRow.AddChild(printerDriverContainer); @@ -34,35 +30,27 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections installButton = textImageButtonFactory.Generate(LocalizedString.Get("Install Driver")); installButton.Click += (sender, e) => { - UiThread.RunOnIdle(installButton_Click); + UiThread.RunOnIdle(() => + { + bool canContinue = this.InstallDriver(); + if (canContinue) + { + connectionWizard.ChangeToSetupBaudOrComPortOne(); + } + }); }; skipButton = textImageButtonFactory.Generate(LocalizedString.Get("Skip")); - skipButton.Click += new EventHandler(skipButton_Click); + skipButton.Click += (s, e) => connectionWizard.ChangeToSetupBaudOrComPortOne(); //Add buttons to buttonContainer footerRow.AddChild(installButton); footerRow.AddChild(skipButton); footerRow.AddChild(new HorizontalSpacer()); - footerRow.AddChild(cancelButton); } } - private void installButton_Click() - { - bool canContinue = this.OnSave(); - if (canContinue) - { - UiThread.RunOnIdle(MoveToNextWidget); - } - } - - private void skipButton_Click(object sender, EventArgs mouseEvent) - { - UiThread.RunOnIdle(MoveToNextWidget); - } - private FlowLayoutWidget createPrinterDriverContainer() { FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); @@ -86,23 +74,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return container; } - private void MoveToNextWidget() - { - // you can call this like this - // AfterUiEvents.AddAction(new AfterUIAction(MoveToNextWidget)); - - if (this.ActivePrinter.BaudRate == null) - { - Parent.AddChild(new SetupStepBaudRate((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else - { - Parent.AddChild(new SetupStepComPortOne((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - } - private void InstallDriver(string fileName) { switch (OsInformation.OperatingSystem) @@ -114,9 +85,10 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { Process driverInstallerProcess = new Process(); // Prepare the process to run + // Enter in the command line arguments, everything you would enter after the executable name itself - driverInstallerProcess.StartInfo.Arguments = Path.GetFullPath(fileName); + // Enter the executable to run, including the complete path string printerDriverInstallerExePathAndFileName = Path.GetFullPath(Path.Combine(".", "InfInstaller.exe")); @@ -137,7 +109,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections } else { - throw new Exception(string.Format("Can't find dirver {0}.", fileName)); + throw new Exception(string.Format("Can't find driver {0}.", fileName)); } break; @@ -151,8 +123,10 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { var driverInstallerProcess = new Process(); // Prepare the process to run + // Enter in the command line arguments, everything you would enter after the executable name itself driverInstallerProcess.StartInfo.Arguments = Path.GetFullPath(fileName); + // Enter the executable to run, including the complete path string printerDriverInstallerExePathAndFileName = Path.Combine(".", "InfInstaller.exe"); @@ -177,28 +151,28 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections } else { - throw new Exception(string.Format("Can't find dirver {0}.", fileName)); + throw new Exception("Can't find driver: " + fileName); } break; } } - private bool OnSave() + private bool InstallDriver() { try { - string printerDriverMessageLabel = LocalizedString.Get("Installing"); - string printerDriverMessageLabelFull = string.Format("{0}...", printerDriverMessageLabel); - printerDriverMessage.Text = printerDriverMessageLabelFull; - foreach (string driverPath in this.driversToInstall) + printerDriverMessage.Text = "Installing".Localize() + "..."; + + foreach (string driverPath in ActiveSliceSettings.Instance.PrinterDrivers()) { InstallDriver(driverPath); } + return true; } catch (Exception) { - printerDriverMessage.Text = LocalizedString.Get("Sorry, we were unable to install the driver."); + printerDriverMessage.Text = "Sorry, we were unable to install the driver.".Localize(); return false; } } diff --git a/PrinterControls/PrinterConnections/SetupStepMakeModelName.cs b/PrinterControls/PrinterConnections/SetupStepMakeModelName.cs index d9de33bf7..4638b03b3 100644 --- a/PrinterControls/PrinterConnections/SetupStepMakeModelName.cs +++ b/PrinterControls/PrinterConnections/SetupStepMakeModelName.cs @@ -7,6 +7,7 @@ using MatterHackers.MatterControl.SettingsManagement; using System.Collections.Generic; using System.Linq; using MatterHackers.MatterControl.CustomWidgets; +using MatterHackers.MatterControl.SlicerConfiguration; namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections { @@ -19,8 +20,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private MHTextEditWidget printerNameInput; - private List printerCustomCommands; - private TextWidget printerNameError; private TextWidget printerModelError; private TextWidget printerMakeError; @@ -31,8 +30,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private bool usingDefaultName; - public SetupStepMakeModelName(ConnectionWindow windowController, GuiWidget containerWindowToClose, PrinterSetupStatus printerSetupStatus = null) - : base(windowController, containerWindowToClose, printerSetupStatus) + public SetupStepMakeModelName(ConnectionWizard windowController) : base(windowController) { //Construct inputs printerNameContainer = createPrinterNameContainer(); @@ -59,7 +57,14 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections //Construct buttons nextButton = textImageButtonFactory.Generate(LocalizedString.Get("Save & Continue")); nextButton.Name = "Save & Continue Button"; - nextButton.Click += new EventHandler(NextButton_Click); + nextButton.Click += (s, e) => + { + bool canContinue = this.OnSave(); + if (canContinue) + { + UiThread.RunOnIdle(connectionWizard.Close); + } + }; //Add buttons to buttonContainer footerRow.AddChild(nextButton); @@ -68,10 +73,10 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections usingDefaultName = true; - SetElementState(); + SetElementVisibility(); } - private void SetElementState() + private void SetElementVisibility() { printerModelContainer.Visible = (this.ActivePrinter.Make != null); nextButton.Visible = (this.ActivePrinter.Model != null && this.ActivePrinter.Make != null); @@ -79,93 +84,104 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private FlowLayoutWidget createPrinterNameContainer() { + TextWidget printerNameLabel = new TextWidget("Name".Localize() + ":", 0, 0, 12) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = new BorderDouble(0, 0, 0, 1) + }; + + printerNameInput = new MHTextEditWidget(this.ActivePrinter.Name) + { + HAnchor = HAnchor.ParentLeftRight, + }; + printerNameInput.KeyPressed += (s, e) => this.usingDefaultName = false; + + printerNameError = new TextWidget("Give your printer a name.".Localize(), 0, 0, 10) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = new BorderDouble(top: 3) + }; + FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); container.Margin = new BorderDouble(0, 5); - BorderDouble elementMargin = new BorderDouble(top: 3); - - string printerNameLabelTxt = LocalizedString.Get("Name"); - string printerNameLabelTxtFull = string.Format("{0}:", printerNameLabelTxt); - TextWidget printerNameLabel = new TextWidget(printerNameLabelTxtFull, 0, 0, 12); - printerNameLabel.TextColor = this.defaultTextColor; - printerNameLabel.HAnchor = HAnchor.ParentLeftRight; - printerNameLabel.Margin = new BorderDouble(0, 0, 0, 1); - - printerNameInput = new MHTextEditWidget(this.ActivePrinter.Name); - printerNameInput.HAnchor = HAnchor.ParentLeftRight; - printerNameInput.KeyPressed += PrinterNameInput_KeyPressed; - - printerNameError = new TextWidget(LocalizedString.Get("Give your printer a name."), 0, 0, 10); - printerNameError.TextColor = ActiveTheme.Instance.PrimaryTextColor; - printerNameError.HAnchor = HAnchor.ParentLeftRight; - printerNameError.Margin = elementMargin; - container.AddChild(printerNameLabel); container.AddChild(printerNameInput); container.AddChild(printerNameError); container.HAnchor = HAnchor.ParentLeftRight; + return container; } private FlowLayoutWidget createPrinterMakeContainer() { - FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); - container.Margin = new BorderDouble(0, 5); BorderDouble elementMargin = new BorderDouble(top: 3); - string printerManufacturerLabelTxt = LocalizedString.Get("Make"); - string printerManufacturerLabelTxtFull = string.Format("{0}:", printerManufacturerLabelTxt); - TextWidget printerManufacturerLabel = new TextWidget(printerManufacturerLabelTxtFull, 0, 0, 12); - printerManufacturerLabel.TextColor = this.defaultTextColor; - printerManufacturerLabel.HAnchor = HAnchor.ParentLeftRight; - printerManufacturerLabel.Margin = elementMargin; + TextWidget printerManufacturerLabel = new TextWidget("Make".Localize() + ":", 0, 0, 12) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; - printerManufacturerSelector = new PrinterChooser(); - printerManufacturerSelector.HAnchor = HAnchor.ParentLeftRight; - printerManufacturerSelector.Margin = elementMargin; - printerManufacturerSelector.ManufacturerDropList.SelectionChanged += new EventHandler(ManufacturerDropList_SelectionChanged); + printerManufacturerSelector = new PrinterChooser() + { + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; + printerManufacturerSelector.ManufacturerDropList.SelectionChanged += ManufacturerDropList_SelectionChanged; - printerMakeError = new TextWidget(LocalizedString.Get("Select the printer manufacturer"), 0, 0, 10); - printerMakeError.TextColor = ActiveTheme.Instance.PrimaryTextColor; - printerMakeError.HAnchor = HAnchor.ParentLeftRight; - printerMakeError.Margin = elementMargin; + printerMakeError = new TextWidget("Select the printer manufacturer".Localize(), 0, 0, 10) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; + FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); + container.Margin = new BorderDouble(0, 5); container.AddChild(printerManufacturerLabel); container.AddChild(printerManufacturerSelector); container.AddChild(printerMakeError); - container.HAnchor = HAnchor.ParentLeftRight; + return container; } private FlowLayoutWidget createPrinterModelContainer(string make = "Other") { - FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); - container.Margin = new BorderDouble(0, 5); BorderDouble elementMargin = new BorderDouble(top: 3); - string printerModelLabelTxt = LocalizedString.Get("Model"); - string printerModelLabelTxtFull = string.Format("{0}:", printerModelLabelTxt); - TextWidget printerModelLabel = new TextWidget(printerModelLabelTxtFull, 0, 0, 12); - printerModelLabel.TextColor = this.defaultTextColor; - printerModelLabel.HAnchor = HAnchor.ParentLeftRight; - printerModelLabel.Margin = elementMargin; + TextWidget printerModelLabel = new TextWidget("Model".Localize() + ":", 0, 0, 12) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; - ModelChooser printerModelSelector = new ModelChooser(make); - printerModelSelector.HAnchor = HAnchor.ParentLeftRight; - printerModelSelector.Margin = elementMargin; + ModelChooser printerModelSelector = new ModelChooser(make) + { + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; printerModelSelector.ModelDropList.SelectionChanged += new EventHandler(ModelDropList_SelectionChanged); printerModelSelector.SelectIfOnlyOneModel(); - printerModelError = new TextWidget(LocalizedString.Get("Select the printer model"), 0, 0, 10); - printerModelError.TextColor = ActiveTheme.Instance.PrimaryTextColor; - printerModelError.HAnchor = HAnchor.ParentLeftRight; - printerModelError.Margin = elementMargin; + printerModelError = new TextWidget("Select the printer model".Localize(), 0, 0, 10) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = HAnchor.ParentLeftRight, + Margin = elementMargin + }; + FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom); + container.Margin = new BorderDouble(0, 5); container.AddChild(printerModelLabel); container.AddChild(printerModelSelector); container.AddChild(printerModelError); - container.HAnchor = HAnchor.ParentLeftRight; + return container; } @@ -174,7 +190,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections ActivePrinter.Make = ((DropDownList)sender).SelectedValue; ActivePrinter.Model = null; ReconstructModelSelector(); - SetElementState(); + SetElementVisibility(); } private void ReconstructModelSelector() @@ -183,8 +199,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections int currentIndex = contentRow.GetChildIndex(printerModelContainer); contentRow.RemoveChild(printerModelContainer); - - printerModelContainer = createPrinterModelContainer(ActivePrinter.Make); contentRow.AddChild(printerModelContainer, currentIndex); contentRow.Invalidate(); @@ -197,101 +211,53 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections UiThread.RunOnIdle(() => { ActivePrinter.Model = ((DropDownList)sender).SelectedLabel; - currentPrinterSetupStatus.LoadSetupSettings(ActivePrinter.Make, ActivePrinter.Model); + printerModelError.Visible = false; - SetElementState(); + SetElementVisibility(); if (usingDefaultName) { // Use ManufacturerDropList.SelectedLabel instead of ActivePrinter.Make to ensure the mapped Unicode values are picked up string mappedMakeText = printerManufacturerSelector.ManufacturerDropList.SelectedLabel; - string printerInputName = String.Format("{0} {1}", mappedMakeText, this.ActivePrinter.Model); - string query = "SELECT Name FROM Printer WHERE Name LIKE @printerName;"; - var names = Datastore.Instance.dbSQLite.Query(query, printerInputName + "%").Select(item => item.Name).ToList(); + string printerInputName = String.Format("{0} {1}", mappedMakeText, this.ActivePrinter.Model); + var names = ActiveSliceSettings.ProfileData.Profiles.Where(p => p.Name.StartsWith(printerInputName)).Select(p => p.Name).ToList(); + if (!names.Contains(printerInputName)) + { + printerNameInput.Text = printerInputName; + } + else + { - if (!names.Contains(printerInputName)) - { - printerNameInput.Text = printerInputName; - } - else - { - - int printerModelCount = 0; //Used to keep track of how many of the printer models we run into before and empty one - string possiblePrinterName; + int printerModelCount = 1; //Used to keep track of how many of the printer models we run into before and empty one + string possiblePrinterName; - do - { - printerModelCount++; - possiblePrinterName = String.Format("{0} ({1})", printerInputName, printerModelCount); - } while (names.Contains(possiblePrinterName)); - - - printerNameInput.Text = possiblePrinterName; - } + do + { + possiblePrinterName = String.Format("{0} ({1})", printerInputName, printerModelCount++); + } while (names.Contains(possiblePrinterName)); + printerNameInput.Text = possiblePrinterName; + } } }); } - private void PrinterNameInput_KeyPressed(object sender, KeyPressEventArgs e) - { - this.usingDefaultName = false; - } - - private void MoveToNextWidget() - { - if (Parent != null) // if it hasn't been closed - { - if (this.ActivePrinter.BaudRate == null) - { - Parent.AddChild(new SetupStepBaudRate((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else if (this.currentPrinterSetupStatus.DriversToInstall.Count > 0) - { - Parent.AddChild(new SetupStepInstallDriver((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - else - { - Parent.AddChild(new SetupStepComPortOne((ConnectionWindow)Parent, Parent, this.currentPrinterSetupStatus)); - Parent.RemoveChild(this); - } - } - } - - private void NextButton_Click(object sender, EventArgs mouseEvent) - { - bool canContinue = this.OnSave(); - if (canContinue) - { - this.currentPrinterSetupStatus.LoadCalibrationPrints(); - UiThread.RunOnIdle(MoveToNextWidget); - } - } - - public int ExistingPrinterCount() - { - return Datastore.Instance.RecordCount("Printer"); - } - - private class sqlName - { - public string Name { get; set; } - } - private bool OnSave() { - if (printerNameInput.Text != "") + if (!string.IsNullOrEmpty(printerNameInput.Text)) { this.ActivePrinter.Name = printerNameInput.Text; + if (this.ActivePrinter.Make == null || this.ActivePrinter.Model == null) { return false; } else { - Datastore.Instance.dbSQLite.RunInTransaction(currentPrinterSetupStatus.Save); + // TODO: Plumb in saving the profile to disk, then setting the instance to be the active profile + System.Diagnostics.Debugger.Launch(); + + ActiveSliceSettings.AcquireNewProfile(ActivePrinter.Make, ActivePrinter.Model, ActivePrinter.Name); return true; } } @@ -300,6 +266,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections this.printerNameError.TextColor = RGBA_Bytes.Red; this.printerNameError.Text = "Printer name cannot be blank"; this.printerNameError.Visible = true; + return false; } } diff --git a/PrinterControls/TemperatureIndicator.cs b/PrinterControls/TemperatureIndicator.cs index b7755cb53..b203d6bca 100644 --- a/PrinterControls/TemperatureIndicator.cs +++ b/PrinterControls/TemperatureIndicator.cs @@ -493,8 +493,8 @@ namespace MatterHackers.MatterControl protected override double GetPreheatTemperature() { - string tempValue = ActiveSliceSettings.Instance.GetMaterialValue("temperature", extruderIndex0Based + 1); - if (tempValue == "Unknown") + string tempValue = ActiveSliceSettings.Instance.GetExtruderTemperature(extruderIndex0Based); + if (string.IsNullOrEmpty(tempValue)) { return 0.0; } diff --git a/Queue/OptionsMenu/ExportToFolderProcess.cs b/Queue/OptionsMenu/ExportToFolderProcess.cs index e5a275550..9fcc2c986 100644 --- a/Queue/OptionsMenu/ExportToFolderProcess.cs +++ b/Queue/OptionsMenu/ExportToFolderProcess.cs @@ -181,7 +181,7 @@ namespace MatterHackers.MatterControl.PrintQueue } } - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; // now copy all the gcode to the path given for (int i = 0; i < savedGCodeFileNames.Count; i++) @@ -191,7 +191,7 @@ namespace MatterHackers.MatterControl.PrintQueue string outputFileName = Path.ChangeExtension(originalFileName, ".gcode"); string outputPathAndName = Path.Combine(exportPath, outputFileName); - if (ActivePrinterProfile.Instance.DoPrintLeveling) + if (ActiveSliceSettings.Instance.DoPrintLeveling) { GCodeFileLoaded unleveledGCode = new GCodeFileLoaded(savedGcodeFileName); diff --git a/Queue/OptionsMenu/QueueOptionsMenu.cs b/Queue/OptionsMenu/QueueOptionsMenu.cs index 24d96bef5..06a14866b 100644 --- a/Queue/OptionsMenu/QueueOptionsMenu.cs +++ b/Queue/OptionsMenu/QueueOptionsMenu.cs @@ -178,7 +178,7 @@ namespace MatterHackers.MatterControl.PrintQueue private bool exportGCodeToFolderButton_Click() { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { UiThread.RunOnIdle(MustSelectPrinterMessage); } @@ -192,7 +192,7 @@ namespace MatterHackers.MatterControl.PrintQueue private bool exportX3GButton_Click() { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { UiThread.RunOnIdle(MustSelectPrinterMessage); } diff --git a/Queue/PrintItemWrapper.cs b/Queue/PrintItemWrapper.cs index be6825cce..018963b9e 100644 --- a/Queue/PrintItemWrapper.cs +++ b/Queue/PrintItemWrapper.cs @@ -268,7 +268,7 @@ namespace MatterHackers.MatterControl.PrintQueue return FileLocation; } - string engineString = ((int)ActivePrinterProfile.Instance.ActiveSliceEngineType).ToString(); + string engineString = ((int)ActiveSliceSettings.Instance.ActiveSliceEngineType).ToString(); string gcodeFileName = this.FileHashCode.ToString() + "_" + engineString + "_" + ActiveSliceSettings.Instance.GetHashCode().ToString(); string gcodePathAndFileName = Path.Combine(ApplicationDataStorage.Instance.GCodeOutputPath, gcodeFileName + ".gcode"); @@ -300,11 +300,11 @@ namespace MatterHackers.MatterControl.PrintQueue } // check if there is a known line at the end of the file (this will let us know if slicer finished building the file). - switch (ActivePrinterProfile.Instance.ActiveSliceEngineType) + switch (ActiveSliceSettings.Instance.ActiveSliceEngineType) { - case ActivePrinterProfile.SlicingEngineTypes.CuraEngine: - case ActivePrinterProfile.SlicingEngineTypes.MatterSlice: - case ActivePrinterProfile.SlicingEngineTypes.Slic3r: + case SlicingEngineTypes.CuraEngine: + case SlicingEngineTypes.MatterSlice: + case SlicingEngineTypes.Slic3r: if (gcodeFileContents.Contains("filament used =")) { gCodeFileIsComplete = true; diff --git a/Queue/QueueDataWidget.cs b/Queue/QueueDataWidget.cs index e6cb0aba3..303810a1f 100644 --- a/Queue/QueueDataWidget.cs +++ b/Queue/QueueDataWidget.cs @@ -192,7 +192,7 @@ namespace MatterHackers.MatterControl.PrintQueue shopButton.Click += (sender, e) => { double activeFilamentDiameter = 0; - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { activeFilamentDiameter = 3; if (ActiveSliceSettings.Instance.FilamentDiameter < 2) @@ -217,7 +217,7 @@ namespace MatterHackers.MatterControl.PrintQueue buttonPanel1.AddChild(queueMenuContainer); } - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent((object sender, EventArgs e) => + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((object sender, EventArgs e) => { queueMenuContainer.RemoveAllChildren(); // the printer changed reload the queueMenue diff --git a/SettingsManagement/PrinterSettings.cs b/SettingsManagement/PrinterSettings.cs index 6fdf638e0..b74aad5c8 100644 --- a/SettingsManagement/PrinterSettings.cs +++ b/SettingsManagement/PrinterSettings.cs @@ -1,4 +1,5 @@ using MatterHackers.MatterControl.DataStorage; +using MatterHackers.MatterControl.SlicerConfiguration; using System.Collections.Generic; namespace MatterHackers.MatterControl @@ -25,8 +26,12 @@ namespace MatterHackers.MatterControl private void LoadDataIfNeeded() { + // TODO: Review int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + //Lazy load the data (rather than hook to printer change event) - if (ActivePrinterProfile.Instance.ActivePrinter.Id != ActiveSettingsPrinterId) + if (printerID != ActiveSettingsPrinterId) { LoadData(); } @@ -35,7 +40,7 @@ namespace MatterHackers.MatterControl public string get(string key) { string result = null; - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { //No printer selected } @@ -53,7 +58,7 @@ namespace MatterHackers.MatterControl public void set(string key, string value) { - if (ActivePrinterProfile.Instance.ActivePrinter == null) + if (ActiveSliceSettings.Instance == null) { //No printer selected } @@ -68,9 +73,13 @@ namespace MatterHackers.MatterControl } else { + // TODO: Review int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + setting = new PrinterSetting(); setting.Name = key; - setting.PrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + setting.PrinterId = printerID; settingsDictionary[key] = setting; } @@ -82,21 +91,25 @@ namespace MatterHackers.MatterControl private void LoadData() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { settingsDictionary = new Dictionary(); foreach (PrinterSetting s in GetPrinterSettings()) { settingsDictionary[s.Name] = s; } - ActiveSettingsPrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + // TODO: Review int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + + ActiveSettingsPrinterId = printerID; } } private IEnumerable GetPrinterSettings() { //Retrieve a list of settings from the Datastore - string query = string.Format("SELECT * FROM PrinterSetting WHERE PrinterId = {0};", ActivePrinterProfile.Instance.ActivePrinter.Id); + string query = string.Format("SELECT * FROM PrinterSetting WHERE PrinterId = {0};", ActiveSliceSettings.Instance.Id); return Datastore.Instance.dbSQLite.Query(query); } } diff --git a/SlicerConfiguration/CuraEngineInfo.cs b/SlicerConfiguration/CuraEngineInfo.cs index b42cfd274..3ab69249d 100644 --- a/SlicerConfiguration/CuraEngineInfo.cs +++ b/SlicerConfiguration/CuraEngineInfo.cs @@ -10,9 +10,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { } - public override ActivePrinterProfile.SlicingEngineTypes GetSliceEngineType() + public override SlicingEngineTypes GetSliceEngineType() { - return ActivePrinterProfile.SlicingEngineTypes.CuraEngine; + return SlicingEngineTypes.CuraEngine; } protected override string getWindowsPath() diff --git a/SlicerConfiguration/MatterSliceInfo.cs b/SlicerConfiguration/MatterSliceInfo.cs index 48d5417b7..1af0041a5 100644 --- a/SlicerConfiguration/MatterSliceInfo.cs +++ b/SlicerConfiguration/MatterSliceInfo.cs @@ -13,9 +13,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public static string DisplayName = "MatterSlice"; - public override ActivePrinterProfile.SlicingEngineTypes GetSliceEngineType() + public override SlicingEngineTypes GetSliceEngineType() { - return ActivePrinterProfile.SlicingEngineTypes.MatterSlice; + return SlicingEngineTypes.MatterSlice; } public override bool Exists() diff --git a/SlicerConfiguration/Settings/ActiveSliceSettings.cs b/SlicerConfiguration/Settings/ActiveSliceSettings.cs new file mode 100644 index 000000000..187367ed7 --- /dev/null +++ b/SlicerConfiguration/Settings/ActiveSliceSettings.cs @@ -0,0 +1,281 @@ +/* +Copyright (c) 2016, Lars Brubaker, John Lewin +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 MatterHackers.MatterControl.PrinterCommunication; +using System.IO; +using System.Net; +using Newtonsoft.Json; +using MatterHackers.MatterControl.SettingsManagement; +using MatterHackers.Agg; +using System.Linq; + +namespace MatterHackers.MatterControl.SlicerConfiguration +{ + public enum NamedSettingsLayers { MHBaseSettings, OEMSettings, Quality, Material, User, All } + + public class ActiveSliceSettings + { + private static readonly string userDataPath = DataStorage.ApplicationDataStorage.ApplicationUserDataPath; + private static readonly string profilesPath = Path.Combine(userDataPath, "Profiles"); + private static readonly string profilesDBPath = Path.Combine(profilesPath, "profiles.json"); + + public static RootedObjectEventHandler ActivePrinterChanged = new RootedObjectEventHandler(); + + private static SettingsProfile activeInstance = null; + public static SettingsProfile Instance + { + get + { + return activeInstance; + } + set + { + if (activeInstance != value) + { + // If we have an active printer, run Disable otherwise skip to prevent empty ActiveSliceSettings due to null ActivePrinter + if (activeInstance != null) + { + PrinterConnectionAndCommunication.Instance.Disable(); + } + + activeInstance = value; + if (activeInstance != null) + { + BedSettings.SetMakeAndModel(activeInstance.Make, activeInstance.Model); + } + + OnActivePrinterChanged(null); + } + } + } + + static ActiveSliceSettings() + { + // Ensure the profiles directory exists + Directory.CreateDirectory(profilesPath); + + // Load or import the profiles.json document + if (File.Exists(profilesDBPath)) + { + ProfileData = JsonConvert.DeserializeObject(File.ReadAllText(profilesDBPath)); + } + else + { + ProfileData = new ProfileData(); + + // Import class profiles from the db into local json files + DataStorage.ClassicDB.ClassicSqlitePrinterProfiles.ImportPrinters(ProfileData, profilesPath); + File.WriteAllText(profilesDBPath, JsonConvert.SerializeObject(ProfileData, Formatting.Indented)); + + // TODO: Upload new profiles to webservice + } + + if (!string.IsNullOrEmpty(ProfileData.ActiveProfileID)) + { + Instance = LoadProfile(ProfileData.ActiveProfileID); + } + else + { + // Load an empty profile with just the MatterHackers base settings from config.json + Instance = new SettingsProfile(LoadEmptyProfile()); + } + } + + public static void SetActiveProfileID(int id) + { + ProfileData.ActiveProfileID = id.ToString(); + File.WriteAllText(profilesDBPath, JsonConvert.SerializeObject(ProfileData, Formatting.Indented)); + } + + public static LayeredProfile LoadEmptyProfile() + { + return new LayeredProfile(new OemProfile(), LoadMatterHackersBaseLayer()); + } + + public static ProfileData ProfileData { get; private set; } + + public static void CheckForAndDoAutoConnect() + { + bool connectionAvailable; + + var autoConnectProfile = GetAutoConnectProfile(out connectionAvailable); + if (autoConnectProfile != null) + { + //ActiveSliceSettings.Instance = autoConnectProfile; + if (connectionAvailable) + { + PrinterConnectionAndCommunication.Instance.HaltConnectionThread(); + PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); + } + } + } + + internal static void SwitchToProfile(int id) + { + var profile = LoadProfile(id); + + SetActiveProfileID(id); + + if (profile != null) + { + Instance = profile; + } + } + + internal static SettingsProfile LoadProfile(int id) + { + string profileID = ProfileData.Profiles.Where(p => p.Id == id.ToString()).FirstOrDefault()?.Id.ToString(); + if (!string.IsNullOrEmpty(profileID)) + { + return LoadProfile(profileID); + } + + return null; + } + + internal static SettingsProfile LoadProfile(string profileID) + { + string profilePath = Path.Combine(profilesPath, profileID + ".json"); + return File.Exists(profilePath) ? LoadProfileFromDisk(profilePath) : null; + } + + internal static void AcquireNewProfile(string make, string model, string printerName) + { + string guid = Guid.NewGuid().ToString(); + + OemProfile printerProfile = LoadHttpOemProfile(make, model); + SettingsLayer baseConfig = LoadMatterHackersBaseLayer(); + + var layeredProfile = new LayeredProfile( + printerProfile, + baseConfig); + layeredProfile.DocumentPath = Path.Combine(profilesPath, guid + ".json"); + layeredProfile.Save(); + + ProfileData.Profiles.Add(new PrinterInfo + { + Name = printerName, + Id = guid + }); + + Instance = new SettingsProfile(layeredProfile); + } + + private static SettingsProfile LoadProfileFromDisk(string profilePath) + { + return new SettingsProfile(LayeredProfile.LoadFile(profilePath)); + } + + private static SettingsLayer LoadMatterHackersBaseLayer() + { + // TODO: Build if missing? + string baseConfigPath = Path.Combine(profilesPath, "config.json"); + return JsonConvert.DeserializeObject(File.ReadAllText(baseConfigPath)); + } + + private static OemProfile LoadHttpOemProfile(string make, string model) + { + var client = new WebClient(); + string profileText = client.DownloadString(string.Format("http://matterdata.azurewebsites.net/api/oemprofiles/{0}/{1}/", make, model)); + var printerProfile = JsonConvert.DeserializeObject(profileText); + return printerProfile; + } + + private static void OnActivePrinterChanged(EventArgs e) + { + ActivePrinterChanged.CallEvents(null, e); + } + + private static SettingsProfile GetAutoConnectProfile(out bool connectionAvailable) + { + // Load the last selected profile, see if the port is active + + // Return the profile if valid + + // otherwise (not the best idea IMO), iterate all profiles, trying to find relevant matches and change the selection dynamically rather than as last selected by the user + + /* + string[] comportNames = FrostedSerialPort.GetPortNames(); + + Printer printerToSelect = null; + connectionAvailable = false; + + foreach (Printer printer in Datastore.Instance.dbSQLite.Query("SELECT * FROM Printer;")) + { + if (printer.AutoConnectFlag) + { + printerToSelect = printer; + bool portIsAvailable = comportNames.Contains(printer.ComPort); + if (portIsAvailable) + { + // We found a printer that we can select and connect to. + connectionAvailable = true; + return printer; + } + } + } + + // return a printer we can connect to even though we can't connect + return printerToSelect; + */ + + connectionAvailable = false; + return null; + } + + /* + + private static SettingsProfile LoadBestProfile() + { + // Conceptually, load settings means + // Read from state the currently selected profile/printer token + // - Check for/update/load the base MatterHackers layer + // - Check for/update/load the OEM layer + // - Set the quality layer to the currently selected quality profile + // - Set the material layer to the currently selected material profile + // - Check for/update/load the customer layer + + // Load profiles document + + var activeProfile = ProfileData.Profiles.Where(p => p.ProfileToken == ProfileData.ActiveProfileID).FirstOrDefault(); + if (activeProfile != null) + { + printerProfilePath = Path.Combine(profilesPath, activeProfile.ProfileToken + ".json"); + } + + // or this + return LoadProfileFromDisk(printerProfilePath); + } */ + + + } + + public enum SlicingEngineTypes { Slic3r, CuraEngine, MatterSlice }; +} \ No newline at end of file diff --git a/SlicerConfiguration/Settings/LayeredProfile.cs b/SlicerConfiguration/Settings/LayeredProfile.cs new file mode 100644 index 000000000..1d449afb0 --- /dev/null +++ b/SlicerConfiguration/Settings/LayeredProfile.cs @@ -0,0 +1,306 @@ +/* +Copyright (c) 2016, Lars Brubaker, John Lewin +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 Newtonsoft.Json; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System; +using System.IO; + +namespace MatterHackers.MatterControl.SlicerConfiguration +{ + public class LayeredProfile + { + [JsonIgnore] + internal SettingsLayer QualityLayer { get; private set; } + + [JsonIgnore] + internal SettingsLayer MaterialLayer { get; private set; } + + public LayeredProfile(OemProfile printerProfile, SettingsLayer baseConfig) + { + this.OemProfile = printerProfile; + this.BaseLayer = baseConfig; + } + + [OnDeserialized] + internal void OnDeserializedMethod(StreamingContext context) + { + QualityLayer = GetQualityLayer(ActiveQualityKey); + MaterialLayer = GetMaterialLayer(ActiveMaterialKey); ; + } + + public OemProfile OemProfile { get; set; } + + internal SettingsLayer GetMaterialLayer(string key) + { + if (string.IsNullOrEmpty(key)) + { + return null; + } + + // Find the first matching layer in either the user or the OEM layers + SettingsLayer layer = null; + if (!MaterialLayers.TryGetValue(key, out layer)) + { + OemProfile.MaterialLayers.TryGetValue(key, out layer); + } + + return layer; + } + + internal SettingsLayer GetQualityLayer(string key) + { + // Find the first matching layer in either the user or the OEM layers + SettingsLayer layer = null; + if (key != null && !QualityLayers.TryGetValue(key, out layer)) + { + OemProfile.QualityLayers.TryGetValue(key, out layer); + } + + return layer; + } + + public string ActiveMaterialKey + { + get + { + return GetValue("MatterControl.ActiveMaterialKey"); + } + internal set + { + SetActiveValue("MatterControl.ActiveMaterialKey", value); + MaterialLayer = GetMaterialLayer(value); + Save(); + } + } + + public string ActiveQualityKey + { + get + { + return GetValue("MatterControl.ActiveQualityKey"); + } + internal set + { + SetActiveValue("MatterControl.ActiveQualityKey", value); + QualityLayer = GetQualityLayer(value); + + Save(); + } + } + + + public string GetMaterialPresetKey(int extruderIndex) + { + if (extruderIndex >= MaterialSettingsKeys.Count) + { + return null; + } + + return MaterialSettingsKeys[extruderIndex]; + } + + public void SetMaterialPreset(int extruderIndex, string materialKey) + { + if (extruderIndex >= PrinterCommunication.PrinterConnectionAndCommunication.MAX_EXTRUDERS) + { + throw new ArgumentOutOfRangeException("Requested extruder index is outside of bounds: " + extruderIndex); + } + + // TODO: This should really be in SettingsProfile and should be run when the extruder count changes + if (MaterialSettingsKeys.Count <= extruderIndex) + { + var resizedArray = new string[extruderIndex + 1]; + MaterialSettingsKeys.CopyTo(resizedArray); + MaterialSettingsKeys = new List(resizedArray); + } + + MaterialSettingsKeys[extruderIndex] = materialKey; + + if (extruderIndex == 0) + { + ActiveMaterialKey = materialKey; + ApplicationController.Instance.ReloadAdvancedControlsPanel(); + } + + Save(); + } + + public List MaterialSettingsKeys { get; set; } = new List(); + + public string DocumentPath { get; set; } + + internal void Save() + { + File.WriteAllText(DocumentPath, JsonConvert.SerializeObject(this)); + } + + /// + /// User settings overrides + /// + public SettingsLayer UserLayer { get; } = new SettingsLayer(); + + public IEnumerable AllMaterialKeys() + { + return MaterialLayers.Keys.Union(this.OemProfile.MaterialLayers.Keys); + } + + public IEnumerable AllQualityKeys() + { + return QualityLayers.Keys.Union(this.OemProfile.QualityLayers.Keys); + } + + internal static LayeredProfile LoadFile(string printerProfilePath) + { + var layeredProfile = JsonConvert.DeserializeObject(File.ReadAllText(printerProfilePath)); + layeredProfile.DocumentPath = printerProfilePath; + + return layeredProfile; + } + + // TODO: Hookup OEM layers + /// + /// Should contain both user created and oem specified material layers + /// + public Dictionary MaterialLayers { get; } = new Dictionary(); + + // TODO: Hookup OEM layers + /// + /// Should contain both user created and oem specified quality layers + /// + public Dictionary QualityLayers { get; } = new Dictionary(); + + + /// + ///Returns the settings value at the 'top' of the stack + /// + public string GetValue(string sliceSetting) + { + return GetValue(sliceSetting, settingsLayers); + } + + public string GetValue(string sliceSetting, IEnumerable layers) + { + foreach (SettingsLayer layer in layers) + { + string value; + if (layer.TryGetValue(sliceSetting, out value)) + { + return value; + } + } + + return ""; + } + + public SettingsLayer BaseLayer { get; set; } + + private IEnumerable settingsLayers + { + get + { + if (this.UserLayer != null) + { + yield return this.UserLayer; + } + + if (this.MaterialLayer != null) + { + yield return this.MaterialLayer; + } + + if (this.QualityLayer != null) + { + yield return this.QualityLayer; + } + + if (this.OemProfile.OemLayer != null) + { + yield return this.OemProfile.OemLayer; + } + + yield return this.BaseLayer; + } + } + + internal void SetActiveValue(string sliceSetting, string sliceValue) + { + SetActiveValue(sliceSetting, sliceValue, UserLayer); + } + + internal void SetActiveValue(string sliceSetting, string sliceValue, SettingsLayer layer) + { + layer[sliceSetting] = sliceValue; + Save(); + } + + internal void ClearValue(string sliceSetting) + { + ClearValue(sliceSetting, UserLayer); + } + + internal void ClearValue(string sliceSetting, SettingsLayer layer) + { + if(layer.ContainsKey(sliceSetting)) + { + layer.Remove(sliceSetting); + } + + // TODO: Reconsider this frequency + Save(); + } + } + + public class OemProfile + { + public OemProfile() { } + + public OemProfile(Dictionary settingsDictionary) + { + OemLayer = new SettingsLayer(settingsDictionary); + } + + /// + /// Printer settings from OEM + /// + public SettingsLayer OemLayer { get; } = new SettingsLayer(); + + /// + /// List of Material presets from OEM + /// + public Dictionary MaterialLayers { get; } = new Dictionary(); + + /// + /// List of Quality presets from OEM + /// + public Dictionary QualityLayers { get; } = new Dictionary(); + } +} \ No newline at end of file diff --git a/SlicerConfiguration/Settings/SettingsDiagram.cd b/SlicerConfiguration/Settings/SettingsDiagram.cd new file mode 100644 index 000000000..0c5db6a2f --- /dev/null +++ b/SlicerConfiguration/Settings/SettingsDiagram.cd @@ -0,0 +1,77 @@ + + + + + + + + + + + IBAAAAEAAABAAAAAAAAAAAAAAIAAABAAQAgAAEAAAAA= + SlicerConfiguration\Settings\ActiveSliceSettings.cs + + + + + + + + + + + SlicerConfiguration\Settings\SettingsProfile.cs + + + + + + + + + + JCADAcoArLgkCEwJMG9CQD0AAEAjEMYASRgMAA5VAAQ= + SlicerConfiguration\Settings\SettingsProfile.cs + + + + + + + + + AAAACMQEKABAAAABEEAGAAQBAgABAAQEAAQIAAAQBAA= + SlicerConfiguration\Settings\LayeredProfile.cs + SlicerConfiguration\ActiveSliceSettings.cs + + + + + + + + + + + + AAAAAIAAAgAAAAAAEAAAAAQAAAAAAAAAAEAAAAAAAAA= + SlicerConfiguration\Settings\SettingsProfile.cs + + + + + + AAAASAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAA= + SlicerConfiguration\Settings\LayeredProfile.cs + SlicerConfiguration\ActiveSliceSettings.cs + + + + + + IAAAgQgCCCAAAAAAIAAAAgQAAAAAEAAAAAwAIBJEAAA= + DataStorage\Models.cs + + + + \ No newline at end of file diff --git a/SlicerConfiguration/ActiveSliceSettings.cs b/SlicerConfiguration/Settings/SettingsProfile.cs similarity index 57% rename from SlicerConfiguration/ActiveSliceSettings.cs rename to SlicerConfiguration/Settings/SettingsProfile.cs index 8265e9761..7a3e3e1cd 100644 --- a/SlicerConfiguration/ActiveSliceSettings.cs +++ b/SlicerConfiguration/Settings/SettingsProfile.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Lars Brubaker +Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -28,14 +28,12 @@ either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; -using MatterHackers.Agg.PlatformAbstract; using MatterHackers.Agg.UI; using MatterHackers.Localizations; -using MatterHackers.MatterControl.ConfigurationPage.PrintLeveling; using MatterHackers.MatterControl.ContactForm; -using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.VectorMath; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; @@ -45,55 +43,23 @@ using System.Text; namespace MatterHackers.MatterControl.SlicerConfiguration { - /// AbsoluteBaseSettings = 0, EditableBaseSettings = 1, PresetOverrides... 2-n (examples: QualitySettings = 2, MaterialSettings = 3) - public enum RequestedSettingsLayer { MHBaseSettings, OEMSettings, Quality, Material, User } - - public class SettingsLayer + using System.Net; + using ConfigurationPage.PrintLeveling; + using SettingsDictionary = Dictionary; + using DataStorage; + using Agg.PlatformAbstract; + public class SettingsProfile { - //Container class representing a collection of setting along with the meta info for that collection - public Dictionary settingsDictionary; - - public SliceSettingsCollection settingsCollectionData; - - public SettingsLayer(SliceSettingsCollection settingsCollection, Dictionary settingsDictionary) - { - this.settingsCollectionData = settingsCollection; - this.settingsDictionary = settingsDictionary; - } - } - - public class ActiveSliceSettings - { - private static ActiveSliceSettings globalInstance = null; private static string configFileExtension = "slice"; - private List activeSettingsLayers; - public RootedObjectEventHandler CommitStatusChanged = new RootedObjectEventHandler(); + public RootedObjectEventHandler SettingsChanged = new RootedObjectEventHandler(); + + public RootedObjectEventHandler DoPrintLevelingChanged = new RootedObjectEventHandler(); + + private LayeredProfile layeredProfile; + private int settingsHashCode; - private bool hasUncommittedChanges = false; - - public bool HasUncommittedChanges - { - get - { - return hasUncommittedChanges; - } - set - { - if (this.hasUncommittedChanges != value) - { - this.hasUncommittedChanges = value; - OnCommitStatusChanged(); - } - } - } - - private void OnCommitStatusChanged() - { - CommitStatusChanged.CallEvents(this, null); - } - private void OnSettingsChanged() { //Set hash code back to 0 @@ -101,154 +67,122 @@ namespace MatterHackers.MatterControl.SlicerConfiguration SettingsChanged.CallEvents(this, null); } - // private so that it can only be gotten through the Instance - private ActiveSliceSettings() + public bool PrinterSelected => layeredProfile.OemProfile.OemLayer.Keys.Count > 0; + + internal SettingsProfile(LayeredProfile profile) { + layeredProfile = profile; } - public static ActiveSliceSettings Instance + public SettingsLayer BaseLayer => layeredProfile.BaseLayer; + + public SettingsLayer OemLayer => layeredProfile.OemProfile.OemLayer; + + public SettingsLayer UserLayer => layeredProfile.UserLayer; + + public string ActiveMaterialKey => layeredProfile.ActiveMaterialKey; + + public string ActiveQualityKey { get { - if (globalInstance == null) - { - globalInstance = new ActiveSliceSettings(); - globalInstance.LoadAllSettings(); - } - - return globalInstance; + return layeredProfile.ActiveQualityKey; + } + set + { + layeredProfile.ActiveQualityKey = value; } } - public void LoadAllSettings() + public bool InBaseConfig(string name) { - this.activeSettingsLayers = new List(); - globalInstance.LoadSettingsForPrinter(); - - //Ordering matters - Material presets trump Quality - globalInstance.LoadSettingsForQuality(); - globalInstance.LoadSettingsForMaterial(); - globalInstance.LoadSettingsForUser(); - - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); - - PrintLevelingPlane.Instance.SetPrintLevelingEquation( - levelingData.SampledPosition0, - levelingData.SampledPosition1, - levelingData.SampledPosition2, - ActiveSliceSettings.Instance.PrintCenter); - } - OnSettingsChanged(); - - this.HasUncommittedChanges = false; + //Check whether the default settings (layer 0) contain a settings definition + return BaseLayer.ContainsKey(name); } - public void LoadSettingsForMaterial() + internal void RunInTransaction(Action action) { - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - SettingsLayer materialSettingsLayer; - SliceSettingsCollection collection; - if (ActivePrinterProfile.Instance.GetMaterialSetting(1) != 0) - { - int materialOneSettingsID = ActivePrinterProfile.Instance.GetMaterialSetting(1); - collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == materialOneSettingsID).Take(1).FirstOrDefault(); - materialSettingsLayer = LoadConfigurationSettingsFromDatastore(collection); - } - else - { - materialSettingsLayer = new SettingsLayer(new SliceSettingsCollection(), new Dictionary()); - } - this.activeSettingsLayers.Add(materialSettingsLayer); - } + // TODO: Implement RunInTransaction + // Suspend writes + action(this); + // Commit } - public double GetActiveValueAsDouble(string keyToLookUp, double valueOnError) + public IEnumerable AllMaterialKeys() { - double foundValue; - if (!double.TryParse(GetActiveValue(keyToLookUp), out foundValue)) - { - return valueOnError; - } - - return foundValue; + return layeredProfile.AllMaterialKeys(); } - public string GetMaterialValue(string sliceSetting, int extruderNumber1Based) + public IEnumerable AllQualityKeys() { - int numberOfActiveLayers = activeSettingsLayers.Count; - string settingValue = null; - if (ActivePrinterProfile.Instance.GetMaterialSetting(extruderNumber1Based) != 0) - { - int materialOneSettingsID = ActivePrinterProfile.Instance.GetMaterialSetting(extruderNumber1Based); - SliceSettingsCollection collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == materialOneSettingsID).Take(1).FirstOrDefault(); - SettingsLayer printerSettingsLayer = LoadConfigurationSettingsFromDatastore(collection); - if (printerSettingsLayer.settingsDictionary.ContainsKey(sliceSetting)) - { - settingValue = printerSettingsLayer.settingsDictionary[sliceSetting].Value; - } - } + return layeredProfile.AllQualityKeys(); + } - if (settingValue == null) + public class SettingsConverter + { + public static void LoadConfigurationSettingsFromFileAsUnsaved(string pathAndFileName) { - //Go through settings layers one-by-one, starting with quality (index = 2), in reverse order, until we find a layer that contains the value - int startingLayer = Math.Min(numberOfActiveLayers - 1, 2); - for (int i = startingLayer; i >= 0; i--) + try { - if (activeSettingsLayers[i].settingsDictionary.ContainsKey(sliceSetting)) + if (File.Exists(pathAndFileName)) { - settingValue = activeSettingsLayers[i].settingsDictionary[sliceSetting].Value; - return settingValue; + string[] lines = System.IO.File.ReadAllLines(pathAndFileName); + foreach (string line in lines) + { + //Ignore commented lines + if (line.Trim() != "" && !line.StartsWith("#")) + { + string[] settingLine = line.Split('='); + if (settingLine.Length > 1) + { + string keyName = settingLine[0].Trim(); + string settingDefaultValue = settingLine[1].Trim(); + + //Add the setting to the active layer + //SaveValue(keyName, settingDefaultValue); + throw new NotImplementedException("load to dictionary"); + } + } + } } } - } - - if (settingValue == null) - { - settingValue = "Unknown"; - } - - return settingValue; - } - - public void LoadSettingsForQuality() - { - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - SettingsLayer qualitySettingsLayer; - SliceSettingsCollection collection; - if (ActivePrinterProfile.Instance.ActiveQualitySettingsID != 0) + catch (Exception e) { - int materialOneSettingsID = ActivePrinterProfile.Instance.ActiveQualitySettingsID; - collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == materialOneSettingsID).Take(1).FirstOrDefault(); - qualitySettingsLayer = LoadConfigurationSettingsFromDatastore(collection); + Debug.Print(e.Message); + GuiWidget.BreakInDebugger(); + Debug.WriteLine(string.Format("Error loading configuration: {0}", e)); } - else - { - qualitySettingsLayer = new SettingsLayer(new SliceSettingsCollection(), new Dictionary()); - } - this.activeSettingsLayers.Add(qualitySettingsLayer); } } - public void LoadSettingsForUser() + public string GetExtruderTemperature(int extruderIndex) { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (extruderIndex >= layeredProfile.MaterialSettingsKeys.Count) { - SettingsLayer userSettingsLayer = new SettingsLayer(new SliceSettingsCollection(), new Dictionary()); - this.activeSettingsLayers.Add(userSettingsLayer); + return null; } + + string materialKey = layeredProfile.MaterialSettingsKeys[extruderIndex]; + SettingsLayer layer = layeredProfile.GetMaterialLayer(materialKey); + + string result; + layer.TryGetValue("temperature", out result); + return result; } - public void LoadSettingsForPrinter() + internal SettingsLayer GetMaterialLayer(string key) { - //Load default settings from the .ini file as first layer - LoadDefaultConfigrationSettings(); + return layeredProfile.GetMaterialLayer(key); + } - //Load printer settings from database as second layer - LoadPrinterConfigurationSettings(); + internal SettingsLayer GetQualityLayer(string key) + { + return layeredProfile.GetQualityLayer(key); + } + + internal void SetMaterialPreset(int extruderIndex, string text) + { + layeredProfile.SetMaterialPreset(extruderIndex, text); } public bool HasFan() @@ -283,7 +217,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration double targetTemp = 0; if (HasHeatedBed()) { - double.TryParse(ActiveSliceSettings.Instance.GetActiveValue("bed_temperature"), out targetTemp); + double.TryParse(GetActiveValue("bed_temperature"), out targetTemp); } return targetTemp; } @@ -321,7 +255,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } - public int SupportExtruder { get @@ -356,7 +289,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } - public bool RaftEnabled { get @@ -373,20 +305,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } - public Dictionary DefaultSettings - { - get - { - return activeSettingsLayers[0].settingsDictionary; - } - } - - public bool Contains(string sliceSetting) - { - //Check whether the default settings (layer 0) contain a settings definition - return DefaultSettings.ContainsKey(sliceSetting); - } - public double MaxFanSpeed { get @@ -439,6 +357,11 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } + internal string GetMaterialPresetKey(int extruderIndex) + { + return layeredProfile.GetMaterialPresetKey(extruderIndex); + } + public double FirstLayerExtrusionWidth { get @@ -528,8 +451,13 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { get { + if (ExtrudersShareTemperature) + { + return 1; + } + int extruderCount; - string extruderCountString = ActiveSliceSettings.Instance.GetActiveValue("extruder_count"); + string extruderCountString = GetActiveValue("extruder_count"); if (!int.TryParse(extruderCountString, out extruderCount)) { return 1; @@ -543,13 +471,13 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { get { - return (int.Parse(ActiveSliceSettings.Instance.GetActiveValue("extruders_share_temperature")) == 1); + return (int.Parse(GetActiveValue("extruders_share_temperature")) == 1); } } public Vector2 GetOffset(int extruderIndex) { - string currentOffsets = ActiveSliceSettings.Instance.GetActiveValue("extruder_offset"); + string currentOffsets = GetActiveValue("extruder_offset"); string[] offsets = currentOffsets.Split(','); int count = 0; foreach (string offset in offsets) @@ -583,53 +511,160 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } + private PrintLevelingData printLevelingData = null; + public PrintLevelingData PrintLevelingData + { + get + { + if (printLevelingData == null) + { + printLevelingData = PrintLevelingData.Create( + layeredProfile.GetValue("MatterControl.PrintLevelingData"), + layeredProfile.GetValue("MatterControl.PrintLevelingProbePositions")); + + PrintLevelingPlane.Instance.SetPrintLevelingEquation( + printLevelingData.SampledPosition0, + printLevelingData.SampledPosition1, + printLevelingData.SampledPosition2, + ActiveSliceSettings.Instance.PrintCenter); + } + + return printLevelingData; + } + set + { + printLevelingData = value; + layeredProfile.SetActiveValue("MatterControl.PrintLevelingData", JsonConvert.SerializeObject(PrintLevelingData)); + } + } + + public bool DoPrintLeveling + { + get + { + return layeredProfile.GetValue("MatterControl.PrintLevelingEnabled") == "true"; + } + + set + { + // Early exit if already set + if(value == this.DoPrintLeveling) + { + return; + } + + layeredProfile.SetActiveValue("MatterControl.PrintLevelingEnabled", value ? "true" : "false"); + + DoPrintLevelingChanged.CallEvents(this, null); + + if (value) + { + PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; + PrintLevelingPlane.Instance.SetPrintLevelingEquation( + levelingData.SampledPosition0, + levelingData.SampledPosition1, + levelingData.SampledPosition2, + ActiveSliceSettings.Instance.PrintCenter); + } + } + } + + private static readonly SlicingEngineTypes defaultEngineType = SlicingEngineTypes.MatterSlice; + + public SlicingEngineTypes ActiveSliceEngineType + { + get + { + string engineType = layeredProfile.GetValue("MatterControl.SlicingEngine"); + if (string.IsNullOrEmpty(engineType)) + { + return defaultEngineType; + } + + var engine = (SlicingEngineTypes)Enum.Parse(typeof(SlicingEngineTypes), engineType); + return engine; + } + set + { + SetActiveValue("MatterControl.SlicingEngine", value.ToString()); + } + } + + public SliceEngineMapping ActiveSliceEngine + { + get + { + switch (ActiveSliceEngineType) + { + case SlicingEngineTypes.CuraEngine: + return EngineMappingCura.Instance; + + case SlicingEngineTypes.MatterSlice: + return EngineMappingsMatterSlice.Instance; + + case SlicingEngineTypes.Slic3r: + return Slic3rEngineMappings.Instance; + + default: + return null; + } + } + } + /// - ///Returns the settings value at the 'top' of the stack + ///Returns the first matching value discovered while enumerating the settings layers /// public string GetActiveValue(string sliceSetting) { - int numberOfActiveLayers = activeSettingsLayers.Count; - - //Go through settings layers one-by-one, in reverse order, until we find a layer that contains the value - for (int i = numberOfActiveLayers - 1; i >= 0; i--) - { - if (activeSettingsLayers[i].settingsDictionary.ContainsKey(sliceSetting)) - { - return activeSettingsLayers[i].settingsDictionary[sliceSetting].Value; - } - } - - return "Unknown"; + return layeredProfile.GetValue(sliceSetting); } - public void Remove(string sliceSetting, RequestedSettingsLayer requestedLayer) + public string GetActiveValue(string sliceSetting, IEnumerable layers) { - int layerIndex = (int)requestedLayer; - if(activeSettingsLayers[layerIndex].settingsDictionary.ContainsKey(sliceSetting)) - { - activeSettingsLayers[layerIndex].settingsDictionary.Remove(sliceSetting); - } + return layeredProfile.GetValue(sliceSetting, layers); + } + + public void SetActiveValue(string sliceSetting, string sliceValue) + { + layeredProfile.SetActiveValue(sliceSetting, sliceValue); + } + + public void SetActiveValue(string sliceSetting, string sliceValue, SettingsLayer persistenceLayer) + { + layeredProfile.SetActiveValue(sliceSetting, sliceValue, persistenceLayer); + } + + public void ClearValue(string sliceSetting) + { + layeredProfile.ClearValue(sliceSetting); + } + + public void ClearValue(string sliceSetting, SettingsLayer persistenceLayer) + { + layeredProfile.ClearValue(sliceSetting, persistenceLayer); } /// /// Returns whether or not the setting is overridden by the active layer /// - /// AbsoluteBaseSettings = 0, EditableBaseSettings = 1, PresetOverrides... 2-n (examples: QualitySettings = 2, MaterialSettings = 3) - /// - /// - public bool SettingExistsInLayer(string sliceSetting, RequestedSettingsLayer requestedLayer) + public bool SettingExistsInLayer(string sliceSetting, NamedSettingsLayers layer) { - bool settingExistsInLayer; - int layerIndex = (int)requestedLayer; - if (layerIndex < activeSettingsLayers.Count) + if (layeredProfile == null) { - settingExistsInLayer = activeSettingsLayers[layerIndex].settingsDictionary.ContainsKey(sliceSetting); + return false; } - else + + switch (layer) { - settingExistsInLayer = false; + case NamedSettingsLayers.Quality: + return layeredProfile?.QualityLayer?.ContainsKey(sliceSetting) == true; + case NamedSettingsLayers.Material: + return layeredProfile?.MaterialLayer?.ContainsKey(sliceSetting) == true; + case NamedSettingsLayers.User: + return layeredProfile?.UserLayer?.ContainsKey(sliceSetting) == true; + default: + return false; } - return settingExistsInLayer; } public Vector2 GetActiveVector2(string sliceSetting) @@ -645,190 +680,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration return valueAsVector2; } - public void LoadPrinterConfigurationSettings() - { - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - SliceSettingsCollection collection; - if (ActivePrinterProfile.Instance.ActivePrinter.DefaultSettingsCollectionId != 0) - { - int activePrinterSettingsID = ActivePrinterProfile.Instance.ActivePrinter.DefaultSettingsCollectionId; - collection = Datastore.Instance.dbSQLite.Table().Where(v => v.Id == activePrinterSettingsID).Take(1).FirstOrDefault(); - } - else - { - collection = new SliceSettingsCollection(); - collection.Name = ActivePrinterProfile.Instance.ActivePrinter.Name; - collection.Commit(); - - ActivePrinterProfile.Instance.ActivePrinter.DefaultSettingsCollectionId = collection.Id; - ActivePrinterProfile.Instance.ActivePrinter.Commit(); - } - SettingsLayer printerSettingsLayer = LoadConfigurationSettingsFromDatastore(collection); - this.activeSettingsLayers.Add(printerSettingsLayer); - } - } - - private SettingsLayer LoadConfigurationSettingsFromDatastore(SliceSettingsCollection collection) - { - Dictionary settingsDictionary = new Dictionary(); - foreach (SliceSetting s in GetCollectionSettings(collection.Id)) - { - settingsDictionary[s.Name] = s; - } - - return new SettingsLayer(collection, settingsDictionary); - } - - private IEnumerable GetCollectionSettings(int collectionId) - { - string query = string.Format("SELECT * FROM SliceSetting WHERE SettingsCollectionID = {0};", collectionId); - return Datastore.Instance.dbSQLite.Query(query); - } - - private void LoadDefaultConfigrationSettings() - { - SliceSettingsCollection defaultCollection = new SliceSettingsCollection(); - defaultCollection.Name = "__default__"; - SettingsLayer defaultSettingsLayer = LoadConfigurationSettingsFromFile(Path.Combine("PrinterSettings", "config.ini"), defaultCollection); - this.activeSettingsLayers.Add(defaultSettingsLayer); - } - - public void LoadSettingsFromIni() - { - OpenFileDialogParams openParams = new OpenFileDialogParams("Load Slice Configuration|*.slice;*.ini"); - openParams.ActionButtonLabel = "Load Configuration"; - openParams.Title = "MatterControl: Select A File"; - - FileDialog.OpenFileDialog(openParams, onSettingsFileSelected); - } - - private void onSettingsFileSelected(OpenFileDialogParams openParams) - { - if (openParams.FileNames != null) - { - LoadConfigurationSettingsFromFileAsUnsaved(openParams.FileName); - ApplicationController.Instance.ReloadAdvancedControlsPanel(); - } - } - - public SettingsLayer LoadConfigurationSettingsFromFile(string pathAndFileName, SliceSettingsCollection collection) - { - Dictionary settingsDictionary = new Dictionary(); - SettingsLayer activeCollection; - try - { - if (StaticData.Instance.FileExists(pathAndFileName)) - { - foreach (string line in StaticData.Instance.ReadAllLines(pathAndFileName)) - { - //Ignore commented lines - if (!line.StartsWith("#")) - { - string[] settingLine = line.Split('='); - string keyName = settingLine[0].Trim(); - string settingDefaultValue = settingLine[1].Trim(); - - SliceSetting sliceSetting = new SliceSetting(); - sliceSetting.Name = keyName; - sliceSetting.Value = settingDefaultValue; - - settingsDictionary.Add(keyName, sliceSetting); - } - } - activeCollection = new SettingsLayer(collection, settingsDictionary); - return activeCollection; - } - return null; - } - catch (Exception e) - { - Debug.Print(e.Message); - GuiWidget.BreakInDebugger(); - Debug.WriteLine(string.Format("Error loading configuration: {0}", e)); - return null; - } - } - - public void LoadConfigurationSettingsFromFileAsUnsaved(string pathAndFileName) - { - try - { - if (File.Exists(pathAndFileName)) - { - string[] lines = System.IO.File.ReadAllLines(pathAndFileName); - foreach (string line in lines) - { - //Ignore commented lines - if (line.Trim() != "" && !line.StartsWith("#")) - { - string[] settingLine = line.Split('='); - if (settingLine.Length > 1) - { - string keyName = settingLine[0].Trim(); - string settingDefaultValue = settingLine[1].Trim(); - - //Add the setting to the active layer - SaveValue(keyName, settingDefaultValue, RequestedSettingsLayer.OEMSettings); - } - } - } - } - } - catch (Exception e) - { - Debug.Print(e.Message); - GuiWidget.BreakInDebugger(); - Debug.WriteLine(string.Format("Error loading configuration: {0}", e)); - } - } - - public void SaveValue(string keyName, string keyValue, RequestedSettingsLayer settingsLayer) - { - int layerIndex = (int)settingsLayer; - SettingsLayer layer = this.activeSettingsLayers[layerIndex]; - - if (layer.settingsDictionary.ContainsKey(keyName) - && layer.settingsDictionary[keyName].Value != keyValue) - { - layer.settingsDictionary[keyName].Value = keyValue; - - OnSettingsChanged(); - HasUncommittedChanges = true; - } - else - { - SliceSetting sliceSetting = new SliceSetting(); - sliceSetting.Name = keyName; - sliceSetting.Value = keyValue; - sliceSetting.SettingsCollectionId = layer.settingsCollectionData.Id; - - layer.settingsDictionary[keyName] = sliceSetting; - - OnSettingsChanged(); - HasUncommittedChanges = true; - } - } - - public void CommitChanges() - { - CommitLayerChanges(RequestedSettingsLayer.OEMSettings); - CommitLayerChanges(RequestedSettingsLayer.Material); - CommitLayerChanges(RequestedSettingsLayer.Quality); - CommitLayerChanges(RequestedSettingsLayer.User); - HasUncommittedChanges = false; - } - - public void CommitLayerChanges(RequestedSettingsLayer requestedLayer) - { - int layerIndex = (int)requestedLayer; - SettingsLayer layer = this.activeSettingsLayers[layerIndex]; - foreach (KeyValuePair item in layer.settingsDictionary) - { - item.Value.Commit(); - } - } - public void SaveAs() { SaveFileDialogParams saveParams = new SaveFileDialogParams("Save Slice Configuration".Localize() + "|*." + configFileExtension); @@ -848,14 +699,15 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { if (this.settingsHashCode == 0) { - // make a new dictionary so we only hash on the current values and keys. - StringBuilder bigStringForHashCode = new StringBuilder(); - foreach (KeyValuePair setting in this.DefaultSettings) + var bigStringForHashCode = new StringBuilder(); + + foreach (var kvp in this.BaseLayer) { - string activeValue = GetActiveValue(setting.Key); - bigStringForHashCode.Append(setting.Key); + string activeValue = GetActiveValue(kvp.Key); + bigStringForHashCode.Append(kvp.Key); bigStringForHashCode.Append(activeValue); } + this.settingsHashCode = bigStringForHashCode.ToString().GetHashCode(); } return this.settingsHashCode; @@ -863,26 +715,19 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public void GenerateConfigFile(string fileName, bool replaceMacroValues) { - List configFileAsList = new List(); - - foreach (KeyValuePair setting in this.DefaultSettings) + using (var outstream = new StreamWriter(fileName)) { - string activeValue = GetActiveValue(setting.Key); - if (replaceMacroValues) + foreach (var kvp in this.BaseLayer) { + string activeValue = GetActiveValue(kvp.Key); + if (replaceMacroValues) + { + activeValue = GCodeProcessing.ReplaceMacroValues(activeValue); + } + outstream.Write(string.Format("{0} = {1}\n", kvp.Key, activeValue)); activeValue = GCodeProcessing.ReplaceMacroValues(activeValue); } - string settingString = string.Format("{0} = {1}", setting.Key, activeValue); - configFileAsList.Add(settingString); } - string configFileAsString = string.Join("\n", configFileAsList.ToArray()); - - //To do - add file extension if it doesn't exist - - FileStream fs = new FileStream(fileName, FileMode.Create); - StreamWriter sw = new System.IO.StreamWriter(fs); - sw.Write(configFileAsString); - sw.Close(); } public bool IsValid() @@ -909,7 +754,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration // If we have print leveling turned on then make sure we don't have any leveling commands in the start gcode. if (PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling) { - string[] startGCode = ActiveSliceSettings.Instance.GetActiveValue("start_gcode").Replace("\\n", "\n").Split('\n'); + string[] startGCode = GetActiveValue("start_gcode").Replace("\\n", "\n").Split('\n'); foreach (string startGCodeLine in startGCode) { if (startGCodeLine.StartsWith("G29")) @@ -1002,7 +847,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration if (!ValidateGoodSpeedSettingGreaterThan0("bridge_speed", normalSpeedLocation)) return false; if (!ValidateGoodSpeedSettingGreaterThan0("external_perimeter_speed", normalSpeedLocation)) return false; if (!ValidateGoodSpeedSettingGreaterThan0("first_layer_speed", normalSpeedLocation)) return false; - if (!ValidateGoodSpeedSettingGreaterThan0("resume_first_layer_speed", normalSpeedLocation)) return false; if (!ValidateGoodSpeedSettingGreaterThan0("gap_fill_speed", normalSpeedLocation)) return false; if (!ValidateGoodSpeedSettingGreaterThan0("infill_speed", normalSpeedLocation)) return false; if (!ValidateGoodSpeedSettingGreaterThan0("perimeter_speed", normalSpeedLocation)) return false; @@ -1043,7 +887,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } if (!valueWasNumber - || (ActivePrinterProfile.Instance.ActiveSliceEngine.MapContains(speedSetting) + || (ActiveSliceSettings.Instance.ActiveSliceEngine.MapContains(speedSetting) && speedToCheck <= 0)) { OrganizerSettingsData data = SliceSettingsOrganizer.Instance.GetSettingsData(speedSetting); @@ -1057,5 +901,279 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } return true; } + + public bool AutoConnectFlag + { + get + { + return layeredProfile.GetValue("MatterControl.AutoConnectFlag") == "true"; + } + set + { + layeredProfile.SetActiveValue("MatterControl.AutoConnectFlag", value ? "true" : "false"); + } + } + + public string BaudRate + { + get + { + return layeredProfile.GetValue("MatterControl.BaudRate"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.BaudRate", value); + } + } + + public string ComPort + { + get + { + return layeredProfile.GetValue("MatterControl.ComPort"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.ComPort", value); + } + } + + public string SlicingEngine + { + get + { + return layeredProfile.GetValue("MatterControl.SlicingEngine"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.SlicingEngine", value); + } + } + + public string DriverType + { + get + { + return layeredProfile.GetValue("MatterControl.DriverType"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.DriverType", value); + } + } + public string DeviceToken + { + get + { + return layeredProfile.GetValue("MatterControl.DeviceToken"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.DeviceToken", value); + } + } + + public string DeviceType => layeredProfile.GetValue("MatterControl.DeviceType"); + + public string Make => layeredProfile.GetValue("MatterControl.Make"); + + // Rename to PrinterName + public string Name + { + get + { + return layeredProfile.GetValue("MatterControl.PrinterName"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.PrinterName", value); + } + } + + public string Id + { + get + { + return layeredProfile.GetValue("MatterControl.PrinterID"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.PrinterID", value); + } + } + + public string Model => layeredProfile.GetValue("MatterControl.Model"); + + public string ManualMovementSpeeds + { + get + { + return layeredProfile.GetValue("MatterControl.ManualMovementSpeeds"); + } + set + { + layeredProfile.SetActiveValue("MatterControl.ManualMovementSpeeds", value); + } + } + + + private List printerDrivers = null; + + public List PrinterDrivers() + { + if(printerDrivers == null) + { + printerDrivers = GetPrintDrivers(); + } + + return printerDrivers; + } + + private List GetPrintDrivers() + { + var drivers = new List(); + + //Determine what if any drivers are needed + string infFileNames = GetActiveValue("windows_driver"); + if (!string.IsNullOrEmpty(infFileNames)) + { + string[] fileNames = infFileNames.Split(','); + foreach (string fileName in fileNames) + { + switch (OsInformation.OperatingSystem) + { + case OSType.Windows: + + string pathForInf = Path.GetFileNameWithoutExtension(fileName); + + // TODO: It's really unexpected that the driver gets copied to the temp folder every time a printer is setup. I'd think this only needs + // to happen when the infinstaller is run (More specifically - move this to *after* the user clicks Install Driver) + + string infPath = Path.Combine("Drivers", pathForInf); + string infPathAndFileToInstall = Path.Combine(infPath, fileName); + + if (StaticData.Instance.FileExists(infPathAndFileToInstall)) + { + // Ensure the output directory exists + string destTempPath = Path.GetFullPath(Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "inf", pathForInf)); + if (!Directory.Exists(destTempPath)) + { + Directory.CreateDirectory(destTempPath); + } + + string destTempInf = Path.GetFullPath(Path.Combine(destTempPath, fileName)); + + // Sync each file from StaticData to the location on disk for serial drivers + foreach (string file in StaticData.Instance.GetFiles(infPath)) + { + using (Stream outstream = File.OpenWrite(Path.Combine(destTempPath, Path.GetFileName(file)))) + using (Stream instream = StaticData.Instance.OpenSteam(file)) + { + instream.CopyTo(outstream); + } + } + + drivers.Add(destTempInf); + } + break; + + default: + break; + } + } + } + + return drivers; + } + + public void GetMacros(string make, string model) + { + Dictionary macroDict = new Dictionary(); + macroDict["Lights On"] = "M42 P6 S255"; + macroDict["Lights Off"] = "M42 P6 S0"; + macroDict["Offset 0.8"] = "M565 Z0.8;\nM500"; + macroDict["Offset 0.9"] = "M565 Z0.9;\nM500"; + macroDict["Offset 1"] = "M565 Z1;\nM500"; + macroDict["Offset 1.1"] = "M565 Z1.1;\nM500"; + macroDict["Offset 1.2"] = "M565 Z1.2;\nM500"; + macroDict["Z Offset"] = "G1 Z10;\nG28;\nG29;\nG1 Z10;\nG1 X5 Y5 F4000;\nM117;"; + + string defaultMacros = GetActiveValue("default_macros"); + var printerCustomCommands = new List(); + if (!string.IsNullOrEmpty(defaultMacros)) + { + foreach (string macroName in defaultMacros.Split(',')) + { + string macroValue; + if (macroDict.TryGetValue(macroName.Trim(), out macroValue)) + { + CustomCommands customMacro = new CustomCommands(); + customMacro.Name = macroName.Trim(); + customMacro.Value = macroValue; + + printerCustomCommands.Add(customMacro); + } + } + } + } } + + public class SettingsLayer : SettingsDictionary + { + public SettingsLayer() { } + + public SettingsLayer(Dictionary settingsDictionary) + { + foreach(var kvp in settingsDictionary) + { + this[kvp.Key] = kvp.Value; + } + } + + public string Name { get; set; } + public string Source { get; set; } + public string ETag { get; set; } + + public string ValueOrDefault(string key, string defaultValue = "") + { + string foundValue; + this.TryGetValue(key, out foundValue); + + return foundValue ?? defaultValue; + } + + public string ValueOrNull(string key) + { + string foundValue; + this.TryGetValue(key, out foundValue); + + return foundValue; + } + } + + public class ProfileData + { + public string ActiveProfileID { get; set; } + public List Profiles { get; set; } = new List(); + } + + public class PrinterInfo + { + public string Make { get; set; } = "Unknown"; + public string Model { get; set; } = "Unknown"; + public string Name { get; set; } + public string ComPort { get; set; } + public bool AutoConnectFlag { get; set; } + public string Id { get; set; } + public string BaudRate { get; set; } + public string ProfileToken { get; set; } + public string DriverType { get; internal set; } + public string CurrentSlicingEngine { get; internal set; } + + internal void Delete() + { + throw new NotImplementedException(); + } + } + } \ No newline at end of file diff --git a/SlicerConfiguration/SettingsControlBar.cs b/SlicerConfiguration/SettingsControlBar.cs index 222c445da..aa1888eef 100644 --- a/SlicerConfiguration/SettingsControlBar.cs +++ b/SlicerConfiguration/SettingsControlBar.cs @@ -37,23 +37,13 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { public class SettingsControlBar : FlowLayoutWidget { - private event EventHandler unregisterEvents; - public string activeMaterialPreset; - public string activeQualityPreset; - public SettingsControlBar() { this.HAnchor = HAnchor.ParentLeftRight; - int numberOfHeatedExtruders = 1; - if (!ActiveSliceSettings.Instance.ExtrudersShareTemperature) - { - numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount; - } + int numberOfHeatedExtruders = ActiveSliceSettings.Instance.ExtruderCount; - SliceSelectorWidget qualityPresetDropDown = new SliceSelectorWidget("Quality".Localize(), RGBA_Bytes.Yellow, "quality"); - this.activeQualityPreset = qualityPresetDropDown.DropDownList.SelectedLabel; - this.AddChild(qualityPresetDropDown); + this.AddChild(new PresetSelectorWidget("Quality".Localize(), RGBA_Bytes.Yellow, "quality", 0)); this.AddChild(new GuiWidget(8, 0)); if (numberOfHeatedExtruders > 1) @@ -68,28 +58,17 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } int colorIndex = i % colorList.Count; RGBA_Bytes color = colorList[colorIndex]; - this.AddChild(new SliceSelectorWidget(string.Format("{0} {1}", "Material".Localize(), i + 1), color, "material", i + 1)); + this.AddChild(new PresetSelectorWidget(string.Format("{0} {1}", "Material".Localize(), i), color, "material", i)); } } else { - SliceSelectorWidget materialPresetDropDown = new SliceSelectorWidget("Material".Localize(), RGBA_Bytes.Orange, "material"); - this.activeMaterialPreset = materialPresetDropDown.DropDownList.SelectedLabel; - this.AddChild(materialPresetDropDown); + this.AddChild(new PresetSelectorWidget("Material".Localize(), RGBA_Bytes.Orange, "material", 0)); } this.Height = 60 * TextWidget.GlobalPointSizeScaleRatio; } - - public override void OnClosed(EventArgs e) - { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } - base.OnClosed(e); - } } } \ No newline at end of file diff --git a/SlicerConfiguration/SettingsControlSelectors.cs b/SlicerConfiguration/SettingsControlSelectors.cs index 9efd71dfc..7f78fd9ac 100644 --- a/SlicerConfiguration/SettingsControlSelectors.cs +++ b/SlicerConfiguration/SettingsControlSelectors.cs @@ -44,7 +44,7 @@ using System.Linq; namespace MatterHackers.MatterControl.SlicerConfiguration { - public class SliceSelectorWidget : FlowLayoutWidget + public class PresetSelectorWidget : FlowLayoutWidget { private Button editButton; private ImageButtonFactory imageButtonFactory = new ImageButtonFactory(); @@ -53,35 +53,32 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private string filterLabel; public AnchoredDropDownList DropDownList; private TupleList> DropDownMenuItems = new TupleList>(); - private int presetIndex; //For multiple materials - public SliceSelectorWidget(string label, RGBA_Bytes accentColor, string tag = null, int presetIndex = 1) + private int extruderIndex; //For multiple materials + + public PresetSelectorWidget(string label, RGBA_Bytes accentColor, string tag, int extruderIndex) : base(FlowDirection.TopToBottom) { - this.presetIndex = presetIndex; + this.extruderIndex = extruderIndex; this.filterLabel = label; - if (tag == null) - { - this.filterTag = label.ToLower(); - } - else - { - this.filterTag = tag; - } - + this.filterTag = (tag == null) ? label.ToLower() : tag; + this.HAnchor = HAnchor.ParentLeftRight; this.VAnchor = Agg.UI.VAnchor.Max_FitToChildren_ParentHeight; this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - GuiWidget accentBar = new GuiWidget(7, 5); - accentBar.BackgroundColor = accentColor; - accentBar.HAnchor = HAnchor.ParentLeftRight; + GuiWidget accentBar = new GuiWidget(7, 5) + { + BackgroundColor = accentColor, + HAnchor = HAnchor.ParentLeftRight + }; - - TextWidget labelText = new TextWidget(LocalizedString.Get(label).ToUpper()); - labelText.TextColor = ActiveTheme.Instance.PrimaryTextColor; - labelText.HAnchor = Agg.UI.HAnchor.ParentCenter; - labelText.Margin = new BorderDouble(0, 3, 0, 6); + TextWidget labelText = new TextWidget(label.Localize().ToUpper()) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + HAnchor = Agg.UI.HAnchor.ParentCenter, + Margin = new BorderDouble(0, 3, 0, 6) + }; this.AddChild(labelText); this.AddChild(GetPulldownContainer()); @@ -159,38 +156,27 @@ namespace MatterHackers.MatterControl.SlicerConfiguration ApplicationController.Instance.ReloadAdvancedControlsPanel(); } - private IEnumerable GetCollections() - { - //Retrieve a list of collections matching from the Datastore - if (ActivePrinterProfile.Instance.ActivePrinter != null) - { - string query = string.Format("SELECT * FROM SliceSettingsCollection WHERE Tag = '{0}' AND PrinterId = {1} ORDER BY Name;", filterTag, ActivePrinterProfile.Instance.ActivePrinter.Id); - return Datastore.Instance.dbSQLite.Query(query); - } - - return Enumerable.Empty(); - } - private void onItemSelect(object sender, EventArgs e) { + var activeSettings = ActiveSliceSettings.Instance; MenuItem item = (MenuItem)sender; if (filterTag == "material") { - if (ActivePrinterProfile.Instance.GetMaterialSetting(presetIndex) != Int32.Parse(item.Value)) + if (activeSettings.GetMaterialPresetKey(extruderIndex) != item.Text) { - ActivePrinterProfile.Instance.SetMaterialSetting(presetIndex, Int32.Parse(item.Value)); + activeSettings.SetMaterialPreset(extruderIndex, item.Text); } } else if (filterTag == "quality") { - if (ActivePrinterProfile.Instance.ActiveQualitySettingsID != Int32.Parse(item.Value)) + if (activeSettings.ActiveQualityKey != item.Text) { - ActivePrinterProfile.Instance.ActiveQualitySettingsID = Int32.Parse(item.Value); + activeSettings.ActiveQualityKey = item.Text; } } + UiThread.RunOnIdle(() => { - ActiveSliceSettings.Instance.LoadAllSettings(); ApplicationController.Instance.ReloadAdvancedControlsPanel(); }); } @@ -204,18 +190,17 @@ namespace MatterHackers.MatterControl.SlicerConfiguration #else UiThread.RunOnIdle(() => { - ActiveSliceSettings.Instance.LoadAllSettings(); ApplicationController.Instance.ReloadAdvancedControlsPanel(); if (filterTag == "material") { if (ApplicationController.Instance.EditMaterialPresetsWindow == null) { - ApplicationController.Instance.EditMaterialPresetsWindow = new SlicePresetsWindow(ReloadOptions, filterLabel, filterTag, false, 0); + ApplicationController.Instance.EditMaterialPresetsWindow = new SlicePresetsWindow(ReloadOptions, filterLabel, filterTag, false); ApplicationController.Instance.EditMaterialPresetsWindow.Closed += (popupWindowSender, popupWindowSenderE) => { ApplicationController.Instance.EditMaterialPresetsWindow = null; }; } else { - ApplicationController.Instance.EditMaterialPresetsWindow.ChangeToSlicePresetFromID(0); + ApplicationController.Instance.EditMaterialPresetsWindow.ChangeToSlicePresetFromID(""); ApplicationController.Instance.EditMaterialPresetsWindow.BringToFront(); } } @@ -223,12 +208,12 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { if (ApplicationController.Instance.EditQualityPresetsWindow == null) { - ApplicationController.Instance.EditQualityPresetsWindow = new SlicePresetsWindow(ReloadOptions, filterLabel, filterTag, false, 0); + ApplicationController.Instance.EditQualityPresetsWindow = new SlicePresetsWindow(ReloadOptions, filterLabel, filterTag, false); ApplicationController.Instance.EditQualityPresetsWindow.Closed += (popupWindowSender, popupWindowSenderE) => { ApplicationController.Instance.EditQualityPresetsWindow = null; }; } else { - ApplicationController.Instance.EditQualityPresetsWindow.ChangeToSlicePresetFromID(0); + ApplicationController.Instance.EditQualityPresetsWindow.ChangeToSlicePresetFromID(""); ApplicationController.Instance.EditQualityPresetsWindow.BringToFront(); } } @@ -241,13 +226,15 @@ namespace MatterHackers.MatterControl.SlicerConfiguration AnchoredDropDownList dropDownList = new AnchoredDropDownList("- default -", maxHeight: 300); dropDownList.Margin = new BorderDouble(0, 3); dropDownList.MinimumSize = new Vector2(dropDownList.LocalBounds.Width, dropDownList.LocalBounds.Height); + MenuItem defaultMenuItem = dropDownList.AddItem("- default -", "0"); defaultMenuItem.Selected += new EventHandler(onItemSelect); - foreach (SliceSettingsCollection collection in GetCollections()) + var listSource = (filterTag == "material") ? ActiveSliceSettings.Instance.AllMaterialKeys() : ActiveSliceSettings.Instance.AllQualityKeys(); + foreach (var presetName in listSource) { - MenuItem menuItem = dropDownList.AddItem(collection.Name, collection.Id.ToString()); - menuItem.Selected += new EventHandler(onItemSelect); + MenuItem menuItem = dropDownList.AddItem(presetName, presetName); + menuItem.Selected += onItemSelect; } // put in a small bottom region @@ -280,33 +267,29 @@ namespace MatterHackers.MatterControl.SlicerConfiguration dropDownList.MenuItems.Add(new MenuItem(container)); } - if (filterTag == "material") + try { - try - { - dropDownList.SelectedValue = ActivePrinterProfile.Instance.GetMaterialSetting(presetIndex).ToString(); - } - catch (Exception e) - { - Debug.Print(e.Message); - GuiWidget.BreakInDebugger(); - //Unable to set selected value - } - } - else if (filterTag == "quality") - { - try - { - dropDownList.SelectedValue = ActivePrinterProfile.Instance.ActiveQualitySettingsID.ToString(); - } - catch (Exception e) - { - Debug.Print(e.Message); - GuiWidget.BreakInDebugger(); - //Unable to set selected value - } - } + string settingsKey; + if (filterTag == "material") + { + settingsKey = ActiveSliceSettings.Instance.GetMaterialPresetKey(extruderIndex); + } + else + { + settingsKey = ActiveSliceSettings.Instance.ActiveQualityKey; + } + + if (!string.IsNullOrEmpty(settingsKey)) + { + dropDownList.SelectedValue = settingsKey; + } + } + catch (Exception ex) + { + GuiWidget.BreakInDebugger(ex.Message); + } + return dropDownList; } } @@ -332,18 +315,18 @@ namespace MatterHackers.MatterControl.SlicerConfiguration if (engineAllowed) { MenuItem item = AddItem(engineMenuItem.Name); - ActivePrinterProfile.SlicingEngineTypes itemEngineType = engineMenuItem.GetSliceEngineType(); + SlicingEngineTypes itemEngineType = engineMenuItem.GetSliceEngineType(); item.Selected += (sender, e) => { - if (ActivePrinterProfile.Instance.ActiveSliceEngineType != itemEngineType) + if (ActiveSliceSettings.Instance.ActiveSliceEngineType != itemEngineType) { - ActivePrinterProfile.Instance.ActiveSliceEngineType = itemEngineType; + ActiveSliceSettings.Instance.ActiveSliceEngineType = itemEngineType; ApplicationController.Instance.ReloadAdvancedControlsPanel(); } }; //Set item as selected if it matches the active slice engine - if (engineMenuItem.GetSliceEngineType() == ActivePrinterProfile.Instance.ActiveSliceEngineType) + if (engineMenuItem.GetSliceEngineType() == ActiveSliceSettings.Instance.ActiveSliceEngineType) { SelectedLabel = engineMenuItem.Name; } @@ -357,11 +340,10 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { SelectedLabel = MatterSliceInfo.DisplayName; } - catch (Exception e) + catch (Exception ex) { - Debug.Print(e.Message); - GuiWidget.BreakInDebugger(); - throw new Exception("MatterSlice is not available, for some strange reason"); + GuiWidget.BreakInDebugger(ex.Message); + throw new Exception("Unable to find MatterSlice executable"); } } diff --git a/SlicerConfiguration/Slic3rInfo.cs b/SlicerConfiguration/Slic3rInfo.cs index e36833b7a..e529a8dcb 100644 --- a/SlicerConfiguration/Slic3rInfo.cs +++ b/SlicerConfiguration/Slic3rInfo.cs @@ -10,9 +10,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { } - public override ActivePrinterProfile.SlicingEngineTypes GetSliceEngineType() + public override SlicingEngineTypes GetSliceEngineType() { - return ActivePrinterProfile.SlicingEngineTypes.Slic3r; + return SlicingEngineTypes.Slic3r; } protected override string getWindowsPath() diff --git a/SlicerConfiguration/SliceEngineInfo.cs b/SlicerConfiguration/SliceEngineInfo.cs index 6fdeb7e02..56321f21c 100644 --- a/SlicerConfiguration/SliceEngineInfo.cs +++ b/SlicerConfiguration/SliceEngineInfo.cs @@ -13,7 +13,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration protected abstract string getLinuxPath(); - public abstract ActivePrinterProfile.SlicingEngineTypes GetSliceEngineType(); + public abstract SlicingEngineTypes GetSliceEngineType(); public SliceEngineInfo(string name) { diff --git a/SlicerConfiguration/SlicePresetsWindow/SlicePresetDetailWidget.cs b/SlicerConfiguration/SlicePresetsWindow/SlicePresetDetailWidget.cs index 43935709a..12272f6cf 100644 --- a/SlicerConfiguration/SlicePresetsWindow/SlicePresetDetailWidget.cs +++ b/SlicerConfiguration/SlicePresetsWindow/SlicePresetDetailWidget.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Lars Brubaker +Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -32,6 +32,7 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.DataStorage; +using MatterHackers.MatterControl.DataStorage.ClassicDB; using MatterHackers.MatterControl.FieldValidation; using MatterHackers.VectorMath; using System; @@ -145,53 +146,37 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private PresetListControl settingsRowContainer; private FlowLayoutWidget errorMessageContainer; - private FlowLayoutWidget GetMiddleRow() + private GuiWidget GetMiddleRow() { - FlowLayoutWidget container = new FlowLayoutWidget(); - container.HAnchor = HAnchor.ParentLeftRight; - container.VAnchor = Agg.UI.VAnchor.ParentBottomTop; - container.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor; + NamedSettingsLayers layerFilter = NamedSettingsLayers.Material; + List layerFilters = null; - FlowLayoutWidget topBottomContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - topBottomContainer.AnchorAll(); + if (layerFilter != NamedSettingsLayers.All) + { + var settings = ActiveSliceSettings.Instance; - FlowLayoutWidget addContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); - addContainer.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; - addContainer.HAnchor = Agg.UI.HAnchor.ParentLeftRight; + // TODO: The editing context needs to provide the key + System.Diagnostics.Debugger.Break(); + string layerKey = settings.ActiveMaterialKey; - TextWidget errorMessage = new TextWidget("Oops! Please select a setting first.", pointSize: 10); - errorMessage.TextColor = ActiveTheme.Instance.SecondaryAccentColor; + layerFilters = new List { settings.BaseLayer, settings.OemLayer }; - errorMessageContainer = new FlowLayoutWidget(); - errorMessageContainer.HAnchor = Agg.UI.HAnchor.ParentLeftRight; - errorMessageContainer.BackgroundColor = ActiveTheme.Instance.TransparentDarkOverlay; - errorMessageContainer.Visible = false; - errorMessageContainer.Padding = new BorderDouble(3); + switch (layerFilter) + { + case NamedSettingsLayers.Material: + layerFilters.Add(settings.GetMaterialLayer(layerKey)); + break; - errorMessageContainer.AddChild(new HorizontalSpacer()); - errorMessageContainer.AddChild(errorMessage); - errorMessageContainer.AddChild(new HorizontalSpacer()); + case NamedSettingsLayers.Quality: + layerFilters.Add(settings.GetQualityLayer(layerKey)); + break; + } + } - addSettingsContainer = new FlowLayoutWidget(); - addSettingsContainer.Padding = new BorderDouble(3); - addSettingsContainer.BackgroundColor = ActiveTheme.Instance.TransparentDarkOverlay; - addSettingsContainer.HAnchor = HAnchor.ParentLeftRight; + var settingsWidget = new SliceSettingsWidget(layerFilters, NamedSettingsLayers.Material); + settingsWidget.settingsControlBar.Visible = false; - PopulateAddSettingRow(); - - addContainer.AddChild(addSettingsContainer); - addContainer.AddChild(errorMessageContainer); - - settingsRowContainer = new PresetListControl(); - settingsRowContainer.HAnchor = HAnchor.ParentLeftRight; - - LoadSettingsRows(); - - topBottomContainer.AddChild(addContainer); - topBottomContainer.AddChild(settingsRowContainer); - - container.AddChild(topBottomContainer); - return container; + return settingsWidget; } private FlowLayoutWidget GetBottomRow() @@ -326,7 +311,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { itemName = "{0} ({1})".FormatWith(itemName, setting.ExtraSettings.Replace("\\n", " ")); } - if (ActivePrinterProfile.Instance.ActiveSliceEngine.MapContains(setting.SlicerConfigName)) + if (ActiveSliceSettings.Instance.ActiveSliceEngine.MapContains(setting.SlicerConfigName)) { MenuItem settingMenuItem = settingDropDownList.AddItem(itemName, itemValue); settingMenuItem.Selected += new EventHandler(OnItemSelected); @@ -376,7 +361,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration OrganizerSettingsData settingData = SliceSettingsOrganizer.Instance.GetSettingsData(item.Key); // Don't add row if there is no entry - if (settingData != null && ActivePrinterProfile.Instance.ActiveSliceEngine.MapContains(settingData.SlicerConfigName)) + if (settingData != null && ActiveSliceSettings.Instance.ActiveSliceEngine.MapContains(settingData.SlicerConfigName)) { FlowLayoutWidget row = GetSettingsRow(settingData, item.Value.Value); row.Padding = new BorderDouble(3, 3, 3, 6); @@ -510,7 +495,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration double minSettingNameWidth = 400; - if (ActiveSliceSettings.Instance.Contains(settingData.SlicerConfigName)) + if (ActiveSliceSettings.Instance.InBaseConfig(settingData.SlicerConfigName)) { int intEditWidth = 60; int doubleEditWidth = 60; @@ -897,14 +882,18 @@ namespace MatterHackers.MatterControl.SlicerConfiguration Dictionary settingsDictionary = new Dictionary(); SliceSettingsCollection collection = new SliceSettingsCollection(); - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { + // TODO: Review bindings to int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + collection.Name = string.Format("{0} ({1})", windowController.filterLabel, noExistingPresets.ToString()); collection.Tag = windowController.filterTag; - collection.PrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + collection.PrinterId = printerID; } - windowController.ActivePresetLayer = new SettingsLayer(collection, settingsDictionary); + windowController.ActivePresetLayer = new ClassicSqlitePrinterProfiles.ClassicSettingsLayer(collection, settingsDictionary); } public int ExistingPresetsCount() @@ -923,9 +912,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration saveActivePresets(); windowController.functionToCallOnSave(this, null); windowController.ChangeToSlicePresetList(); - ActiveSliceSettings.Instance.LoadAllSettings(); - // Disabled this as the panel is already reloaded from LoadAllSettings LBB 2015 01 03. - //ApplicationController.Instance.ReloadAdvancedControlsPanel(); } }); } @@ -950,7 +936,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration settingsDictionary.Add(s.Name, newSetting); } - SettingsLayer duplicateLayer = new SettingsLayer(duplicateCollection, settingsDictionary); + var duplicateLayer = new ClassicSqlitePrinterProfiles.ClassicSettingsLayer(duplicateCollection, settingsDictionary); windowController.ActivePresetLayer = duplicateLayer; windowController.ChangeToSlicePresetDetail(); }); diff --git a/SlicerConfiguration/SlicePresetsWindow/SlicePresetListWidget.cs b/SlicerConfiguration/SlicePresetsWindow/SlicePresetListWidget.cs index 4931c5951..8e1fad04a 100644 --- a/SlicerConfiguration/SlicePresetsWindow/SlicePresetListWidget.cs +++ b/SlicerConfiguration/SlicePresetsWindow/SlicePresetListWidget.cs @@ -174,10 +174,14 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { if (File.Exists(openParams.FileName)) { + // TODO: Review bindings to int printerID + int printerID; + int.TryParse(ActiveSliceSettings.Instance.Id, out printerID); + //Create collection to hold preset settings settingsCollection = new SliceSettingsCollection(); settingsCollection.Tag = windowController.filterTag; - settingsCollection.PrinterId = ActivePrinterProfile.Instance.ActivePrinter.Id; + settingsCollection.PrinterId = printerID; settingsCollection.Name = System.IO.Path.GetFileNameWithoutExtension(openParams.FileName); settingsCollection.Commit(); @@ -211,10 +215,10 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private IEnumerable GetCollections() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { //Retrieve a list of collections matching from the Datastore - string query = string.Format("SELECT * FROM SliceSettingsCollection WHERE Tag = '{0}' AND PrinterId = {1} ORDER BY Name;", windowController.filterTag, ActivePrinterProfile.Instance.ActivePrinter.Id); + string query = string.Format("SELECT * FROM SliceSettingsCollection WHERE Tag = '{0}' AND PrinterId = {1} ORDER BY Name;", windowController.filterTag, ActiveSliceSettings.Instance.Id); return Datastore.Instance.dbSQLite.Query(query); } @@ -257,33 +261,34 @@ namespace MatterHackers.MatterControl.SlicerConfiguration Button materialRemoveLink = linkButtonFactory.Generate("remove"); materialRemoveLink.Margin = new BorderDouble(left: 4); + this.DebugShowBounds = true; materialRemoveLink.VAnchor = Agg.UI.VAnchor.ParentCenter; materialRemoveLink.Click += (sender, e) => { UiThread.RunOnIdle(() => { //Unwind this setting if it is currently active - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { + /* if (preset.Id == ActivePrinterProfile.Instance.ActiveQualitySettingsID) { ActivePrinterProfile.Instance.ActiveQualitySettingsID = 0; } - string[] activeMaterialPresets = ActivePrinterProfile.Instance.ActivePrinter.MaterialCollectionIds.Split(','); + string[] activeMaterialPresets = ActiveSliceSettings.Instance.MaterialCollectionIds.Split(','); for (int i = 0; i < activeMaterialPresets.Count(); i++) { int index = 0; Int32.TryParse(activeMaterialPresets[i], out index); if (preset.Id == index) { - ActivePrinterProfile.Instance.SetMaterialSetting(i + 1, 0); + ActiveSliceSettings.Instance.SetMaterialPreset(i, ""); } - } + } */ } preset.Delete(); windowController.ChangeToSlicePresetList(); - ActiveSliceSettings.Instance.LoadAllSettings(); ApplicationController.Instance.ReloadAdvancedControlsPanel(); }); }; diff --git a/SlicerConfiguration/SlicePresetsWindow/SlicePresetsWindow.cs b/SlicerConfiguration/SlicePresetsWindow/SlicePresetsWindow.cs index 6f960f7d6..ea599d610 100644 --- a/SlicerConfiguration/SlicePresetsWindow/SlicePresetsWindow.cs +++ b/SlicerConfiguration/SlicePresetsWindow/SlicePresetsWindow.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Lars Brubaker +Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -30,6 +30,7 @@ either expressed or implied, of the FreeBSD Project. using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.DataStorage; +using MatterHackers.MatterControl.DataStorage.ClassicDB; using MatterHackers.VectorMath; using System; using System.Collections.Generic; @@ -41,9 +42,15 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public EventHandler functionToCallOnSave; public string filterTag; public string filterLabel; - public SettingsLayer ActivePresetLayer; - public SlicePresetsWindow(EventHandler functionToCallOnSave, string filterLabel, string filterTag, bool showList = true, int collectionID = 0) + // TODO: Short term compile hack + public ClassicSqlitePrinterProfiles.ClassicSettingsLayer ActivePresetLayer + { + get; + set; + } + + public SlicePresetsWindow(EventHandler functionToCallOnSave, string filterLabel, string filterTag, bool showList = true, string presetKey = null) : base(640, 480) { AlwaysOnTopOfMain = true; @@ -61,6 +68,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } else { + /* if (collectionID == 0) { ChangeToSlicePresetDetail(); @@ -68,7 +76,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration else { ChangeToSlicePresetDetail(GetCollection(collectionID)); - } + } */ } ShowAsSystemWindow(); this.MinimumSize = new Vector2(640, 480); @@ -86,13 +94,12 @@ namespace MatterHackers.MatterControl.SlicerConfiguration this.RemoveAllChildren(); this.AddChild(slicePresetWidget); this.Invalidate(); + } - ApplicationController.Instance.ReloadAdvancedControlsPanel(); - } - - public void ChangeToSlicePresetFromID(int collectionId) + public void ChangeToSlicePresetFromID(string collectionId) { - ChangeToSlicePresetDetail(GetCollection(collectionId)); + throw new NotImplementedException(); + //ChangeToSlicePresetDetail(GetCollection(collectionId)); } public void ChangeToSlicePresetDetail(SliceSettingsCollection collection = null) @@ -104,8 +111,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { settingsDictionary[s.Name] = s; } - - this.ActivePresetLayer = new SettingsLayer(collection, settingsDictionary); + this.ActivePresetLayer = new ClassicSqlitePrinterProfiles.ClassicSettingsLayer(collection, settingsDictionary); } UiThread.RunOnIdle(DoChangeToSlicePresetDetail); } diff --git a/SlicerConfiguration/SliceSettingsDetailControl.cs b/SlicerConfiguration/SliceSettingsDetailControl.cs index 61e0c5164..020e1d95c 100644 --- a/SlicerConfiguration/SliceSettingsDetailControl.cs +++ b/SlicerConfiguration/SliceSettingsDetailControl.cs @@ -92,7 +92,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { UiThread.RunOnIdle(() => { - ActiveSliceSettings.Instance.LoadSettingsFromIni(); + // TODO: jlewin + throw new NotImplementedException(); + // ActiveSliceSettings.Instance.LoadSettingsFromIni(); }); return true; } @@ -128,9 +130,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration //Set the name and callback function of the menu items slicerOptionsMenuItems = new TupleList> { - { "Import".Localize(), ImportSettingsMenu_Click}, - {"Export".Localize(), ExportSettingsMenu_Click}, - {"Restore All".Localize(), RestoreAllSettingsMenu_Click}, + { "Import".Localize(), ImportSettingsMenu_Click }, + { "Export".Localize(), ExportSettingsMenu_Click }, + { "Restore All".Localize(), RestoreAllSettingsMenu_Click }, }; //Add the menu items to the menu itself diff --git a/SlicerConfiguration/SliceSettingsWidget.cs b/SlicerConfiguration/SliceSettingsWidget.cs index 837fc9281..d76896bd4 100644 --- a/SlicerConfiguration/SliceSettingsWidget.cs +++ b/SlicerConfiguration/SliceSettingsWidget.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Lars Brubaker +Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -30,10 +30,8 @@ using MatterHackers.Agg; using MatterHackers.Agg.Image; using MatterHackers.Agg.PlatformAbstract; using MatterHackers.Agg.UI; -using MatterHackers.Agg.VertexSource; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; -using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.VectorMath; using System; @@ -42,6 +40,31 @@ using System.Linq; namespace MatterHackers.MatterControl.SlicerConfiguration { + public class NoSettingsWidget : FlowLayoutWidget + { + public NoSettingsWidget() : base (FlowDirection.TopToBottom, vAnchor: VAnchor.ParentTop) + { + this.AnchorAll(); + this.Padding = new BorderDouble(3, 0); + + var noConnectionMessageContainer = new AltGroupBox(new TextWidget(LocalizedString.Get("No Printer Selected"), pointSize: 18, textColor: ActiveTheme.Instance.SecondaryAccentColor)); + noConnectionMessageContainer.Margin = new BorderDouble(top: 10); + noConnectionMessageContainer.BorderColor = ActiveTheme.Instance.PrimaryTextColor; + noConnectionMessageContainer.HAnchor = Agg.UI.HAnchor.ParentLeftRight; + noConnectionMessageContainer.Height = 90; + + string noConnectionString = LocalizedString.Get("No printer is currently selected. Please select a printer to edit slice settings."); + noConnectionString += "\n\n" + LocalizedString.Get("NOTE: You need to select a printer, but do not need to connect to it."); + TextWidget noConnectionMessage = new TextWidget(noConnectionString, pointSize: 10); + noConnectionMessage.Margin = new BorderDouble(5); + noConnectionMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor; + noConnectionMessage.VAnchor = VAnchor.ParentCenter; + + noConnectionMessageContainer.AddChild(noConnectionMessage); + this.AddChild(noConnectionMessageContainer); + } + } + public class SliceSettingsWidget : GuiWidget { private static List settingToReloadUiWhenChanged = new List() @@ -63,14 +86,36 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private TabControl categoryTabs; private AltGroupBox noConnectionMessageContainer; - private SettingsControlBar settingsControlBar; - private string activeMaterialPreset; - private string activeQualityPreset; + internal SettingsControlBar settingsControlBar; - private TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory(); + private TextImageButtonFactory textImageButtonFactory; - public SliceSettingsWidget() + private List layerFilters = null; + private SettingsLayer persistenceLayer = null; + + private NamedSettingsLayers viewFilter; + + public SliceSettingsWidget(List layerFilters = null, NamedSettingsLayers viewFilter = NamedSettingsLayers.All) { + this.layerFilters = layerFilters; + this.viewFilter = viewFilter; + + // The last layer of the layerFilters is the target persistence layer + persistenceLayer = layerFilters?.Last() ?? ActiveSliceSettings.Instance.UserLayer; + + textImageButtonFactory = new TextImageButtonFactory(); + textImageButtonFactory.normalFillColor = RGBA_Bytes.Transparent; + textImageButtonFactory.FixedHeight = 15 * TextWidget.GlobalPointSizeScaleRatio; + textImageButtonFactory.fontSize = 8; + textImageButtonFactory.borderWidth = 1; + textImageButtonFactory.normalBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200); + textImageButtonFactory.hoverBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200); + + this.textImageButtonFactory.disabledTextColor = RGBA_Bytes.Gray; + this.textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor; + this.textImageButtonFactory.normalTextColor = ActiveTheme.Instance.SecondaryTextColor; + this.textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor; + int minSettingNameWidth = (int)(180 * TextWidget.GlobalPointSizeScaleRatio + .5); buttonFactory.FixedHeight = 20 * TextWidget.GlobalPointSizeScaleRatio; buttonFactory.fontSize = 10; @@ -88,8 +133,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration BackgroundColor = ActiveTheme.Instance.TransparentDarkOverlay, Padding = new BorderDouble(8, 12, 8, 8) }; - this.activeMaterialPreset = settingsControlBar.activeMaterialPreset; - this.activeQualityPreset = settingsControlBar.activeQualityPreset; pageTopToBottomLayout.AddChild(settingsControlBar); @@ -136,7 +179,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration categoryTabs.TabBar.AddChild(new HorizontalSpacer()); categoryTabs.TabBar.AddChild(sliceSettingsDetailControl); - if (sliceSettingsDetailControl.SelectedValue == "Advanced" && ActivePrinterProfile.Instance.ActiveSliceEngineType == ActivePrinterProfile.SlicingEngineTypes.Slic3r) + if (sliceSettingsDetailControl.SelectedValue == "Advanced" && ActiveSliceSettings.Instance.ActiveSliceEngineType == SlicingEngineTypes.Slic3r) { TabPage extraSettingsPage = new TabPage("Other"); SimpleTextTabWidget extraSettingsTextTabWidget = new SimpleTextTabWidget(extraSettingsPage, "Other Tab", 16, @@ -241,17 +284,13 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private void AddHandlers() { PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); - ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(APP_onPrinterStatusChanged, ref unregisterEvents); + ActiveSliceSettings.ActivePrinterChanged.RegisterEvent(APP_onPrinterStatusChanged, ref unregisterEvents); PrinterConnectionAndCommunication.Instance.EnableChanged.RegisterEvent(onPrinterStatusChanged, ref unregisterEvents); } public override void OnClosed(EventArgs e) { - if (unregisterEvents != null) - { - unregisterEvents(this, null); - } - + unregisterEvents?.Invoke(this, null); base.OnClosed(e); } @@ -269,7 +308,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private void SetVisibleControls() { - if (ActivePrinterProfile.Instance.ActivePrinter != null) + if (ActiveSliceSettings.Instance != null) { categoryTabs.Visible = true; settingsControlBar.Visible = true; @@ -331,7 +370,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { bool settingShouldBeShown = CheckIfShouldBeShown(settingInfo); - if (ActivePrinterProfile.Instance.ActiveSliceEngine.MapContains(settingInfo.SlicerConfigName) + if (ActiveSliceSettings.Instance.ActiveSliceEngine.MapContains(settingInfo.SlicerConfigName) && settingShouldBeShown) { addedSettingToSubGroup = true; @@ -482,12 +521,12 @@ namespace MatterHackers.MatterControl.SlicerConfiguration FlowLayoutWidget topToBottomSettings = new FlowLayoutWidget(FlowDirection.TopToBottom); topToBottomSettings.HAnchor = Agg.UI.HAnchor.Max_FitToChildren_ParentWidth; - foreach (KeyValuePair item in ActiveSliceSettings.Instance.DefaultSettings) + foreach (var kvp in ActiveSliceSettings.Instance.BaseLayer) { - if (!SliceSettingsOrganizer.Instance.Contains(UserLevel, item.Key)) + if (!SliceSettingsOrganizer.Instance.Contains(UserLevel, kvp.Key)) { - OrganizerSettingsData settingInfo = new OrganizerSettingsData(item.Key, item.Key, OrganizerSettingsData.DataEditTypes.STRING); - if (ActivePrinterProfile.Instance.ActiveSliceEngine.MapContains(settingInfo.SlicerConfigName)) + OrganizerSettingsData settingInfo = new OrganizerSettingsData(kvp.Key, kvp.Key, OrganizerSettingsData.DataEditTypes.STRING); + if (ActiveSliceSettings.Instance.ActiveSliceEngine.MapContains(settingInfo.SlicerConfigName)) { GuiWidget controlsForThisSetting = CreateSettingInfoUIControls(settingInfo, minSettingNameWidth, 0); topToBottomSettings.AddChild(controlsForThisSetting); @@ -525,7 +564,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public static RootedObjectEventHandler SettingChanged = new RootedObjectEventHandler(); - private void CallEventsOnSettingsChange(OrganizerSettingsData settingData) + private void OnSettingsChanged(OrganizerSettingsData settingData) { SettingChanged.CallEvents(this, new StringEventArgs(settingData.SlicerConfigName)); @@ -535,27 +574,62 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } } + private class SettingsRow : FlowLayoutWidget + { + public string SettingsKey { get; set; } + public string SettingsValue { get; set; } + + public Action ValueChanged { get; set; } + public Action UpdateStyle { get; set; } + + public SettingsRow() + { + Margin = new BorderDouble(0, 2); + Padding = new BorderDouble(3); + HAnchor = Agg.UI.HAnchor.ParentLeftRight; + } + + public void RefreshValue() + { + string latestValue = ActiveSliceSettings.Instance.GetActiveValue(this.SettingsKey); + //if(latestValue != SettingsValue) + { + ValueChanged?.Invoke(latestValue); + } + + UpdateStyle?.Invoke(); + + SettingsValue = latestValue; + } + } + + private static readonly RGBA_Bytes materialSettingBackgroundColor = new RGBA_Bytes(255, 127, 0, 108); + private static readonly RGBA_Bytes userSettingBackgroundColor = new RGBA_Bytes(68, 95, 220, 108); + private static readonly RGBA_Bytes qualitySettingBackgroundColor = new RGBA_Bytes(255, 255, 0, 108); + private GuiWidget CreateSettingInfoUIControls(OrganizerSettingsData settingData, double minSettingNameWidth, int extruderIndex) { GuiWidget container = new GuiWidget(); - FlowLayoutWidget leftToRightLayout = new FlowLayoutWidget(); - - this.textImageButtonFactory.normalFillColor = RGBA_Bytes.Transparent; - this.textImageButtonFactory.FixedHeight = 15 * TextWidget.GlobalPointSizeScaleRatio; - this.textImageButtonFactory.fontSize = 8; - this.textImageButtonFactory.borderWidth = 1; - this.textImageButtonFactory.normalBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200); - this.textImageButtonFactory.hoverBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200); - - this.textImageButtonFactory.disabledTextColor = RGBA_Bytes.Gray; - this.textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor; - this.textImageButtonFactory.normalTextColor = ActiveTheme.Instance.SecondaryTextColor; - this.textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor; this.HAnchor = HAnchor.ParentLeftRight; - Action restoreActiveSetting; + string sliceSettingValue = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - if (ActiveSliceSettings.Instance.Contains(settingData.SlicerConfigName)) + var settingsRow = new SettingsRow() + { + SettingsKey = settingData.SlicerConfigName, + SettingsValue = sliceSettingValue + }; + + if (!ActiveSliceSettings.Instance.InBaseConfig(settingData.SlicerConfigName)) + { + // the setting we think we are adding is not in the config.ini it may have been deprecated + TextWidget settingName = new TextWidget(String.Format("Setting '{0}' not found in config.ini", settingData.SlicerConfigName)); + settingName.TextColor = ActiveTheme.Instance.PrimaryTextColor; + settingName.MinimumSize = new Vector2(minSettingNameWidth, settingName.MinimumSize.y); + settingsRow.AddChild(settingName); + settingsRow.BackgroundColor = RGBA_Bytes.Red; + } + else { int intEditWidth = (int)(60 * TextWidget.GlobalPointSizeScaleRatio + .5); int doubleEditWidth = (int)(60 * TextWidget.GlobalPointSizeScaleRatio + .5); @@ -566,80 +640,77 @@ namespace MatterHackers.MatterControl.SlicerConfiguration int vectorXYEditWidth = (int)(60 * TextWidget.GlobalPointSizeScaleRatio + .5); int multiLineEditHeight = (int)(60 * TextWidget.GlobalPointSizeScaleRatio + .5); - string sliceSettingValue = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - leftToRightLayout.Margin = new BorderDouble(0, 2); - leftToRightLayout.Padding = new BorderDouble(3); - leftToRightLayout.HAnchor = Agg.UI.HAnchor.ParentLeftRight; if (settingData.DataEditType != OrganizerSettingsData.DataEditTypes.MULTI_LINE_TEXT) { - string localizedPresentationName = settingData.PresentationName.Localize(); - - GuiWidget nameHolder = new GuiWidget(HAnchor.AbsolutePosition, VAnchor.FitToChildren | VAnchor.ParentCenter) + var nameHolder = new GuiWidget(HAnchor.AbsolutePosition, VAnchor.FitToChildren | VAnchor.ParentCenter) { Width = minSettingNameWidth, Padding = new BorderDouble(0, 0, 5, 0), }; - { - GuiWidget presentationName = new WrappedTextWidget(localizedPresentationName, minSettingNameWidth, pointSize: 10, textColor: ActiveTheme.Instance.PrimaryTextColor); - nameHolder.AddChild(presentationName); - } + nameHolder.AddChild(new WrappedTextWidget( + settingData.PresentationName.Localize(), + minSettingNameWidth, + pointSize: 10, + textColor: ActiveTheme.Instance.PrimaryTextColor)); - leftToRightLayout.AddChild(nameHolder); + settingsRow.AddChild(nameHolder); } switch (settingData.DataEditType) { case OrganizerSettingsData.DataEditTypes.INT: { - int currentValue = 0; + int currentValue; int.TryParse(sliceSettingValue, out currentValue); - MHNumberEdit intEditWidget = new MHNumberEdit(currentValue, pixelWidth: intEditWidth, tabIndex: tabIndexForItem++); - intEditWidget.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => + + var intEditWidget = new MHNumberEdit(currentValue, pixelWidth: intEditWidth, tabIndex: tabIndexForItem++) { - intEditWidget.Text = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true }; intEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => { - Action localRestore = restoreActiveSetting; SaveSetting(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString()); - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); - }; - intEditWidget.SelectAllOnFocus = true; + settingsRow.UpdateStyle(); - leftToRightLayout.AddChild(intEditWidget); - leftToRightLayout.AddChild(GetExtraSettingsWidget(settingData)); + OnSettingsChanged(settingData); + }; + + settingsRow.AddChild(intEditWidget); + settingsRow.AddChild(GetExtraSettingsWidget(settingData)); + + settingsRow.ValueChanged = (text) => intEditWidget.Text = text; } break; case OrganizerSettingsData.DataEditTypes.DOUBLE: { - double currentValue = 0; + double currentValue; double.TryParse(sliceSettingValue, out currentValue); - MHNumberEdit doubleEditWidget = new MHNumberEdit(currentValue, allowNegatives: true, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++); - doubleEditWidget.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => + + var doubleEditWidget = new MHNumberEdit(currentValue, allowNegatives: true, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++) { - double currentValue2 = 0; - double.TryParse(ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName), out currentValue2); - doubleEditWidget.ActuallNumberEdit.Value = currentValue2; - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true }; - doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => { - Action localRestore = restoreActiveSetting; SaveSetting(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString()); - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(doubleEditWidget); + settingsRow.AddChild(GetExtraSettingsWidget(settingData)); + + settingsRow.ValueChanged = (text) => + { + double currentValue2 = 0; + double.TryParse(text, out currentValue2); + doubleEditWidget.ActuallNumberEdit.Value = currentValue2; }; - doubleEditWidget.SelectAllOnFocus = true; - leftToRightLayout.AddChild(doubleEditWidget); - leftToRightLayout.AddChild(GetExtraSettingsWidget(settingData)); } break; @@ -648,11 +719,14 @@ namespace MatterHackers.MatterControl.SlicerConfiguration const string multiValuesAreDiffernt = "-"; FlowLayoutWidget content = new FlowLayoutWidget(); - MHNumberEdit doubleEditWidget = new MHNumberEdit(0, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++); - doubleEditWidget.ToolTipText = settingData.HelpText; - doubleEditWidget.Name = settingData.PresentationName + " Textbox"; + var doubleEditWidget = new MHNumberEdit(0, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++) + { + ToolTipText = settingData.HelpText, + Name = settingData.PresentationName + " Textbox", + SelectAllOnFocus = true + }; - double currentValue = 0; + double currentValue; bool ChangesMultipleOtherSettings = settingData.SetSettingsOnChange.Count > 0; if (ChangesMultipleOtherSettings) { @@ -684,14 +758,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration doubleEditWidget.ActuallNumberEdit.Value = currentValue; } doubleEditWidget.ActuallNumberEdit.InternalTextEditWidget.MarkAsStartingState(); - - restoreActiveSetting = () => - { - double currentValue2 = 0; - double.TryParse(ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName), out currentValue2); - doubleEditWidget.ActuallNumberEdit.Value = currentValue2; - CallEventsOnSettingsChange(settingData); - }; + doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => { NumberEdit numberEdit = (NumberEdit)sender; @@ -707,49 +774,55 @@ namespace MatterHackers.MatterControl.SlicerConfiguration // also always save to the local setting SaveSetting(settingData.SlicerConfigName, numberEdit.Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - - CallEventsOnSettingsChange(settingData); + settingsRow.UpdateStyle(); + OnSettingsChanged(settingData); }; - doubleEditWidget.SelectAllOnFocus = true; content.AddChild(doubleEditWidget); content.AddChild(GetExtraSettingsWidget(settingData)); if (settingData.QuickMenuSettings.Count > 0) { - leftToRightLayout.AddChild(CreateQuickMenu(settingData, content, doubleEditWidget.ActuallNumberEdit.InternalTextEditWidget)); + settingsRow.AddChild(CreateQuickMenu(settingData, content, doubleEditWidget.ActuallNumberEdit.InternalTextEditWidget)); } else { - leftToRightLayout.AddChild(content); + settingsRow.AddChild(content); } + + settingsRow.ValueChanged = (text) => + { + double currentValue2 = 0; + double.TryParse(text, out currentValue2); + doubleEditWidget.ActuallNumberEdit.Value = currentValue2; + }; } break; case OrganizerSettingsData.DataEditTypes.OFFSET: { - double currentValue = 0; + double currentValue; double.TryParse(sliceSettingValue, out currentValue); - MHNumberEdit doubleEditWidget = new MHNumberEdit(currentValue, allowDecimals: true, allowNegatives: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++); - doubleEditWidget.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => + var doubleEditWidget = new MHNumberEdit(currentValue, allowDecimals: true, allowNegatives: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++) { - double currentValue2 = 0; - double.TryParse(ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName), out currentValue2); - doubleEditWidget.ActuallNumberEdit.Value = currentValue2; - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true + }; doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => - { - SaveSetting(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); - }; - doubleEditWidget.SelectAllOnFocus = true; - leftToRightLayout.AddChild(doubleEditWidget); - leftToRightLayout.AddChild(GetExtraSettingsWidget(settingData)); + { + SaveSetting(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString()); + settingsRow.UpdateStyle(); + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(doubleEditWidget); + settingsRow.AddChild(GetExtraSettingsWidget(settingData)); + + settingsRow.ValueChanged = (text) => + { + double currentValue2; + double.TryParse(text, out currentValue2); + doubleEditWidget.ActuallNumberEdit.Value = currentValue2; + }; } break; @@ -757,18 +830,16 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { FlowLayoutWidget content = new FlowLayoutWidget(); - MHTextEditWidget stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++); - stringEdit.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => + var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++) { - stringEdit.Text = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true }; stringEdit.ActualTextEditWidget.EditComplete += (sender, e) => { - TextEditWidget textEditWidget = (TextEditWidget)sender; - string text = textEditWidget.Text; - text = text.Trim(); + var textEditWidget = (TextEditWidget)sender; + string text = textEditWidget.Text.Trim(); + bool isPercent = text.Contains("%"); if (isPercent) { @@ -783,11 +854,10 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } textEditWidget.Text = text; SaveSetting(settingData.SlicerConfigName, textEditWidget.Text); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); }; - stringEdit.SelectAllOnFocus = true; stringEdit.ActualTextEditWidget.InternalTextEditWidget.AllSelected += (sender, e) => { @@ -805,12 +875,14 @@ namespace MatterHackers.MatterControl.SlicerConfiguration if (settingData.QuickMenuSettings.Count > 0) { - leftToRightLayout.AddChild(CreateQuickMenu(settingData, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget)); + settingsRow.AddChild(CreateQuickMenu(settingData, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget)); } else { - leftToRightLayout.AddChild(content); + settingsRow.AddChild(content); } + + settingsRow.ValueChanged = (text) => stringEdit.Text = text; } break; @@ -818,14 +890,12 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { FlowLayoutWidget content = new FlowLayoutWidget(); - MHTextEditWidget stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++); - stringEdit.ToolTipText = settingData.HelpText; - - restoreActiveSetting = () => + var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++) { - stringEdit.Text = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true }; + string startingText = stringEdit.Text; stringEdit.ActualTextEditWidget.EditComplete += (sender, e) => { @@ -856,10 +926,8 @@ namespace MatterHackers.MatterControl.SlicerConfiguration startingText = stringEdit.Text; } SaveSetting(settingData.SlicerConfigName, textEditWidget.Text); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); + OnSettingsChanged(settingData); // make sure we are still looking for the final validation before saving. if (textEditWidget.ContainsFocus) @@ -875,7 +943,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration }); } }; - stringEdit.SelectAllOnFocus = true; stringEdit.ActualTextEditWidget.InternalTextEditWidget.AllSelected += (sender, e) => { @@ -893,105 +960,88 @@ namespace MatterHackers.MatterControl.SlicerConfiguration if (settingData.QuickMenuSettings.Count > 0) { - leftToRightLayout.AddChild(CreateQuickMenu(settingData, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget)); + settingsRow.AddChild(CreateQuickMenu(settingData, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget)); } else { - leftToRightLayout.AddChild(content); + settingsRow.AddChild(content); } + + settingsRow.ValueChanged = (text) => stringEdit.Text = text; } break; case OrganizerSettingsData.DataEditTypes.CHECK_BOX: { - CheckBox checkBoxWidget = new CheckBox(""); - checkBoxWidget.Name = settingData.PresentationName + " Checkbox"; - checkBoxWidget.ToolTipText = settingData.HelpText; - checkBoxWidget.VAnchor = Agg.UI.VAnchor.ParentBottom; - checkBoxWidget.TextColor = ActiveTheme.Instance.PrimaryTextColor; - checkBoxWidget.Checked = (sliceSettingValue == "1"); - restoreActiveSetting = () => + var checkBoxWidget = new CheckBox("") { - checkBoxWidget.Checked = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName) == "1"; - CallEventsOnSettingsChange(settingData); + Name = settingData.PresentationName + " Checkbox", + ToolTipText = settingData.HelpText, + VAnchor = Agg.UI.VAnchor.ParentBottom, + TextColor = ActiveTheme.Instance.PrimaryTextColor, + Checked = sliceSettingValue == "1" }; checkBoxWidget.CheckedStateChanged += (sender, e) => { - if (((CheckBox)sender).Checked) - { - SaveSetting(settingData.SlicerConfigName, "1"); - } - else - { - SaveSetting(settingData.SlicerConfigName, "0"); - } - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); + bool isChecked = ((CheckBox)sender).Checked; + SaveSetting(settingData.SlicerConfigName, isChecked ? "1" : "0"); + settingsRow.UpdateStyle(); - CallEventsOnSettingsChange(settingData); + OnSettingsChanged(settingData); }; - leftToRightLayout.AddChild(checkBoxWidget); + settingsRow.AddChild(checkBoxWidget); + + settingsRow.ValueChanged = (text) => checkBoxWidget.Checked = text == "1"; } break; case OrganizerSettingsData.DataEditTypes.STRING: { - MHTextEditWidget stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: 120, tabIndex: tabIndexForItem++); + var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: 120, tabIndex: tabIndexForItem++); stringEdit.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => - { - stringEdit.Text = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - CallEventsOnSettingsChange(settingData); - }; stringEdit.ActualTextEditWidget.EditComplete += (sender, e) => { SaveSetting(settingData.SlicerConfigName, ((TextEditWidget)sender).Text); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); + settingsRow.UpdateStyle(); - CallEventsOnSettingsChange(settingData); + OnSettingsChanged(settingData); }; - leftToRightLayout.AddChild(stringEdit); + settingsRow.AddChild(stringEdit); + + settingsRow.ValueChanged = (text) => stringEdit.Text = text; } break; case OrganizerSettingsData.DataEditTypes.MULTI_LINE_TEXT: { string convertedNewLines = sliceSettingValue.Replace("\\n", "\n"); - MHTextEditWidget stringEdit = new MHTextEditWidget(convertedNewLines, pixelWidth: 320, pixelHeight: multiLineEditHeight, multiLine: true, tabIndex: tabIndexForItem++); - restoreActiveSetting = () => - { - stringEdit.Text = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName).Replace("\\n", "\n"); - CallEventsOnSettingsChange(settingData); - }; + var stringEdit = new MHTextEditWidget(convertedNewLines, pixelWidth: 320, pixelHeight: multiLineEditHeight, multiLine: true, tabIndex: tabIndexForItem++); + stringEdit.ActualTextEditWidget.EditComplete += (sender, e) => { SaveSetting(settingData.SlicerConfigName, ((TextEditWidget)sender).Text.Replace("\n", "\\n")); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); + settingsRow.UpdateStyle(); - CallEventsOnSettingsChange(settingData); + OnSettingsChanged(settingData); }; - leftToRightLayout.AddChild(stringEdit); + settingsRow.AddChild(stringEdit); + + settingsRow.ValueChanged = (text) => stringEdit.Text = text.Replace("\\n", "\n"); } break; case OrganizerSettingsData.DataEditTypes.LIST: { - StyledDropDownList selectableOptions = new StyledDropDownList("None", maxHeight: 200); - selectableOptions.ToolTipText = settingData.HelpText; - selectableOptions.Margin = new BorderDouble(); - string[] listItems = settingData.ExtraSettings.Split(','); - restoreActiveSetting = () => + var selectableOptions = new StyledDropDownList("None", maxHeight: 200) { - selectableOptions.SelectedLabel = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName); - CallEventsOnSettingsChange(settingData); + ToolTipText = settingData.HelpText, + Margin = new BorderDouble() }; - foreach (string listItem in listItems) + foreach (string listItem in settingData.ExtraSettings.Split(',')) { MenuItem newItem = selectableOptions.AddItem(listItem); if (newItem.Text == sliceSettingValue) @@ -1003,49 +1053,43 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { MenuItem menuItem = ((MenuItem)sender); SaveSetting(settingData.SlicerConfigName, menuItem.Text); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); }; } - leftToRightLayout.AddChild(selectableOptions); + settingsRow.AddChild(selectableOptions); + + settingsRow.ValueChanged = (text) => selectableOptions.SelectedLabel = text; } break; case OrganizerSettingsData.DataEditTypes.HARDWARE_PRESENT: { - CheckBox checkBoxWidget = new CheckBox(""); - checkBoxWidget.Name = settingData.PresentationName + " Checkbox"; - checkBoxWidget.ToolTipText = settingData.HelpText; - checkBoxWidget.VAnchor = Agg.UI.VAnchor.ParentBottom; - checkBoxWidget.TextColor = ActiveTheme.Instance.PrimaryTextColor; - checkBoxWidget.Checked = (sliceSettingValue == "1"); - restoreActiveSetting = () => + var checkBoxWidget = new CheckBox("") { - checkBoxWidget.Checked = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName) == "1"; - CallEventsOnSettingsChange(settingData); + Name = settingData.PresentationName + " Checkbox", + ToolTipText = settingData.HelpText, + VAnchor = Agg.UI.VAnchor.ParentBottom, + TextColor = ActiveTheme.Instance.PrimaryTextColor, + Checked = sliceSettingValue == "1" }; + checkBoxWidget.CheckedStateChanged += (sender, e) => { - if (((CheckBox)sender).Checked) - { - SaveSetting(settingData.SlicerConfigName, "1"); - // Now show all of the settings that this control is associated with. - } - else - { - SaveSetting(settingData.SlicerConfigName, "0"); - // Now hide all of the settings that this control is associated with. - } - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); + bool isChecked = ((CheckBox)sender).Checked; + SaveSetting(settingData.SlicerConfigName, isChecked ? "1" : "0"); - CallEventsOnSettingsChange(settingData); + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); }; - leftToRightLayout.AddChild(checkBoxWidget); + settingsRow.AddChild(checkBoxWidget); + + settingsRow.ValueChanged = (text) => checkBoxWidget.Checked = text == "1"; } break; @@ -1056,20 +1100,50 @@ namespace MatterHackers.MatterControl.SlicerConfiguration { xyValueStrings = new string[] { "0", "0" }; } - double currentXValue = 0; - double.TryParse(xyValueStrings[0], out currentXValue); - MHNumberEdit xEditWidget = new MHNumberEdit(currentXValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++); - xEditWidget.ToolTipText = settingData.HelpText; - xEditWidget.Margin = new BorderDouble(0, 0, 30 * TextWidget.GlobalPointSizeScaleRatio, 0); - double currentYValue = 0; - double.TryParse(xyValueStrings[1], out currentYValue); - MHNumberEdit yEditWidget = new MHNumberEdit(currentYValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++); - yEditWidget.ToolTipText = settingData.HelpText; - restoreActiveSetting = () => + double currentXValue; + double.TryParse(xyValueStrings[0], out currentXValue); + + var xEditWidget = new MHNumberEdit(currentXValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++) { - double currentValue2 = 0; - string[] xyValueStrings2 = ActiveSliceSettings.Instance.GetActiveValue(settingData.SlicerConfigName).Split(','); + ToolTipText = settingData.HelpText, + Margin = new BorderDouble(0, 0, 30 * TextWidget.GlobalPointSizeScaleRatio, 0), + SelectAllOnFocus = true + }; + + double currentYValue; + double.TryParse(xyValueStrings[1], out currentYValue); + + var yEditWidget = new MHNumberEdit(currentYValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++) + { + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true + }; + + xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => + { + SaveSetting(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString()); + + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(xEditWidget); + + yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => + { + SaveSetting(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString()); + + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(yEditWidget); + + settingsRow.ValueChanged = (text) => + { + double currentValue2; + string[] xyValueStrings2 = text.Split(','); if (xyValueStrings2.Length != 2) { xyValueStrings2 = new string[] { "0", "0" }; @@ -1080,104 +1154,149 @@ namespace MatterHackers.MatterControl.SlicerConfiguration double.TryParse(xyValueStrings2[1], out currentValue2); yEditWidget.ActuallNumberEdit.Value = currentValue2; - CallEventsOnSettingsChange(settingData); }; - xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => - { - SaveSetting(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - - CallEventsOnSettingsChange(settingData); - }; - xEditWidget.SelectAllOnFocus = true; - leftToRightLayout.AddChild(xEditWidget); - - yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => - { - SaveSetting(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - - CallEventsOnSettingsChange(settingData); - }; - yEditWidget.SelectAllOnFocus = true; - leftToRightLayout.AddChild(yEditWidget); } break; case OrganizerSettingsData.DataEditTypes.OFFSET2: { Vector2 offset = ActiveSliceSettings.Instance.GetOffset(extruderIndex); - MHNumberEdit xEditWidget = new MHNumberEdit(offset.x, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++); - xEditWidget.ToolTipText = settingData.HelpText; - MHNumberEdit yEditWidget = new MHNumberEdit(offset.y, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++); - restoreActiveSetting = () => + + var xEditWidget = new MHNumberEdit(offset.x, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++) + { + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true, + Margin = new BorderDouble(0, 0, 30 * TextWidget.GlobalPointSizeScaleRatio, 0) + }; + + var yEditWidget = new MHNumberEdit(offset.y, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++) + { + ToolTipText = settingData.HelpText, + SelectAllOnFocus = true + }; + + xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => + { + int extruderIndexLocal = extruderIndex; + SaveCommaSeparatedIndexSetting(extruderIndexLocal, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString()); + + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(xEditWidget); + + + yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => + { + int extruderIndexLocal = extruderIndex; + SaveCommaSeparatedIndexSetting(extruderIndexLocal, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString()); + + settingsRow.UpdateStyle(); + + OnSettingsChanged(settingData); + }; + settingsRow.AddChild(yEditWidget); + + settingsRow.ValueChanged = (text) => { Vector2 offset2 = ActiveSliceSettings.Instance.GetOffset(extruderIndex); xEditWidget.ActuallNumberEdit.Value = offset2.x; yEditWidget.ActuallNumberEdit.Value = offset2.y; - CallEventsOnSettingsChange(settingData); }; - yEditWidget.ToolTipText = settingData.HelpText; - { - xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => - { - int extruderIndexLocal = extruderIndex; - SaveCommaSeparatedIndexSetting(extruderIndexLocal, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - CallEventsOnSettingsChange(settingData); - }; - xEditWidget.SelectAllOnFocus = true; - xEditWidget.Margin = new BorderDouble(0, 0, 30 * TextWidget.GlobalPointSizeScaleRatio, 0); - leftToRightLayout.AddChild(xEditWidget); - } - { - yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) => - { - int extruderIndexLocal = extruderIndex; - SaveCommaSeparatedIndexSetting(extruderIndexLocal, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString()); - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - - CallEventsOnSettingsChange(settingData); - }; - yEditWidget.SelectAllOnFocus = true; - leftToRightLayout.AddChild(yEditWidget); - } } break; default: - restoreActiveSetting = null; - TextWidget missingSetting = new TextWidget(String.Format("Missing the setting for '{0}'.", settingData.DataEditType.ToString())); - missingSetting.TextColor = ActiveTheme.Instance.PrimaryTextColor; - missingSetting.BackgroundColor = RGBA_Bytes.Red; - leftToRightLayout.AddChild(missingSetting); + var missingSetting = new TextWidget(String.Format("Missing the setting for '{0}'.", settingData.DataEditType.ToString())) + { + TextColor = ActiveTheme.Instance.PrimaryTextColor, + BackgroundColor = RGBA_Bytes.Red + }; + settingsRow.AddChild(missingSetting); break; } } - else // the setting we think we are adding is not in the config.ini it may have been deprecated - { - restoreActiveSetting = null; - TextWidget settingName = new TextWidget(String.Format("Setting '{0}' not found in config.ini", settingData.SlicerConfigName)); - settingName.TextColor = ActiveTheme.Instance.PrimaryTextColor; - settingName.MinimumSize = new Vector2(minSettingNameWidth, settingName.MinimumSize.y); - leftToRightLayout.AddChild(settingName); - leftToRightLayout.BackgroundColor = RGBA_Bytes.Red; - } container.HAnchor = HAnchor.ParentLeftRight; container.VAnchor = VAnchor.FitToChildren; - { - Action localRestore = restoreActiveSetting; - SetBackgroundColorAndRestoreButton(leftToRightLayout, settingData, localRestore); - } - container.AddChild(leftToRightLayout); + var restoreButton = new Button(new ButtonViewStates(new ImageWidget(restoreNormal), new ImageWidget(restoreHover), new ImageWidget(restorePressed), new ImageWidget(restoreNormal))) + { + Name = "Restore " + settingData.SlicerConfigName, + VAnchor = VAnchor.ParentCenter, + Margin = new BorderDouble(0, 0, 5, 0), + ToolTipText = "Restore Default".Localize() + }; + + restoreButton.Click += (sender, e) => + { + // Revert the user override + if (persistenceLayer == null) + { + ActiveSliceSettings.Instance.ClearValue(settingData.SlicerConfigName); + } + else + { + ActiveSliceSettings.Instance.ClearValue(settingData.SlicerConfigName, persistenceLayer); + } + + settingsRow.RefreshValue(); + }; + + settingsRow.AddChild(new GuiWidget(HAnchor.ParentLeftRight)); + settingsRow.AddChild(restoreButton); + + container.AddChild(settingsRow); + + // Define the UpdateStyle implementation + settingsRow.UpdateStyle = () => + { + if (persistenceLayer.ContainsKey(settingData.SlicerConfigName)) + { + switch (this.viewFilter) + { + case NamedSettingsLayers.All: + settingsRow.BackgroundColor = userSettingBackgroundColor; + break; + case NamedSettingsLayers.Material: + settingsRow.BackgroundColor = materialSettingBackgroundColor; + break; + case NamedSettingsLayers.Quality: + settingsRow.BackgroundColor = qualitySettingBackgroundColor; + break; + } + + restoreButton.Visible = true; + } + else if (layerFilters == null) + { + if (ActiveSliceSettings.Instance.SettingExistsInLayer(settingData.SlicerConfigName, NamedSettingsLayers.Material)) + { + settingsRow.BackgroundColor = materialSettingBackgroundColor; + } + else if (ActiveSliceSettings.Instance.SettingExistsInLayer(settingData.SlicerConfigName, NamedSettingsLayers.Quality)) + { + settingsRow.BackgroundColor = qualitySettingBackgroundColor; + } + else + { + settingsRow.BackgroundColor = RGBA_Bytes.Transparent; + } + + restoreButton.Visible = false; + } + else + { + restoreButton.Visible = false; + settingsRow.BackgroundColor = RGBA_Bytes.Transparent; + } + }; + + // Invoke the UpdateStyle implementation + settingsRow.UpdateStyle(); return container; } @@ -1185,6 +1304,7 @@ namespace MatterHackers.MatterControl.SlicerConfiguration static ImageBuffer restoreNormal = EnsureRestoreButtonImages(); static ImageBuffer restoreHover; static ImageBuffer restorePressed; + static ImageBuffer EnsureRestoreButtonImages() { int size = (int)(16 * TextWidget.GlobalPointSizeScaleRatio); @@ -1212,64 +1332,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration return imageBuffer; } - private void SetBackgroundColorAndRestoreButton(GuiWidget container, OrganizerSettingsData settingData, Action restoreAction) - { - var existingRestoretButton = container.Children