public double ExtruderTemperature(int extruderIndex)
        {
            if (extruderIndex == 0)
            {
                return(printerSettings.GetValue <double>(SettingsKey.temperature));
            }
            else
            {
                // Check if there is a material override for this extruder
                // Otherwise, use the SettingsLayers that is bound to this extruder
                if (extruderIndex < printerSettings.MaterialSettingsKeys.Count)
                {
                    string materialKey         = printerSettings.MaterialSettingsKeys[extruderIndex];
                    PrinterSettingsLayer layer = printerSettings.GetMaterialLayer(materialKey);

                    if (layer != null)
                    {
                        string result = "0";
                        if (layer.TryGetValue(SettingsKey.temperature, out result))
                        {
                            double value = 0;
                            if (double.TryParse(result, out value))
                            {
                                return(value);
                            }
                        }
                    }
                }

                // else return the normal settings cascade
                return(printerSettings.GetValue <double>(SettingsKey.temperature));
            }
        }
        public void SetValue(string settingsKey, string settingsValue, PrinterSettingsLayer layer = null)
        {
            // Stash user overrides if a non-user override is being set
            if (layer != null && layer != UserLayer)
            {
                StashUserOverride(layer, settingsKey);
            }
            else
            {
                // Remove any staged/conflicting user override, making this the new and active user override
                if (StagedUserSettings.ContainsKey(settingsKey))
                {
                    StagedUserSettings.Remove(settingsKey);
                }
            }

            var persistenceLayer = layer ?? UserLayer;

            // If the setting exists and is set to the requested value, exit without setting or saving
            string existingValue;

            if (persistenceLayer.TryGetValue(settingsKey, out existingValue) && existingValue == settingsValue)
            {
                return;
            }

            // Otherwise, set and save
            persistenceLayer[settingsKey] = settingsValue;
            Save();

            ActiveSliceSettings.OnSettingChanged(settingsKey);
        }
        public string ExtruderTemperature(int extruderIndex)
        {
            if (extruderIndex >= printerSettings.MaterialSettingsKeys.Count)
            {
                // MaterialSettingsKeys is empty or lacks a value for the given extruder index
                //
                // If extruder index zero was requested, return the layer cascade temperature value, otherwise null
                return((extruderIndex == 0) ? printerSettings.GetValue("temperature") : null);
            }

            string materialKey = printerSettings.MaterialSettingsKeys[extruderIndex];

            if (extruderIndex == 0 && (string.IsNullOrEmpty(materialKey) || printerSettings.UserLayer.ContainsKey("temperature")))
            {
                // In the case where a user override exists or MaterialSettingsKeys is populated with multiple extruder
                // positions but position 0 is empty and thus unassigned, use layer cascade to resolve temp
                return(printerSettings.GetValue("temperature"));
            }

            // Otherwise, use the SettingsLayers that is bound to this extruder
            PrinterSettingsLayer layer = printerSettings.GetMaterialLayer(materialKey);

            string result = "0";

            layer?.TryGetValue("temperature", out result);
            return(result);
        }
		public void firstLayerSpeedEqualsAcceptableValue(PrinterSettings settings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerSpeedString;
			if (!layer.TryGetValue(SettingsKey.first_layer_speed, out firstLayerSpeedString))
			{
				return;
			}

			double firstLayerSpeed;
			if (firstLayerSpeedString.Contains("%"))
			{
				string infillSpeedString = settings.GetValue("infill_speed");
				double infillSpeed = double.Parse(infillSpeedString);

				firstLayerSpeedString = firstLayerSpeedString.Replace("%", "");

				double FirstLayerSpeedPercent = double.Parse(firstLayerSpeedString);

				firstLayerSpeed = FirstLayerSpeedPercent * infillSpeed / 100.0;
			}
			else
			{
				firstLayerSpeed = double.Parse(firstLayerSpeedString);
			}

			Assert.Greater(firstLayerSpeed, 5, "Unexpected firstLayerSpeedEqualsAcceptableValue value: " + sourceFile);
		}
        private void RestoreUserOverride(PrinterSettingsLayer settingsLayer, string settingsKey)
        {
            string stagedUserOverride;

            if (StagedUserSettings.TryGetValue(settingsKey, out stagedUserOverride))
            {
                StagedUserSettings.Remove(settingsKey);
                UserLayer[settingsKey] = stagedUserOverride;
            }
        }
        internal void ClearValue(string sliceSetting, PrinterSettingsLayer layer = null)
        {
            var persistenceLayer = layer ?? UserLayer;

            if (persistenceLayer.ContainsKey(sliceSetting))
            {
                persistenceLayer.Remove(sliceSetting);
                Save();
            }
        }
        /// <summary>
        /// Move conflicting user overrides to the temporary staging area, allowing presets values to take effect
        /// </summary>
        private void StashUserOverride(PrinterSettingsLayer settingsLayer, string settingsKey)
        {
            string userOverride;

            if (this.UserLayer.TryGetValue(settingsKey, out userOverride))
            {
                this.UserLayer.Remove(settingsKey);
                this.StagedUserSettings.Add(settingsKey, userOverride);
            }
        }
        /// <summary>
        /// Move conflicting user overrides to the temporary staging area, allowing presets values to take effect
        /// </summary>
        public void DeactivateConflictingUserOverrides(PrinterSettingsLayer settingsLayer)
        {
            if (settingsLayer == null)
            {
                return;
            }

            foreach (var settingsKey in settingsLayer.Keys)
            {
                StashUserOverride(settingsLayer, settingsKey);
            }
        }
        public SettingsContext(PrinterConfig printer, IEnumerable <PrinterSettingsLayer> layerCascade, NamedSettingsLayers viewFilter)
        {
            this.printer      = printer;
            this.layerCascade = layerCascade;
            this.ViewFilter   = viewFilter;

            // When editing presets, LayerCascade contains a filtered list of settings layers. If the list is null we're in the primarySettingsView
            this.IsPrimarySettingsView = layerCascade == null;

            // The last layer of the layerFilters is the target persistence
            this.persistenceLayer = layerCascade?.First() ?? printer.Settings.UserLayer;
        }
Exemple #10
0
        public void CopyFrom(PrinterSettings printerSettings)
        {
            this.OemLayer       = printerSettings.OemLayer;
            this.MaterialLayers = printerSettings.MaterialLayers;
            this.QualityLayers  = printerSettings.QualityLayers;
            this.UserLayer      = printerSettings.UserLayer;

            this.ID                 = printerSettings.ID;
            this.QualityLayer       = GetQualityLayer(printerSettings.ActiveQualityKey);
            this.MaterialLayer      = GetMaterialLayer(printerSettings.ActiveMaterialKey);
            this.StagedUserSettings = printerSettings.StagedUserSettings;
            this.Macros             = printerSettings.Macros;
        }
        internal static void ImportFromExisting(string settingsFilePath)
        {
            if (string.IsNullOrEmpty(settingsFilePath) || !File.Exists(settingsFilePath))
            {
                return;
            }

            var printerInfo = new PrinterInfo
            {
                Name = Path.GetFileNameWithoutExtension(settingsFilePath),
                ID   = Guid.NewGuid().ToString()
            };

            string importType = Path.GetExtension(settingsFilePath).ToLower();

            switch (importType)
            {
            case ".printer":
                var profile = ProfileManager.LoadProfileFromDisk(settingsFilePath);
                profile.ID = printerInfo.ID;

                // TODO: Resolve name conflicts
                profile.SetName(printerInfo.Name);

                Instance.Profiles.Add(printerInfo);

                profile.SaveChanges();
                break;

            case ".ini":
                var settingsToImport = PrinterSettingsLayer.LoadFromIni(settingsFilePath);

                var layeredProfile = new PrinterSettings()
                {
                    ID       = printerInfo.ID,
                    OemLayer = settingsToImport
                };

                // TODO: Resolve name conflicts
                layeredProfile.UserLayer[SettingsKey.printer_name.ToString()] = printerInfo.Name;

                Instance.Profiles.Add(printerInfo);

                layeredProfile.Save();

                break;
            }

            ProfileManager.Instance.Save();
        }
        private GuiWidget CreateSliceSettingsWidget(PrinterSettingsLayer persistenceLayer)
        {
            var layerCascade = new List <PrinterSettingsLayer>
            {
                persistenceLayer,
                ActiveSliceSettings.Instance.OemLayer,
                ActiveSliceSettings.Instance.BaseLayer
            };

            return(new SliceSettingsWidget(layerCascade, presetsContext.LayerType)
            {
                ShowControlBar = false
            });
        }
        private GuiWidget CreateSliceSettingsWidget(PrinterSettingsLayer persistenceLayer)
        {
            var layerCascade = new List <PrinterSettingsLayer>
            {
                persistenceLayer,
                ActiveSliceSettings.Instance.OemLayer,
                ActiveSliceSettings.Instance.BaseLayer
            };

            var settingsWidget = new SliceSettingsWidget(layerCascade, presetsContext.LayerType);

            settingsWidget.settingsControlBar.Visible = false;

            return(settingsWidget);
        }
Exemple #14
0
        internal void SetValue(string settingsKey, string settingsValue, PrinterSettingsLayer layer = null)
        {
            var persistenceLayer = layer ?? UserLayer;

            // If the setting exists and is set the requested value, exit without setting or saving
            string existingValue;

            if (persistenceLayer.TryGetValue(settingsKey, out existingValue) && existingValue == settingsValue)
            {
                return;
            }

            // Otherwise, set and save
            persistenceLayer[settingsKey] = settingsValue;
            Save();
        }
        public void Merge(PrinterSettingsLayer destinationLayer, PrinterSettings settingsToImport, List <PrinterSettingsLayer> rawSourceFilter, bool setLayerName)
        {
            HashSet <string> skipKeys = new HashSet <string>
            {
                "layer_id",
            };

            if (!setLayerName)
            {
                skipKeys.Add(SettingsKey.layer_name);
            }

            var destinationFilter = new List <PrinterSettingsLayer>
            {
                OemLayer,
                BaseLayer,
                destinationLayer,
            }.Where(layer => layer != null);

            var sourceFilter = rawSourceFilter.Where(layer => layer != null);

            foreach (var keyName in PrinterSettings.KnownSettings)
            {
                if (settingsToImport.Contains(keyName))
                {
                    // Compare the value to import to the layer cascade value and only set if different
                    string currentValue = this.GetValue(keyName, destinationFilter).Trim();
                    string importValue  = settingsToImport.GetValue(keyName, sourceFilter).Trim();

                    if (!string.IsNullOrEmpty(importValue) &&
                        currentValue != keyName &&
                        !skipKeys.Contains(keyName))
                    {
                        destinationLayer[keyName] = importValue;
                    }
                }
            }

            if (setLayerName)
            {
                destinationLayer[SettingsKey.layer_name] = settingsToImport.GetValue(SettingsKey.layer_name, sourceFilter);
            }

            this.Save();

            ApplicationController.Instance.ReloadAdvancedControlsPanel();
        }
        private GuiWidget CreateSliceSettingsWidget(PrinterConfig printer, PrinterSettingsLayer persistenceLayer)
        {
            var settingsContext = new SettingsContext(
                printer,
                new List <PrinterSettingsLayer>
            {
                persistenceLayer,
                printer.Settings.OemLayer,
                printer.Settings.BaseLayer
            },
                presetsContext.LayerType);

            return(new SliceSettingsWidget(printer, settingsContext, theme)
            {
                ShowControlBar = false
            });
        }
