diff --git a/MatterControlLib/ActionBar/TemperatureWidgetBase.cs b/MatterControlLib/ActionBar/TemperatureWidgetBase.cs index 5a3a95e1d..70f631b6f 100644 --- a/MatterControlLib/ActionBar/TemperatureWidgetBase.cs +++ b/MatterControlLib/ActionBar/TemperatureWidgetBase.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2017, Kevin Pope, John Lewin +Copyright (c) 2018, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -46,7 +46,6 @@ namespace MatterHackers.MatterControl.ActionBar protected ImageWidget ImageWidget; - protected EventHandler unregisterEvents; protected PrinterConfig printer; protected List alwaysEnabled; @@ -111,12 +110,8 @@ namespace MatterHackers.MatterControl.ActionBar }; container.AddChild(DirectionIndicator); - void CommunicationStateChanged(object s, EventArgs e) - { - this.EnableControls(); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; foreach (var child in this.Children) { @@ -157,12 +152,19 @@ namespace MatterHackers.MatterControl.ActionBar public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + base.OnClosed(e); } bool? isEnabled = null; + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + this.EnableControls(); + } + private void EnableControls() { bool status = printer.Connection.IsConnected && !printer.Connection.PrinterIsPrinting; diff --git a/MatterControlLib/ActionBar/TemperatureWidgetBed.cs b/MatterControlLib/ActionBar/TemperatureWidgetBed.cs index 571ae4bff..c8190b684 100644 --- a/MatterControlLib/ActionBar/TemperatureWidgetBed.cs +++ b/MatterControlLib/ActionBar/TemperatureWidgetBed.cs @@ -31,7 +31,6 @@ using System; using System.Collections.Generic; using System.Linq; using MatterHackers.Agg; -using MatterHackers.Agg.ImageProcessing; using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.Localizations; @@ -48,6 +47,7 @@ namespace MatterHackers.MatterControl.ActionBar private string waitingForBedToHeatMessage = "The bed is currently heating and its target temperature cannot be changed until it reaches {0}°C.\n\nYou can set the starting bed temperature in SETTINGS -> Filament -> Temperatures.\n\n{1}".Localize(); private string waitingForBedToHeatTitle = "Waiting For Bed To Heat".Localize(); private Dictionary allUiFields = new Dictionary(); + private RunningInterval runningInterval; public TemperatureWidgetBed(PrinterConfig printer, ThemeConfig theme) : base(printer, "150.3°", theme) @@ -60,12 +60,8 @@ namespace MatterHackers.MatterControl.ActionBar this.PopupContent = this.GetPopupContent(ApplicationController.Instance.MenuTheme); - void BedTemperatureRead(object s, EventArgs e) - { - DisplayCurrentTemperature(); - } - printer.Connection.BedTemperatureRead += BedTemperatureRead; - this.Closed += (s, e) => printer.Connection.BedTemperatureRead -= BedTemperatureRead; + // Register listeners + printer.Connection.BedTemperatureRead += Connection_BedTemperatureRead; } protected override int ActualTemperature => (int)printer.Connection.ActualBedTemperature; @@ -141,11 +137,10 @@ namespace MatterHackers.MatterControl.ActionBar Margin = new BorderDouble(0, 5, 0, 0), }; - var runningInterval = UiThread.SetInterval(() => + runningInterval = UiThread.SetInterval(() => { graph.AddData(this.ActualTemperature); }, 1); - this.Closed += (s, e) => UiThread.ClearInterval(runningInterval); var settingsRow = temperatureRow.DescendantsAndSelf().FirstOrDefault(); @@ -200,6 +195,15 @@ namespace MatterHackers.MatterControl.ActionBar base.OnDraw(graphics2D); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + printer.Connection.BedTemperatureRead -= Connection_BedTemperatureRead; + UiThread.ClearInterval(runningInterval); + + base.OnClosed(e); + } + protected override void SetTargetTemperature(double targetTemp) { double goalTemp = (int)(targetTemp + .5); @@ -215,5 +219,10 @@ namespace MatterHackers.MatterControl.ActionBar printer.Connection.TargetBedTemperature = (int)(targetTemp + .5); } } + + private void Connection_BedTemperatureRead(object s, EventArgs e) + { + DisplayCurrentTemperature(); + } } } \ No newline at end of file diff --git a/MatterControlLib/ActionBar/TemperatureWidgetExtruder.cs b/MatterControlLib/ActionBar/TemperatureWidgetExtruder.cs index 15d2f375a..20737093d 100644 --- a/MatterControlLib/ActionBar/TemperatureWidgetExtruder.cs +++ b/MatterControlLib/ActionBar/TemperatureWidgetExtruder.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2017, Kevin Pope, John Lewin +Copyright (c) 2018, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -29,10 +29,8 @@ either expressed or implied, of the FreeBSD Project. using System; using System.Collections.Generic; -using System.IO; using System.Linq; using MatterHackers.Agg; -using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.ConfigurationPage; @@ -190,6 +188,7 @@ namespace MatterHackers.MatterControl.ActionBar private string sliceSettingsNote = "Note: Slice Settings are applied before the print actually starts. Changes while printing will not effect the active print.".Localize(); private string waitingForExtruderToHeatMessage = "The extruder is currently heating and its target temperature cannot be changed until it reaches {0}°C.\n\nYou can set the starting extruder temperature in 'Slice Settings' -> 'Filament'.\n\n{1}".Localize(); private Dictionary allUiFields = new Dictionary(); + private RunningInterval runningInterval; public TemperatureWidgetHotend(PrinterConfig printer, int hotendIndex, ThemeConfig theme) : base(printer, "150.3°", theme) @@ -201,12 +200,8 @@ namespace MatterHackers.MatterControl.ActionBar this.PopupContent = this.GetPopupContent(ApplicationController.Instance.MenuTheme); - void HotendTemperatureRead(object s, EventArgs e) - { - DisplayCurrentTemperature(); - } - printer.Connection.HotendTemperatureRead += HotendTemperatureRead; - this.Closed += (s, e) => printer.Connection.HotendTemperatureRead -= HotendTemperatureRead; + // Register listeners + printer.Connection.HotendTemperatureRead += Connection_HotendTemperatureRead; } protected override int ActualTemperature => (int)printer.Connection.GetActualHotendTemperature(this.hotendIndex); @@ -284,12 +279,12 @@ namespace MatterHackers.MatterControl.ActionBar Width = widget.Width - 20, Height = 35, // this works better if it is a common multiple of the Width }; - var runningInterval = UiThread.SetInterval(() => + + runningInterval = UiThread.SetInterval(() => { graph.AddData(this.ActualTemperature); }, 1); - this.Closed += (s, e) => UiThread.ClearInterval(runningInterval); - + var valueField = temperatureRow.Descendants().FirstOrDefault(); valueField.Name = "Temperature Input"; @@ -423,6 +418,15 @@ namespace MatterHackers.MatterControl.ActionBar base.OnDraw(graphics2D); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + printer.Connection.HotendTemperatureRead -= Connection_HotendTemperatureRead; + UiThread.ClearInterval(runningInterval); + + base.OnClosed(e); + } + protected override void SetTargetTemperature(double targetTemp) { double goalTemp = (int)(targetTemp + .5); @@ -438,5 +442,11 @@ namespace MatterHackers.MatterControl.ActionBar printer.Connection.SetTargetHotendTemperature(hotendIndex, (int)(targetTemp + .5)); } } + + private void Connection_HotendTemperatureRead(object s, EventArgs e) + { + DisplayCurrentTemperature(); + } + } } \ No newline at end of file diff --git a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/CalibrateProbeLastPagelInstructions.cs b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/CalibrateProbeLastPagelInstructions.cs index 2ab42cc8d..c95d5fdbe 100644 --- a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/CalibrateProbeLastPagelInstructions.cs +++ b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/CalibrateProbeLastPagelInstructions.cs @@ -27,6 +27,7 @@ of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ +using System; using System.Collections.Generic; using System.IO; using MatterHackers.Agg.Platform; @@ -39,6 +40,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class CalibrateProbeLastPagelInstructions : PrinterSetupWizardPage { + private bool pageWasActive = false; private List autoProbePositions; private List manualProbePositions; @@ -80,14 +82,18 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); } - // TODO: Why not use OnClosed? - this.Closed += (s, e) => - { - // move from this wizard to the print leveling wizard if needed - ApplicationController.Instance.RunAnyRequiredPrinterSetup(printer, theme); - }; + pageWasActive = true; base.PageIsBecomingActive(); } + + public override void OnClosed(EventArgs e) + { + if (pageWasActive) + { + // move from this wizard to the print leveling wizard if needed + ApplicationController.Instance.RunAnyRequiredPrinterSetup(printer, theme); + } + } } } \ No newline at end of file diff --git a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/FindBedHeight.cs b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/FindBedHeight.cs index 68bd8c519..f23b7fb25 100644 --- a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/FindBedHeight.cs +++ b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/FindBedHeight.cs @@ -48,6 +48,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling protected JogControls.MoveButton zPlusControl; protected JogControls.MoveButton zMinusControl; + private RunningInterval runningInterval; public FindBedHeight(PrinterSetupWizard context, string pageDescription, string setZHeightCoarseInstruction1, string setZHeightCoarseInstruction2, double moveDistance, List probePositions, int probePositionsBeingEditedIndex) @@ -75,14 +76,12 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling Margin = new BorderDouble(10, 0), }; - var runningInterval = UiThread.SetInterval(() => + runningInterval = UiThread.SetInterval(() => { Vector3 destinationPosition = printer.Connection.CurrentDestination; zPosition.Text = "Z: {0:0.00}".FormatWith(destinationPosition.Z); }, .3); - this.Closed += (s, e) => UiThread.ClearInterval(runningInterval); - zButtonsAndInfo.AddChild(zPosition); contentRow.AddChild(zButtonsAndInfo); @@ -108,7 +107,10 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void OnClosed(EventArgs e) { + // Unregister listeners + UiThread.ClearInterval(runningInterval); this.DialogWindow.KeyDown -= TopWindowKeyDown; + base.OnClosed(e); } diff --git a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs index 54cba63be..a4d1129e2 100644 --- a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs +++ b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/HomePrinterPage.cs @@ -36,7 +36,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class HomePrinterPage : PrinterSetupWizardPage { - private EventHandler unregisterEvents; private bool autoAdvance; public HomePrinterPage(PrinterSetupWizard context, string headerText, string instructionsText, bool autoAdvance) @@ -47,17 +46,15 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= CheckHomeFinished; + base.OnClosed(e); } public override void PageIsBecomingActive() { - // make sure we don't have anything left over - unregisterEvents?.Invoke(this, null); - printer.Connection.CommunicationStateChanged += CheckHomeFinished; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CheckHomeFinished; printer.Connection.HomeAxis(PrinterConnection.Axis.XYZ); @@ -77,9 +74,8 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling private void CheckHomeFinished(object sender, EventArgs e) { - if(printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) + if (printer.Connection.DetailedPrintingState != DetailedPrintingState.HomingAxis) { - unregisterEvents?.Invoke(this, null); NextButton.Enabled = true; if (printer.Settings.Helpers.UseZProbe()) @@ -91,7 +87,6 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling public override void PageIsBecomingInactive() { - unregisterEvents?.Invoke(this, null); NextButton.Enabled = true; base.PageIsBecomingInactive(); diff --git a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/WaitForTempPage.cs b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/WaitForTempPage.cs index 49a2044de..c0670dfd8 100644 --- a/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/WaitForTempPage.cs +++ b/MatterControlLib/ConfigurationPage/PrintLeveling/WizardPages/WaitForTempPage.cs @@ -40,13 +40,14 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling private ProgressBar bedProgressBar; private TextWidget bedProgressBarText; private double bedStartingTemp; + private RunningInterval runningInterval; private TextWidget bedDoneText; - double bedTargetTemp; + private double bedTargetTemp; private ProgressBar hotEndProgressBar; private TextWidget hotEndProgressBarText; private TextWidget hotEndDoneText; - double hotEndTargetTemp; + private double hotEndTargetTemp; public WaitForTempPage(PrinterSetupWizard context, string step, string instructions, @@ -167,8 +168,7 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { bedStartingTemp = printer.Connection.ActualBedTemperature; - var runningInterval = UiThread.SetInterval(ShowTempChangeProgress, 1); - this.Closed += (s, e) => UiThread.ClearInterval(runningInterval); + runningInterval = UiThread.SetInterval(ShowTempChangeProgress, 1); if (bedTargetTemp > 0) { @@ -201,6 +201,14 @@ namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling base.PageIsBecomingInactive(); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + UiThread.ClearInterval(runningInterval); + + base.OnClosed(e); + } + private void ShowTempChangeProgress() { if (hotEndTargetTemp > 0) diff --git a/MatterControlLib/CustomWidgets/InlineEditControl.cs b/MatterControlLib/CustomWidgets/InlineEditControl.cs index 19b9cb18b..4baa29046 100644 --- a/MatterControlLib/CustomWidgets/InlineEditControl.cs +++ b/MatterControlLib/CustomWidgets/InlineEditControl.cs @@ -81,8 +81,7 @@ namespace MatterHackers.MatterControl.CustomWidgets VAnchor = VAnchor.Fit; HAnchor = HAnchor.Fit; - var runningInterval = UiThread.SetInterval(HideIfApplicable, .1); - this.Closed += (s, e) => UiThread.ClearInterval(runningInterval); + runningInterval = UiThread.SetInterval(HideIfApplicable, .1); } public Color TextColor { get; set; } = Color.Black; @@ -100,6 +99,8 @@ namespace MatterHackers.MatterControl.CustomWidgets public Func ForceHide { get; set; } private Func _getDisplayString = (value) => "{0:0.0}".FormatWith(value); + private RunningInterval runningInterval; + public Func GetDisplayString { get => _getDisplayString; @@ -187,6 +188,14 @@ namespace MatterHackers.MatterControl.CustomWidgets base.OnMouseDown(mouseEvent); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + UiThread.ClearInterval(runningInterval); + + base.OnClosed(e); + } + private void HideIfApplicable() { if (this.Visible) diff --git a/MatterControlLib/CustomWidgets/PrintingWindow/BedStatusWidget.cs b/MatterControlLib/CustomWidgets/PrintingWindow/BedStatusWidget.cs index c30b66ad9..80dbb0abb 100644 --- a/MatterControlLib/CustomWidgets/PrintingWindow/BedStatusWidget.cs +++ b/MatterControlLib/CustomWidgets/PrintingWindow/BedStatusWidget.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2017, Lars Brubaker, John Lewin +Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -37,12 +37,8 @@ namespace MatterHackers.MatterControl.CustomWidgets public BedStatusWidget(PrinterConfig printer, bool smallScreen, ThemeConfig theme) : base(printer, smallScreen ? "Bed".Localize() : "Bed Temperature".Localize(), theme) { - void BedTemperatureRead(object s, EventArgs e) - { - UpdateTemperatures(); - } - printer.Connection.BedTemperatureRead += BedTemperatureRead; - this.Closed += (s, e) => printer.Connection.BedTemperatureRead -= BedTemperatureRead; + // Register listeners + printer.Connection.BedTemperatureRead += Connection_BedTemperatureRead; } public override void UpdateTemperatures() @@ -52,8 +48,21 @@ namespace MatterHackers.MatterControl.CustomWidgets progressBar.RatioComplete = targetValue != 0 ? actualValue / targetValue : 1; - this.actualTemp.Text = $"{actualValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters - this.targetTemp.Text = $"{targetValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + actualTemp.Text = $"{actualValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + targetTemp.Text = $"{targetValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + } + + private void Connection_BedTemperatureRead(object s, EventArgs e) + { + this.UpdateTemperatures(); + } + + public override void OnClosed(EventArgs e) + { + // Unregister listeners + printer.Connection.BedTemperatureRead -= Connection_BedTemperatureRead; + + base.OnClosed(e); } } } \ No newline at end of file diff --git a/MatterControlLib/CustomWidgets/PrintingWindow/ExtruderStatusWidget.cs b/MatterControlLib/CustomWidgets/PrintingWindow/ExtruderStatusWidget.cs index 260e5408c..45f006942 100644 --- a/MatterControlLib/CustomWidgets/PrintingWindow/ExtruderStatusWidget.cs +++ b/MatterControlLib/CustomWidgets/PrintingWindow/ExtruderStatusWidget.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2017, Lars Brubaker, John Lewin +Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -41,12 +41,8 @@ namespace MatterHackers.MatterControl.CustomWidgets { this.extruderIndex = extruderIndex; - void HotendTemperatureRead(object s, EventArgs e) - { - UpdateTemperatures(); - } - printer.Connection.HotendTemperatureRead += HotendTemperatureRead; - this.Closed += (s, e) => printer.Connection.HotendTemperatureRead -= HotendTemperatureRead; + // Register listeners + printer.Connection.HotendTemperatureRead += Connection_HotendTemperatureRead; } public override void UpdateTemperatures() @@ -56,8 +52,21 @@ namespace MatterHackers.MatterControl.CustomWidgets progressBar.RatioComplete = targetValue != 0 ? actualValue / targetValue : 1; - this.actualTemp.Text = $"{actualValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters - this.targetTemp.Text = $"{targetValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + actualTemp.Text = $"{actualValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + targetTemp.Text = $"{targetValue:0}".PadLeft(3, (char)0x2007) + "°"; // put in padding spaces to make it at least 3 characters + } + + public override void OnClosed(EventArgs e) + { + // Unregister listeners + printer.Connection.HotendTemperatureRead -= Connection_HotendTemperatureRead; + + base.OnClosed(e); + } + + private void Connection_HotendTemperatureRead(object s, EventArgs e) + { + UpdateTemperatures(); } } } \ No newline at end of file diff --git a/MatterControlLib/EeProm/EePromRepetierWindow.cs b/MatterControlLib/EeProm/EePromRepetierWindow.cs index 6fa199759..da7fd35b6 100644 --- a/MatterControlLib/EeProm/EePromRepetierWindow.cs +++ b/MatterControlLib/EeProm/EePromRepetierWindow.cs @@ -44,7 +44,6 @@ namespace MatterHackers.MatterControl.EeProm { private static Regex nameSanitizer = new Regex("[^_a-zA-Z0-9-]", RegexOptions.Compiled); - private EventHandler unregisterEvents; protected PrinterConfig printer; public EEPromPage(PrinterConfig printer) @@ -52,25 +51,18 @@ namespace MatterHackers.MatterControl.EeProm { this.HeaderText = "EEProm Settings".Localize(); this.WindowSize = new VectorMath.Vector2(663, 575); - headerRow.Margin = this.headerRow.Margin.Clone(bottom: 0); - this.printer = printer; - // Close window if printer is disconnected - void CommunicationStateChanged(object s, EventArgs e) - { - if (!printer.Connection.IsConnected) - { - this.DialogWindow.CloseOnIdle(); - } - } + headerRow.Margin = this.headerRow.Margin.Clone(bottom: 0); + printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; } public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; + base.OnClosed(e); } @@ -80,6 +72,14 @@ namespace MatterHackers.MatterControl.EeProm string printerName = printer.Settings.GetValue(SettingsKey.printer_name).Replace(" ", "_"); return nameSanitizer.Replace(printerName, ""); } + + private void CommunicationStateChanged(object s, EventArgs e) + { + if (!printer.Connection.IsConnected) + { + this.DialogWindow.CloseOnIdle(); + } + } } public class RepetierEEPromPage : EEPromPage @@ -87,8 +87,6 @@ namespace MatterHackers.MatterControl.EeProm private EePromRepetierStorage currentEePromSettings; private FlowLayoutWidget settingsColumn; - private EventHandler unregisterEvents; - public RepetierEEPromPage(PrinterConfig printer) : base(printer) { @@ -249,7 +247,6 @@ namespace MatterHackers.MatterControl.EeProm currentEePromSettings.SettingAdded -= NewSettingReadFromPrinter; } - unregisterEvents?.Invoke(this, null); base.OnClosed(e); } diff --git a/MatterControlLib/Library/Widgets/HardwareTreeView.cs b/MatterControlLib/Library/Widgets/HardwareTreeView.cs index ef79f849e..d58b62598 100644 --- a/MatterControlLib/Library/Widgets/HardwareTreeView.cs +++ b/MatterControlLib/Library/Widgets/HardwareTreeView.cs @@ -149,19 +149,8 @@ namespace MatterHackers.MatterControl.PrintLibrary rootColumn.AddChild(materialsNode); - // need to be hooked up to every existing PrinterConfig and every new PrinterConfig - void AnyPrinterSettingChanged(object s, EventArgs e) - { - string settingsName = (e as StringEventArgs)?.Data; - if (settingsName != null && settingsName == SettingsKey.printer_name) - { - HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme); - this.Invalidate(); - } - } - - PrinterSettings.AnyPrinterSettingChanged += AnyPrinterSettingChanged; - this.Closed += (s, e) => PrinterSettings.AnyPrinterSettingChanged -= AnyPrinterSettingChanged; + // Register listeners + PrinterSettings.AnyPrinterSettingChanged += Printer_SettingChanged; // Rebuild the treeview anytime the Profiles list changes ProfileManager.ProfilesListChanged.RegisterEvent((s, e) => @@ -232,5 +221,23 @@ namespace MatterHackers.MatterControl.PrintLibrary printersNode.Expanded = true; } + + public override void OnClosed(EventArgs e) + { + // Unregister listeners + PrinterSettings.AnyPrinterSettingChanged -= Printer_SettingChanged; + + base.OnClosed(e); + } + + private void Printer_SettingChanged(object s, EventArgs e) + { + string settingsName = (e as StringEventArgs)?.Data; + if (settingsName != null && settingsName == SettingsKey.printer_name) + { + HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme); + this.Invalidate(); + } + } } } diff --git a/MatterControlLib/PartPreviewWindow/GCode2DWidget.cs b/MatterControlLib/PartPreviewWindow/GCode2DWidget.cs index 89e9d9cfd..87628eb06 100644 --- a/MatterControlLib/PartPreviewWindow/GCode2DWidget.cs +++ b/MatterControlLib/PartPreviewWindow/GCode2DWidget.cs @@ -62,7 +62,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow private PrinterConfig printer; private static Color gridColor = new Color(190, 190, 190, 255); - private EventHandler unregisterEvents; private ImageBuffer bedImage; public GCode2DWidget(PrinterConfig printer, ThemeConfig theme) @@ -73,12 +72,9 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.LocalBounds = new RectangleDouble(0, 0, 100, 100); this.AnchorAll(); + // Register listeners printer.Bed.LoadedGCodeChanged += LoadedGCodeChanged; - - // make sure we have good settings - printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; Printer_SettingChanged(this, null); @@ -317,10 +313,10 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); - - printer.Bed.GCodeRenderer?.Dispose(); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; printer.Bed.LoadedGCodeChanged -= LoadedGCodeChanged; + printer.Bed.GCodeRenderer?.Dispose(); base.OnClosed(e); } diff --git a/MatterControlLib/PartPreviewWindow/GCode3DWidget.cs b/MatterControlLib/PartPreviewWindow/GCode3DWidget.cs index a74096b3b..1cf9a1a63 100644 --- a/MatterControlLib/PartPreviewWindow/GCode3DWidget.cs +++ b/MatterControlLib/PartPreviewWindow/GCode3DWidget.cs @@ -42,8 +42,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow { public class GCodePanel : FlowLayoutWidget { - private EventHandler unregisterEvents; - private BedConfig sceneContext; private ThemeConfig theme; private PrinterConfig printer; @@ -96,23 +94,23 @@ namespace MatterHackers.MatterControl.PartPreviewWindow var firstSection = this.Children().First(); firstSection.BorderColor = Color.Transparent; // Disable top border on first item to produce a more flat, dark top edge - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent) - { - if (stringEvent.Data == "extruder_offset") - { - printer.Bed.GCodeRenderer?.Clear3DGCode(); - } - } - } + // Register listeners printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; - printer.Bed.LoadedGCodeChanged += Bed_LoadedGCodeChanged; printer.Bed.RendererOptions.PropertyChanged += RendererOptions_PropertyChanged; } + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent) + { + if (stringEvent.Data == "extruder_offset") + { + printer.Bed.GCodeRenderer?.Clear3DGCode(); + } + } + } + private void RefreshGCodeDetails(PrinterConfig printer) { loadedGCodeSection.CloseAllChildren(); @@ -216,10 +214,11 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; printer.Bed.RendererOptions.PropertyChanged -= RendererOptions_PropertyChanged; printer.Bed.LoadedGCodeChanged -= Bed_LoadedGCodeChanged; - unregisterEvents?.Invoke(this, null); base.OnClosed(e); } } diff --git a/MatterControlLib/PartPreviewWindow/GCodeDetails/GCodeDetailsView.cs b/MatterControlLib/PartPreviewWindow/GCodeDetails/GCodeDetailsView.cs index d1ad46fa6..ac3b4b73d 100644 --- a/MatterControlLib/PartPreviewWindow/GCodeDetails/GCodeDetailsView.cs +++ b/MatterControlLib/PartPreviewWindow/GCodeDetails/GCodeDetailsView.cs @@ -40,13 +40,19 @@ namespace MatterHackers.MatterControl.PartPreviewWindow { public class GCodeDetailsView : FlowLayoutWidget { - private EventHandler unregisterEvents; private ThemeConfig theme; + private GCodeFile gCodeMemoryFile; + private PrinterConfig printer; + private TextWidget costTextWidget; + private TextWidget massTextWidget; + private GuiWidget conditionalCostContainer; public GCodeDetailsView(GCodeFile gCodeMemoryFile, PrinterConfig printer, ThemeConfig theme) : base(FlowDirection.TopToBottom) { this.theme = theme; + this.gCodeMemoryFile = gCodeMemoryFile; + this.printer = printer; // put in the print time AddSetting("Print Time".Localize(), gCodeMemoryFile.EstimatedPrintTime()); @@ -57,36 +63,17 @@ namespace MatterHackers.MatterControl.PartPreviewWindow AddSetting("Filament Volume".Localize(), gCodeMemoryFile.FilamentVolume(printer)); // Cost info is only displayed when available - conditionalCostPanel is invisible when cost <= 0 - TextWidget costTextWidget = AddSetting("Estimated Cost".Localize(), gCodeMemoryFile.EstimatedCost(printer)); + costTextWidget = AddSetting("Estimated Cost".Localize(), gCodeMemoryFile.EstimatedCost(printer)); - TextWidget massTextWidget = AddSetting("Estimated Mass".Localize(), gCodeMemoryFile.EstimatedMass(printer)); + massTextWidget = AddSetting("Estimated Mass".Localize(), gCodeMemoryFile.EstimatedMass(printer)); - var conditionalCostContainer = costTextWidget.Parent; + conditionalCostContainer = costTextWidget.Parent; conditionalCostContainer.Visible = gCodeMemoryFile.TotalCost(printer) > 0; - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent) - { - if (stringEvent.Data == SettingsKey.filament_cost - || stringEvent.Data == SettingsKey.filament_diameter - || stringEvent.Data == SettingsKey.filament_density) - { - massTextWidget.Text = gCodeMemoryFile.EstimatedMass(printer); - conditionalCostContainer.Visible = gCodeMemoryFile.TotalCost(printer) > 0; - - if (gCodeMemoryFile.TotalCost(printer) > 0) - { - costTextWidget.Text = gCodeMemoryFile.EstimatedCost(printer); - } - } - } - } printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; } - TextWidget AddSetting(string title, string value) + private TextWidget AddSetting(string title, string value) { var textWidget = new TextWidget(value, textColor: theme.TextColor, pointSize: theme.DefaultFontSize) { @@ -107,8 +94,29 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } + + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent) + { + if (stringEvent.Data == SettingsKey.filament_cost + || stringEvent.Data == SettingsKey.filament_diameter + || stringEvent.Data == SettingsKey.filament_density) + { + massTextWidget.Text = gCodeMemoryFile.EstimatedMass(printer); + conditionalCostContainer.Visible = gCodeMemoryFile.TotalCost(printer) > 0; + + if (gCodeMemoryFile.TotalCost(printer) > 0) + { + costTextWidget.Text = gCodeMemoryFile.EstimatedCost(printer); + } + } + } + } } } diff --git a/MatterControlLib/PartPreviewWindow/MainViewWidget.cs b/MatterControlLib/PartPreviewWindow/MainViewWidget.cs index 197a2c0aa..9fa7df99b 100644 --- a/MatterControlLib/PartPreviewWindow/MainViewWidget.cs +++ b/MatterControlLib/PartPreviewWindow/MainViewWidget.cs @@ -1,703 +1,703 @@ -/* -Copyright (c) 2018, 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 System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using MatterHackers.Agg; -using MatterHackers.Agg.Platform; -using MatterHackers.Agg.UI; -using MatterHackers.Localizations; -using MatterHackers.MatterControl.CustomWidgets; -using MatterHackers.MatterControl.PartPreviewWindow.PlusTab; -using MatterHackers.MatterControl.PrintLibrary; -using MatterHackers.MatterControl.SlicerConfiguration; -using MatterHackers.VectorMath; -using Newtonsoft.Json; - -namespace MatterHackers.MatterControl.PartPreviewWindow -{ - public class MainViewWidget : FlowLayoutWidget - { - private EventHandler unregisterEvents; - private ChromeTab printerTab = null; - private ChromeTabs tabControl; - - private int partCount = 0; - private ThemeConfig theme; - private Toolbar statusBar; - private FlowLayoutWidget tasksContainer; - private GuiWidget stretchStatusPanel; - - public MainViewWidget(ThemeConfig theme) - : base(FlowDirection.TopToBottom) - { - this.AnchorAll(); - this.theme = theme; - this.Name = "PartPreviewContent"; - this.BackgroundColor = theme.BackgroundColor; - - // Push TouchScreenMode into GuiWidget - GuiWidget.TouchScreenMode = UserSettings.Instance.IsTouchScreen; - - var extensionArea = new LeftClipFlowLayoutWidget() - { - BackgroundColor = theme.TabBarBackground, - VAnchor = VAnchor.Stretch, - Padding = new BorderDouble(left: 8) - }; - - tabControl = new ChromeTabs(extensionArea, theme) - { - VAnchor = VAnchor.Stretch, - HAnchor = HAnchor.Stretch, - BackgroundColor = theme.BackgroundColor, - BorderColor = theme.MinimalShade, - Border = new BorderDouble(left: 1), - }; - - tabControl.PlusClicked += (s, e) => - { - UiThread.RunOnIdle(() => - { - this.CreatePartTab().ConfigureAwait(false); - }); - }; - - tabControl.ActiveTabChanged += (s, e) => - { - if (this.tabControl.ActiveTab?.TabContent is PartTabPage tabPage) - { - var dragDropData = ApplicationController.Instance.DragDropData; - - // Set reference on tab change - dragDropData.View3DWidget = tabPage.view3DWidget; - dragDropData.SceneContext = tabPage.sceneContext; - - ApplicationController.Instance.PrinterTabSelected = true; - } - else - { - ApplicationController.Instance.PrinterTabSelected = false; - } - - ApplicationController.Instance.MainTabKey = tabControl.SelectedTabKey; - }; - - // Force the ActionArea to be as high as ButtonHeight - tabControl.TabBar.ActionArea.MinimumSize = new Vector2(0, theme.ButtonHeight); - tabControl.TabBar.BackgroundColor = theme.TabBarBackground; - tabControl.TabBar.BorderColor = theme.BackgroundColor; - - // Force common padding into top region - tabControl.TabBar.Padding = theme.TabbarPadding.Clone(top: theme.TabbarPadding.Top * 2, bottom: 0); - - // add in a what's new button - var seeWhatsNewButton = new LinkLabel("What's New...".Localize(), theme) - { - Name = "What's New Link", - ToolTipText = "See what's new in this version of MatterControl".Localize(), - VAnchor = VAnchor.Center, - Margin = new BorderDouble(10, 0), - TextColor = theme.TextColor - }; - seeWhatsNewButton.Click += (s, e) => UiThread.RunOnIdle(() => - { - UserSettings.Instance.set(UserSettingsKey.LastReadWhatsNew, JsonConvert.SerializeObject(DateTime.Now)); - DialogWindow.Show(new HelpPage("What's New")); - }); - - tabControl.TabBar.ActionArea.AddChild(seeWhatsNewButton); - - // add in the update available button - var updateAvailableButton = new LinkLabel("Update Available".Localize(), theme) - { - Visible = false, - Name = "Update Available Link", - ToolTipText = "There is a new update available for download".Localize(), - VAnchor = VAnchor.Center, - Margin = new BorderDouble(10, 0) - }; - - // make the function inline so we don't have to create members for the buttons - EventHandler SetLinkButtonsVisibility = (s, e) => - { - if (UserSettings.Instance.HasLookedAtWhatsNew()) - { - // hide it - seeWhatsNewButton.Visible = false; - } - - if (UpdateControlData.Instance.UpdateStatus == UpdateControlData.UpdateStatusStates.UpdateAvailable) - { - updateAvailableButton.Visible = true; - // if we are going to show the update link hide the whats new link no matter what - seeWhatsNewButton.Visible = false; - } - else - { - updateAvailableButton.Visible = false; - } - }; - - UserSettings.Instance.SettingChanged += SetLinkButtonsVisibility; - this.Closed += (s, e) => UserSettings.Instance.SettingChanged -= SetLinkButtonsVisibility; - - RunningInterval showUpdateInterval = null; - updateAvailableButton.VisibleChanged += (s, e) => - { - if (!updateAvailableButton.Visible) - { - if (showUpdateInterval != null) - { - UiThread.ClearInterval(showUpdateInterval); - showUpdateInterval = null; - } - return; - } - - showUpdateInterval = UiThread.SetInterval(() => - { - double displayTime = 1; - double pulseTime = 1; - double totalSeconds = 0; - var textWidgets = updateAvailableButton.Descendants().Where((w) => w.Visible == true).ToArray(); - Color startColor = theme.TextColor; - // Show a highlight on the button as the user did not click it - Animation flashBackground = null; - flashBackground = new Animation() - { - DrawTarget = updateAvailableButton, - FramesPerSecond = 10, - Update = (s1, updateEvent) => - { - totalSeconds += updateEvent.SecondsPassed; - if (totalSeconds < displayTime) - { - double blend = AttentionGetter.GetFadeInOutPulseRatio(totalSeconds, pulseTime); - var color = new Color(startColor, (int)((1 - blend) * 255)); - foreach (var textWidget in textWidgets) - { - textWidget.TextColor = color; - } - } - else - { - foreach (var textWidget in textWidgets) - { - textWidget.TextColor = startColor; - } - flashBackground.Stop(); - } - } - }; - flashBackground.Start(); - }, 120); - }; - - SetLinkButtonsVisibility(this, null); - updateAvailableButton.Click += (s, e) => UiThread.RunOnIdle(() => - { - UpdateControlData.Instance.CheckForUpdate(); - DialogWindow.Show(); - }); - - tabControl.TabBar.ActionArea.AddChild(updateAvailableButton); - - this.AddChild(tabControl); - - ApplicationController.Instance.NotifyPrintersTabRightElement(extensionArea); - - var printer = ApplicationController.Instance.ActivePrinter; - - // Store tab - tabControl.AddTab( - new ChromeTab("Store", "Store".Localize(), tabControl, new StoreTabPage(theme), theme, hasClose: false) - { - MinimumSize = new Vector2(0, theme.TabButtonHeight), - Name = "Store Tab", - Padding = new BorderDouble(15, 0), - }); - - // Library tab - var libraryWidget = new LibraryWidget(this, theme) - { - BackgroundColor = theme.BackgroundColor - }; - - tabControl.AddTab( - new ChromeTab("Library", "Library".Localize(), tabControl, libraryWidget, theme, hasClose: false) - { - MinimumSize = new Vector2(0, theme.TabButtonHeight), - Name = "Library Tab", - Padding = new BorderDouble(15, 0), - }); - - // Hardware tab - tabControl.AddTab( - new ChromeTab( - "Hardware", - "Hardware".Localize(), - tabControl, - new HardwareTabPage(theme) - { - BackgroundColor = theme.BackgroundColor - }, - theme, - hasClose: false) - { - MinimumSize = new Vector2(0, theme.TabButtonHeight), - Name = "Hardware Tab", - Padding = new BorderDouble(15, 0), - }); - - // Printer tab - if (printer.Settings.PrinterSelected) - { - this.CreatePrinterTab(printer, theme); - } - else - { - if (ApplicationController.Instance.Workspaces.Count == 0) - { - this.CreatePartTab().ConfigureAwait(false); - } - } - - string tabKey = ApplicationController.Instance.MainTabKey; - - if (string.IsNullOrEmpty(tabKey)) - { - if (printer.Settings.PrinterSelected) - { - tabKey = printer.Settings.GetValue(SettingsKey.printer_name); - } - else - { - tabKey = "Hardware"; - } - } - - // HACK: Restore to the first printer tab if PrinterTabSelected and tabKey not found. This allows sign in/out to remain on the printer tab across different users - if (!tabControl.AllTabs.Any(t => t.Key == tabKey) - && ApplicationController.Instance.PrinterTabSelected) - { - var key = tabControl.AllTabs.Where(t => t.TabContent is PrinterTabPage).FirstOrDefault()?.Key; - if (key != null) - { - tabKey = key; - } - } - - var brandMenu = new BrandMenuButton(theme) - { - HAnchor = HAnchor.Fit, - VAnchor = VAnchor.Fit, - BackgroundColor = theme.TabBarBackground, - Padding = theme.TabbarPadding.Clone(right: theme.DefaultContainerPadding) - }; - - tabControl.TabBar.ActionArea.AddChild(brandMenu, 0); - - // Restore active tabs - foreach (var workspace in ApplicationController.Instance.Workspaces) - { - this.CreatePartTab(workspace); - } - - tabControl.SelectedTabKey = tabKey; - - statusBar = new Toolbar(theme) - { - HAnchor = HAnchor.Stretch, - VAnchor = VAnchor.Absolute, - Padding = 1, - Height = 22, - BackgroundColor = theme.BackgroundColor, - Border = new BorderDouble(top: 1), - BorderColor = theme.BorderColor20, - }; - this.AddChild(statusBar); - - statusBar.ActionArea.VAnchor = VAnchor.Stretch; - - tasksContainer = new FlowLayoutWidget(FlowDirection.LeftToRight) - { - HAnchor = HAnchor.Fit, - VAnchor = VAnchor.Stretch, - BackgroundColor = theme.MinimalShade, - Name = "runningTasksPanel" - }; - statusBar.AddChild(tasksContainer); - - var tasks = ApplicationController.Instance.Tasks; - - tasks.TasksChanged += (s, e) => - { - RenderRunningTasks(theme, tasks); - }; - - stretchStatusPanel = new GuiWidget() - { - HAnchor = HAnchor.Stretch, - VAnchor = VAnchor.Stretch, - Padding = new BorderDouble(right: 3), - Margin = new BorderDouble(right: 2, top: 1, bottom: 1), - Border = new BorderDouble(1), - BackgroundColor = theme.MinimalShade.WithAlpha(10), - BorderColor = theme.SlightShade, - Width = 200 - }; - statusBar.AddChild(stretchStatusPanel); - - var panelBackgroundColor = theme.MinimalShade.WithAlpha(10); - - statusBar.AddChild( - this.CreateThemeStatusPanel(theme, panelBackgroundColor)); - - statusBar.AddChild( - this.CreateNetworkStatusPanel(theme)); - - this.RenderRunningTasks(theme, tasks); - - UpdateControlData.Instance.UpdateStatusChanged.RegisterEvent((s, e) => - { - SetLinkButtonsVisibility(s, new StringEventArgs("Unknown")); - }, ref unregisterEvents); - - void Printer_SettingChanged(object s, EventArgs e) - { - var activePrinter = ApplicationController.Instance.ActivePrinter; - - if (e is StringEventArgs stringEvent - && stringEvent.Data == SettingsKey.printer_name - && printerTab != null) - { - printerTab.Text = activePrinter.Settings.GetValue(SettingsKey.printer_name); - } - } - printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; - - ApplicationController.Instance.OpenPrintersChanged += OpenPrinters_Changed; - - ApplicationController.Instance.MainView = this; - } - - private void OpenPrinters_Changed(object sender, OpenPrintersChangedEventArgs e) - { - var activePrinter = e.Printer; - - if (e.Operation == OpenPrintersChangedEventArgs.OperationType.Add) - { - if (activePrinter.Settings.PrinterSelected) - { - // Create and switch to new printer tab - tabControl.ActiveTab = this.CreatePrinterTab(activePrinter, theme); - tabControl.RefreshTabPointers(); - } - } - else - { - // Close existing printer tabs - if (tabControl.AllTabs.FirstOrDefault(t => t.TabContent is PrinterTabPage printerTab - && printerTab.printer.Settings.ID == activePrinter.Settings.ID) is ITab tab - && tab.TabContent is PrinterTabPage printerPage) - { - tabControl.RemoveTab(tab); - tabControl.RefreshTabPointers(); - } - } - } - - private GuiWidget CreateNetworkStatusPanel(ThemeConfig theme) - { - var networkStatus = new GuiWidget() - { - HAnchor = HAnchor.Absolute, - VAnchor = VAnchor.Stretch, - Padding = new BorderDouble(right: 3), - Margin = new BorderDouble(right: 2, top: 1, bottom: 1), - Border = new BorderDouble(1), - BackgroundColor = theme.MinimalShade.WithAlpha(10), - BorderColor = theme.SlightShade, - Width = 120 - }; - if (ApplicationController.ServicesStatusType != null) - { - var instance = Activator.CreateInstance(ApplicationController.ServicesStatusType); - if (instance is GuiWidget guiWidget) - { - guiWidget.HAnchor = HAnchor.Stretch; - guiWidget.VAnchor = VAnchor.Stretch; - networkStatus.AddChild(guiWidget); - } - } - - return networkStatus; - } - - private GuiWidget CreateThemeStatusPanel(ThemeConfig theme, Color panelBackgroundColor) - { - var themePanel = new GuiWidget() - { - HAnchor = HAnchor.Absolute, - VAnchor = VAnchor.Stretch, - Padding = new BorderDouble(right: 3), - Margin = new BorderDouble(right: 2, top: 1, bottom: 1), - Border = new BorderDouble(1), - BackgroundColor = panelBackgroundColor, - BorderColor = theme.SlightShade, - Cursor = Cursors.Hand, - ToolTipText = "Theme".Localize(), - Width = 40 - }; - - themePanel.AddChild( - new ImageWidget(AggContext.StaticData.LoadIcon("theme.png", 16, 16, theme.InvertIcons), false) - { - HAnchor = HAnchor.Left | HAnchor.Absolute, - VAnchor = VAnchor.Center | VAnchor.Absolute, - Selectable = false - }); - - themePanel.AddChild( - new ColorButton(theme.PrimaryAccentColor) - { - HAnchor = HAnchor.Right | HAnchor.Absolute, - VAnchor = VAnchor.Center | VAnchor.Absolute, - Width = 12, - Height = 12, - Selectable = false - }); - - themePanel.Click += (s, e) => - { - themePanel.BackgroundColor = theme.DropList.Open.BackgroundColor; - - var menuTheme = AppContext.MenuTheme; - var widget = new GuiWidget() - { - HAnchor = HAnchor.Absolute, - VAnchor = VAnchor.Fit, - Width = 650, - Border = 1, - BorderColor = theme.DropList.Open.BackgroundColor, - // Padding = theme.DefaultContainerPadding, - BackgroundColor = menuTheme.BackgroundColor - }; - - widget.Closed += (s2, e2) => - { - themePanel.BackgroundColor = panelBackgroundColor; - }; - - var section = ApplicationSettingsPage.CreateThemePanel(menuTheme); - widget.AddChild(section); - - var systemWindow = this.Parents().FirstOrDefault(); - systemWindow.ShowPopup( - new MatePoint(themePanel) - { - Mate = new MateOptions(MateEdge.Right, MateEdge.Top), - AltMate = new MateOptions(MateEdge.Right, MateEdge.Top) - }, - new MatePoint(widget) - { - Mate = new MateOptions(MateEdge.Right, MateEdge.Bottom), - AltMate = new MateOptions(MateEdge.Right, MateEdge.Bottom) - }); - }; - return themePanel; - } - - public ChromeTabs TabControl => tabControl; - - private ChromeTab CreatePrinterTab(PrinterConfig printer, ThemeConfig theme) - { - // Printer page is in fixed position - var tab1 = tabControl.AllTabs.FirstOrDefault(); - - var printerTabPage = tab1?.TabContent as PrinterTabPage; - if (printerTabPage == null - || printerTabPage.printer != printer) - { - // TODO - call save before remove - // printerTabPage.sceneContext.SaveChanges(); - - if (printerTabPage != null) - { - tabControl.RemoveTab(tab1); - } - - printerTab = new ChromeTab( - printer.Settings.GetValue(SettingsKey.printer_name), - printer.Settings.GetValue(SettingsKey.printer_name), - tabControl, - new PrinterTabPage(printer, theme, "unused_tab_title"), - theme, - tabImageUrl: ApplicationController.Instance.GetFavIconUrl(oemName: printer.Settings.GetValue(SettingsKey.make))) - { - Name = "3D View Tab", - MinimumSize = new Vector2(120, theme.TabButtonHeight) - }; - - printerTab.CloseClicked += (s, e) => - { - ApplicationController.Instance.ClosePrinter(printer); - }; - - void Printer_SettingChanged(object s, EventArgs e) - { - string settingsName = (e as StringEventArgs)?.Data; - if (settingsName != null && settingsName == SettingsKey.printer_name) - { - printerTab.Title = printer.Settings.GetValue(SettingsKey.printer_name); - } - } - printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; - - // Add printer into fixed position - if (tabControl.AllTabs.Any()) - { - tabControl.AddTab(printerTab, 3); - } - else - { - tabControl.AddTab(printerTab); - } - - return printerTab; - } - else if (printerTab != null) - { - tabControl.ActiveTab = tab1; - return tab1 as ChromeTab; - } - - return null; - } - - public async Task CreatePartTab() - { - var history = ApplicationController.Instance.Library.PlatingHistory; - - var workspace = new PartWorkspace() - { - Name = "New Design".Localize() + (partCount == 0 ? "" : $" ({partCount})"), - SceneContext = new BedConfig(history) - }; - - partCount++; - - await workspace.SceneContext.LoadContent( - new EditContext() - { - ContentStore = ApplicationController.Instance.Library.PlatingHistory, - SourceItem = history.NewPlatingItem() - }); - - ApplicationController.Instance.Workspaces.Add(workspace); - - var newTab = CreatePartTab(workspace); - tabControl.ActiveTab = newTab; - - return newTab; - } - - public ChromeTab CreatePartTab(PartWorkspace workspace) - { - var partTab = new ChromeTab( - workspace.Name, - workspace.Name, - tabControl, - new PartTabPage(null, workspace.SceneContext, theme, ""), - theme, - AggContext.StaticData.LoadIcon("cube.png", 16, 16, theme.InvertIcons)) - { - Name = "newPart" + tabControl.AllTabs.Count(), - MinimumSize = new Vector2(120, theme.TabButtonHeight) - }; - - tabControl.AddTab(partTab); - - partTab.CloseClicked += (s, e) => - { - ApplicationController.Instance.Workspaces.Remove(workspace); - }; - - return partTab; - } - - public override void OnClosed(EventArgs e) - { - unregisterEvents?.Invoke(this, null); - base.OnClosed(e); - } - - private void RenderRunningTasks(ThemeConfig theme, RunningTasksConfig tasks) - { - var rows = tasksContainer.Children.OfType().ToList(); - var displayedTasks = new HashSet(rows.Select(taskRow => taskRow.taskDetails)); - var runningTasks = tasks.RunningTasks; - - // Remove expired items - foreach (var row in rows) - { - if (!runningTasks.Contains(row.taskDetails)) - { - row.Close(); - } - } - - var progressBackgroundColor = new Color(theme.AccentMimimalOverlay, 35); - - // Add new items - foreach (var taskItem in tasks.RunningTasks.Where(t => !displayedTasks.Contains(t))) - { - var runningTaskPanel = new RunningTaskStatusPanel("", taskItem, theme) - { - HAnchor = HAnchor.Absolute, - VAnchor = VAnchor.Stretch, - Margin = new BorderDouble(right: 2, top: 1, bottom: 1), - Border = new BorderDouble(1), - BorderColor = theme.SlightShade, - ProgressBackgroundColor = progressBackgroundColor, - Width = 200 - }; - - tasksContainer.AddChild(runningTaskPanel); - } - - tasksContainer.Invalidate(); - } - } +/* +Copyright (c) 2018, 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 System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MatterHackers.Agg; +using MatterHackers.Agg.Platform; +using MatterHackers.Agg.UI; +using MatterHackers.Localizations; +using MatterHackers.MatterControl.CustomWidgets; +using MatterHackers.MatterControl.PartPreviewWindow.PlusTab; +using MatterHackers.MatterControl.PrintLibrary; +using MatterHackers.MatterControl.SlicerConfiguration; +using MatterHackers.VectorMath; +using Newtonsoft.Json; + +namespace MatterHackers.MatterControl.PartPreviewWindow +{ + public class MainViewWidget : FlowLayoutWidget + { + private EventHandler unregisterEvents; + private ChromeTabs tabControl; + + private int partCount = 0; + private ThemeConfig theme; + private Toolbar statusBar; + private FlowLayoutWidget tasksContainer; + private GuiWidget stretchStatusPanel; + private LinkLabel seeWhatsNewButton; + private LinkLabel updateAvailableButton; + + public MainViewWidget(ThemeConfig theme) + : base(FlowDirection.TopToBottom) + { + this.AnchorAll(); + this.theme = theme; + this.Name = "PartPreviewContent"; + this.BackgroundColor = theme.BackgroundColor; + + // Push TouchScreenMode into GuiWidget + GuiWidget.TouchScreenMode = UserSettings.Instance.IsTouchScreen; + + var extensionArea = new LeftClipFlowLayoutWidget() + { + BackgroundColor = theme.TabBarBackground, + VAnchor = VAnchor.Stretch, + Padding = new BorderDouble(left: 8) + }; + + tabControl = new ChromeTabs(extensionArea, theme) + { + VAnchor = VAnchor.Stretch, + HAnchor = HAnchor.Stretch, + BackgroundColor = theme.BackgroundColor, + BorderColor = theme.MinimalShade, + Border = new BorderDouble(left: 1), + }; + + tabControl.PlusClicked += (s, e) => + { + UiThread.RunOnIdle(() => + { + this.CreatePartTab().ConfigureAwait(false); + }); + }; + + tabControl.ActiveTabChanged += (s, e) => + { + if (this.tabControl.ActiveTab?.TabContent is PartTabPage tabPage) + { + var dragDropData = ApplicationController.Instance.DragDropData; + + // Set reference on tab change + dragDropData.View3DWidget = tabPage.view3DWidget; + dragDropData.SceneContext = tabPage.sceneContext; + + ApplicationController.Instance.PrinterTabSelected = true; + } + else + { + ApplicationController.Instance.PrinterTabSelected = false; + } + + ApplicationController.Instance.MainTabKey = tabControl.SelectedTabKey; + }; + + // Force the ActionArea to be as high as ButtonHeight + tabControl.TabBar.ActionArea.MinimumSize = new Vector2(0, theme.ButtonHeight); + tabControl.TabBar.BackgroundColor = theme.TabBarBackground; + tabControl.TabBar.BorderColor = theme.BackgroundColor; + + // Force common padding into top region + tabControl.TabBar.Padding = theme.TabbarPadding.Clone(top: theme.TabbarPadding.Top * 2, bottom: 0); + + // add in a what's new button + seeWhatsNewButton = new LinkLabel("What's New...".Localize(), theme) + { + Name = "What's New Link", + ToolTipText = "See what's new in this version of MatterControl".Localize(), + VAnchor = VAnchor.Center, + Margin = new BorderDouble(10, 0), + TextColor = theme.TextColor + }; + seeWhatsNewButton.Click += (s, e) => UiThread.RunOnIdle(() => + { + UserSettings.Instance.set(UserSettingsKey.LastReadWhatsNew, JsonConvert.SerializeObject(DateTime.Now)); + DialogWindow.Show(new HelpPage("What's New")); + }); + + tabControl.TabBar.ActionArea.AddChild(seeWhatsNewButton); + + // add in the update available button + updateAvailableButton = new LinkLabel("Update Available".Localize(), theme) + { + Visible = false, + Name = "Update Available Link", + ToolTipText = "There is a new update available for download".Localize(), + VAnchor = VAnchor.Center, + Margin = new BorderDouble(10, 0) + }; + + // Register listeners + UserSettings.Instance.SettingChanged += SetLinkButtonsVisibility; + + RunningInterval showUpdateInterval = null; + updateAvailableButton.VisibleChanged += (s, e) => + { + if (!updateAvailableButton.Visible) + { + if (showUpdateInterval != null) + { + UiThread.ClearInterval(showUpdateInterval); + showUpdateInterval = null; + } + return; + } + + showUpdateInterval = UiThread.SetInterval(() => + { + double displayTime = 1; + double pulseTime = 1; + double totalSeconds = 0; + var textWidgets = updateAvailableButton.Descendants().Where((w) => w.Visible == true).ToArray(); + Color startColor = theme.TextColor; + // Show a highlight on the button as the user did not click it + Animation flashBackground = null; + flashBackground = new Animation() + { + DrawTarget = updateAvailableButton, + FramesPerSecond = 10, + Update = (s1, updateEvent) => + { + totalSeconds += updateEvent.SecondsPassed; + if (totalSeconds < displayTime) + { + double blend = AttentionGetter.GetFadeInOutPulseRatio(totalSeconds, pulseTime); + var color = new Color(startColor, (int)((1 - blend) * 255)); + foreach (var textWidget in textWidgets) + { + textWidget.TextColor = color; + } + } + else + { + foreach (var textWidget in textWidgets) + { + textWidget.TextColor = startColor; + } + flashBackground.Stop(); + } + } + }; + flashBackground.Start(); + }, 120); + }; + + SetLinkButtonsVisibility(this, null); + updateAvailableButton.Click += (s, e) => UiThread.RunOnIdle(() => + { + UpdateControlData.Instance.CheckForUpdate(); + DialogWindow.Show(); + }); + + tabControl.TabBar.ActionArea.AddChild(updateAvailableButton); + + this.AddChild(tabControl); + + ApplicationController.Instance.NotifyPrintersTabRightElement(extensionArea); + + var printer = ApplicationController.Instance.ActivePrinter; + + // Store tab + tabControl.AddTab( + new ChromeTab("Store", "Store".Localize(), tabControl, new StoreTabPage(theme), theme, hasClose: false) + { + MinimumSize = new Vector2(0, theme.TabButtonHeight), + Name = "Store Tab", + Padding = new BorderDouble(15, 0), + }); + + // Library tab + var libraryWidget = new LibraryWidget(this, theme) + { + BackgroundColor = theme.BackgroundColor + }; + + tabControl.AddTab( + new ChromeTab("Library", "Library".Localize(), tabControl, libraryWidget, theme, hasClose: false) + { + MinimumSize = new Vector2(0, theme.TabButtonHeight), + Name = "Library Tab", + Padding = new BorderDouble(15, 0), + }); + + // Hardware tab + tabControl.AddTab( + new ChromeTab( + "Hardware", + "Hardware".Localize(), + tabControl, + new HardwareTabPage(theme) + { + BackgroundColor = theme.BackgroundColor + }, + theme, + hasClose: false) + { + MinimumSize = new Vector2(0, theme.TabButtonHeight), + Name = "Hardware Tab", + Padding = new BorderDouble(15, 0), + }); + + // Printer tab + if (printer.Settings.PrinterSelected) + { + this.CreatePrinterTab(printer, theme); + } + else + { + if (ApplicationController.Instance.Workspaces.Count == 0) + { + this.CreatePartTab().ConfigureAwait(false); + } + } + + string tabKey = ApplicationController.Instance.MainTabKey; + + if (string.IsNullOrEmpty(tabKey)) + { + if (printer.Settings.PrinterSelected) + { + tabKey = printer.Settings.GetValue(SettingsKey.printer_name); + } + else + { + tabKey = "Hardware"; + } + } + + // HACK: Restore to the first printer tab if PrinterTabSelected and tabKey not found. This allows sign in/out to remain on the printer tab across different users + if (!tabControl.AllTabs.Any(t => t.Key == tabKey) + && ApplicationController.Instance.PrinterTabSelected) + { + var key = tabControl.AllTabs.Where(t => t.TabContent is PrinterTabPage).FirstOrDefault()?.Key; + if (key != null) + { + tabKey = key; + } + } + + var brandMenu = new BrandMenuButton(theme) + { + HAnchor = HAnchor.Fit, + VAnchor = VAnchor.Fit, + BackgroundColor = theme.TabBarBackground, + Padding = theme.TabbarPadding.Clone(right: theme.DefaultContainerPadding) + }; + + tabControl.TabBar.ActionArea.AddChild(brandMenu, 0); + + // Restore active tabs + foreach (var workspace in ApplicationController.Instance.Workspaces) + { + this.CreatePartTab(workspace); + } + + tabControl.SelectedTabKey = tabKey; + + statusBar = new Toolbar(theme) + { + HAnchor = HAnchor.Stretch, + VAnchor = VAnchor.Absolute, + Padding = 1, + Height = 22, + BackgroundColor = theme.BackgroundColor, + Border = new BorderDouble(top: 1), + BorderColor = theme.BorderColor20, + }; + this.AddChild(statusBar); + + statusBar.ActionArea.VAnchor = VAnchor.Stretch; + + tasksContainer = new FlowLayoutWidget(FlowDirection.LeftToRight) + { + HAnchor = HAnchor.Fit, + VAnchor = VAnchor.Stretch, + BackgroundColor = theme.MinimalShade, + Name = "runningTasksPanel" + }; + statusBar.AddChild(tasksContainer); + + var tasks = ApplicationController.Instance.Tasks; + + tasks.TasksChanged += (s, e) => + { + RenderRunningTasks(theme, tasks); + }; + + stretchStatusPanel = new GuiWidget() + { + HAnchor = HAnchor.Stretch, + VAnchor = VAnchor.Stretch, + Padding = new BorderDouble(right: 3), + Margin = new BorderDouble(right: 2, top: 1, bottom: 1), + Border = new BorderDouble(1), + BackgroundColor = theme.MinimalShade.WithAlpha(10), + BorderColor = theme.SlightShade, + Width = 200 + }; + statusBar.AddChild(stretchStatusPanel); + + var panelBackgroundColor = theme.MinimalShade.WithAlpha(10); + + statusBar.AddChild( + this.CreateThemeStatusPanel(theme, panelBackgroundColor)); + + statusBar.AddChild( + this.CreateNetworkStatusPanel(theme)); + + this.RenderRunningTasks(theme, tasks); + + // Register listeners + PrinterSettings.AnyPrinterSettingChanged += Printer_SettingChanged; + ApplicationController.Instance.OpenPrintersChanged += OpenPrinters_Changed; + + UpdateControlData.Instance.UpdateStatusChanged.RegisterEvent((s, e) => + { + SetLinkButtonsVisibility(s, new StringEventArgs("Unknown")); + }, ref unregisterEvents); + + ApplicationController.Instance.MainView = this; + } + + private void SetLinkButtonsVisibility (object s, StringEventArgs e) + { + if (UserSettings.Instance.HasLookedAtWhatsNew()) + { + // hide it + seeWhatsNewButton.Visible = false; + } + + if (UpdateControlData.Instance.UpdateStatus == UpdateControlData.UpdateStatusStates.UpdateAvailable) + { + updateAvailableButton.Visible = true; + // if we are going to show the update link hide the whats new link no matter what + seeWhatsNewButton.Visible = false; + } + else + { + updateAvailableButton.Visible = false; + } + } + + private void OpenPrinters_Changed(object sender, OpenPrintersChangedEventArgs e) + { + var activePrinter = e.Printer; + + if (e.Operation == OpenPrintersChangedEventArgs.OperationType.Add) + { + if (activePrinter.Settings.PrinterSelected) + { + // Create and switch to new printer tab + tabControl.ActiveTab = this.CreatePrinterTab(activePrinter, theme); + tabControl.RefreshTabPointers(); + } + } + else + { + // Close existing printer tabs + if (tabControl.AllTabs.FirstOrDefault(t => t.TabContent is PrinterTabPage printerTab + && printerTab.printer.Settings.ID == activePrinter.Settings.ID) is ITab tab + && tab.TabContent is PrinterTabPage printerPage) + { + tabControl.RemoveTab(tab); + tabControl.RefreshTabPointers(); + } + } + } + + private GuiWidget CreateNetworkStatusPanel(ThemeConfig theme) + { + var networkStatus = new GuiWidget() + { + HAnchor = HAnchor.Absolute, + VAnchor = VAnchor.Stretch, + Padding = new BorderDouble(right: 3), + Margin = new BorderDouble(right: 2, top: 1, bottom: 1), + Border = new BorderDouble(1), + BackgroundColor = theme.MinimalShade.WithAlpha(10), + BorderColor = theme.SlightShade, + Width = 120 + }; + if (ApplicationController.ServicesStatusType != null) + { + var instance = Activator.CreateInstance(ApplicationController.ServicesStatusType); + if (instance is GuiWidget guiWidget) + { + guiWidget.HAnchor = HAnchor.Stretch; + guiWidget.VAnchor = VAnchor.Stretch; + networkStatus.AddChild(guiWidget); + } + } + + return networkStatus; + } + + private GuiWidget CreateThemeStatusPanel(ThemeConfig theme, Color panelBackgroundColor) + { + var themePanel = new GuiWidget() + { + HAnchor = HAnchor.Absolute, + VAnchor = VAnchor.Stretch, + Padding = new BorderDouble(right: 3), + Margin = new BorderDouble(right: 2, top: 1, bottom: 1), + Border = new BorderDouble(1), + BackgroundColor = panelBackgroundColor, + BorderColor = theme.SlightShade, + Cursor = Cursors.Hand, + ToolTipText = "Theme".Localize(), + Width = 40 + }; + + themePanel.AddChild( + new ImageWidget(AggContext.StaticData.LoadIcon("theme.png", 16, 16, theme.InvertIcons), false) + { + HAnchor = HAnchor.Left | HAnchor.Absolute, + VAnchor = VAnchor.Center | VAnchor.Absolute, + Selectable = false + }); + + themePanel.AddChild( + new ColorButton(theme.PrimaryAccentColor) + { + HAnchor = HAnchor.Right | HAnchor.Absolute, + VAnchor = VAnchor.Center | VAnchor.Absolute, + Width = 12, + Height = 12, + Selectable = false + }); + + themePanel.Click += (s, e) => + { + themePanel.BackgroundColor = theme.DropList.Open.BackgroundColor; + + var menuTheme = AppContext.MenuTheme; + var widget = new GuiWidget() + { + HAnchor = HAnchor.Absolute, + VAnchor = VAnchor.Fit, + Width = 650, + Border = 1, + BorderColor = theme.DropList.Open.BackgroundColor, + // Padding = theme.DefaultContainerPadding, + BackgroundColor = menuTheme.BackgroundColor + }; + + widget.Closed += (s2, e2) => + { + themePanel.BackgroundColor = panelBackgroundColor; + }; + + var section = ApplicationSettingsPage.CreateThemePanel(menuTheme); + widget.AddChild(section); + + var systemWindow = this.Parents().FirstOrDefault(); + systemWindow.ShowPopup( + new MatePoint(themePanel) + { + Mate = new MateOptions(MateEdge.Right, MateEdge.Top), + AltMate = new MateOptions(MateEdge.Right, MateEdge.Top) + }, + new MatePoint(widget) + { + Mate = new MateOptions(MateEdge.Right, MateEdge.Bottom), + AltMate = new MateOptions(MateEdge.Right, MateEdge.Bottom) + }); + }; + return themePanel; + } + + public ChromeTabs TabControl => tabControl; + + private ChromeTab CreatePrinterTab(PrinterConfig printer, ThemeConfig theme) + { + // Printer page is in fixed position + var tab1 = tabControl.AllTabs.FirstOrDefault(); + + var printerTabPage = tab1?.TabContent as PrinterTabPage; + if (printerTabPage == null + || printerTabPage.printer != printer) + { + // TODO - call save before remove + // printerTabPage.sceneContext.SaveChanges(); + + if (printerTabPage != null) + { + tabControl.RemoveTab(tab1); + } + + var printerTab = new ChromeTab( + printer.Settings.GetValue(SettingsKey.printer_name), + printer.Settings.GetValue(SettingsKey.printer_name), + tabControl, + new PrinterTabPage(printer, theme, "unused_tab_title"), + theme, + tabImageUrl: ApplicationController.Instance.GetFavIconUrl(oemName: printer.Settings.GetValue(SettingsKey.make))) + { + Name = "3D View Tab", + MinimumSize = new Vector2(120, theme.TabButtonHeight) + }; + + printerTab.CloseClicked += (s, e) => + { + ApplicationController.Instance.ClosePrinter(printer); + }; + + printer.Settings.SettingChanged += Printer_SettingChanged; + + // Unregister listener on Tab close + printerTab.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; + // Add printer into fixed position + if (tabControl.AllTabs.Any()) + { + tabControl.AddTab(printerTab, 3); + } + else + { + tabControl.AddTab(printerTab); + } + + return printerTab; + } + else if (tab1 != null) + { + tabControl.ActiveTab = tab1; + return tab1 as ChromeTab; + } + + return null; + } + + public async Task CreatePartTab() + { + var history = ApplicationController.Instance.Library.PlatingHistory; + + var workspace = new PartWorkspace() + { + Name = "New Design".Localize() + (partCount == 0 ? "" : $" ({partCount})"), + SceneContext = new BedConfig(history) + }; + + partCount++; + + await workspace.SceneContext.LoadContent( + new EditContext() + { + ContentStore = ApplicationController.Instance.Library.PlatingHistory, + SourceItem = history.NewPlatingItem() + }); + + ApplicationController.Instance.Workspaces.Add(workspace); + + var newTab = CreatePartTab(workspace); + tabControl.ActiveTab = newTab; + + return newTab; + } + + public ChromeTab CreatePartTab(PartWorkspace workspace) + { + var partTab = new ChromeTab( + workspace.Name, + workspace.Name, + tabControl, + new PartTabPage(null, workspace.SceneContext, theme, ""), + theme, + AggContext.StaticData.LoadIcon("cube.png", 16, 16, theme.InvertIcons)) + { + Name = "newPart" + tabControl.AllTabs.Count(), + MinimumSize = new Vector2(120, theme.TabButtonHeight) + }; + + tabControl.AddTab(partTab); + + partTab.CloseClicked += (s, e) => + { + ApplicationController.Instance.Workspaces.Remove(workspace); + }; + + return partTab; + } + + public override void OnClosed(EventArgs e) + { + // Unregister listeners + PrinterSettings.AnyPrinterSettingChanged -= Printer_SettingChanged; + UserSettings.Instance.SettingChanged -= SetLinkButtonsVisibility; + + unregisterEvents?.Invoke(this, null); + base.OnClosed(e); + } + + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent + && stringEvent.Data == SettingsKey.printer_name) + { + // Try to find a printer tab for the given printer + + // If found, update its title + System.Diagnostics.Debugger.Break(); + // + //printerTab.Title = activePrinter.Settings.GetValue(SettingsKey.printer_name); + } + } + + + private void RenderRunningTasks(ThemeConfig theme, RunningTasksConfig tasks) + { + var rows = tasksContainer.Children.OfType().ToList(); + var displayedTasks = new HashSet(rows.Select(taskRow => taskRow.taskDetails)); + var runningTasks = tasks.RunningTasks; + + // Remove expired items + foreach (var row in rows) + { + if (!runningTasks.Contains(row.taskDetails)) + { + row.Close(); + } + } + + var progressBackgroundColor = new Color(theme.AccentMimimalOverlay, 35); + + // Add new items + foreach (var taskItem in tasks.RunningTasks.Where(t => !displayedTasks.Contains(t))) + { + var runningTaskPanel = new RunningTaskStatusPanel("", taskItem, theme) + { + HAnchor = HAnchor.Absolute, + VAnchor = VAnchor.Stretch, + Margin = new BorderDouble(right: 2, top: 1, bottom: 1), + Border = new BorderDouble(1), + BorderColor = theme.SlightShade, + ProgressBackgroundColor = progressBackgroundColor, + Width = 200 + }; + + tasksContainer.AddChild(runningTaskPanel); + } + + tasksContainer.Invalidate(); + } + } } \ No newline at end of file diff --git a/MatterControlLib/PartPreviewWindow/PrinterTabPage.cs b/MatterControlLib/PartPreviewWindow/PrinterTabPage.cs index 72d0fc755..a14eafe7d 100644 --- a/MatterControlLib/PartPreviewWindow/PrinterTabPage.cs +++ b/MatterControlLib/PartPreviewWindow/PrinterTabPage.cs @@ -53,7 +53,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow internal PrinterActionsBar printerActionsBar; private DockingTabControl sideBar; private SliceSettingsWidget sliceSettingsWidget; - private EventHandler unregisterEvents; public PrinterTabPage(PrinterConfig printer, ThemeConfig theme, string tabTitle) : base(printer, printer.Bed, theme, tabTitle) @@ -219,12 +218,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow printer.Bed.RendererOptions.PropertyChanged += RendererOptions_PropertyChanged; - void CommunicationStateChanged(object s, EventArgs e) - { - this.SetSliderVisibility(); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; } private void RendererOptions_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) @@ -390,9 +384,9 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(null, null); - + // Unregister listeners sceneContext.LoadedGCodeChanged -= BedPlate_LoadedGCodeChanged; + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; printer.ViewState.VisibilityChanged -= ProcessOptionalTabs; printer.ViewState.ViewModeChanged -= ViewState_ViewModeChanged; printer.Bed.RendererOptions.PropertyChanged -= RendererOptions_PropertyChanged; @@ -467,6 +461,11 @@ namespace MatterHackers.MatterControl.PartPreviewWindow sideBar.Rebuild(); } + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + this.SetSliderVisibility(); + } + public static GuiWidget PrintProgressWidget(PrinterConfig printer, ThemeConfig theme) { var bodyRow = new GuiWidget() diff --git a/MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs b/MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs index a9969abbf..21b9388ce 100644 --- a/MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs +++ b/MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs @@ -75,11 +75,11 @@ namespace MatterHackers.MatterControl.PartPreviewWindow VAnchor = VAnchor.Fit }; - var scene = sceneContext.Scene; + scene = sceneContext.Scene; // put in a make permanent button var icon = AggContext.StaticData.LoadIcon("noun_766157.png", 16, 16, theme.InvertIcons).SetPreMultiply(); - var flattenButton = new IconButton(icon, theme) + flattenButton = new IconButton(icon, theme) { Margin = theme.ButtonSpacing, ToolTipText = "Flatten".Localize(), @@ -93,7 +93,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow toolbar.AddChild(flattenButton); // put in a remove button - var removeButton = new IconButton(AggContext.StaticData.LoadIcon("remove.png", 16, 16, theme.InvertIcons), theme) + removeButton = new IconButton(AggContext.StaticData.LoadIcon("remove.png", 16, 16, theme.InvertIcons), theme) { Margin = theme.ButtonSpacing, ToolTipText = "Delete".Localize(), @@ -116,7 +116,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow }; toolbar.AddChild(removeButton); - var overflowButton = new OverflowBar.OverflowMenuButton(theme) + overflowButton = new OverflowBar.OverflowMenuButton(theme) { Enabled = scene.SelectedItem != null, }; @@ -152,27 +152,17 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.ContentPanel = editorPanel; editorPanel.Padding = new BorderDouble(theme.DefaultContainerPadding, 0); - void scene_SelectionChanged(object sender, EventArgs e) - { - if (editorPanel.Children.FirstOrDefault()?.DescendantsAndSelf().FirstOrDefault() is SectionWidget firstSectionWidget) - { - firstSectionWidget.Margin = firstSectionWidget.Margin.Clone(top: 0); - } - - var selectedItem = scene.SelectedItem; - - flattenButton.Enabled = selectedItem?.CanFlatten == true; - removeButton.Enabled = selectedItem != null; - overflowButton.Enabled = selectedItem != null; - } - - scene.SelectionChanged += scene_SelectionChanged; - this.Closed += (s, e) => scene.SelectionChanged -= scene_SelectionChanged; + // Register listeners + scene.SelectionChanged += Scene_SelectionChanged; } public GuiWidget ContentPanel { get; set; } private JsonPathContext pathResolver = new JsonPathContext(); + private IconButton flattenButton; + private IconButton removeButton; + private OverflowBar.OverflowMenuButton overflowButton; + private InteractiveScene scene; public void SetActiveItem(IObject3D selectedItem) { @@ -371,5 +361,27 @@ namespace MatterHackers.MatterControl.PartPreviewWindow children.Add(content); }); } + + public override void OnClosed(EventArgs e) + { + // Unregister listeners + scene.SelectionChanged -= Scene_SelectionChanged; + + base.OnClosed(e); + } + + private void Scene_SelectionChanged(object sender, EventArgs e) + { + if (editorPanel.Children.FirstOrDefault()?.DescendantsAndSelf().FirstOrDefault() is SectionWidget firstSectionWidget) + { + firstSectionWidget.Margin = firstSectionWidget.Margin.Clone(top: 0); + } + + var selectedItem = scene.SelectedItem; + + flattenButton.Enabled = selectedItem?.CanFlatten == true; + removeButton.Enabled = selectedItem != null; + overflowButton.Enabled = selectedItem != null; + } } } \ No newline at end of file diff --git a/MatterControlLib/PartPreviewWindow/View3D/MeshViewerWidget.cs b/MatterControlLib/PartPreviewWindow/View3D/MeshViewerWidget.cs index 8fe33f3cb..d2427585a 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/MeshViewerWidget.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/MeshViewerWidget.cs @@ -270,15 +270,10 @@ namespace MatterHackers.MeshVisualizer gCodeMeshColor = new Color(theme.PrimaryAccentColor, 35); - void selection_Changed (object sender, EventArgs e) - { - Invalidate(); - lastSelectionChangedMs = UiThread.CurrentTimerMs; - } - + // Register listeners scene.SelectionChanged += selection_Changed; - this.Closed += (s, e) => scene.SelectionChanged -= selection_Changed; + BuildVolumeColor = new ColorF(.2, .8, .3, .2).ToColor(); this.interactionLayer.DrawGlTransparentContent += Draw_GlTransparentContent; @@ -334,6 +329,14 @@ namespace MatterHackers.MeshVisualizer base.OnLoad(args); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + scene.SelectionChanged -= selection_Changed; + + base.OnClosed(e); + } + public override void FindNamedChildrenRecursive(string nameToSearchFor, List foundChildren, RectangleDouble touchingBounds, SearchType seachType, bool allowInvalidItems = true) { foreach (InteractionVolume child in interactionLayer.InteractionVolumes) @@ -883,6 +886,12 @@ namespace MatterHackers.MeshVisualizer } } + void selection_Changed(object sender, EventArgs e) + { + Invalidate(); + lastSelectionChangedMs = UiThread.CurrentTimerMs; + } + public enum ModelRenderStyle { Solid, diff --git a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PauseResumeButton.cs b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PauseResumeButton.cs index 1030dc6d5..2cc155e2c 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PauseResumeButton.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PauseResumeButton.cs @@ -44,7 +44,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow private GuiWidget finishSetupButton; private GuiWidget startPrintButton; - private EventHandler unregisterEvents; private PrinterConfig printer; private ThemeConfig theme; @@ -79,36 +78,19 @@ namespace MatterHackers.MatterControl.PartPreviewWindow Margin = theme.ButtonSpacing }); - void CommunicationStateChanged(object s, EventArgs e) - { - UiThread.RunOnIdle(SetButtonStates); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; - - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent - && (stringEvent.Data == SettingsKey.z_probe_z_offset - || stringEvent.Data == SettingsKey.print_leveling_data - || stringEvent.Data == SettingsKey.print_leveling_solution - || stringEvent.Data == SettingsKey.bed_temperature - || stringEvent.Data == SettingsKey.print_leveling_enabled - || stringEvent.Data == SettingsKey.print_leveling_required_to_print - || stringEvent.Data == SettingsKey.filament_has_been_loaded)) - { - SetButtonStates(); - } - } + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; SetButtonStates(); } public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } @@ -160,5 +142,25 @@ namespace MatterHackers.MatterControl.PartPreviewWindow break; } } + + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + UiThread.RunOnIdle(SetButtonStates); + } + + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent + && (stringEvent.Data == SettingsKey.z_probe_z_offset + || stringEvent.Data == SettingsKey.print_leveling_data + || stringEvent.Data == SettingsKey.print_leveling_solution + || stringEvent.Data == SettingsKey.bed_temperature + || stringEvent.Data == SettingsKey.print_leveling_enabled + || stringEvent.Data == SettingsKey.print_leveling_required_to_print + || stringEvent.Data == SettingsKey.filament_has_been_loaded)) + { + SetButtonStates(); + } + } } } \ No newline at end of file diff --git a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrintPopupMenu.cs b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrintPopupMenu.cs index 4a0f33f40..c00e671f5 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrintPopupMenu.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrintPopupMenu.cs @@ -45,7 +45,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public class PrintPopupMenu : PopupMenuButton { private PrinterConfig printer; - private EventHandler unregisterEvents; private Dictionary allUiFields = new Dictionary(); private SettingsContext settingsContext; @@ -183,35 +182,37 @@ namespace MatterHackers.MatterControl.PartPreviewWindow Padding = theme.TextButtonPadding.Clone(right: 5) }); - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent) - { - string settingsKey = stringEvent.Data; - if (allUiFields.TryGetValue(settingsKey, out UIField uifield)) - { - string currentValue = settingsContext.GetValue(settingsKey); - if (uifield.Value != currentValue - || settingsKey == "com_port") - { - uifield.SetValue( - currentValue, - userInitiated: false); - } - } - } - } - + // Register listeners printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; } public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent) + { + string settingsKey = stringEvent.Data; + if (allUiFields.TryGetValue(settingsKey, out UIField uifield)) + { + string currentValue = settingsContext.GetValue(settingsKey); + if (uifield.Value != currentValue + || settingsKey == "com_port") + { + uifield.SetValue( + currentValue, + userInitiated: false); + } + } + } + } + private class IgnoredFlowLayout : FlowLayoutWidget, IIgnoredPopupChild { public IgnoredFlowLayout() diff --git a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterActionsBar.cs b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterActionsBar.cs index 5cc4db383..205bfd28f 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterActionsBar.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterActionsBar.cs @@ -48,7 +48,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public class PrinterActionsBar : OverflowBar { private PrinterConfig printer; - private EventHandler unregisterEvents; private static MarlinEEPromPage marlinEEPromPage = null; private static RepetierEEPromPage repetierEEPromPage = null; @@ -203,15 +202,8 @@ namespace MatterHackers.MatterControl.PartPreviewWindow } }; - void ConnectionSucceeded(object s, EventArgs e) - { - UiThread.RunOnIdle(() => - { - PrintRecovery.CheckIfNeedToRecoverPrint(printer); - }); - } + // Register listeners printer.Connection.ConnectionSucceeded += ConnectionSucceeded; - this.Closed += (s, e) => printer.Connection.ConnectionSucceeded -= ConnectionSucceeded; } bool buttonIsBeingClicked; @@ -246,10 +238,20 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.ConnectionSucceeded -= ConnectionSucceeded; + base.OnClosed(e); } + private void ConnectionSucceeded(object s, EventArgs e) + { + UiThread.RunOnIdle(() => + { + PrintRecovery.CheckIfNeedToRecoverPrint(printer); + }); + } + private void GeneratePrinterOverflowMenu(PopupMenu popupMenu, ThemeConfig theme) { var menuActions = new List() diff --git a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterConnectButton.cs b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterConnectButton.cs index 5a03633c3..cd431c7e2 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterConnectButton.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/PrinterConnectButton.cs @@ -45,7 +45,6 @@ namespace MatterHackers.MatterControl.ActionBar private GuiWidget connectButton; private GuiWidget disconnectButton; - private EventHandler unregisterEvents; private PrinterConfig printer; private bool listenForConnectFailed = false; @@ -146,47 +145,21 @@ namespace MatterHackers.MatterControl.ActionBar child.Margin = theme.ButtonSpacing; } - void CommunicationStateChanged(object s, EventArgs e) - { - this.SetVisibleStates(); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; - - void EnableChanged(object s, EventArgs e) - { - SetVisibleStates(); - } - printer.Connection.EnableChanged += EnableChanged; - this.Closed += (s, e) => printer.Connection.EnableChanged -= EnableChanged; - - void ConnectionFailed(object s, EventArgs e) - { -#if !__ANDROID__ - // TODO: Someday this functionality should be revised to an awaitable Connect() call in the Connect button that - // shows troubleshooting on failed attempts, rather than hooking the failed event and trying to determine if the - // Connect button started the task - if (listenForConnectFailed - && UiThread.CurrentTimerMs - connectStartMs < 25000) - { - UiThread.RunOnIdle(() => - { - // User initiated connect attempt failed, show port selection dialog - DialogWindow.Show(new SetupStepComPortOne(printer)); - }); - } -#endif - listenForConnectFailed = false; - } - printer.Connection.ConnectionFailed += ConnectionFailed; - this.Closed += (s, e) => printer.Connection.ConnectionFailed -= ConnectionFailed; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; + printer.Connection.EnableChanged += Connection_EnableChanged; + printer.Connection.ConnectionFailed += Connection_Failed; this.SetVisibleStates(); } public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + printer.Connection.EnableChanged -= Connection_EnableChanged; + printer.Connection.ConnectionFailed -= Connection_Failed; + base.OnClosed(e); } @@ -219,6 +192,25 @@ namespace MatterHackers.MatterControl.ActionBar new SetupWizardTroubleshooting(ApplicationController.Instance.ActivePrinter)); } + private void Connection_Failed(object s, EventArgs e) + { +#if !__ANDROID__ + // TODO: Someday this functionality should be revised to an awaitable Connect() call in the Connect button that + // shows troubleshooting on failed attempts, rather than hooking the failed event and trying to determine if the + // Connect button started the task + if (listenForConnectFailed + && UiThread.CurrentTimerMs - connectStartMs < 25000) + { + UiThread.RunOnIdle(() => + { + // User initiated connect attempt failed, show port selection dialog + DialogWindow.Show(new SetupStepComPortOne(printer)); + }); + } +#endif + listenForConnectFailed = false; + } + private void SetChildVisible(GuiWidget visibleChild, bool enabled) { foreach (var child in Children) @@ -259,5 +251,15 @@ namespace MatterHackers.MatterControl.ActionBar break; } } + + private void Connection_EnableChanged(object s, EventArgs e) + { + SetVisibleStates(); + } + + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + this.SetVisibleStates(); + } } } \ No newline at end of file diff --git a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/SliceButton.cs b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/SliceButton.cs index b5da449d5..d233b1082 100644 --- a/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/SliceButton.cs +++ b/MatterControlLib/PartPreviewWindow/View3D/PrinterBar/SliceButton.cs @@ -40,8 +40,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow { private PrinterConfig printer; private PrinterTabPage printerTabPage; - private EventHandler unregisterEvents; - private bool activelySlicing { get; set; } + private bool activelySlicing; public SliceButton(PrinterConfig printer, PrinterTabPage printerTabPage, ThemeConfig theme) : base("Slice".Localize(), theme) @@ -53,12 +52,8 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.HoverColor = theme.ToolbarButtonHover; this.MouseDownColor = theme.ToolbarButtonDown; - void CommunicationStateChanged(object s, EventArgs e) - { - UiThread.RunOnIdle(SetButtonStates); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; SetButtonStates(); } @@ -71,10 +66,17 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + base.OnClosed(e); } + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + UiThread.RunOnIdle(SetButtonStates); + } + private void SetButtonStates() { switch (printer.Connection.CommunicationState) diff --git a/MatterControlLib/PartPreviewWindow/ViewControls3D.cs b/MatterControlLib/PartPreviewWindow/ViewControls3D.cs index 34e4dbf2c..b491983e6 100644 --- a/MatterControlLib/PartPreviewWindow/ViewControls3D.cs +++ b/MatterControlLib/PartPreviewWindow/ViewControls3D.cs @@ -93,6 +93,9 @@ namespace MatterHackers.MatterControl.PartPreviewWindow private MainViewWidget mainViewWidget = null; private PopupMenuButton bedMenuButton; private ThemeConfig theme; + private UndoBuffer undoBuffer; + private IconButton undoButton; + private IconButton redoButton; internal void NotifyResetView() { @@ -283,6 +286,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow : base(theme) { this.theme = theme; + this.undoBuffer = undoBuffer; this.ActionArea.Click += (s, e) => { view3DWidget.InteractionLayer.Focus(); @@ -317,7 +321,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.AddChild(new ToolbarSeparator(theme)); - var undoButton = new IconButton(AggContext.StaticData.LoadIcon("Undo_grey_16x.png", 16, 16, theme.InvertIcons), theme) + undoButton = new IconButton(AggContext.StaticData.LoadIcon("Undo_grey_16x.png", 16, 16, theme.InvertIcons), theme) { Name = "3D View Undo", ToolTipText = "Undo", @@ -339,7 +343,7 @@ namespace MatterHackers.MatterControl.PartPreviewWindow }; this.AddChild(undoButton); - var redoButton = new IconButton(AggContext.StaticData.LoadIcon("Redo_grey_16x.png", 16, 16, theme.InvertIcons), theme) + redoButton = new IconButton(AggContext.StaticData.LoadIcon("Redo_grey_16x.png", 16, 16, theme.InvertIcons), theme) { Name = "3D View Redo", Margin = theme.ButtonSpacing, @@ -377,15 +381,6 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.AddChild(new ToolbarSeparator(theme)); - void undoBuffer_Changed(object sender, EventArgs e) - { - undoButton.Enabled = undoBuffer.UndoCount > 0; - redoButton.Enabled = undoBuffer.RedoCount > 0; - } - - undoBuffer.Changed += undoBuffer_Changed; - this.Closed += (s, e) => undoBuffer.Changed -= undoBuffer_Changed; - undoButton.Enabled = undoBuffer.UndoCount > 0; redoButton.Enabled = undoBuffer.RedoCount > 0; @@ -495,12 +490,20 @@ namespace MatterHackers.MatterControl.PartPreviewWindow this.AddChild(button); } + // Register listeners + undoBuffer.Changed += UndoBuffer_Changed; sceneContext.Scene.SelectionChanged += Scene_SelectionChanged; // Run on load Scene_SelectionChanged(null, null); } + private void UndoBuffer_Changed(object sender, EventArgs e) + { + undoButton.Enabled = undoBuffer.UndoCount > 0; + redoButton.Enabled = undoBuffer.RedoCount > 0; + } + private IconButton CreateOpenButton(ThemeConfig theme) { var openButton = new IconButton(AggContext.StaticData.LoadIcon("fa-folder-open_16.png", 16, 16, theme.InvertIcons), theme) @@ -852,7 +855,10 @@ namespace MatterHackers.MatterControl.PartPreviewWindow public override void OnClosed(EventArgs e) { + // Unregister listeners + undoBuffer.Changed -= UndoBuffer_Changed; sceneContext.Scene.SelectionChanged -= Scene_SelectionChanged; + base.OnClosed(e); } } diff --git a/MatterControlLib/PrinterControls/ControlWidgets/AdjustmentControls.cs b/MatterControlLib/PrinterControls/ControlWidgets/AdjustmentControls.cs index f600c3e2e..10eca0f0d 100644 --- a/MatterControlLib/PrinterControls/ControlWidgets/AdjustmentControls.cs +++ b/MatterControlLib/PrinterControls/ControlWidgets/AdjustmentControls.cs @@ -52,7 +52,7 @@ namespace MatterHackers.MatterControl.PrinterControls private readonly double minFeedRateRatio = .25; private readonly double maxFeedRateRatio = 3; - private EventHandler unregisterEvents; + private PrinterConfig printer; private AdjustmentControls(PrinterConfig printer, ThemeConfig theme) : base (FlowDirection.TopToBottom) @@ -60,6 +60,8 @@ namespace MatterHackers.MatterControl.PrinterControls double sliderWidth = 300 * GuiWidget.DeviceScale; double sliderThumbWidth = 10 * GuiWidget.DeviceScale; + this.printer = printer; + SettingsRow settingsRow; { @@ -178,25 +180,8 @@ namespace MatterHackers.MatterControl.PrinterControls settingsRow.AddChild(extrusionValue); } - void Printer_SettingChanged(object s, EventArgs e) - { - var eventArgs = e as StringEventArgs; - if (eventArgs?.Data == SettingsKey.extrusion_ratio) - { - double extrusionRatio = printer.Settings.GetValue(SettingsKey.extrusion_ratio); - extrusionRatioSlider.Value = extrusionRatio; - extrusionValue.ActuallNumberEdit.Value = Math.Round(extrusionRatio, 2); - } - else if (eventArgs?.Data == SettingsKey.feedrate_ratio) - { - double feedrateRatio = printer.Settings.GetValue(SettingsKey.feedrate_ratio); - feedRateRatioSlider.Value = feedrateRatio; - feedRateValue.ActuallNumberEdit.Value = Math.Round(feedrateRatio, 2); - } - } + // Register listeners printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; - } public static SectionWidget CreateSection(PrinterConfig printer, ThemeConfig theme) @@ -216,8 +201,27 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } + + private void Printer_SettingChanged(object s, EventArgs e) + { + var eventArgs = e as StringEventArgs; + if (eventArgs?.Data == SettingsKey.extrusion_ratio) + { + double extrusionRatio = printer.Settings.GetValue(SettingsKey.extrusion_ratio); + extrusionRatioSlider.Value = extrusionRatio; + extrusionValue.ActuallNumberEdit.Value = Math.Round(extrusionRatio, 2); + } + else if (eventArgs?.Data == SettingsKey.feedrate_ratio) + { + double feedrateRatio = printer.Settings.GetValue(SettingsKey.feedrate_ratio); + feedRateRatioSlider.Value = feedrateRatio; + feedRateValue.ActuallNumberEdit.Value = Math.Round(feedrateRatio, 2); + } + } } } \ No newline at end of file diff --git a/MatterControlLib/PrinterControls/ControlWidgets/CalibrationControls.cs b/MatterControlLib/PrinterControls/ControlWidgets/CalibrationControls.cs index dcb0df006..56b8efa74 100644 --- a/MatterControlLib/PrinterControls/ControlWidgets/CalibrationControls.cs +++ b/MatterControlLib/PrinterControls/ControlWidgets/CalibrationControls.cs @@ -41,9 +41,8 @@ namespace MatterHackers.MatterControl.PrinterControls { public class CalibrationControls : FlowLayoutWidget { - private EventHandler unregisterEvents; - private PrinterConfig printer; + private RoundedToggleSwitch printLevelingSwitch; private CalibrationControls(PrinterConfig printer, ThemeConfig theme) : base(FlowDirection.TopToBottom) @@ -82,7 +81,7 @@ namespace MatterHackers.MatterControl.PrinterControls if (!printer.Settings.GetValue(SettingsKey.print_leveling_required_to_print)) { // put in the switch - var printLevelingSwitch = new RoundedToggleSwitch(theme) + printLevelingSwitch = new RoundedToggleSwitch(theme) { VAnchor = VAnchor.Center, Margin = new BorderDouble(left: 16), @@ -93,17 +92,10 @@ namespace MatterHackers.MatterControl.PrinterControls printer.Settings.Helpers.DoPrintLeveling(printLevelingSwitch.Checked); }; - void Settings_PrintLevelingEnabledChanged(object sender, EventArgs e) - { - printLevelingSwitch.Checked = printer.Settings.GetValue(SettingsKey.print_leveling_enabled); - } - + // TODO: Why is this listener conditional? If the leveling changes somehow, shouldn't we be updated the UI to reflect that? + // Register listeners printer.Settings.PrintLevelingEnabledChanged += Settings_PrintLevelingEnabledChanged; - this.Closed += (s,e) => - { - printer.Settings.PrintLevelingEnabledChanged -= Settings_PrintLevelingEnabledChanged; - }; - + settingsRow.AddChild(printLevelingSwitch); } @@ -136,11 +128,9 @@ namespace MatterHackers.MatterControl.PrinterControls } } + // Register listeners printer.Connection.CommunicationStateChanged += PrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= PrinterStatusChanged; - printer.Connection.EnableChanged += PrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.EnableChanged -= PrinterStatusChanged; SetVisibleControls(); } @@ -164,10 +154,19 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.PrintLevelingEnabledChanged -= Settings_PrintLevelingEnabledChanged; + printer.Connection.CommunicationStateChanged -= PrinterStatusChanged; + printer.Connection.EnableChanged -= PrinterStatusChanged; + base.OnClosed(e); } + private void Settings_PrintLevelingEnabledChanged(object sender, EventArgs e) + { + printLevelingSwitch.Checked = printer.Settings.GetValue(SettingsKey.print_leveling_enabled); + } + private void PrinterStatusChanged(object sender, EventArgs e) { SetVisibleControls(); diff --git a/MatterControlLib/PrinterControls/ControlWidgets/FanControls.cs b/MatterControlLib/PrinterControls/ControlWidgets/FanControls.cs index 3cab0db47..598ce84dc 100644 --- a/MatterControlLib/PrinterControls/ControlWidgets/FanControls.cs +++ b/MatterControlLib/PrinterControls/ControlWidgets/FanControls.cs @@ -40,18 +40,17 @@ namespace MatterHackers.MatterControl.PrinterControls { public class FanControls : FlowLayoutWidget { - private EventHandler unregisterEvents; - private EditableNumberDisplay fanSpeedDisplay; private ICheckbox toggleSwitch; + private PrinterConfig printer; private FanControls(PrinterConfig printer, ThemeConfig theme) : base(FlowDirection.TopToBottom) { this.HAnchor = HAnchor.Stretch; this.HAnchor = HAnchor.Stretch; - + this.printer = printer; //Matt's test editing to add a on/off toggle switch bool fanActive = printer.Connection.FanSpeed0To255 != 0; @@ -119,22 +118,8 @@ namespace MatterHackers.MatterControl.PrinterControls container.AddChild(toggleSwitch); settingsRow.ActionWidget = toggleSwitch; - // CreateFanControls - void FanSpeedSet(object s, EventArgs e) - { - if ((int)printer.Connection.FanSpeed0To255 > 0) - { - toggleSwitch.Checked = true; - } - else - { - toggleSwitch.Checked = false; - } - - fanSpeedDisplay.Value = printer.Connection.FanSpeed0To255 * 100 / 255; - } - printer.Connection.FanSpeedSet += FanSpeedSet; - this.Closed += (s, e) => printer.Connection.FanSpeedSet -= FanSpeedSet; + // Register listeners + printer.Connection.FanSpeedSet += Connection_FanSpeedSet; } public static SectionWidget CreateSection(PrinterConfig printer, ThemeConfig theme) @@ -144,8 +129,24 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.FanSpeedSet -= Connection_FanSpeedSet; + base.OnClosed(e); } + + private void Connection_FanSpeedSet(object s, EventArgs e) + { + if ((int)printer.Connection.FanSpeed0To255 > 0) + { + toggleSwitch.Checked = true; + } + else + { + toggleSwitch.Checked = false; + } + + fanSpeedDisplay.Value = printer.Connection.FanSpeed0To255 * 100 / 255; + } } } \ No newline at end of file diff --git a/MatterControlLib/PrinterControls/ControlWidgets/MovementControls.cs b/MatterControlLib/PrinterControls/ControlWidgets/MovementControls.cs index 3d31472e4..02a823566 100644 --- a/MatterControlLib/PrinterControls/ControlWidgets/MovementControls.cs +++ b/MatterControlLib/PrinterControls/ControlWidgets/MovementControls.cs @@ -53,8 +53,6 @@ namespace MatterHackers.MatterControl.PrinterControls private LimitCallingFrequency reportDestinationChanged = null; - private EventHandler unregisterEvents; - private MovementControls(PrinterConfig printer, XYZColors xyzColors, ThemeConfig theme) : base (FlowDirection.TopToBottom) { @@ -72,6 +70,9 @@ namespace MatterHackers.MatterControl.PrinterControls this.AddChild(jogControls); this.AddChild(AddToDisableableList(GetHWDestinationBar())); + + // Register listeners + printer.Connection.DestinationChanged += Connection_DestinationChanged; } public static SectionWidget CreateSection(PrinterConfig printer, ThemeConfig theme) @@ -90,7 +91,9 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.DestinationChanged -= Connection_DestinationChanged; + base.OnClosed(e); } @@ -209,16 +212,15 @@ namespace MatterHackers.MatterControl.PrinterControls }); }); - void DestinationChanged(object s, EventArgs e) - { - reportDestinationChanged.CallEvent(); - } - printer.Connection.DestinationChanged += DestinationChanged; - this.Closed += (s, e) => printer.Connection.DestinationChanged -= DestinationChanged; - return hwDestinationBar; } + + private void Connection_DestinationChanged(object s, EventArgs e) + { + reportDestinationChanged.CallEvent(); + } + private void SetDestinationPositionText(TextWidget xPosition, TextWidget yPosition, TextWidget zPosition) { Vector3 destinationPosition = printer.Connection.CurrentDestination; @@ -250,7 +252,6 @@ namespace MatterHackers.MatterControl.PrinterControls private Button clearZOffsetButton; private FlowLayoutWidget zOffsetStreamContainer; - private EventHandler unregisterEvents; private bool allowRemoveButton; private ThemeConfig theme; private PrinterSettings printerSettings; @@ -263,16 +264,6 @@ namespace MatterHackers.MatterControl.PrinterControls this.HAnchor = HAnchor.Fit; this.VAnchor = VAnchor.Fit | VAnchor.Center; - void Printer_SettingChanged(object s, EventArgs e) - { - if ((e as StringEventArgs)?.Data == SettingsKey.baby_step_z_offset) - { - OffsetStreamChanged(null, null); - } - } - printerSettings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printerSettings.SettingChanged -= Printer_SettingChanged; - zOffsetStreamContainer = new FlowLayoutWidget(FlowDirection.LeftToRight) { Margin = new BorderDouble(3, 0), @@ -303,6 +294,9 @@ namespace MatterHackers.MatterControl.PrinterControls printerSettings.SetValue(SettingsKey.baby_step_z_offset, "0"); }; zOffsetStreamContainer.AddChild(clearZOffsetButton); + + // Register listeners + printerSettings.SettingChanged += Printer_SettingChanged; } internal void OffsetStreamChanged(object sender, EventArgs e) @@ -318,8 +312,18 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(null, null); + // Unregister listeners + printerSettings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } + + private void Printer_SettingChanged(object s, EventArgs e) + { + if ((e as StringEventArgs)?.Data == SettingsKey.baby_step_z_offset) + { + OffsetStreamChanged(null, null); + } + } } } diff --git a/MatterControlLib/PrinterControls/ControlWidgets/PowerControls.cs b/MatterControlLib/PrinterControls/ControlWidgets/PowerControls.cs index c847f38cf..cac94ae05 100644 --- a/MatterControlLib/PrinterControls/ControlWidgets/PowerControls.cs +++ b/MatterControlLib/PrinterControls/ControlWidgets/PowerControls.cs @@ -1,5 +1,5 @@ /* -Copyright (c) 2014, Kevin Pope +Copyright (c) 2018, Kevin Pope, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without @@ -28,7 +28,6 @@ either expressed or implied, of the FreeBSD Project. */ using System; -using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.ConfigurationPage; @@ -39,7 +38,6 @@ namespace MatterHackers.MatterControl.PrinterControls { public class PowerControls : FlowLayoutWidget { - private EventHandler unregisterEvents; private PrinterConfig printer; private SettingsItem settingsItem; @@ -66,26 +64,9 @@ namespace MatterHackers.MatterControl.PrinterControls }, enforceGutter: false)); - void CommunicationStateChanged(object s, EventArgs e) - { - this.Enabled = printer.Connection.IsConnected - && printer.Settings.GetValue(SettingsKey.has_power_control); - } - printer.Connection.CommunicationStateChanged += CommunicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= CommunicationStateChanged; - - void AtxPowerStateChanged(object s, EventArgs e) - { - if (settingsItem.SettingsControl is ICheckbox toggleSwitch) - { - if (toggleSwitch.Checked != printer.Connection.AtxPowerEnabled) - { - toggleSwitch.Checked = printer.Connection.AtxPowerEnabled; - } - } - } - printer.Connection.AtxPowerStateChanged += AtxPowerStateChanged; - this.Closed += (s, e) => printer.Connection.AtxPowerStateChanged -= AtxPowerStateChanged; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; + printer.Connection.AtxPowerStateChanged += Connection_AtxPowerStateChanged; } public static SectionWidget CreateSection(PrinterConfig printer, ThemeConfig theme) @@ -103,8 +84,28 @@ namespace MatterHackers.MatterControl.PrinterControls public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + printer.Connection.AtxPowerStateChanged -= Connection_AtxPowerStateChanged; + base.OnClosed(e); } + + private void Connection_CommunicationStateChanged(object s, EventArgs e) + { + this.Enabled = printer.Connection.IsConnected + && printer.Settings.GetValue(SettingsKey.has_power_control); + } + + private void Connection_AtxPowerStateChanged(object s, EventArgs e) + { + if (settingsItem.SettingsControl is ICheckbox toggleSwitch) + { + if (toggleSwitch.Checked != printer.Connection.AtxPowerEnabled) + { + toggleSwitch.Checked = printer.Connection.AtxPowerEnabled; + } + } + } } } \ No newline at end of file diff --git a/MatterControlLib/PrinterControls/JogControls.cs b/MatterControlLib/PrinterControls/JogControls.cs index 0ba92ec3c..7bb5bc8fb 100644 --- a/MatterControlLib/PrinterControls/JogControls.cs +++ b/MatterControlLib/PrinterControls/JogControls.cs @@ -68,7 +68,6 @@ namespace MatterHackers.MatterControl private GuiWidget disableableEButtons; private GuiWidget keyboardFocusBorder; private GuiWidget keyboardImage; - private EventHandler unregisterEvents; private GuiWidget xyGrid = null; public JogControls(PrinterConfig printer, XYZColors colors, ThemeConfig theme) @@ -208,8 +207,8 @@ namespace MatterHackers.MatterControl this.PerformLayout(); + // Register listeners printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; } internal void SetEnabledLevels(bool enableBabysteppingMode, bool enableEControls) @@ -271,7 +270,9 @@ namespace MatterHackers.MatterControl public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); } diff --git a/MatterControlLib/PrinterControls/ManualPrinterControls.cs b/MatterControlLib/PrinterControls/ManualPrinterControls.cs index 9f57ce897..f0cb52d04 100644 --- a/MatterControlLib/PrinterControls/ManualPrinterControls.cs +++ b/MatterControlLib/PrinterControls/ManualPrinterControls.cs @@ -56,21 +56,19 @@ namespace MatterHackers.MatterControl private GuiWidget tuningAdjustmentControlsContainer; private MovementControls movementControlsContainer; private GuiWidget calibrationControlsContainer; - private ThemeConfig theme; - public PrinterConfig Printer { get; } + private PrinterConfig printer; private FlowLayoutWidget column; public ManualPrinterControls(PrinterConfig printer, ThemeConfig theme) { this.theme = theme; - this.Printer = printer; + this.printer = printer; this.ScrollArea.HAnchor |= HAnchor.Stretch; this.AnchorAll(); this.AutoScroll = true; this.HAnchor = HAnchor.Stretch; this.VAnchor = VAnchor.Stretch; - this.Name = "ManualPrinterControls"; int headingPointSize = theme.H1PointSize; @@ -107,15 +105,16 @@ namespace MatterHackers.MatterControl // HACK: this is a hack to make the layout engine fire again for this control UiThread.RunOnIdle(() => tuningAdjustmentControlsContainer.Width = tuningAdjustmentControlsContainer.Width + 1); + // Register listeners printer.Connection.CommunicationStateChanged += onPrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= onPrinterStatusChanged; - printer.Connection.EnableChanged += onPrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.EnableChanged -= onPrinterStatusChanged; SetVisibleControls(); } + // Public printer member for AddPluginControls plugins + public PrinterConfig Printer => printer; + public GuiWidget AddPluginWidget(SectionWidget sectionWidget) { // Section not active due to constraints @@ -155,6 +154,15 @@ namespace MatterHackers.MatterControl base.OnLoad(args); } + public override void OnClosed(EventArgs e) + { + // Unregister listeners + printer.Connection.CommunicationStateChanged -= onPrinterStatusChanged; + printer.Connection.EnableChanged -= onPrinterStatusChanged; + + base.OnClosed(e); + } + private void onPrinterStatusChanged(object sender, EventArgs e) { SetVisibleControls(); diff --git a/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortManual.cs b/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortManual.cs index 88f4ad7da..5f9017c55 100644 --- a/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortManual.cs +++ b/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortManual.cs @@ -61,7 +61,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private TextWidget printerComPortHelpMessage; private TextWidget printerComPortError; - private EventHandler unregisterEvents; protected List SerialPortButtonsList = new List(); private PrinterConfig printer; @@ -112,8 +111,8 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections this.AddPageAction(connectButton); this.AddPageAction(refreshButton); - printer.Connection.CommunicationStateChanged += onPrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= onPrinterStatusChanged; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; } protected override void OnCancel(out bool abortCancel) @@ -124,7 +123,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + base.OnClosed(e); } @@ -187,7 +188,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return container; } - private void onPrinterStatusChanged(object sender, EventArgs e) + private void Connection_CommunicationStateChanged(object sender, EventArgs e) { if (printer.Connection.IsConnected) { diff --git a/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs b/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs index 4d1f80a00..be7ece892 100644 --- a/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs +++ b/MatterControlLib/PrinterControls/PrinterConnections/SetupStepComPortTwo.cs @@ -36,7 +36,6 @@ using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PrinterCommunication; -using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.SerialPortCommunication.FrostedSerial; namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections @@ -49,7 +48,6 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections private GuiWidget connectButton; private TextWidget printerErrorMessage; - private EventHandler unregisterEvents; private PrinterConfig printer; public SetupStepComPortTwo(PrinterConfig printer) @@ -91,12 +89,12 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections DialogWindow.ChangeToPage(new SetupStepComPortOne(printer)); }; - printer.Connection.CommunicationStateChanged += onPrinterStatusChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= onPrinterStatusChanged; - this.AddPageAction(nextButton); this.AddPageAction(backButton); this.AddPageAction(connectButton); + + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; } protected override void OnCancel(out bool abortCancel) @@ -107,7 +105,9 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + base.OnClosed(e); } @@ -169,7 +169,7 @@ namespace MatterHackers.MatterControl.PrinterControls.PrinterConnections return container; } - private void onPrinterStatusChanged(object sender, EventArgs e) + private void Connection_CommunicationStateChanged(object sender, EventArgs e) { if (printer.Connection.IsConnected) { diff --git a/MatterControlLib/SetupWizard/AndroidConnectDevicePage.cs b/MatterControlLib/SetupWizard/AndroidConnectDevicePage.cs index 347eda2a9..508e6036f 100644 --- a/MatterControlLib/SetupWizard/AndroidConnectDevicePage.cs +++ b/MatterControlLib/SetupWizard/AndroidConnectDevicePage.cs @@ -39,8 +39,6 @@ namespace MatterHackers.MatterControl { public class AndroidConnectDevicePage : DialogPage { - private EventHandler unregisterEvents; - private TextWidget generalError; private GuiWidget connectButton; @@ -53,6 +51,7 @@ namespace MatterHackers.MatterControl private FlowLayoutWidget retryButtonContainer; private FlowLayoutWidget connectButtonContainer; + private PrinterConfig printer; public AndroidConnectDevicePage() { @@ -69,10 +68,9 @@ namespace MatterHackers.MatterControl contentRow.AddChild(new TextWidget("3. Press 'Connect'.".Localize(), 0, 0, 12,textColor:theme.TextColor)); //Add inputs to main container - var printer = ApplicationController.Instance.ActivePrinter; - printer.Connection.CommunicationStateChanged += communicationStateChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= communicationStateChanged; - + printer = ApplicationController.Instance.ActivePrinter; + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; + connectButtonContainer = new FlowLayoutWidget() { HAnchor = HAnchor.Stretch, @@ -113,7 +111,7 @@ namespace MatterHackers.MatterControl troubleshootButton.Click += (s, e) => UiThread.RunOnIdle(() => { DialogWindow.ChangeToPage( - new SetupWizardTroubleshooting(ApplicationController.Instance.ActivePrinter)); + new SetupWizardTroubleshooting(printer)); }); retryButtonContainer = new FlowLayoutWidget() @@ -144,7 +142,7 @@ namespace MatterHackers.MatterControl void ConnectButton_Click(object sender, EventArgs mouseEvent) { - ApplicationController.Instance.ActivePrinter.Connection.Connect(); + printer.Connection.Connect(); } void NextButton_Click(object sender, EventArgs mouseEvent) @@ -155,7 +153,7 @@ namespace MatterHackers.MatterControl UiThread.RunOnIdle(this.DialogWindow.Close); } - private void communicationStateChanged(object sender, EventArgs args) + private void Connection_CommunicationStateChanged(object sender, EventArgs args) { UiThread.RunOnIdle(() => updateControls(false)); } @@ -199,7 +197,9 @@ namespace MatterHackers.MatterControl public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + base.OnClosed(e); } } diff --git a/MatterControlLib/SetupWizard/SetupWizardTroubleshooting.cs b/MatterControlLib/SetupWizard/SetupWizardTroubleshooting.cs index 0105e2021..4d22c73c0 100644 --- a/MatterControlLib/SetupWizard/SetupWizardTroubleshooting.cs +++ b/MatterControlLib/SetupWizard/SetupWizardTroubleshooting.cs @@ -24,8 +24,6 @@ namespace MatterHackers.MatterControl { private GuiWidget nextButton; - private EventHandler unregisterEvents; - private CriteriaRow connectToPrinterRow; // Used in Android @@ -52,14 +50,13 @@ namespace MatterHackers.MatterControl this.AddPageAction(nextButton); - // Register for connection notifications - printer.Connection.CommunicationStateChanged += ConnectionStatusChanged; - this.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= ConnectionStatusChanged; + // Register listeners + printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged; } - public void ConnectionStatusChanged(object test, EventArgs args) + public void Connection_CommunicationStateChanged(object test, EventArgs args) { - if(printer.Connection.CommunicationState == CommunicationStates.Connected && connectToPrinterRow != null) + if (printer.Connection.CommunicationState == CommunicationStates.Connected && connectToPrinterRow != null) { connectToPrinterRow.SetSuccessful(); nextButton.Visible = true; @@ -78,12 +75,14 @@ namespace MatterHackers.MatterControl public override void OnClosed(EventArgs e) { - if(checkForPermissionTimer != null) + // Unregister listeners + printer.Connection.CommunicationStateChanged -= Connection_CommunicationStateChanged; + + if (checkForPermissionTimer != null) { checkForPermissionTimer.Dispose(); } - unregisterEvents?.Invoke(this, null); base.OnClosed(e); } diff --git a/MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs b/MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs index dea5f8275..ebec355fa 100644 --- a/MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs +++ b/MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs @@ -50,7 +50,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private ThemeConfig theme; private PrinterConfig printer; private GuiWidget pullDownContainer; - private EventHandler unregisterEvents; public PresetSelectorWidget(PrinterConfig printer, string label, Color accentColor, NamedSettingsLayers layerType, ThemeConfig theme) : base(FlowDirection.TopToBottom) @@ -83,20 +82,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration pullDownContainer.AddChild(this.GetPulldownContainer()); this.AddChild(pullDownContainer); + // Register listeners printer.Settings.MaterialPresetChanged += ActiveSliceSettings_MaterialPresetChanged; - - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent - && (stringEvent.Data == SettingsKey.default_material_presets - || stringEvent.Data == SettingsKey.layer_name)) - { - RebuildDropDownList(); - } - } - printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; } public FlowLayoutWidget GetPulldownContainer() @@ -226,12 +214,23 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public override void OnClosed(EventArgs e) { + // Unregister listeners printer.Settings.MaterialPresetChanged -= ActiveSliceSettings_MaterialPresetChanged; - unregisterEvents?.Invoke(this, null); + printer.Settings.SettingChanged -= Printer_SettingChanged; base.OnClosed(e); } + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent + && (stringEvent.Data == SettingsKey.default_material_presets + || stringEvent.Data == SettingsKey.layer_name)) + { + RebuildDropDownList(); + } + } + private void ActiveSliceSettings_MaterialPresetChanged(object sender, EventArgs e) { RebuildDropDownList(); diff --git a/MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs b/MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs index d4d8df8d6..314c16582 100644 --- a/MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs +++ b/MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs @@ -109,7 +109,6 @@ namespace MatterHackers.MatterControl.SlicerConfiguration private int groupPanelCount = 0; private List<(GuiWidget widget, SliceSettingData settingData)> settingsRows; private TextWidget filteredItemsHeading; - private EventHandler unregisterEvents; private Action externalExtendMenu; private string scopeName; @@ -179,14 +178,11 @@ namespace MatterHackers.MatterControl.SlicerConfiguration VAnchor = VAnchor.Stretch, }; scrollable.ScrollArea.HAnchor = HAnchor.Stretch; - //scrollable.ScrollArea.VAnchor = VAnchor.Fit; var tabContainer = new FlowLayoutWidget(FlowDirection.TopToBottom) { VAnchor = VAnchor.Fit, HAnchor = HAnchor.Stretch, - //DebugShowBounds = true, - //MinimumSize = new Vector2(200, 200) }; scrollable.AddChild(tabContainer); @@ -319,27 +315,8 @@ namespace MatterHackers.MatterControl.SlicerConfiguration } }; - void Printer_SettingChanged(object s, EventArgs e) - { - if (e is StringEventArgs stringEvent) - { - string settingsKey = stringEvent.Data; - if (this.allUiFields.TryGetValue(settingsKey, out UIField uifield)) - { - string currentValue = settingsContext.GetValue(settingsKey); - if (uifield.Value != currentValue - || settingsKey == "com_port") - { - uifield.SetValue( - currentValue, - userInitiated: false); - } - } - } - } - + // Register listeners printer.Settings.SettingChanged += Printer_SettingChanged; - this.Closed += (s, e) => printer.Settings.SettingChanged -= Printer_SettingChanged; } this.PerformLayout(); @@ -898,6 +875,25 @@ namespace MatterHackers.MatterControl.SlicerConfiguration List widgetsThatWereExpanded = new List(); + private void Printer_SettingChanged(object s, EventArgs e) + { + if (e is StringEventArgs stringEvent) + { + string settingsKey = stringEvent.Data; + if (this.allUiFields.TryGetValue(settingsKey, out UIField uifield)) + { + string currentValue = settingsContext.GetValue(settingsKey); + if (uifield.Value != currentValue + || settingsKey == "com_port") + { + uifield.SetValue( + currentValue, + userInitiated: false); + } + } + } + } + private void ShowFilteredView() { widgetsThatWereExpanded.Clear(); @@ -922,7 +918,9 @@ namespace MatterHackers.MatterControl.SlicerConfiguration public override void OnClosed(EventArgs e) { - unregisterEvents?.Invoke(this, null); + // Unregister listeners + printer.Settings.SettingChanged -= Printer_SettingChanged; + base.OnClosed(e); }