Exemple #17
0
        private GuiWidget CreateSliceSettingsWidget(PrinterConfig printer, PrinterSettingsLayer persistenceLayer)
        {
            var settingsContext = new SettingsContext(
                printer,
                new List <PrinterSettingsLayer>
            {
                persistenceLayer,
                ActiveSliceSettings.Instance.OemLayer,
                ActiveSliceSettings.Instance.BaseLayer
            },
                presetsContext.LayerType);

            return(new SliceSettingsWidget(printer, settingsContext, ApplicationController.Instance.Theme)
            {
                ShowControlBar = false
            });
        }
Exemple #18
0
        public static PrinterSettingsLayer LoadFromIni(TextReader reader)
        {
            var layer = new PrinterSettingsLayer();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                var segments = line.Split('=');
                if (!line.StartsWith("#") && !string.IsNullOrEmpty(line))
                {
                    string key = segments[0].Trim();
                    layer[key] = segments[1].Trim();
                }
            }

            return(layer);
        }
        internal void ClearValue(string settingsKey, PrinterSettingsLayer layer = null)
        {
            var persistenceLayer = layer ?? UserLayer;

            if (persistenceLayer.ContainsKey(settingsKey))
            {
                persistenceLayer.Remove(settingsKey);

                // Restore user overrides if a non-user override is being cleared
                if (layer != null && layer != UserLayer)
                {
                    RestoreUserOverride(layer, settingsKey);
                }

                Save();

                ActiveSliceSettings.OnSettingChanged(settingsKey);
            }
        }
        public void CopyFrom(PrinterSettings printerSettings)
        {
            //this.OemLayer.Clear();
            //foreach(var kvp in printerSettings.OemLayer)
            //{
            //	this.OemLayer.Add(kvp.Key, kvp.Value);
            //}

            this.OemLayer       = printerSettings.OemLayer;
            this.MaterialLayers = printerSettings.MaterialLayers;
            this.QualityLayers  = printerSettings.QualityLayers;
            this.UserLayer      = printerSettings.UserLayer;

            this.ActiveMaterialKey = printerSettings.ActiveMaterialKey;
            this.ActiveQualityKey  = printerSettings.ActiveQualityKey;

            this.QualityLayer  = GetQualityLayer(ActiveQualityKey);
            this.MaterialLayer = GetMaterialLayer(ActiveMaterialKey);
        }
Exemple #21
0
        public static PrinterSettingsLayer LoadFromIni(string filePath)
        {
            var settings = from line in File.ReadAllLines(filePath)
                           let segments = line.Split('=')
                                          where !line.StartsWith("#") && !string.IsNullOrEmpty(line) && segments.Length == 2
                                          select new
            {
                Key   = segments[0].Trim(),
                Value = segments[1].Trim()
            };

            var layer = new PrinterSettingsLayer();

            foreach (var setting in settings)
            {
                layer[setting.Key] = setting.Value;
            }

            return(layer);
        }
        public void SetValue(string settingsKey, string settingsValue, PrinterSettingsLayer layer = null)
        {
            var persistenceLayer = layer ?? UserLayer;

            if (settingsKey == SettingsKey.active_theme_name)
            {
                // also save it to the user settings so we can load it first thing on startup before a profile is loaded.
                UserSettings.Instance.set(UserSettingsKey.ActiveThemeName, settingsValue);
            }

            // If the setting exists and is set the requested value, exit without setting or saving
            string existingValue;

            if (persistenceLayer.TryGetValue(settingsKey, out existingValue) && existingValue == settingsValue)
            {
                return;
            }

            // Otherwise, set and save
            persistenceLayer[settingsKey] = settingsValue;
            Save();
        }
        public void ClearValue(string settingsKey, PrinterSettingsLayer layer = null)
        {
            var persistenceLayer = layer ?? UserLayer;

            if (persistenceLayer.ContainsKey(settingsKey))
            {
                persistenceLayer.Remove(settingsKey);

                // Restore user overrides if a non-user override is being cleared
                if (layer != null && layer != UserLayer)
                {
                    RestoreUserOverride(layer, settingsKey);
                }

                if (PrinterSettings.SettingsData.TryGetValue(settingsKey, out SliceSettingData settingData))
                {
                    if (settingData.DataEditType == SliceSettingData.DataEditTypes.CHECK_BOX)
                    {
                        string checkedKey = this.GetValue <bool>(settingsKey) ? "OnValue" : "OffValue";

                        // Linked settings should be updated in all cases (user clicked checkbox, user clicked clear)
                        foreach (var setSettingsData in settingData.SetSettingsOnChange)
                        {
                            if (setSettingsData.TryGetValue(checkedKey, out string targetValue))
                            {
                                if (this.GetValue(setSettingsData["TargetSetting"]) != targetValue)
                                {
                                    this.SetValue(setSettingsData["TargetSetting"], targetValue);
                                }
                            }
                        }
                    }
                }

                this.OnSettingChanged(settingsKey);
            }
        }
        private void MenuItem_Selected(object sender, EventArgs e)
        {
            // When a preset is selected store the current values of all known settings to compare against after applying the preset
            Dictionary <string, string> settingBeforeChange = new Dictionary <string, string>();

            foreach (var keyName in PrinterSettings.KnownSettings)
            {
                settingBeforeChange.Add(keyName, printer.Settings.GetValue(keyName));
            }

            var      activeSettings = printer.Settings;
            MenuItem item           = (MenuItem)sender;

            PrinterSettingsLayer prevSelection = null;
            PrinterSettingsLayer nextSelection = null;

            if (layerType == NamedSettingsLayers.Material)
            {
                if (extruderIndex == 0)
                {
                    if (activeSettings.ActiveMaterialKey != item.Value)
                    {
                        // Restore deactivated user overrides by iterating the Material preset we're coming off of
                        activeSettings.RestoreConflictingUserOverrides(activeSettings.MaterialLayer);

                        activeSettings.ActiveMaterialKey = item.Value;

                        // Deactivate conflicting user overrides by iterating the Material preset we've just switched to
                        activeSettings.DeactivateConflictingUserOverrides(activeSettings.MaterialLayer);
                    }
                }
                else                 // set the temperature for the given extruder
                {
                    var selectedMaterial = activeSettings.MaterialLayers.Where(l => l.LayerID == item.Value).FirstOrDefault();
                    if (selectedMaterial != null)
                    {
                        // first check if the material has an explicit temperature for T1
                        if (selectedMaterial.TryGetValue(SettingsKey.temperature1, out string temperature1))
                        {
                            activeSettings.SetValue(SettingsKey.temperature1, temperature1);
                        }
                        else
                        {
                            selectedMaterial.TryGetValue(SettingsKey.temperature, out string temperature);
                            activeSettings.SetValue(SettingsKey.temperature1, temperature);
                        }
                    }
                    else
                    {
                        activeSettings.SetValue(SettingsKey.temperature1, printer.Settings.GetValue(SettingsKey.temperature));
                    }
                }
            }
            else if (layerType == NamedSettingsLayers.Quality)
            {
                if (activeSettings.ActiveQualityKey != item.Value)
                {
                    prevSelection = activeSettings.QualityLayer;
                    // Restore deactivated user overrides by iterating the Quality preset we're coming off of
                    activeSettings.RestoreConflictingUserOverrides(activeSettings.QualityLayer);

                    activeSettings.ActiveQualityKey = item.Value;
                    nextSelection = activeSettings.QualityLayer;

                    // Deactivate conflicting user overrides by iterating the Quality preset we've just switched to
                    activeSettings.DeactivateConflictingUserOverrides(activeSettings.QualityLayer);
                }
            }

            // Ensure that activated or deactivated user overrides are always persisted to disk
            activeSettings.Save();

            UiThread.RunOnIdle(() =>
            {
                var settingsToUpdate = new HashSet <string>();
                foreach (var keyName in PrinterSettings.KnownSettings)
                {
                    if (settingBeforeChange[keyName] != printer.Settings.GetValue(keyName))
                    {
                        settingsToUpdate.Add(keyName);
                    }
                }

                if (prevSelection != null)
                {
                    foreach (var kvp in prevSelection)
                    {
                        settingsToUpdate.Add(kvp.Key);
                    }
                }

                if (nextSelection != null)
                {
                    foreach (var kvp in nextSelection)
                    {
                        settingsToUpdate.Add(kvp.Key);
                    }
                }

                foreach (var keyName in settingsToUpdate)
                {
                    printer.Settings.OnSettingChanged(keyName);
                }
            });

            editButton.Enabled = item.Text != defaultMenuItemText;
        }
		public static PrinterSettingsLayer LoadFromIni(TextReader reader)
		{
			var layer = new PrinterSettingsLayer();

			string line;
			while ((line = reader.ReadLine()) != null)
			{
				var segments = line.Split('=');
				if (!line.StartsWith("#") && !string.IsNullOrEmpty(line))
				{
					string key = segments[0].Trim();
					layer[key] = segments[1].Trim();
				}
			}

			return layer;
		}
 public PresetsContext(ObservableCollection <PrinterSettingsLayer> settingsLayers, PrinterSettingsLayer activeLayer)
 {
     this.PersistenceLayer = activeLayer;
     this.PresetLayers     = settingsLayers;
 }
		private static void AddComMenuItems(SliceSettingData settingData, PrinterSettingsLayer persistenceLayer, SettingsRow settingsRow, DropDownList selectableOptions)
		{
			selectableOptions.MenuItems.Clear();
			string machineSpecificComPortValue = ActiveSliceSettings.Instance.Helpers.ComPort();
			foreach (string listItem in FrostedSerialPort.GetPortNames())
			{
				MenuItem newItem = selectableOptions.AddItem(listItem);
				if (newItem.Text == machineSpecificComPortValue)
				{
					selectableOptions.SelectedLabel = machineSpecificComPortValue;
				}

				newItem.Selected += (sender, e) =>
				{
					MenuItem menuItem = ((MenuItem)sender);

					// Directly set the ComPort
					if (persistenceLayer == null)
					{
						ActiveSliceSettings.Instance.Helpers.SetComPort(menuItem.Text);
					}
					else
					{
						ActiveSliceSettings.Instance.Helpers.SetComPort(menuItem.Text, persistenceLayer);
					}

					settingsRow.UpdateStyle();

					OnSettingsChanged(settingData);
				};
			}
		}
Exemple #28
0
 public void SetComPort(string port, PrinterSettingsLayer layer)
 {
     printerSettings.SetValue($"{Environment.MachineName}_com_port", port, layer);
 }
		private static void SaveCommaSeparatedIndexSetting(int extruderIndexLocal, List<PrinterSettingsLayer> layerCascade, string slicerConfigName, string newSingleValue, PrinterSettingsLayer persistenceLayer)
		{
			string[] settings = GetActiveValue(slicerConfigName, layerCascade).Split(',');
			if (settings.Length > extruderIndexLocal)
			{
				settings[extruderIndexLocal] = newSingleValue;
			}
			else
			{
				string[] newSettings = new string[extruderIndexLocal + 1];
				for (int i = 0; i < extruderIndexLocal + 1; i++)
				{
					newSettings[i] = "";
					if (i < settings.Length)
					{
						newSettings[i] = settings[i];
					}
					else if (i == extruderIndexLocal)
					{
						newSettings[i] = newSingleValue;
					}
				}

				settings = newSettings;
			}

			string newValue = string.Join(",", settings);
			ActiveSliceSettings.Instance.SetValue(slicerConfigName, newValue, persistenceLayer);
		}
		public PresetsContext(ObservableCollection<PrinterSettingsLayer> settingsLayers, PrinterSettingsLayer activeLayer)
		{
			this.PersistenceLayer = activeLayer;
			this.PresetLayers = settingsLayers;
		}
		public void testBottomSolidLayersOneMM(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("bottom_solid_layers", out settingValue))
			{
				return;
			}

			Assert.AreEqual("1mm", settingValue, "bottom_solid_layers should be 1mm: " + sourceFile);
		}
		public void testFirstLayerBedTemperatureNotInStartGcode(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("start_gcode", out settingValue))
			{
				return;
			}

			Assert.False(settingValue.Contains("first_layer_bed_temperature"), "start_gcode should not contain first_layer_bed_temperature: " + sourceFile);
		}
		public void maxFanSpeedNotGreaterThanOneHundred(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("max_fan_speed", out settingValue))
			{
				return;
			}

			Assert.LessOrEqual(int.Parse(settingValue), 100, "max_fan_speed should be less than or equal to 100: " + sourceFile);
		}
		public void noCurlyBracketsInEndGcode(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("end_gcode", out settingValue))
			{
				return;
			}

			Assert.False(settingValue.Contains("{"), "end_gcode should not contain braces: " + sourceFile);
		}
		public void firstLayerExtrusionWidthAcceptableValue(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerExtrusionWidth;
			if (!layer.TryGetValue(SettingsKey.first_layer_extrusion_width, out firstLayerExtrusionWidth))
			{
				return;
			}

			float convertedFirstLayerExtrusionWidth;

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);
			float acceptableValue = float.Parse(nozzleDiameter) * 4;

			if (firstLayerExtrusionWidth.Contains("%"))
			{
				string reformatFirstLayerExtrusionWidth = firstLayerExtrusionWidth.Replace("%", " ");
				convertedFirstLayerExtrusionWidth = float.Parse(reformatFirstLayerExtrusionWidth) / 100;
			}
			else
			{
				convertedFirstLayerExtrusionWidth = float.Parse(firstLayerExtrusionWidth);
			}

			Assert.LessOrEqual(convertedFirstLayerExtrusionWidth, acceptableValue, "Unexpected firstLayerExtrusionWidthAcceptableValue value: " + sourceFile);
		}
Exemple #36
0
        internal static bool ImportFromExisting(string settingsFilePath)
        {
            if (string.IsNullOrEmpty(settingsFilePath) || !File.Exists(settingsFilePath))
            {
                return(false);
            }

            var printerInfo = new PrinterInfo
            {
                Name = Path.GetFileNameWithoutExtension(settingsFilePath),
                ID   = Guid.NewGuid().ToString()
            };
            bool   importSuccessful = false;
            string importType       = Path.GetExtension(settingsFilePath).ToLower();

            switch (importType)
            {
            case ProfileManager.ProfileExtension:
                var profile = PrinterSettings.LoadFile(settingsFilePath);
                profile.ID = printerInfo.ID;
                profile.ClearValue(SettingsKey.device_token);
                printerInfo.DeviceToken = "";

                // TODO: Resolve name conflicts
                profile.Helpers.SetName(printerInfo.Name);

                Instance.Profiles.Add(printerInfo);

                profile.Save();
                importSuccessful = true;
                break;

            case ".ini":
                //Scope variables
            {
                var settingsToImport = PrinterSettingsLayer.LoadFromIni(settingsFilePath);
                var layeredProfile   = new PrinterSettings()
                {
                    ID = printerInfo.ID,
                };

                bool containsValidSetting = false;
                var  activeSettings       = layeredProfile;

                foreach (var item in settingsToImport)
                {
                    if (activeSettings.Contains(item.Key))
                    {
                        containsValidSetting = true;
                        string currentValue = activeSettings.GetValue(item.Key).Trim();
                        // Compare the value to import to the layer cascade value and only set if different
                        if (currentValue != item.Value)
                        {
                            activeSettings.OemLayer[item.Key] = item.Value;
                        }
                    }
                }
                if (containsValidSetting)
                {
                    // TODO: Resolve name conflicts
                    layeredProfile.UserLayer[SettingsKey.printer_name] = printerInfo.Name;

                    layeredProfile.ClearValue(SettingsKey.device_token);
                    printerInfo.DeviceToken = "";
                    Instance.Profiles.Add(printerInfo);

                    layeredProfile.Save();
                    importSuccessful = true;
                }
            }
            break;
            }
            return(importSuccessful);
        }
Exemple #37
0
        internal static bool ImportFromExisting(string settingsFilePath)
        {
            if (string.IsNullOrEmpty(settingsFilePath) || !File.Exists(settingsFilePath))
            {
                return(false);
            }

            string fileName             = Path.GetFileNameWithoutExtension(settingsFilePath);
            var    existingPrinterNames = Instance.ActiveProfiles.Select(p => p.Name);

            var printerInfo = new PrinterInfo
            {
                Name  = agg_basics.GetNonCollidingName(existingPrinterNames, fileName),
                ID    = Guid.NewGuid().ToString(),
                Make  = "Other",
                Model = "Other",
            };

            bool importSuccessful = false;

            string importType = Path.GetExtension(settingsFilePath).ToLower();

            switch (importType)
            {
            case ProfileManager.ProfileExtension:
                // Add the Settings as a profile before performing any actions on it to ensure file paths resolve
            {
                Instance.Profiles.Add(printerInfo);

                var printerSettings = PrinterSettings.LoadFile(settingsFilePath);
                printerSettings.ID = printerInfo.ID;
                printerSettings.ClearValue(SettingsKey.device_token);
                printerInfo.DeviceToken = "";

                // TODO: Resolve name conflicts
                printerSettings.Helpers.SetName(printerInfo.Name);

                if (printerSettings.OemLayer.ContainsKey(SettingsKey.make))
                {
                    printerInfo.Make = printerSettings.OemLayer[SettingsKey.make];
                }

                if (printerSettings.OemLayer.ContainsKey(SettingsKey.model))
                {
                    printerInfo.Model = printerSettings.OemLayer[SettingsKey.model] ?? "Other";
                }

                printerSettings.Save();
                importSuccessful = true;
            }
            break;

            case ".ini":
                //Scope variables
            {
                var settingsToImport = PrinterSettingsLayer.LoadFromIni(settingsFilePath);
                var printerSettings  = new PrinterSettings()
                {
                    ID = printerInfo.ID,
                };

                bool containsValidSetting = false;

                printerSettings.OemLayer = new PrinterSettingsLayer();

                printerSettings.OemLayer[SettingsKey.make]  = "Other";
                printerSettings.OemLayer[SettingsKey.model] = "Other";

                foreach (var item in settingsToImport)
                {
                    if (printerSettings.Contains(item.Key))
                    {
                        containsValidSetting = true;
                        string currentValue = printerSettings.GetValue(item.Key).Trim();
                        // Compare the value to import to the layer cascade value and only set if different
                        if (currentValue != item.Value)
                        {
                            printerSettings.OemLayer[item.Key] = item.Value;
                        }
                    }
                }

                if (containsValidSetting)
                {
                    printerSettings.UserLayer[SettingsKey.printer_name] = printerInfo.Name;

                    printerSettings.ClearValue(SettingsKey.device_token);
                    printerInfo.DeviceToken = "";

                    printerInfo.Make  = printerSettings.OemLayer[SettingsKey.make] ?? "Other";
                    printerInfo.Model = printerSettings.OemLayer[SettingsKey.model] ?? "Other";

                    Instance.Profiles.Add(printerInfo);

                    printerSettings.Helpers.SetName(printerInfo.Name);

                    printerSettings.Save();
                    importSuccessful = true;
                }
            }
            break;
            }
            return(importSuccessful);
        }
		public SliceSettingsWidget(List<PrinterSettingsLayer> layerCascade = null, NamedSettingsLayers viewFilter = NamedSettingsLayers.All)
		{
			this.layerCascade = layerCascade;
			this.viewFilter = viewFilter;

			// The last layer of the layerFilters is the target persistence layer
			persistenceLayer = layerCascade?.First() ?? ActiveSliceSettings.Instance.UserLayer;

			textImageButtonFactory = new TextImageButtonFactory();
			textImageButtonFactory.normalFillColor = RGBA_Bytes.Transparent;
			textImageButtonFactory.FixedHeight = 15 * GuiWidget.DeviceScale;
			textImageButtonFactory.fontSize = 8;
			textImageButtonFactory.borderWidth = 1;
			textImageButtonFactory.normalBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);
			textImageButtonFactory.hoverBorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);

			this.textImageButtonFactory.disabledTextColor = RGBA_Bytes.Gray;
			this.textImageButtonFactory.hoverTextColor = ActiveTheme.Instance.PrimaryTextColor;
			this.textImageButtonFactory.normalTextColor = ActiveTheme.Instance.SecondaryTextColor;
			this.textImageButtonFactory.pressedTextColor = ActiveTheme.Instance.PrimaryTextColor;

			buttonFactory.FixedHeight = 20 * GuiWidget.DeviceScale;
			buttonFactory.fontSize = 10;
			buttonFactory.normalFillColor = RGBA_Bytes.White;
			buttonFactory.normalTextColor = RGBA_Bytes.DarkGray;

			FlowLayoutWidget pageTopToBottomLayout = new FlowLayoutWidget(FlowDirection.TopToBottom, vAnchor: Agg.UI.VAnchor.ParentTop);
			pageTopToBottomLayout.AnchorAll();
			pageTopToBottomLayout.Padding = new BorderDouble(3, 0);
			this.AddChild(pageTopToBottomLayout);

			settingsControlBar = new SettingsControlBar()
			{
				HAnchor = HAnchor.ParentLeftRight,
				BackgroundColor = ActiveTheme.Instance.TransparentDarkOverlay,
				Padding = new BorderDouble(8, 12, 8, 8)
			};

			pageTopToBottomLayout.AddChild(settingsControlBar);

			noConnectionMessageContainer = new AltGroupBox(new TextWidget("No Printer Selected".Localize(), pointSize: 18, textColor: ActiveTheme.Instance.SecondaryAccentColor));
			noConnectionMessageContainer.Margin = new BorderDouble(top: 10);
			noConnectionMessageContainer.BorderColor = ActiveTheme.Instance.PrimaryTextColor;
			noConnectionMessageContainer.HAnchor = Agg.UI.HAnchor.ParentLeftRight;
			noConnectionMessageContainer.Height = 90;

			string noConnectionString = "No printer is currently selected. Please select a printer to edit slice settings.".Localize();
			noConnectionString += "\n\n" + "NOTE: You need to select a printer, but do not need to connect to it.".Localize();
			TextWidget noConnectionMessage = new TextWidget(noConnectionString, pointSize: 10);
			noConnectionMessage.Margin = new BorderDouble(5);
			noConnectionMessage.TextColor = ActiveTheme.Instance.PrimaryTextColor;
			noConnectionMessage.VAnchor = VAnchor.ParentCenter;

			noConnectionMessageContainer.AddChild(noConnectionMessage);
			pageTopToBottomLayout.AddChild(noConnectionMessageContainer);

			topCategoryTabs = new TabControl();
			topCategoryTabs.TabBar.BorderColor = ActiveTheme.Instance.PrimaryTextColor;
			topCategoryTabs.Margin = new BorderDouble(top: 8);
			topCategoryTabs.AnchorAll();

			sliceSettingsDetailControl = new SliceSettingsDetailControl(layerCascade);

			List<TabBar> sideTabBarsListForLayout = new List<TabBar>();
			for (int topCategoryIndex = 0; topCategoryIndex < SliceSettingsOrganizer.Instance.UserLevels[UserLevel].CategoriesList.Count; topCategoryIndex++)
			{
				OrganizerCategory category = SliceSettingsOrganizer.Instance.UserLevels[UserLevel].CategoriesList[topCategoryIndex];
				string categoryPageLabel = category.Name.Localize();
				TabPage categoryPage = new TabPage(categoryPageLabel);
				SimpleTextTabWidget textTabWidget = new SimpleTextTabWidget(categoryPage, category.Name + " Tab", 16,
					ActiveTheme.Instance.TabLabelSelected, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes());
				categoryPage.AnchorAll();
				topCategoryTabs.AddTab(textTabWidget);

				TabControl sideTabs = CreateSideTabsAndPages(category);
				sideTabBarsListForLayout.Add(sideTabs.TabBar);

				categoryPage.AddChild(sideTabs);
			}

			topCategoryTabs.TabBar.AddChild(new HorizontalSpacer());
			topCategoryTabs.TabBar.AddChild(sliceSettingsDetailControl);

			if (sliceSettingsDetailControl.SelectedValue == "Advanced" && ActiveSliceSettings.Instance.Helpers.ActiveSliceEngineType() == SlicingEngineTypes.Slic3r)
			{
				TabPage extraSettingsPage = new TabPage("Other");
				SimpleTextTabWidget extraSettingsTextTabWidget = new SimpleTextTabWidget(extraSettingsPage, "Other Tab", 16,
						ActiveTheme.Instance.TabLabelSelected, new RGBA_Bytes(), ActiveTheme.Instance.TabLabelUnselected, new RGBA_Bytes());
				extraSettingsPage.AnchorAll();
				int count;
				TabControl extraSettingsSideTabs = CreateExtraSettingsSideTabsAndPages(topCategoryTabs, out count);
				if (count > 0)
				{
					topCategoryTabs.AddTab(extraSettingsTextTabWidget);
					sideTabBarsListForLayout.Add(extraSettingsSideTabs.TabBar);
					extraSettingsPage.AddChild(extraSettingsSideTabs);
				}
			}

			double sideTabBarsMinimumWidth = 0;
			foreach (TabBar tabBar in sideTabBarsListForLayout)
			{
				sideTabBarsMinimumWidth = Math.Max(sideTabBarsMinimumWidth, tabBar.Width);
			}
			foreach (TabBar tabBar in sideTabBarsListForLayout)
			{
				tabBar.MinimumSize = new Vector2(sideTabBarsMinimumWidth, tabBar.MinimumSize.y);
			}

			// check if there is only one left side tab. If so hide the left tabs and expand the content.
			foreach(var tabList in sideTabBarsListForLayout)
			{
				if(tabList.CountVisibleChildren() == 1)
				{
					tabList.MinimumSize = new Vector2(0, 0);
					tabList.Width = 0;
				}
			}

			pageTopToBottomLayout.AddChild(topCategoryTabs);
			AddHandlers();
			SetVisibleControls();

			// Make sure we are on the right tab when we create this view
			{
				string settingsName = "SliceSettingsWidget_CurrentTab";
				string selectedTab = UserSettings.Instance.get(settingsName);
				topCategoryTabs.SelectTab(selectedTab);

				topCategoryTabs.TabBar.TabIndexChanged += (object sender, EventArgs e) =>
				{
					string selectedTabName = topCategoryTabs.TabBar.SelectedTabName;
					if (!string.IsNullOrEmpty(selectedTabName))
					{
						if (layerCascade == null)
						{
							UserSettings.Instance.set(settingsName, selectedTabName);
						}
					}
				};
			}

			this.AnchorAll();
		}
		public void firstLayerHeightLessThanNozzleDiameter(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerHeight;
			
			if (!layer.TryGetValue(SettingsKey.first_layer_height, out firstLayerHeight))
			{
				return;
			}

			float convertedFirstLayerHeightValue;

			if (firstLayerHeight.Contains("%"))
			{
				string reFormatLayerHeight = firstLayerHeight.Replace("%", " ");
				convertedFirstLayerHeightValue = float.Parse(reFormatLayerHeight) / 100;
			}
			else
			{
				convertedFirstLayerHeightValue = float.Parse(firstLayerHeight);
			}

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);

			Assert.LessOrEqual(convertedFirstLayerHeightValue, float.Parse(nozzleDiameter), "Unexpected firstLayerHeightLessThanNozzleDiameter value: " + sourceFile);
		}
		private static GuiWidget CreateSettingInfoUIControls(SliceSettingData settingData, List<PrinterSettingsLayer> layerCascade, PrinterSettingsLayer persistenceLayer,
			NamedSettingsLayers viewFilter,
			int extruderIndex, out bool addControl, ref int tabIndexForItem)
		{
			addControl = true;
			GuiWidget container = new GuiWidget();

			string sliceSettingValue = GetActiveValue(settingData.SlicerConfigName, layerCascade);

			GuiWidget nameArea = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.FitToChildren | VAnchor.ParentCenter);
			var dataArea = new FlowLayoutWidget();
			GuiWidget unitsArea = new GuiWidget(HAnchor.AbsolutePosition, VAnchor.FitToChildren | VAnchor.ParentCenter)
			{
				Width = settingData.ShowAsOverride ? 50 * GuiWidget.DeviceScale : 5,
			};
			GuiWidget restoreArea = new GuiWidget(HAnchor.AbsolutePosition, VAnchor.FitToChildren | VAnchor.ParentCenter)
			{
				Width = settingData.ShowAsOverride ? 30 * GuiWidget.DeviceScale : 0,
			};

			var settingsRow = new SettingsRow(layerCascade)
			{
				SettingsKey = settingData.SlicerConfigName,
				SettingsValue = sliceSettingValue,
			};
			settingsRow.AddChild(nameArea);
			settingsRow.AddChild(dataArea);
			settingsRow.AddChild(unitsArea);
			settingsRow.AddChild(restoreArea);
			settingsRow.Name = settingData.SlicerConfigName + " Edit Field";

			if (!PrinterSettings.KnownSettings.Contains(settingData.SlicerConfigName))
			{
				// the setting we think we are adding is not in the known settings it may have been deprecated
				TextWidget settingName = new TextWidget(String.Format("Setting '{0}' not found in known settings", settingData.SlicerConfigName));
				settingName.TextColor = ActiveTheme.Instance.PrimaryTextColor;
				//settingName.MinimumSize = new Vector2(minSettingNameWidth, settingName.MinimumSize.y);
				nameArea.AddChild(settingName);
				nameArea.BackgroundColor = RGBA_Bytes.Red;
			}
			else
			{
				int intEditWidth = (int)(60 * GuiWidget.DeviceScale + .5);
				int doubleEditWidth = (int)(60 * GuiWidget.DeviceScale + .5);
				int vectorXYEditWidth = (int)(60 * GuiWidget.DeviceScale + .5);
				int multiLineEditHeight = (int)(120 * GuiWidget.DeviceScale + .5);

				if (settingData.DataEditType != SliceSettingData.DataEditTypes.MULTI_LINE_TEXT)
				{
					var nameHolder = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.FitToChildren | VAnchor.ParentCenter)
					{
						Padding = new BorderDouble(0, 0, 5, 0),
						HAnchor = HAnchor.ParentLeftRight,
					};

					nameHolder.AddChild(new WrappedTextWidget(settingData.PresentationName.Localize(), pointSize: 10, textColor: ActiveTheme.Instance.PrimaryTextColor));

					nameArea.AddChild(nameHolder);
				}

				switch (settingData.DataEditType)
				{
					case SliceSettingData.DataEditTypes.INT:
						{
							FlowLayoutWidget content = new FlowLayoutWidget();
							int currentValue;
							int.TryParse(sliceSettingValue, out currentValue);

							var intEditWidget = new MHNumberEdit(currentValue, pixelWidth: intEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true,
								Name = settingData.PresentationName + " Edit",
							};
							intEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString(), persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							content.AddChild(intEditWidget);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							if (settingData.QuickMenuSettings.Count > 0)
							{
								dataArea.AddChild(CreateQuickMenu(settingData, persistenceLayer, content, intEditWidget.ActuallNumberEdit.InternalTextEditWidget, layerCascade));
							}
							else
							{
								dataArea.AddChild(content);
							}

							settingsRow.ValueChanged = (text) =>
							{
								intEditWidget.Text = text;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.DOUBLE:
						{
							double currentValue;
							double.TryParse(sliceSettingValue, out currentValue);

							var doubleEditWidget = new MHNumberEdit(currentValue, allowNegatives: true, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true
							};
							doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString(), persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(doubleEditWidget);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							settingsRow.ValueChanged = (text) =>
							{
								double currentValue2 = 0;
								double.TryParse(text, out currentValue2);
								doubleEditWidget.ActuallNumberEdit.Value = currentValue2;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.POSITIVE_DOUBLE:
						{
							const string multiValuesAreDiffernt = "-";
							FlowLayoutWidget content = new FlowLayoutWidget();

							var doubleEditWidget = new MHNumberEdit(0, allowDecimals: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								Name = settingData.PresentationName + " Textbox",
								SelectAllOnFocus = true
							};

							double currentValue;
							bool ChangesMultipleOtherSettings = settingData.SetSettingsOnChange.Count > 0;
							if (ChangesMultipleOtherSettings)
							{
								bool allTheSame = true;
								string setting = GetActiveValue(settingData.SetSettingsOnChange[0], layerCascade);
								for (int i = 1; i < settingData.SetSettingsOnChange.Count; i++)
								{
									string nextSetting = GetActiveValue(settingData.SetSettingsOnChange[i], layerCascade);
									if (setting != nextSetting)
									{
										allTheSame = false;
										break;
									}
								}

								if (allTheSame && setting.EndsWith("mm"))
								{
									double.TryParse(setting.Substring(0, setting.Length - 2), out currentValue);
									doubleEditWidget.ActuallNumberEdit.Value = currentValue;
								}
								else
								{
									doubleEditWidget.ActuallNumberEdit.InternalNumberEdit.Text = multiValuesAreDiffernt;
								}
							}
							else // just set the setting normally
							{
								double.TryParse(sliceSettingValue, out currentValue);
								doubleEditWidget.ActuallNumberEdit.Value = currentValue;
							}
							doubleEditWidget.ActuallNumberEdit.InternalTextEditWidget.MarkAsStartingState();
							
							doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								NumberEdit numberEdit = (NumberEdit)sender;
								// If this setting sets other settings, then do that.
								if (ChangesMultipleOtherSettings
									&& numberEdit.Text != multiValuesAreDiffernt)
								{
									foreach (string setting in settingData.SetSettingsOnChange)
									{
										ActiveSliceSettings.Instance.SetValue(setting, numberEdit.Value.ToString() + "mm", persistenceLayer);
									}
								}

								// also always save to the local setting
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, numberEdit.Value.ToString(), persistenceLayer);
								settingsRow.UpdateStyle();
								OnSettingsChanged(settingData);
							};
							content.AddChild(doubleEditWidget);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							if (settingData.QuickMenuSettings.Count > 0)
							{
								dataArea.AddChild(CreateQuickMenu(settingData, persistenceLayer, content, doubleEditWidget.ActuallNumberEdit.InternalTextEditWidget, layerCascade));
							}
							else
							{
								dataArea.AddChild(content);
							}

							settingsRow.ValueChanged = (text) =>
							{
								double currentValue2 = 0;
								double.TryParse(text, out currentValue2);
								doubleEditWidget.ActuallNumberEdit.Value = currentValue2;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.OFFSET:
						{
							double currentValue;
							double.TryParse(sliceSettingValue, out currentValue);
							var doubleEditWidget = new MHNumberEdit(currentValue, allowDecimals: true, allowNegatives: true, pixelWidth: doubleEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true

							};
							doubleEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, ((NumberEdit)sender).Value.ToString(), persistenceLayer);
								settingsRow.UpdateStyle();
								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(doubleEditWidget);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							settingsRow.ValueChanged = (text) =>
							{
								double currentValue2;
								double.TryParse(text, out currentValue2);
								doubleEditWidget.ActuallNumberEdit.Value = currentValue2;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.DOUBLE_OR_PERCENT:
						{
							FlowLayoutWidget content = new FlowLayoutWidget();

							var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true
							};
							stringEdit.ActualTextEditWidget.EditComplete += (sender, e) =>
							{
								var textEditWidget = (TextEditWidget)sender;
								string text = textEditWidget.Text.Trim();

								bool isPercent = text.Contains("%");
								if (isPercent)
								{
									text = text.Substring(0, text.IndexOf("%"));
								}
								double result;
								double.TryParse(text, out result);
								text = result.ToString();
								if (isPercent)
								{
									text += "%";
								}
								textEditWidget.Text = text;
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, textEditWidget.Text, persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							stringEdit.ActualTextEditWidget.InternalTextEditWidget.AllSelected += (sender, e) =>
							{
								// select everything up to the % (if present)
								InternalTextEditWidget textEditWidget = (InternalTextEditWidget)sender;
								int percentIndex = textEditWidget.Text.IndexOf("%");
								if (percentIndex != -1)
								{
									textEditWidget.SetSelection(0, percentIndex - 1);
								}
							};

							content.AddChild(stringEdit);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							if (settingData.QuickMenuSettings.Count > 0)
							{
								dataArea.AddChild(CreateQuickMenu(settingData, persistenceLayer, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget, layerCascade));
							}
							else
							{
								dataArea.AddChild(content);
							}

							settingsRow.ValueChanged = (text) =>
							{
								stringEdit.Text = text;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.INT_OR_MM:
						{
							FlowLayoutWidget content = new FlowLayoutWidget();

							var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: doubleEditWidth - 2, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true
							};

							string startingText = stringEdit.Text;
							stringEdit.ActualTextEditWidget.EditComplete += (sender, e) =>
							{
								TextEditWidget textEditWidget = (TextEditWidget)sender;
								// only validate when we lose focus
								if (!textEditWidget.ContainsFocus)
								{
									string text = textEditWidget.Text;
									text = text.Trim();
									bool isMm = text.Contains("mm");
									if (isMm)
									{
										text = text.Substring(0, text.IndexOf("mm"));
									}
									double result;
									double.TryParse(text, out result);
									text = result.ToString();
									if (isMm)
									{
										text += "mm";
									}
									else
									{
										result = (int)result;
										text = result.ToString();
									}
									textEditWidget.Text = text;
									startingText = stringEdit.Text;
								}
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, textEditWidget.Text, persistenceLayer);
								settingsRow.UpdateStyle();
								OnSettingsChanged(settingData);

								// make sure we are still looking for the final validation before saving.
								if (textEditWidget.ContainsFocus)
								{
									UiThread.RunOnIdle(() =>
									{
										string currentText = textEditWidget.Text;
										int cursorIndex = textEditWidget.InternalTextEditWidget.CharIndexToInsertBefore;
										textEditWidget.Text = startingText;
										textEditWidget.InternalTextEditWidget.MarkAsStartingState();
										textEditWidget.Text = currentText;
										textEditWidget.InternalTextEditWidget.CharIndexToInsertBefore = cursorIndex;
									});
								}
							};

							stringEdit.ActualTextEditWidget.InternalTextEditWidget.AllSelected += (sender, e) =>
							{
								// select everything up to the mm (if present)
								InternalTextEditWidget textEditWidget = (InternalTextEditWidget)sender;
								int mMIndex = textEditWidget.Text.IndexOf("mm");
								if (mMIndex != -1)
								{
									textEditWidget.SetSelection(0, mMIndex - 1);
								}
							};

							content.AddChild(stringEdit);
							unitsArea.AddChild(GetExtraSettingsWidget(settingData));

							if (settingData.QuickMenuSettings.Count > 0)
							{
								dataArea.AddChild(CreateQuickMenu(settingData, persistenceLayer, content, stringEdit.ActualTextEditWidget.InternalTextEditWidget, layerCascade));
							}
							else
							{
								dataArea.AddChild(content);
							}

							settingsRow.ValueChanged = (text) =>
							{
								stringEdit.Text = text;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.CHECK_BOX:
						{
							var checkBoxWidget = new CheckBox("")
							{
								Name = settingData.PresentationName + " Checkbox",
								ToolTipText = settingData.HelpText,
								VAnchor = Agg.UI.VAnchor.ParentBottom,
								TextColor = ActiveTheme.Instance.PrimaryTextColor,
								Checked = sliceSettingValue == "1"
							};
							checkBoxWidget.Click += (sender, e) =>
							{
								bool isChecked = ((CheckBox)sender).Checked;
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, isChecked ? "1" : "0", persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							dataArea.AddChild(checkBoxWidget);

							settingsRow.ValueChanged = (text) =>
							{
								checkBoxWidget.Checked = text == "1";
							};
						}
						break;

					case SliceSettingData.DataEditTypes.STRING:
						{
							var stringEdit = new MHTextEditWidget(sliceSettingValue, pixelWidth: settingData.ShowAsOverride ? 120 : 200, tabIndex: tabIndexForItem++)
							{
								Name = settingData.PresentationName + " Edit",
							};
							stringEdit.ToolTipText = settingData.HelpText;
							
							stringEdit.ActualTextEditWidget.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, ((TextEditWidget)sender).Text, persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							dataArea.AddChild(stringEdit);

							settingsRow.ValueChanged = (text) =>
							{
								stringEdit.Text = text;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.MULTI_LINE_TEXT:
						{
							string convertedNewLines = sliceSettingValue.Replace("\\n", "\n");
							var stringEdit = new MHTextEditWidget(convertedNewLines, pixelWidth: 320, pixelHeight: multiLineEditHeight, multiLine: true, tabIndex: tabIndexForItem++, typeFace: ApplicationController.MonoSpacedTypeFace)
							{
								HAnchor = HAnchor.ParentLeftRight,
							};

							stringEdit.ActualTextEditWidget.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, ((TextEditWidget)sender).Text.Replace("\n", "\\n"), persistenceLayer);
								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							nameArea.HAnchor = HAnchor.AbsolutePosition;
							nameArea.Width = 0;
							dataArea.AddChild(stringEdit);
							dataArea.HAnchor = HAnchor.ParentLeftRight;

							settingsRow.ValueChanged = (text) =>
							{
								stringEdit.Text = text.Replace("\\n", "\n");
							};
						}
						break;

					case SliceSettingData.DataEditTypes.COM_PORT:
						{
#if __ANDROID__
							addControl = false;
#endif
							// The COM_PORT control is unique in its approach to the SlicerConfigName. It uses "com_port" settings name to
							// bind to a context that will place it in the SliceSetting view but it binds its values to a machine
							// specific dictionary key that is not exposed in the UI. At runtime we lookup and store to '<machinename>_com_port'
							// ensuring that a single printer can be shared across different devices and we'll select the correct com port in each case
							var selectableOptions = new DropDownList("None", maxHeight: 200)
							{
								ToolTipText = settingData.HelpText,
								Margin = new BorderDouble(),
								Name = "Com Port Dropdown"
							};

							selectableOptions.Click += (s, e) =>
							{
								AddComMenuItems(settingData, persistenceLayer, settingsRow, selectableOptions);
							};

							AddComMenuItems(settingData, persistenceLayer, settingsRow, selectableOptions);

							dataArea.AddChild(selectableOptions);

							settingsRow.ValueChanged = (text) =>
							{
								// Lookup the machine specific comport value rather than the passed in text value
								selectableOptions.SelectedLabel = ActiveSliceSettings.Instance.Helpers.ComPort();
							};
						}
						break;

					case SliceSettingData.DataEditTypes.LIST:
						{
							var selectableOptions = new DropDownList("None", maxHeight: 200)
							{
								ToolTipText = settingData.HelpText,
								Margin = new BorderDouble()
							};

							foreach (string listItem in settingData.ExtraSettings.Split(','))
							{
								MenuItem newItem = selectableOptions.AddItem(listItem);
								if (newItem.Text == sliceSettingValue)
								{
									selectableOptions.SelectedLabel = sliceSettingValue;
								}

								newItem.Selected += (sender, e) =>
								{
									MenuItem menuItem = ((MenuItem)sender);
									ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, menuItem.Text, persistenceLayer);

									settingsRow.UpdateStyle();

									OnSettingsChanged(settingData);
								};
							}

							dataArea.AddChild(selectableOptions);

							settingsRow.ValueChanged = (text) =>
							{
								selectableOptions.SelectedLabel = text;
							};
						}
						break;

					case SliceSettingData.DataEditTypes.HARDWARE_PRESENT:
						{
							var checkBoxWidget = new CheckBox("")
							{
								Name = settingData.PresentationName + " Checkbox",
								ToolTipText = settingData.HelpText,
								VAnchor = Agg.UI.VAnchor.ParentBottom,
								TextColor = ActiveTheme.Instance.PrimaryTextColor,
								Checked = sliceSettingValue == "1"
							};

							checkBoxWidget.Click += (sender, e) =>
							{
								bool isChecked = ((CheckBox)sender).Checked;
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, isChecked ? "1" : "0", persistenceLayer);

								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};

							dataArea.AddChild(checkBoxWidget);

							settingsRow.ValueChanged = (text) =>
							{
								checkBoxWidget.Checked = text == "1";
							};
						}
						break;

					case SliceSettingData.DataEditTypes.VECTOR2:
						{
							string[] xyValueStrings = sliceSettingValue.Split(',');
							if (xyValueStrings.Length != 2)
							{
								xyValueStrings = new string[] { "0", "0" };
							}

							double currentXValue;
							double.TryParse(xyValueStrings[0], out currentXValue);

							var xEditWidget = new MHNumberEdit(currentXValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true
							};

							double currentYValue;
							double.TryParse(xyValueStrings[1], out currentYValue);

							var yEditWidget = new MHNumberEdit(currentYValue, allowDecimals: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true,
								Margin = new BorderDouble(20, 0, 0, 0),
							};

							xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString(), persistenceLayer);

								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(xEditWidget);
							dataArea.AddChild(new TextWidget("X", pointSize: 10, textColor: ActiveTheme.Instance.PrimaryTextColor)
							{
								VAnchor = VAnchor.ParentCenter,
								Margin = new BorderDouble(5, 0),
							});

							yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "," + yEditWidget.ActuallNumberEdit.Value.ToString(), persistenceLayer);

								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(yEditWidget);
							var yLabel = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.FitToChildren | VAnchor.ParentCenter)
							{
								Padding = new BorderDouble(5, 0),
								HAnchor = HAnchor.ParentLeftRight,
							};
							yLabel.AddChild(new WrappedTextWidget("Y", pointSize: 9, textColor: ActiveTheme.Instance.PrimaryTextColor));
							unitsArea.AddChild(yLabel);

							settingsRow.ValueChanged = (text) =>
							{
								double currentValue2;
								string[] xyValueStrings2 = text.Split(',');
								if (xyValueStrings2.Length != 2)
								{
									xyValueStrings2 = new string[] { "0", "0" };
								}

								double.TryParse(xyValueStrings2[0], out currentValue2);
								xEditWidget.ActuallNumberEdit.Value = currentValue2;

								double.TryParse(xyValueStrings2[1], out currentValue2);
								yEditWidget.ActuallNumberEdit.Value = currentValue2;
							};

						}
						break;

					case SliceSettingData.DataEditTypes.OFFSET2:
						{
							Vector2 offset = ActiveSliceSettings.Instance.Helpers.ExtruderOffset(extruderIndex);

							var xEditWidget = new MHNumberEdit(offset.x, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true,
							};

							var yEditWidget = new MHNumberEdit(offset.y, allowDecimals: true, allowNegatives: true, pixelWidth: vectorXYEditWidth, tabIndex: tabIndexForItem++)
							{
								ToolTipText = settingData.HelpText,
								SelectAllOnFocus = true,
								Margin = new BorderDouble(20, 0, 0, 0),
							};

							xEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								int extruderIndexLocal = extruderIndex;
								SaveCommaSeparatedIndexSetting(extruderIndexLocal, layerCascade, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString(), persistenceLayer);

								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(xEditWidget);
							dataArea.AddChild(new TextWidget("X", pointSize: 10, textColor: ActiveTheme.Instance.PrimaryTextColor)
							{
								VAnchor = VAnchor.ParentCenter,
								Margin = new BorderDouble(5, 0),
							});

							yEditWidget.ActuallNumberEdit.EditComplete += (sender, e) =>
							{
								int extruderIndexLocal = extruderIndex;
								SaveCommaSeparatedIndexSetting(extruderIndexLocal, layerCascade, settingData.SlicerConfigName, xEditWidget.ActuallNumberEdit.Value.ToString() + "x" + yEditWidget.ActuallNumberEdit.Value.ToString(), persistenceLayer);

								settingsRow.UpdateStyle();

								OnSettingsChanged(settingData);
							};
							dataArea.AddChild(yEditWidget);
							var yLabel = new GuiWidget(HAnchor.ParentLeftRight, VAnchor.FitToChildren | VAnchor.ParentCenter)
							{
								Padding = new BorderDouble(5, 0),
								HAnchor = HAnchor.ParentLeftRight,
							};
							yLabel.AddChild(new WrappedTextWidget("Y", pointSize: 9, textColor: ActiveTheme.Instance.PrimaryTextColor));
							unitsArea.AddChild(yLabel);

							settingsRow.ValueChanged = (text) =>
							{
								Vector2 offset2 = ActiveSliceSettings.Instance.Helpers.ExtruderOffset(extruderIndex);
								xEditWidget.ActuallNumberEdit.Value = offset2.x;
								yEditWidget.ActuallNumberEdit.Value = offset2.y;
							};
						}
						break;

					default:
						var missingSetting = new TextWidget(String.Format("Missing the setting for '{0}'.", settingData.DataEditType.ToString()))
						{
							TextColor = ActiveTheme.Instance.PrimaryTextColor,
							BackgroundColor = RGBA_Bytes.Red
						};
						dataArea.AddChild(missingSetting);
						break;
				}
			}

			container.HAnchor = HAnchor.ParentLeftRight;
			container.VAnchor = VAnchor.FitToChildren;

			Button restoreButton = null;
			if (settingData.ShowAsOverride)
			{
				restoreButton = new Button(new ButtonViewStates(new ImageWidget(restoreNormal), new ImageWidget(restoreHover), new ImageWidget(restorePressed), new ImageWidget(restoreNormal)))
				{
					Name = "Restore " + settingData.SlicerConfigName,
					VAnchor = VAnchor.ParentCenter,
					Margin = new BorderDouble(0, 0, 5, 0),
					ToolTipText = "Restore Default".Localize()
				};

				restoreButton.Click += (sender, e) =>
				{
					// Revert the user override 
					if (persistenceLayer == null)
					{
						ActiveSliceSettings.Instance.ClearValue(settingData.SlicerConfigName);
					}
					else
					{
						ActiveSliceSettings.Instance.ClearValue(settingData.SlicerConfigName, persistenceLayer);
					}

					settingsRow.RefreshValue(layerCascade);
					OnSettingsChanged(settingData);
				};

				restoreArea.AddChild(restoreButton);
			}

			container.AddChild(settingsRow);

			// Define the UpdateStyle implementation
			settingsRow.UpdateStyle = () =>
			{
				if (persistenceLayer.ContainsKey(settingData.SlicerConfigName))
				{
					switch (viewFilter)
					{
						case NamedSettingsLayers.All:
							if (settingData.ShowAsOverride)
							{
								settingsRow.BackgroundColor = userSettingBackgroundColor;
							}
							break;
						case NamedSettingsLayers.Material:
							settingsRow.BackgroundColor = materialSettingBackgroundColor;
							break;
						case NamedSettingsLayers.Quality:
							settingsRow.BackgroundColor = qualitySettingBackgroundColor;
							break;
					}

					if(restoreButton != null) restoreButton.Visible = true;
				}
				else if (layerCascade == null)
				{
					if (ActiveSliceSettings.Instance.SettingExistsInLayer(settingData.SlicerConfigName, NamedSettingsLayers.Material))
					{
						settingsRow.BackgroundColor = materialSettingBackgroundColor;
					}
					else if (ActiveSliceSettings.Instance.SettingExistsInLayer(settingData.SlicerConfigName, NamedSettingsLayers.Quality))
					{
						settingsRow.BackgroundColor = qualitySettingBackgroundColor;
					}
					else
					{
						settingsRow.BackgroundColor = RGBA_Bytes.Transparent;
					}

					if (restoreButton != null) restoreButton.Visible = false;
				}
				else
				{
					if (restoreButton != null) restoreButton.Visible = false;
					settingsRow.BackgroundColor = RGBA_Bytes.Transparent;
				}
			};

			// Invoke the UpdateStyle implementation
			settingsRow.UpdateStyle();

			return container;
		}
		private DropDownList CreateDropdown()
		{
			var dropDownList = new DropDownList(defaultMenuItemText, maxHeight: 300, useLeftIcons: true)
			{
				HAnchor = HAnchor.ParentLeftRight,
				MenuItemsPadding = new BorderDouble(10, 4, 10, 6),
			};

			dropDownList.Margin = new BorderDouble(0, 3);
			dropDownList.MinimumSize = new Vector2(dropDownList.LocalBounds.Width, dropDownList.LocalBounds.Height);

			MenuItem defaultMenuItem = dropDownList.AddItem(defaultMenuItemText, "");
			defaultMenuItem.Selected += MenuItem_Selected;

			var listSource = (layerType == NamedSettingsLayers.Material) ? ActiveSliceSettings.Instance.MaterialLayers : ActiveSliceSettings.Instance.QualityLayers;
			foreach (var layer in listSource)
			{
				MenuItem menuItem = dropDownList.AddItem(layer.Name, layer.LayerID);
				menuItem.Selected += MenuItem_Selected;
			}

			MenuItem addNewPreset = dropDownList.AddItem(StaticData.Instance.LoadIcon("icon_plus.png", 32, 32), "Add New Setting...", "new");
			addNewPreset.Selected += (s, e) =>
			{
				var newLayer = new PrinterSettingsLayer();
				if (layerType == NamedSettingsLayers.Quality)
				{
					newLayer.Name = "Quality" + ActiveSliceSettings.Instance.QualityLayers.Count;
					ActiveSliceSettings.Instance.QualityLayers.Add(newLayer);
					ActiveSliceSettings.Instance.ActiveQualityKey = newLayer.LayerID;
				}
				else
				{
					newLayer.Name = "Material" + ActiveSliceSettings.Instance.MaterialLayers.Count;
					ActiveSliceSettings.Instance.MaterialLayers.Add(newLayer);
					ActiveSliceSettings.Instance.SetMaterialPreset(this.extruderIndex, newLayer.LayerID);
				}

				RebuildDropDownList();

				editButton.ClickButton(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
			};

			try
			{
				string settingsKey;

				if (layerType == NamedSettingsLayers.Material)
				{
					settingsKey = ActiveSliceSettings.Instance.GetMaterialPresetKey(extruderIndex);

					ActiveSliceSettings.Instance.MaterialLayers.CollectionChanged += SettingsLayers_CollectionChanged;
					dropDownList.Closed += (s1, e1) =>
					{
						ActiveSliceSettings.Instance.MaterialLayers.CollectionChanged -= SettingsLayers_CollectionChanged;
					};
				}
				else
				{
					settingsKey = ActiveSliceSettings.Instance.ActiveQualityKey;

					ActiveSliceSettings.Instance.QualityLayers.CollectionChanged += SettingsLayers_CollectionChanged;
					dropDownList.Closed += (s1, e1) =>
					{
						ActiveSliceSettings.Instance.QualityLayers.CollectionChanged -= SettingsLayers_CollectionChanged;
					};
				}

				if (!string.IsNullOrEmpty(settingsKey))
				{
					dropDownList.SelectedValue = settingsKey;
				}
			}
			catch (Exception ex)
			{
				GuiWidget.BreakInDebugger(ex.Message);
			}
		
			return dropDownList;
		}
		private GuiWidget CreateSliceSettingsWidget(PrinterSettingsLayer persistenceLayer)
		{
			var layerCascade = new List<PrinterSettingsLayer>
			{
				persistenceLayer,
				ActiveSliceSettings.Instance.OemLayer,
				ActiveSliceSettings.Instance.BaseLayer
			};

			var settingsWidget = new SliceSettingsWidget(layerCascade, presetsContext.LayerType);
			settingsWidget.settingsControlBar.Visible = false;

			return settingsWidget;
		}
		public SelectPartsOfPrinterToImport(string settingsFilePath, PrinterSettingsLayer destinationLayer, string sectionName = null) :
			base(unlocalizedTextForTitle: "Import Wizard")
		{
			this.isMergeIntoUserLayer = destinationLayer == ActiveSliceSettings.Instance.UserLayer;
			this.destinationLayer = destinationLayer;
			this.sectionName = sectionName;

			// TODO: Need to handle load failures for import attempts
			settingsToImport = PrinterSettings.LoadFile(settingsFilePath);

			this.headerLabel.Text = "Select What to Import".Localize();

			this.settingsFilePath = settingsFilePath;

			var scrollWindow = new ScrollableWidget()
			{
				AutoScroll = true,
				HAnchor = HAnchor.ParentLeftRight,
				VAnchor = VAnchor.ParentBottomTop,
			};
			scrollWindow.ScrollArea.HAnchor = HAnchor.ParentLeftRight;
			contentRow.AddChild(scrollWindow);

			var container = new FlowLayoutWidget(FlowDirection.TopToBottom)
			{
				HAnchor = HAnchor.ParentLeftRight,
			};
			scrollWindow.AddChild(container);

			if (isMergeIntoUserLayer)
			{
				container.AddChild(new WrappedTextWidget(importMessage, textColor: ActiveTheme.Instance.PrimaryTextColor));
			}

			// add in the check boxes to select what to import
			container.AddChild(new TextWidget("Main Settings:")
			{
				TextColor = ActiveTheme.Instance.PrimaryTextColor,
				Margin = new BorderDouble(0, 3, 0, isMergeIntoUserLayer ? 10 : 0),
			});

			var mainProfileRadioButton = new RadioButton("Printer Profile")
			{
				TextColor = ActiveTheme.Instance.PrimaryTextColor,
				Margin = new BorderDouble(5, 0),
				HAnchor = HAnchor.ParentLeft,
				Checked = true,
			};
			container.AddChild(mainProfileRadioButton);

			if (settingsToImport.QualityLayers.Count > 0)
			{
				container.AddChild(new TextWidget("Quality Presets:")
				{
					TextColor = ActiveTheme.Instance.PrimaryTextColor,
					Margin = new BorderDouble(0, 3, 0, 15),
				});

				int buttonIndex = 0;
				foreach (var qualitySetting in settingsToImport.QualityLayers)
				{
					RadioButton qualityButton = new RadioButton(qualitySetting.Name)
					{
						TextColor = ActiveTheme.Instance.PrimaryTextColor,
						Margin = new BorderDouble(5, 0, 0, 0),
						HAnchor = HAnchor.ParentLeft,
					};
					container.AddChild(qualityButton);

					int localButtonIndex = buttonIndex;
					qualityButton.CheckedStateChanged += (s, e) =>
					{
						if (qualityButton.Checked)
						{
							selectedQuality = localButtonIndex;
						}
						else
						{
							selectedQuality = -1;
						}
					};

					buttonIndex++;
				}
			}

			if (settingsToImport.MaterialLayers.Count > 0)
			{
				container.AddChild(new TextWidget("Material Presets:")
				{
					TextColor = ActiveTheme.Instance.PrimaryTextColor,
					Margin = new BorderDouble(0, 3, 0, 15),
				});

				int buttonIndex = 0;
				foreach (var materialSetting in settingsToImport.MaterialLayers)
				{
					RadioButton materialButton = new RadioButton(materialSetting.Name)
					{
						TextColor = ActiveTheme.Instance.PrimaryTextColor,
						Margin = new BorderDouble(5, 0),
						HAnchor = HAnchor.ParentLeft,
					};

					container.AddChild(materialButton);

					int localButtonIndex = buttonIndex;
					materialButton.CheckedStateChanged += (s, e) =>
					{
						if (materialButton.Checked)
						{
							selectedMaterial = localButtonIndex;
						}
						else
						{
							selectedMaterial = -1;
						}
					};

					buttonIndex++;
				}
			}

			var mergeButtonTitle = this.isMergeIntoUserLayer ? "Merge".Localize() : "Import".Localize();
			var mergeButton = textImageButtonFactory.Generate(mergeButtonTitle);
			mergeButton.Name = "Merge Profile";
			mergeButton.Click += (s, e) => UiThread.RunOnIdle(() =>
			{
				bool copyName = false;
				PrinterSettingsLayer sourceLayer = null;
				if (selectedMaterial > -1)
				{
					sourceLayer = settingsToImport.MaterialLayers[selectedMaterial];
					copyName = true;
				}
				else if (selectedQuality > -1)
				{
					sourceLayer = settingsToImport.QualityLayers[selectedQuality];
					copyName = true;
				}

				List<PrinterSettingsLayer> sourceFilter;

				if (selectedQuality == -1 && selectedMaterial == -1)
				{
					sourceFilter = new List<PrinterSettingsLayer>()
					{
						settingsToImport.OemLayer,
						settingsToImport.UserLayer
					};
				}
				else
				{
					sourceFilter = new List<PrinterSettingsLayer>()
					{
						sourceLayer
					};
				}

				ActiveSliceSettings.Instance.Merge(destinationLayer, settingsToImport, sourceFilter, copyName);

				this.Parents<SystemWindow>().FirstOrDefault()?.CloseOnIdle();
			});

			footerRow.AddChild(mergeButton);

			footerRow.AddChild(new HorizontalSpacer());
			footerRow.AddChild(cancelButton);

			if (settingsToImport.QualityLayers.Count == 0 && settingsToImport.MaterialLayers.Count == 0)
			{
				// Only main setting so don't ask what to merge just do it.
				UiThread.RunOnIdle(() =>
				{
					var sourceFilter = new List<PrinterSettingsLayer>()
					{
						settingsToImport.OemLayer ?? new PrinterSettingsLayer(),
						settingsToImport.UserLayer ?? new PrinterSettingsLayer()
					};

					ActiveSliceSettings.Instance.Merge(destinationLayer, settingsToImport, sourceFilter, false);
					UiThread.RunOnIdle(ApplicationController.Instance.ReloadAdvancedControlsPanel);

					string successMessage = importPrinterSuccessMessage.FormatWith(Path.GetFileNameWithoutExtension(settingsFilePath));
					if (!isMergeIntoUserLayer)
					{
						string sourceName = isMergeIntoUserLayer ? Path.GetFileNameWithoutExtension(settingsFilePath) : destinationLayer[SettingsKey.layer_name];
						successMessage = ImportSettingsPage.importSettingSuccessMessage.FormatWith(sourceName, sectionName);
					}

					WizardWindow.ChangeToPage(new ImportSucceeded(successMessage)
					{
						WizardWindow = this.WizardWindow,
					});
				});
			}
		}
		private static GuiWidget CreateQuickMenu(SliceSettingData settingData, PrinterSettingsLayer persistenceLayer, GuiWidget content, InternalTextEditWidget internalTextWidget, List<PrinterSettingsLayer> layerCascade)
		{
			string sliceSettingValue = GetActiveValue(settingData.SlicerConfigName, layerCascade);
			FlowLayoutWidget totalContent = new FlowLayoutWidget();

			DropDownList selectableOptions = new DropDownList("Custom", maxHeight: 200);
			selectableOptions.Margin = new BorderDouble(0, 0, 10, 0);

			foreach (QuickMenuNameValue nameValue in settingData.QuickMenuSettings)
			{
				string valueLocal = nameValue.Value;

				MenuItem newItem = selectableOptions.AddItem(nameValue.MenuName);
				if (sliceSettingValue == valueLocal)
				{
					selectableOptions.SelectedLabel = nameValue.MenuName;
				}

				newItem.Selected += (sender, e) =>
				{
					ActiveSliceSettings.Instance.SetValue(settingData.SlicerConfigName, valueLocal, persistenceLayer);
					OnSettingsChanged(settingData);
					internalTextWidget.Text = valueLocal;
					internalTextWidget.OnEditComplete(null);
				};
			}

			// put in the custom menu to allow direct editing
			MenuItem customMenueItem = selectableOptions.AddItem("Custom");

			totalContent.AddChild(selectableOptions);
			content.VAnchor = VAnchor.ParentCenter;
			totalContent.AddChild(content);

			EventHandler localUnregisterEvents = null;

			SettingChanged.RegisterEvent((sender, e) =>
			{
				bool foundSetting = false;
				foreach (QuickMenuNameValue nameValue in settingData.QuickMenuSettings)
				{
					string localName = nameValue.MenuName;
					string newSliceSettingValue = GetActiveValue(settingData.SlicerConfigName, layerCascade);
					if (newSliceSettingValue == nameValue.Value)
					{
						selectableOptions.SelectedLabel = localName;
						foundSetting = true;
						break;
					}
				}

				if (!foundSetting)
				{
					selectableOptions.SelectedLabel = "Custom";
				}
			}, ref localUnregisterEvents);

			totalContent.Closed += (s, e) =>
			{
				localUnregisterEvents?.Invoke(s, e);
			};

			return totalContent;
		}
 public void ClearValue(string sliceSetting, PrinterSettingsLayer persistenceLayer = null)
 {
     layeredProfile.ClearValue(sliceSetting, persistenceLayer);
 }
Exemple #46
0
 public OemProfile(Dictionary <string, string> settingsDictionary)
 {
     OemLayer = new PrinterSettingsLayer(settingsDictionary);
 }
		private void ImportToPreset(string settingsFilePath)
		{
			if (!string.IsNullOrEmpty(settingsFilePath) && File.Exists(settingsFilePath))
			{
				PrinterSettingsLayer newLayer;

				string sectionName = (newMaterialPresetButton.Checked) ? "Material".Localize() : "Quality".Localize();

				string importType = Path.GetExtension(settingsFilePath).ToLower();
				switch (importType)
				{
					case ProfileManager.ProfileExtension:
						newLayer = new PrinterSettingsLayer();
						newLayer[SettingsKey.layer_name] = Path.GetFileNameWithoutExtension(settingsFilePath);

						if (newQualityPresetButton.Checked)
						{
							ActiveSliceSettings.Instance.QualityLayers.Add(newLayer);
						}
						else
						{
							// newMaterialPresetButton.Checked
							ActiveSliceSettings.Instance.MaterialLayers.Add(newLayer);
						}

						// open a wizard to ask what to import to the preset
						WizardWindow.ChangeToPage(new SelectPartsOfPrinterToImport(settingsFilePath, newLayer, sectionName));

						break;

					case ".slice": // legacy presets file extension
					case ".ini":
						var settingsToImport = PrinterSettingsLayer.LoadFromIni(settingsFilePath);

						bool containsValidSetting = false;
						{
							newLayer = new PrinterSettingsLayer();
							newLayer.Name = Path.GetFileNameWithoutExtension(settingsFilePath);

							// Only be the base and oem layers (not the user, quality or material layer)
							var baseAndOEMCascade = new List<PrinterSettingsLayer>
							{
								ActiveSliceSettings.Instance.OemLayer,
								ActiveSliceSettings.Instance.BaseLayer
							};

							foreach (var keyName in PrinterSettings.KnownSettings)
							{
								if (ActiveSliceSettings.Instance.Contains(keyName))
								{
									containsValidSetting = true;
									string currentValue = ActiveSliceSettings.Instance.GetValue(keyName, baseAndOEMCascade).Trim();
									string newValue;
									// Compare the value to import to the layer cascade value and only set if different
									if (settingsToImport.TryGetValue(keyName, out newValue)
										&& currentValue != newValue)
									{
										newLayer[keyName] = newValue;
									}
								}
							}

							if (containsValidSetting)
							{
								if (newMaterialPresetButton.Checked)
								{
									ActiveSliceSettings.Instance.MaterialLayers.Add(newLayer);
								}
								else
								{
									ActiveSliceSettings.Instance.QualityLayers.Add(newLayer);
								}

								ActiveSliceSettings.Instance.Save();

								WizardWindow.ChangeToPage(new ImportSucceeded(importSettingSuccessMessage.FormatWith(Path.GetFileNameWithoutExtension(settingsFilePath), sectionName))
								{
									WizardWindow = this.WizardWindow,
								});
							}
							else
							{
								displayFailedToImportMessage(settingsFilePath);
							}
						}

						break;

					default:
						// Did not figure out what this file is, let the user know we don't understand it
						StyledMessageBox.ShowMessageBox(null, "Oops! Unable to recognize settings file '{0}'.".Localize().FormatWith(Path.GetFileName(settingsFilePath)), "Unable to Import".Localize());
						break;
				}
			}
			Invalidate();
		}
		public void layerHeightLessThanNozzleDiameter(PrinterSettings printerSettings, PrinterSettingsLayer layer, string sourceFile)
		{
			string layerHeight;
			if (!layer.TryGetValue(SettingsKey.layer_height, out layerHeight))
			{
				return;
			}

			float convertedLayerHeight = float.Parse(layerHeight);

			string nozzleDiameter = printerSettings.GetValue(SettingsKey.nozzle_diameter);
			float convertedNozzleDiameterValue = float.Parse(nozzleDiameter);

			Assert.LessOrEqual(convertedLayerHeight, convertedNozzleDiameterValue, "Unexpected layerHeightLessThanNozzleDiameter value: " + sourceFile);
		}
		public void firstLayerExtrusionWidthNotZero(PrinterSettingsLayer layer, string sourceFile)
		{
			string firstLayerExtrusionWidth;
			if (!layer.TryGetValue(SettingsKey.first_layer_extrusion_width, out firstLayerExtrusionWidth))
			{
				return;
			}

			float convertedFirstLayerExtrusionWidth;

			if(firstLayerExtrusionWidth.Contains("%"))
			{
				string reformatFirstLayerExtrusionWidth = firstLayerExtrusionWidth.Replace("%", " ");
				convertedFirstLayerExtrusionWidth = float.Parse(reformatFirstLayerExtrusionWidth);
			}
			else
			{
				convertedFirstLayerExtrusionWidth = float.Parse(firstLayerExtrusionWidth);
			}

			Assert.AreNotEqual(0, convertedFirstLayerExtrusionWidth, "Unexpected firstLayerExtrusionWidthNotZero value: " + sourceFile);
		}
		public static PrinterSettingsLayer LoadFromIni(string filePath)
		{
			var settings = from line in File.ReadAllLines(filePath)
						   let segments = line.Split('=')
						   where !line.StartsWith("#") && !string.IsNullOrEmpty(line) && segments.Length == 2
						   select new
						   {
							   Key = segments[0].Trim(),
							   Value = segments[1].Trim()
						   };

			var layer = new PrinterSettingsLayer();
			foreach (var setting in settings)
			{
				layer[setting.Key] = setting.Value;
			}

			return layer;
		}
		public void printCenterFormatSeparatedByComma(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			
			if (!layer.TryGetValue(SettingsKey.print_center, out settingValue))
			{
				return;
			}

			string[] settingValueToTest = settingValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

			Assert.AreEqual(2, settingValueToTest.Length, "print_center should have two values separated by a comma: " + sourceFile);
		}
Exemple #52
0
        private DropDownList CreateDropdown()
        {
            var dropDownList = new MHDropDownList(defaultMenuItemText, theme, maxHeight: 300, useLeftIcons: true)
            {
                HAnchor          = HAnchor.Stretch,
                VAnchor          = VAnchor.Center,
                MenuItemsPadding = new BorderDouble(10, 7, 7, 7),
            };

            dropDownList.Name        = layerType.ToString() + " DropDown List";
            dropDownList.Margin      = 0;
            dropDownList.MinimumSize = new Vector2(dropDownList.LocalBounds.Width, dropDownList.LocalBounds.Height);

            MenuItem defaultMenuItem = dropDownList.AddItem(defaultMenuItemText, "");

            defaultMenuItem.Selected += MenuItem_Selected;

            var listSource = (layerType == NamedSettingsLayers.Material) ? printer.Settings.MaterialLayers : printer.Settings.QualityLayers;

            foreach (var layer in listSource.OrderBy(l => l.Name))
            {
                MenuItem menuItem = dropDownList.AddItem(layer.Name, layer.LayerID);
                menuItem.Name      = layer.Name + " Menu";
                menuItem.Selected += MenuItem_Selected;
            }

            MenuItem addNewPreset = dropDownList.AddItem(
                AggContext.StaticData.LoadIcon("icon_plus.png", 16, 16),
                "Add New Setting".Localize() + "...",
                "new",
                pointSize: theme.DefaultFontSize);

            addNewPreset.Selected += (s, e) =>
            {
                var newLayer = new PrinterSettingsLayer();
                if (layerType == NamedSettingsLayers.Quality)
                {
                    newLayer.Name = "Quality" + printer.Settings.QualityLayers.Count;
                    printer.Settings.QualityLayers.Add(newLayer);
                    printer.Settings.ActiveQualityKey = newLayer.LayerID;
                }
                else
                {
                    newLayer.Name = "Material" + printer.Settings.MaterialLayers.Count;
                    printer.Settings.MaterialLayers.Add(newLayer);
                    printer.Settings.ActiveMaterialKey = newLayer.LayerID;
                }

                RebuildDropDownList();

                editButton.OnClick(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
            };

            try
            {
                string settingsKey;

                if (layerType == NamedSettingsLayers.Material)
                {
                    if (extruderIndex == 0)
                    {
                        settingsKey = printer.Settings.ActiveMaterialKey;
                    }
                    else                     // try to find the right material based on the extruders temperature
                    {
                        settingsKey = null;
                        var extruderTemp = printer.Settings.GetValue <double>(SettingsKey.temperature1).ToString();
                        foreach (var materialLayer in printer.Settings.MaterialLayers)
                        {
                            if (materialLayer.TryGetValue(SettingsKey.temperature, out string _temp))
                            {
                                if (_temp == extruderTemp)
                                {
                                    settingsKey = materialLayer.LayerID;
                                }
                            }
                        }
                    }
                }
                else
                {
                    settingsKey = printer.Settings.ActiveQualityKey;
                }

                if (!string.IsNullOrEmpty(settingsKey))
                {
                    dropDownList.SelectedValue = settingsKey;
                }
            }
            catch (Exception ex)
            {
                GuiWidget.BreakInDebugger(ex.Message);
            }

            return(dropDownList);
        }
		public void testRetractLengthLessThanTwenty(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("retract_length", out settingValue))
			{
				return;
			}

			Assert.Less(float.Parse(settingValue, CultureInfo.InvariantCulture.NumberFormat), 20, "retract_length should be less than 20: " + sourceFile);
		}
		public void SetComPort(string port, PrinterSettingsLayer layer)
		{
			printerSettings.SetValue($"{Environment.MachineName}_com_port", port, layer);
		}
		public void testExtruderCountGreaterThanZero(PrinterSettingsLayer layer, string sourceFile)
		{
			string settingValue;
			if (!layer.TryGetValue("extruder_count", out settingValue))
			{
				return;
			}

			Assert.Greater(int.Parse(settingValue), 0, "extruder_count should be greater than zero: " + sourceFile);
		}