Ejemplo n.º 1
0
        private void ExtendOverflowMenu(PopupMenu popupMenu)
        {
            popupMenu.CreateHorizontalLine();
            PopupMenu.MenuItem menuItem;

            menuItem        = popupMenu.CreateMenuItem("Import Presets".Localize());
            menuItem.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                AggContext.FileDialogs.OpenFileDialog(
                    new OpenFileDialogParams("settings files|*.printer"),
                    (dialogParams) =>
                {
                    if (!string.IsNullOrEmpty(dialogParams.FileName))
                    {
                        DialogWindow.Show(new ImportSettingsPage(dialogParams.FileName, printer));
                    }
                });
            }, .2);

            popupMenu.CreateHorizontalLine();

            menuItem        = popupMenu.CreateMenuItem("Restore Settings".Localize());
            menuItem.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                DialogWindow.Show <PrinterProfileHistoryPage>();
            }, .2);
            menuItem.Enabled = !string.IsNullOrEmpty(AuthenticationData.Instance.ActiveSessionUsername);

            menuItem        = popupMenu.CreateMenuItem("Reset to Defaults".Localize());
            menuItem.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                StyledMessageBox.ShowMessageBox(
                    (revertSettings) =>
                {
                    if (revertSettings)
                    {
                        bool onlyReloadSliceSettings = true;
                        if (printer.Settings.GetValue <bool>(SettingsKey.print_leveling_required_to_print) &&
                            printer.Settings.GetValue <bool>(SettingsKey.print_leveling_enabled))
                        {
                            onlyReloadSliceSettings = false;
                        }

                        printer.Settings.ClearUserOverrides();
                        printer.Settings.Save();

                        if (onlyReloadSliceSettings)
                        {
                            printer?.Bed.GCodeRenderer?.Clear3DGCode();
                        }
                        else
                        {
                            ApplicationController.Instance.ReloadAll();
                        }
                    }
                },
                    "Resetting to default values will remove your current overrides and restore your original printer settings.\nAre you sure you want to continue?".Localize(),
                    "Revert Settings".Localize(),
                    StyledMessageBox.MessageType.YES_NO);
            }, .2);

            menuItem        = popupMenu.CreateMenuItem("Export".Localize());
            menuItem.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                ActiveSliceSettings.Instance.Helpers.ExportAsMatterControlConfig();
            }, .2);
        }
Ejemplo n.º 2
0
        public HardwareTabPage(ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.theme   = theme;
            this.Padding = 0;
            this.HAnchor = HAnchor.Stretch;
            this.VAnchor = VAnchor.Stretch;

            var toolbar = new Toolbar(theme)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
                Padding = theme.ToolbarPadding
            };

            theme.ApplyBottomBorder(toolbar);

            toolbar.AddChild(new TextButton("Inventory".Localize(), theme)
            {
                Padding     = new BorderDouble(6, 0),
                MinimumSize = new Vector2(0, theme.ButtonHeight),
                Selectable  = false
            });

            this.AddChild(toolbar);

            var horizontalSplitter = new Splitter()
            {
                SplitterDistance   = UserSettings.Instance.LibraryViewWidth,
                SplitterSize       = theme.SplitterWidth,
                SplitterBackground = theme.SplitterBackground,
                HAnchor            = HAnchor.Stretch,
                VAnchor            = VAnchor.Stretch,
            };

            horizontalSplitter.DistanceChanged += (s, e) =>
            {
                UserSettings.Instance.LibraryViewWidth = horizontalSplitter.SplitterDistance;
            };

            this.AddChild(horizontalSplitter);

            var treeView = new HardwareTreeView(theme)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
                Width   = 300,
                Margin  = 5
            };

            treeView.NodeMouseDoubleClick += (s, e) =>
            {
                if (e is MouseEventArgs mouseEvent &&
                    s is GuiWidget clickedWidget &&
                    mouseEvent.Button == MouseButtons.Left &&
                    mouseEvent.Clicks == 2)
                {
                    if (treeView?.SelectedNode.Tag is PrinterInfo printerInfo)
                    {
                        if (ApplicationController.Instance.ActivePrinters.FirstOrDefault(p => p.Settings.ID == printerInfo.ID) is PrinterConfig printer &&
                            ApplicationController.Instance.MainView.TabControl.AllTabs.FirstOrDefault(t => t.TabContent is PrinterTabPage printerTabPage && printerTabPage.printer == printer) is ITab tab)
                        {
                            // Switch to existing printer tab
                            ApplicationController.Instance.MainView.TabControl.ActiveTab = tab;
                        }
                        else
                        {
                            // Open new printer tab
                            ApplicationController.Instance.OpenEmptyPrinter(printerInfo.ID).ConfigureAwait(false);
                        }
                    }
                }
            };

            treeView.NodeMouseClick += (s, e) =>
            {
                if (e is MouseEventArgs mouseEvent &&
                    s is GuiWidget clickedWidget &&
                    mouseEvent.Button == MouseButtons.Right)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        var menu = new PopupMenu(ApplicationController.Instance.MenuTheme);

                        var openMenuItem    = menu.CreateMenuItem("Open".Localize());
                        openMenuItem.Click += async(s2, e2) =>
                        {
                            if (treeView?.SelectedNode.Tag is PrinterInfo printerInfo)
                            {
                                // Open printer
                                await ApplicationController.Instance.OpenEmptyPrinter(printerInfo.ID);
                            }
                        };

                        menu.CreateSeparator();

                        var deleteMenuItem    = menu.CreateMenuItem("Delete".Localize());
                        deleteMenuItem.Click += (s2, e2) =>
                        {
                            if (treeView.SelectedNode.Tag is PrinterInfo printerInfo)
                            {
                                // Delete printer
                                StyledMessageBox.ShowMessageBox(
                                    (deletePrinter) =>
                                {
                                    if (deletePrinter)
                                    {
                                        ProfileManager.Instance.DeletePrinter(printerInfo.ID);
                                    }
                                },
                                    "Are you sure you want to delete printer '{0}'?".Localize().FormatWith(printerInfo.Name),
                                    "Delete Printer?".Localize(),
                                    StyledMessageBox.MessageType.YES_NO,
                                    "Delete Printer".Localize());
                            }
                        };


                        var systemWindow = this.Parents <SystemWindow>().FirstOrDefault();
                        systemWindow.ShowPopup(
                            new MatePoint(clickedWidget)
                        {
                            Mate    = new MateOptions(MateEdge.Left, MateEdge.Top),
                            AltMate = new MateOptions(MateEdge.Left, MateEdge.Top)
                        },
                            new MatePoint(menu)
                        {
                            Mate    = new MateOptions(MateEdge.Left, MateEdge.Top),
                            AltMate = new MateOptions(MateEdge.Right, MateEdge.Top)
                        },
                            altBounds: new RectangleDouble(mouseEvent.X + 1, mouseEvent.Y + 1, mouseEvent.X + 1, mouseEvent.Y + 1));
                    });
                }
            };

            treeView.ScrollArea.HAnchor = HAnchor.Stretch;

            treeView.AfterSelect += async(s, e) =>
            {
                if (treeView.SelectedNode.Tag is PrinterInfo printerInfo)
                {
                    horizontalSplitter.Panel2.CloseAllChildren();
                    horizontalSplitter.Panel2.AddChild(new PrinterDetails(printerInfo, theme)
                    {
                        HAnchor = HAnchor.MaxFitOrStretch,
                        VAnchor = VAnchor.Stretch,
                        Padding = theme.DefaultContainerPadding
                    });
                }
            };
            horizontalSplitter.Panel1.AddChild(treeView);

            horizontalSplitter.Panel2.AddChild(new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
            });
        }
Ejemplo n.º 3
0
        public SimpleTab(string tabLabel, SimpleTabs parentTabControl, GuiWidget tabContent, ThemeConfig theme, string tabImageUrl = null, bool hasClose = true, double pointSize = 12, ImageBuffer iconImage = null)
        {
            this.HAnchor = HAnchor.Fit;
            this.VAnchor = VAnchor.Fit | VAnchor.Bottom;
            this.Padding = 0;
            this.Margin  = 0;
            this.theme   = theme;

            this.TabContent       = tabContent;
            this.parentTabControl = parentTabControl;

            if (iconImage != null)
            {
                tabPill = new TabPill(tabLabel, ActiveTheme.Instance.PrimaryTextColor, iconImage, pointSize);
            }
            else
            {
                tabPill = new TabPill(tabLabel, ActiveTheme.Instance.PrimaryTextColor, tabImageUrl, pointSize);
            }
            tabPill.Margin = (hasClose) ? new BorderDouble(right: 16) : 0;

            this.AddChild(tabPill);

            if (hasClose)
            {
                var closeButton = theme.CreateSmallResetButton();
                closeButton.HAnchor     = HAnchor.Right;
                closeButton.Margin      = new BorderDouble(right: 7, top: 1);
                closeButton.Name        = "Close Tab Button";
                closeButton.ToolTipText = "Close".Localize();
                closeButton.Click      += (sender, e) =>
                {
                    UiThread.RunOnIdle(() =>
                    {
                        if (TabContent is PrinterTabPage printerTab &&
                            printerTab.printer.Connection.PrinterIsPrinting)
                        {
                            StyledMessageBox.ShowMessageBox(
                                (bool response) =>
                            {
                                if (response)
                                {
                                    UiThread.RunOnIdle(() =>
                                    {
                                        this.parentTabControl.RemoveTab(this);
                                        this.CloseClicked?.Invoke(this, null);
                                    });
                                }
                            },
                                "Cancel the current print?".Localize(),
                                "Cancel Print?".Localize(),
                                StyledMessageBox.MessageType.YES_NO,
                                "Cancel Print".Localize(),
                                "Continue Printing".Localize());
                        }
                        else                         // need to handle asking about saving a
                        {
                            UiThread.RunOnIdle(() =>
                            {
                                this.parentTabControl.RemoveTab(this);
                                this.CloseClicked?.Invoke(this, null);
                            });
                        }
                    });
Ejemplo n.º 4
0
        public PrinterBar(PartPreviewContent partPreviewContent, PrinterInfo printerInfo, ThemeConfig theme)
            : base(printerInfo?.Name ?? "", theme)
        {
            headingBar.CloseAllChildren();
            headingBar.AddChild(printerSelector = new PrinterSelector(theme)
            {
                VAnchor         = VAnchor.Fit,
                HAnchor         = HAnchor.Absolute,
                Border          = 0,
                MinimumSize     = Vector2.Zero,
                Width           = 200,
                BackgroundColor = theme.MinimalShade
            });

            printerSelector.SelectionChanged += (s, e) =>
            {
                this.RebuildPlateOptions(partPreviewContent, theme);
            };

            var forcedHeight = printerSelector.Height;

            // add in the create printer button
            var createPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-add-circle_18.png", 18, 18, theme.InvertIcons), theme)
            {
                Name        = "Create Printer",
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing.Clone(left: theme.ButtonSpacing.Right),
                ToolTipText = "Create Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight
            };

            createPrinter.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    //simpleTabs.RemoveTab(simpleTabs.ActiveTab);

                    if (ApplicationController.Instance.ActivePrinter.Connection.PrinterIsPrinting ||
                        ApplicationController.Instance.ActivePrinter.Connection.PrinterIsPaused)
                    {
                        StyledMessageBox.ShowMessageBox("Please wait until the print has finished and try again.".Localize(), "Can't add printers while printing".Localize());
                    }
                    else
                    {
                        DialogWindow.Show(PrinterSetup.GetBestStartPage(PrinterSetup.StartPageOptions.ShowMakeModel));
                    }
                });
            };
            headingBar.AddChild(createPrinter);

            // add in the import printer button
            var importPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-import_18.png", 18, 18, theme.InvertIcons), theme)
            {
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing,
                ToolTipText = "Import Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight
            };

            importPrinter.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    AggContext.FileDialogs.OpenFileDialog(
                        new OpenFileDialogParams(
                            "settings files|*.ini;*.printer;*.slice"),
                        (result) =>
                    {
                        if (!string.IsNullOrEmpty(result.FileName) &&
                            File.Exists(result.FileName))
                        {
                            //simpleTabs.RemoveTab(simpleTabs.ActiveTab);
                            if (ProfileManager.ImportFromExisting(result.FileName))
                            {
                                string importPrinterSuccessMessage = "You have successfully imported a new printer profile. You can find '{0}' in your list of available printers.".Localize();
                                DialogWindow.Show(
                                    new ImportSucceeded(
                                        importPrinterSuccessMessage.FormatWith(Path.GetFileNameWithoutExtension(result.FileName))));
                            }
                            else
                            {
                                StyledMessageBox.ShowMessageBox("Oops! Settings file '{0}' did not contain any settings we could import.".Localize().FormatWith(Path.GetFileName(result.FileName)), "Unable to Import".Localize());
                            }
                        }
                    });
                });
            };
            headingBar.AddChild(importPrinter);

            this.printerInfo = printerInfo;

            this.RebuildPlateOptions(partPreviewContent, theme);

            // Rebuild on change
            ProfileManager.ProfilesListChanged.RegisterEvent((s, e) =>
            {
                this.RebuildPlateOptions(partPreviewContent, theme);
            }, ref unregisterEvents);
        }
Ejemplo n.º 5
0
 private void MustSelectPrinterMessage()
 {
     StyledMessageBox.ShowMessageBox(null, pleaseSelectPrinterMessage, pleaseSelectPrinterTitle);
 }
Ejemplo n.º 6
0
        private FlowLayoutWidget GetDisplayControl()
        {
            FlowLayoutWidget buttonRow = new FlowLayoutWidget();

            buttonRow.HAnchor = HAnchor.ParentLeftRight;
            buttonRow.Margin  = new BorderDouble(top: 4);

            TextWidget settingsLabel = new TextWidget("Display Mode".Localize());

            settingsLabel.AutoExpandBoundsToText = true;
            settingsLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor;
            settingsLabel.VAnchor   = VAnchor.ParentTop;

            Button displayControlRestartButton = textImageButtonFactory.Generate("Restart".Localize());

            displayControlRestartButton.VAnchor = Agg.UI.VAnchor.ParentCenter;
            displayControlRestartButton.Visible = false;
            displayControlRestartButton.Margin  = new BorderDouble(right: 6);
            displayControlRestartButton.Click  += (sender, e) =>
            {
                if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting)
                {
                    StyledMessageBox.ShowMessageBox(null, cannotRestartWhilePrintIsActiveMessage, cannotRestartWhileActive);
                }
                else
                {
                    RestartApplication();
                }
            };

            FlowLayoutWidget optionsContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);

            optionsContainer.Margin = new BorderDouble(bottom: 6);

            DropDownList interfaceOptionsDropList = new DropDownList("Development", maxHeight: 200);

            interfaceOptionsDropList.HAnchor = HAnchor.ParentLeftRight;

            optionsContainer.AddChild(interfaceOptionsDropList);
            optionsContainer.Width = 200;

            interfaceOptionsDropList.AddItem("Normal".Localize(), "responsive");
            interfaceOptionsDropList.AddItem("Touchscreen".Localize(), "touchscreen");

            List <string> acceptableUpdateFeedTypeValues = new List <string>()
            {
                "responsive", "touchscreen"
            };
            string currentDisplayModeType = UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode);

            if (acceptableUpdateFeedTypeValues.IndexOf(currentDisplayModeType) == -1)
            {
                UserSettings.Instance.set(UserSettingsKey.ApplicationDisplayMode, "responsive");
            }

            interfaceOptionsDropList.SelectedValue     = UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode);
            interfaceOptionsDropList.SelectionChanged += (sender, e) =>
            {
                string displayMode = ((DropDownList)sender).SelectedValue;
                if (displayMode != UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode))
                {
                    UserSettings.Instance.set(UserSettingsKey.ApplicationDisplayMode, displayMode);
                    displayControlRestartButton.Visible = true;
                }
            };

            buttonRow.AddChild(settingsLabel);
            buttonRow.AddChild(new HorizontalSpacer());
            buttonRow.AddChild(displayControlRestartButton);
            buttonRow.AddChild(optionsContainer);
            return(buttonRow);
        }
Ejemplo n.º 7
0
        public CloneSettingsPage()
        {
            this.WindowTitle = "Import Printer".Localize();
            this.HeaderText  = "Import Printer".Localize() + ":";
            this.Name        = "Import Printer Window";

            var commonMargin = new BorderDouble(4, 2);

            contentRow.AddChild(new TextWidget("File Path".Localize(), pointSize: theme.DefaultFontSize, textColor: theme.TextColor));

            var pathRow = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
            };

            contentRow.AddChild(pathRow);

            TextButton importButton = null;

            var textEditWidget = new MHTextEditWidget("", theme)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Center
            };

            textEditWidget.ActualTextEditWidget.EditComplete += (s, e) =>
            {
                importButton.Enabled = !string.IsNullOrEmpty(textEditWidget.Text) &&
                                       File.Exists(textEditWidget.Text);
            };
            pathRow.AddChild(textEditWidget);

            // Must come before pathButton.Click definition
            RadioButton copyAndCalibrateOption = null;

            var openButton = new IconButton(AggContext.StaticData.LoadIcon("fa-folder-open_16.png", 16, 16, theme.InvertIcons), theme)
            {
                BackgroundColor = theme.MinimalShade,
                Margin          = new BorderDouble(left: 8)
            };

            openButton.Click += (s, e) =>
            {
                AggContext.FileDialogs.OpenFileDialog(
                    new OpenFileDialogParams("settings files|*.ini;*.printer;*.slice"),
                    (result) =>
                {
                    if (!string.IsNullOrEmpty(result.FileName) &&
                        File.Exists(result.FileName))
                    {
                        textEditWidget.Text = result.FileName;
                    }

                    importButton.Enabled = !string.IsNullOrEmpty(textEditWidget.Text) &&
                                           File.Exists(textEditWidget.Text);
                });
            };
            pathRow.AddChild(openButton);

            var exactCloneColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
                Margin  = new BorderDouble(top: 15)
            };

            contentRow.AddChild(exactCloneColumn);

            var siblingList = new List <GuiWidget>();

            var exactCloneOption = new RadioButton(new RadioButtonViewText("Exact clone".Localize(), theme.TextColor, fontSize: theme.DefaultFontSize))
            {
                HAnchor = HAnchor.Left,
                Margin  = commonMargin,
                Cursor  = Cursors.Hand,
                Name    = "Exact Clone Button",
                Checked = true,
                SiblingRadioButtonList = siblingList
            };

            exactCloneColumn.AddChild(exactCloneOption);
            siblingList.Add(exactCloneOption);

            var exactCloneSummary = new WrappedTextWidget("Copy all settings including hardware calibration".Localize(), pointSize: theme.DefaultFontSize - 1, textColor: theme.TextColor)
            {
                Margin = new BorderDouble(left: 30, bottom: 10, top: 4),
            };

            exactCloneColumn.AddChild(exactCloneSummary);

            var copySettingsColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit
            };

            contentRow.AddChild(copySettingsColumn);

            // Create export button for each plugin
            copyAndCalibrateOption = new RadioButton(new RadioButtonViewText("Copy and recalibrate".Localize(), theme.TextColor, fontSize: theme.DefaultFontSize))
            {
                HAnchor = HAnchor.Left,
                Margin  = commonMargin,
                Cursor  = Cursors.Hand,
                Name    = "Copy and Calibrate Button",
                SiblingRadioButtonList = siblingList
            };
            copySettingsColumn.AddChild(copyAndCalibrateOption);
            siblingList.Add(copyAndCalibrateOption);

            string summary = string.Format(
                "{0}\r\n{1}",
                "Copy everything but hardware specific calibration settings".Localize(),
                "Ideal for cloning settings across different physical printers".Localize());

            var copySummary = new WrappedTextWidget(summary, pointSize: theme.DefaultFontSize - 1, textColor: theme.TextColor)
            {
                Margin = new BorderDouble(left: 30, bottom: 10, top: 4)
            };

            copySettingsColumn.AddChild(copySummary);

            importButton         = theme.CreateDialogButton("Import".Localize());
            importButton.Enabled = false;
            importButton.Name    = "Import Button";
            importButton.Click  += (s, e) =>
            {
                var filePath = textEditWidget.Text;

                if (ProfileManager.ImportFromExisting(filePath, resetSettingsForNewProfile: copyAndCalibrateOption.Checked))
                {
                    string importPrinterSuccessMessage = "You have successfully imported a new printer profile. You can find '{0}' in your list of available printers.".Localize();
                    this.DialogWindow.ChangeToPage(
                        new ImportSucceededPage(
                            importPrinterSuccessMessage.FormatWith(Path.GetFileNameWithoutExtension(filePath))));
                }
                else
                {
                    StyledMessageBox.ShowMessageBox(
                        string.Format(
                            "Oops! Settings file '{0}' did not contain any settings we could import.".Localize(),
                            Path.GetFileName(filePath)),
                        "Unable to Import".Localize());
                }
            };

            this.AddPageAction(importButton);
        }
Ejemplo n.º 8
0
        public HardwareTreeView(ThemeConfig theme)
            : base(theme)
        {
            rootColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit
            };
            this.AddChild(rootColumn);

            // Printers
            printersNode = new TreeNode(theme)
            {
                Text             = "Printers".Localize(),
                HAnchor          = HAnchor.Stretch,
                AlwaysExpandable = true,
                Image            = AggContext.StaticData.LoadIcon("printer.png", 16, 16, theme.InvertIcons)
            };
            printersNode.TreeView = this;

            var forcedHeight = 20;
            var mainRow      = printersNode.Children.FirstOrDefault();

            mainRow.HAnchor = HAnchor.Stretch;
            mainRow.AddChild(new HorizontalSpacer());

            // add in the create printer button
            var createPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-add-circle_18.png", 18, 18, theme.InvertIcons), theme)
            {
                Name        = "Create Printer",
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing.Clone(left: theme.ButtonSpacing.Right),
                ToolTipText = "Create Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight
            };

            createPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                if (ApplicationController.Instance.AnyPrintTaskRunning)
                {
                    StyledMessageBox.ShowMessageBox("Please wait until the print has finished and try again.".Localize(), "Can't add printers while printing".Localize());
                }
                else
                {
                    DialogWindow.Show(PrinterSetup.GetBestStartPage(PrinterSetup.StartPageOptions.ShowMakeModel));
                }
            });
            mainRow.AddChild(createPrinter);

            // add in the import printer button
            var importPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-import_18.png", 18, 18, theme.InvertIcons), theme)
            {
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing,
                ToolTipText = "Import Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight,
                Name        = "Import Printer Button"
            };

            importPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                DialogWindow.Show(new CloneSettingsPage());
            });
            mainRow.AddChild(importPrinter);

            rootColumn.AddChild(printersNode);

            HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
            this.Invalidate();

            // Filament
            var materialsNode = new TreeNode(theme)
            {
                Text             = "Materials".Localize(),
                AlwaysExpandable = true,
                Image            = AggContext.StaticData.LoadIcon("filament.png", 16, 16, theme.InvertIcons)
            };

            materialsNode.TreeView = this;

            rootColumn.AddChild(materialsNode);

            // Register listeners
            PrinterSettings.AnyPrinterSettingChanged += Printer_SettingChanged;

            // Rebuild the treeview anytime the Profiles list changes
            ProfileManager.ProfilesListChanged.RegisterEvent((s, e) =>
            {
                HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
                this.Invalidate();
            }, ref unregisterEvents);
        }
        private async void EnterEditAndCreateSelectionData()
        {
            if (enterEditButtonsContainer.Visible == true)
            {
                enterEditButtonsContainer.Visible = false;
            }

            viewControls3D.ActiveButton = ViewControls3DButtons.PartSelect;
            if (MeshGroups.Count > 0)
            {
                processingProgressControl.Visible = true;
                LockEditControls();
                viewIsInEditModePreLock = true;

                await Task.Run((System.Action) CreateSelectionData);

                if (HasBeenClosed)
                {
                    return;
                }
                // remove the original mesh and replace it with these new meshes
                PullMeshGroupDataFromAsynchLists();

                SelectedMeshGroupIndex   = 0;
                buttonRightPanel.Visible = true;
                UnlockEditControls();
                viewControls3D.ActiveButton = ViewControls3DButtons.PartSelect;

                Invalidate();

                if (DoAddFileAfterCreatingEditData)
                {
                    FileDialog.OpenFileDialog(
                        new OpenFileDialogParams(ApplicationSettings.OpenDesignFileParams, multiSelect: true),
                        (openParams) =>
                    {
                        LoadAndAddPartsToPlate(openParams.FileNames);
                    });
                    DoAddFileAfterCreatingEditData = false;
                }
                else if (pendingPartsToLoad.Count > 0)
                {
                    LoadAndAddPartsToPlate(pendingPartsToLoad.ToArray());
                    pendingPartsToLoad.Clear();
                }
                else
                {
                    if (!PartsAreInPrintVolume())
                    {
                        UiThread.RunOnIdle(() =>
                        {
                            StyledMessageBox.ShowMessageBox((doCentering) =>
                            {
                                if (doCentering)
                                {
                                    AutoArrangePartsInBackground();
                                }
                            }, PartsNotPrintableMessage, PartsNotPrintableTitle, StyledMessageBox.MessageType.YES_NO, "Center on Bed".Localize(), "Cancel".Localize());
                        });
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public bool IsValid()
        {
            try
            {
                if (LayerHeight > NozzleDiameter)
                {
                    string error    = LocalizedString.Get("'Layer Height' must be less than or equal to the 'Nozzle Diameter'.");
                    string details  = string.Format("Layer Height = {0}\nNozzle Diameter = {1}", LayerHeight, NozzleDiameter);
                    string location = LocalizedString.Get("Location: 'Advanced Controls' -> 'Slice Settings' -> 'Print' -> 'Layers/Perimeters'");
                    StyledMessageBox.ShowMessageBox(string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error");
                    return(false);
                }
                else if (FirstLayerHeight > NozzleDiameter)
                {
                    string error    = LocalizedString.Get("First Layer Height' must be less than or equal to the 'Nozzle Diameter'.");
                    string details  = string.Format("First Layer Height = {0}\nNozzle Diameter = {1}", FirstLayerHeight, NozzleDiameter);
                    string location = "Location: 'Advanced Controls' -> 'Slice Settings' -> 'Print' -> 'Layers/Perimeters'";
                    StyledMessageBox.ShowMessageBox(string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error");
                    return(false);
                }

                if (MinFanSpeed > 100)
                {
                    string error    = "The Min Fan Speed can only go as high as 100%.";
                    string details  = string.Format("It is currently set to {0}.", MinFanSpeed);
                    string location = "Location: 'Advanced Controls' -> 'Slice Settings' -> 'Filament' -> 'Cooling' (show all settings)";
                    StyledMessageBox.ShowMessageBox(string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error");
                    return(false);
                }

                if (MaxFanSpeed > 100)
                {
                    string error    = "The Max Fan Speed can only go as high as 100%.";
                    string details  = string.Format("It is currently set to {0}.", MaxFanSpeed);
                    string location = "Location: 'Advanced Controls' -> 'Slice Settings' -> 'Filament' -> 'Cooling' (show all settings)";
                    StyledMessageBox.ShowMessageBox(string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error");
                    return(false);
                }
                if (FillDensity < 0 || FillDensity > 1)
                {
                    string error    = "The Fill Density must be between 0 and 1 inclusive.";
                    string details  = string.Format("It is currently set to {0}.", FillDensity);
                    string location = "Location: 'Advanced Controls' -> 'Slice Settings' -> 'Print' -> 'Infill'";
                    StyledMessageBox.ShowMessageBox(string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error");
                    return(false);
                }

                // If the given speed is part of the current slice engine then check that it is greater than 0.
                if (!ValidateGoodSpeedSettingGreaterThan0("bridge_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("external_perimeter_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("first_layer_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("gap_fill_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("infill_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("perimeter_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("retract_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("small_perimeter_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("solid_infill_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("support_material_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("top_solid_infill_speed"))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("travel_speed"))
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                string stackTraceNoBackslashRs = e.StackTrace.Replace("\r", "");
                ContactFormWindow.Open("Parse Error while slicing", e.Message + stackTraceNoBackslashRs);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 11
0
        public PrinterConnectButton(PrinterConfig printer, ThemeConfig theme)
        {
            this.printer = printer;
            this.HAnchor = HAnchor.Left | HAnchor.Fit;
            this.VAnchor = VAnchor.Fit;
            this.Margin  = 0;
            this.Padding = 0;

            connectButton = new TextIconButton(
                "Connect".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                Name           = "Connect to printer button",
                ToolTipText    = "Connect to the currently selected printer".Localize(),
                MouseDownColor = theme.ToolbarButtonDown,
            };
            connectButton.Click += (s, e) =>
            {
                if (connectButton.Enabled)
                {
                    if (printer.Settings.PrinterSelected)
                    {
                        UserRequestedConnectToActivePrinter();
                    }
                }
            };
            this.AddChild(connectButton);

            theme.ApplyPrimaryActionStyle(connectButton);

            // add the cancel stop button
            cancelConnectButton = new TextIconButton(
                "Cancel".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                ToolTipText     = "Stop trying to connect to the printer.".Localize(),
                BackgroundColor = theme.ToolbarButtonBackground,
                HoverColor      = theme.ToolbarButtonHover,
                MouseDownColor  = theme.ToolbarButtonDown,
            };
            cancelConnectButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                listenForConnectFailed = false;
                ApplicationController.Instance.ConditionalCancelPrint();
                cancelConnectButton.Enabled = false;
            });
            this.AddChild(cancelConnectButton);

            disconnectButton = new TextIconButton(
                "Disconnect".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                Name            = "Disconnect from printer button",
                Visible         = false,
                ToolTipText     = "Disconnect from current printer".Localize(),
                BackgroundColor = theme.ToolbarButtonBackground,
                HoverColor      = theme.ToolbarButtonHover,
                MouseDownColor  = theme.ToolbarButtonDown,
            };
            disconnectButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                if (printer.Connection.PrinterIsPrinting)
                {
                    StyledMessageBox.ShowMessageBox(
                        (bool disconnectCancel) =>
                    {
                        if (disconnectCancel)
                        {
                            printer.Connection.Stop(false);
                            printer.Connection.Disable();
                        }
                    },
                        "WARNING: Disconnecting will stop the current print.\n\nAre you sure you want to disconnect?".Localize(),
                        "Disconnect and stop the current print?".Localize(),
                        StyledMessageBox.MessageType.YES_NO,
                        "Disconnect".Localize(),
                        "Stay Connected".Localize());
                }
                else
                {
                    printer.Connection.Disable();
                }
            });
            this.AddChild(disconnectButton);

            foreach (var child in Children)
            {
                child.VAnchor = VAnchor.Center;
                child.Cursor  = Cursors.Hand;
                child.Margin  = theme.ButtonSpacing;
            }

            printer.Connection.EnableChanged.RegisterEvent((s, e) => SetVisibleStates(), ref unregisterEvents);
            printer.Connection.CommunicationStateChanged.RegisterEvent((s, e) => SetVisibleStates(), ref unregisterEvents);
            printer.Connection.ConnectionFailed.RegisterEvent((s, e) =>
            {
#if !__ANDROID__
                // TODO: Someday this functionality should be revised to an awaitable Connect() call in the Connect button that
                // shows troubleshooting on failed attempts, rather than hooking the failed event and trying to determine if the
                // Connect button started the task
                if (listenForConnectFailed &&
                    UiThread.CurrentTimerMs - connectStartMs < 25000)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        // User initiated connect attempt failed, show port selection dialog
                        DialogWindow.Show(new SetupStepComPortOne(printer));
                    });
                }
#endif
                listenForConnectFailed = false;
            }, ref unregisterEvents);

            this.SetVisibleStates();
        }
Ejemplo n.º 12
0
        public bool IsValid()
        {
            try
            {
                if (LayerHeight > NozzleDiameter)
                {
                    string error    = "'Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("Layer Height = {0}\nNozzle Diameter = {1}".Localize(), LayerHeight, NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }
                else if (FirstLayerHeight > NozzleDiameter)
                {
                    string error    = "'First Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("First Layer Height = {0}\nNozzle Diameter = {1}".Localize(), FirstLayerHeight, NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                // If we have print leveling turned on then make sure we don't have any leveling commands in the start gcode.
                if (PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling)
                {
                    string[] startGCode = ActiveSliceSettings.Instance.GetActiveValue("start_gcode").Replace("\\n", "\n").Split('\n');
                    foreach (string startGCodeLine in startGCode)
                    {
                        if (startGCodeLine.StartsWith("G29"))
                        {
                            string error    = "Start G-Code cannot contain G29 if Print Leveling is enabled.".Localize();
                            string details  = "Your Start G-Code should not contain a G29 if you are planning on using print leveling. Change your start G-Code or turn off print leveling".Localize();
                            string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }

                        if (startGCodeLine.StartsWith("G30"))
                        {
                            string error    = "Start G-Code cannot contain G30 if Print Leveling is enabled.".Localize();
                            string details  = "Your Start G-Code should not contain a G30 if you are planning on using print leveling. Change your start G-Code or turn off print leveling".Localize();
                            string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }
                    }
                }

                if (FirstLayerExtrusionWidth > NozzleDiameter * 4)
                {
                    string error    = "'First Layer Extrusion Width' must be less than or equal to the 'Nozzle Diameter' * 4.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}\nNozzle Diameter = {1}".Localize(), GetActiveValue("first_layer_extrusion_width"), NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FirstLayerExtrusionWidth <= 0)
                {
                    string error    = "'First Layer Extrusion Width' must be greater than 0.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}".Localize(), GetActiveValue("first_layer_extrusion_width"));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (MinFanSpeed > 100)
                {
                    string error    = "The Minimum Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), MinFanSpeed);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (MaxFanSpeed > 100)
                {
                    string error    = "The Maximum Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), MaxFanSpeed);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (ExtruderCount < 1)
                {
                    string error    = "The Extruder Count must be at least 1.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), ExtruderCount);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Printer' -> 'Features'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FillDensity < 0 || FillDensity > 1)
                {
                    string error    = "The Fill Density must be between 0 and 1.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), FillDensity);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Infill'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FillDensity == 1 &&
                    GetActiveValue("infill_type") != "LINES")
                {
                    string error    = "Solid Infill works best when set to LINES.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetActiveValue("infill_type"));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Infill Type'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(true);
                }

                string normalSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Speed'".Localize();
                // If the given speed is part of the current slice engine then check that it is greater than 0.
                if (!ValidateGoodSpeedSettingGreaterThan0("bridge_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("external_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("first_layer_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("gap_fill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("small_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("support_material_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("top_solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("travel_speed", normalSpeedLocation))
                {
                    return(false);
                }

                string retractSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Filament' -> 'Retraction'".Localize();
                if (!ValidateGoodSpeedSettingGreaterThan0("retract_speed", retractSpeedLocation))
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
                string stackTraceNoBackslashRs = e.StackTrace.Replace("\r", "");
                ContactFormWindow.Open("Parse Error while slicing".Localize(), e.Message + stackTraceNoBackslashRs);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Creates a database PrintItem entity, if forceAMF is set, converts to AMF otherwise just copies
        /// the source file to a new library path and updates the PrintItem to point at the new target
        /// </summary>
        private void AddItem(Stream stream, string extension, string displayName, bool forceAMF = true)
        {
            // Create a new entity in the database
            PrintItem printItem = new PrintItem();

            printItem.Name = displayName;
            printItem.PrintItemCollectionID = this.baseLibraryCollection.Id;
            printItem.Commit();

            // Special load processing for mesh data, simple copy below for non-mesh
            if (forceAMF &&
                (extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension.ToUpper())))
            {
                try
                {
                    // Load mesh
                    List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(stream, extension);

                    // Create a new PrintItemWrapper

                    if (!printItem.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath))
                    {
                        string[] metaData = { "Created By", "MatterControl" };
                        if (false)                         //AbsolutePositioned
                        {
                            metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" };
                        }

                        // save a copy to the library and update this to point at it
                        printItem.FileLocation = CreateLibraryPath(".amf");
                        var outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
                        MeshFileIo.Save(meshToConvertAndSave, printItem.FileLocation, outputInfo);
                        printItem.Commit();
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        //Do something special when unauthorized?
                        StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes, unauthorized access", "Unable to save");
                    });
                }
                catch
                {
                    UiThread.RunOnIdle(() =>
                    {
                        StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save");
                    });
                }
            }
            else             // it is not a mesh so just add it
            {
                // Non-mesh content - copy stream to new Library path
                printItem.FileLocation = CreateLibraryPath(extension);
                using (var outStream = File.Create(printItem.FileLocation))
                {
                    stream.CopyTo(outStream);
                }
                printItem.Commit();
            }
        }
        public ApplicationSettingsWidget(ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.HAnchor         = HAnchor.Stretch;
            this.VAnchor         = VAnchor.Fit;
            this.BackgroundColor = theme.Colors.PrimaryBackgroundColor;
            this.theme           = theme;

            var configureIcon = AggContext.StaticData.LoadIcon("fa-cog_16.png", 16, 16, theme.InvertIcons);

#if __ANDROID__
            // Camera Monitoring
            bool hasCamera = true || ApplicationSettings.Instance.get(ApplicationSettingsKey.HardwareHasCamera) == "true";

            var previewButton = new IconButton(configureIcon, theme)
            {
                ToolTipText = "Configure Camera View".Localize()
            };
            previewButton.Click += (s, e) =>
            {
                AppContext.Platform.OpenCameraPreview();
            };

            this.AddSettingsRow(
                new SettingsItem(
                    "Camera Monitoring".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = ActiveSliceSettings.Instance.GetValue <bool>(SettingsKey.publish_bed_image),
                ToggleAction = (itemChecked) =>
                {
                    ActiveSliceSettings.Instance.SetValue(SettingsKey.publish_bed_image, itemChecked ? "1" : "0");
                }
            },
                    previewButton,
                    AggContext.StaticData.LoadIcon("camera-24x24.png", 24, 24))
                );
#endif

            // Print Notifications
            var configureNotificationsButton = new IconButton(configureIcon, theme)
            {
                Name        = "Configure Notification Settings Button",
                ToolTipText = "Configure Notifications".Localize(),
                Margin      = new BorderDouble(left: 6),
                VAnchor     = VAnchor.Center
            };
            configureNotificationsButton.Click += (s, e) =>
            {
                if (OpenPrintNotification != null)
                {
                    UiThread.RunOnIdle(OpenPrintNotification);
                }
            };

            AddMenuItem("Help".Localize(), () =>
            {
                UiThread.RunOnIdle(() =>
                {
                    DialogWindow.Show(new HelpPage("AllGuides"));
                });
            });

            this.AddSettingsRow(
                new SettingsItem(
                    "Notifications".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = UserSettings.Instance.get(UserSettingsKey.PrintNotificationsEnabled) == "true",
                ToggleAction = (itemChecked) =>
                {
                    UserSettings.Instance.set(UserSettingsKey.PrintNotificationsEnabled, itemChecked ? "true" : "false");
                }
            },
                    configureNotificationsButton,
                    AggContext.StaticData.LoadIcon("notify-24x24.png")));

            // Touch Screen Mode
            this.AddSettingsRow(
                new SettingsItem(
                    "Touch Screen Mode".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode) == "touchscreen",
                ToggleAction = (itemChecked) =>
                {
                    string displayMode = itemChecked ? "touchscreen" : "responsive";
                    if (displayMode != UserSettings.Instance.get(UserSettingsKey.ApplicationDisplayMode))
                    {
                        UserSettings.Instance.set(UserSettingsKey.ApplicationDisplayMode, displayMode);
                        ApplicationController.Instance.ReloadAll();
                    }
                }
            }));

            // LanguageControl
            var languageSelector = new LanguageSelector(theme);
            languageSelector.SelectionChanged += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    string languageCode = languageSelector.SelectedValue;
                    if (languageCode != UserSettings.Instance.get(UserSettingsKey.Language))
                    {
                        UserSettings.Instance.set(UserSettingsKey.Language, languageCode);

                        if (languageCode == "L10N")
                        {
                            GenerateLocalizationValidationFile();
                        }

                        ApplicationController.Instance.ResetTranslationMap();
                        ApplicationController.Instance.ReloadAll();
                    }
                });
            };

            this.AddSettingsRow(new SettingsItem("Language".Localize(), languageSelector, theme));

#if !__ANDROID__
            {
                // ThumbnailRendering
                var thumbnailsModeDropList = new DropDownList("", theme.Colors.PrimaryTextColor, maxHeight: 200, pointSize: theme.DefaultFontSize)
                {
                    BorderColor = theme.GetBorderColor(75)
                };
                thumbnailsModeDropList.AddItem("Flat".Localize(), "orthographic");
                thumbnailsModeDropList.AddItem("3D".Localize(), "raytraced");

                thumbnailsModeDropList.SelectedValue     = UserSettings.Instance.ThumbnailRenderingMode;
                thumbnailsModeDropList.SelectionChanged += (s, e) =>
                {
                    string thumbnailRenderingMode = thumbnailsModeDropList.SelectedValue;
                    if (thumbnailRenderingMode != UserSettings.Instance.ThumbnailRenderingMode)
                    {
                        UserSettings.Instance.ThumbnailRenderingMode = thumbnailRenderingMode;

                        UiThread.RunOnIdle(() =>
                        {
                            // Ask if the user they would like to rebuild their thumbnails
                            StyledMessageBox.ShowMessageBox(
                                (bool rebuildThumbnails) =>
                            {
                                if (rebuildThumbnails)
                                {
                                    string directoryToRemove = ApplicationController.CacheablePath("ItemThumbnails", "");
                                    try
                                    {
                                        if (Directory.Exists(directoryToRemove))
                                        {
                                            Directory.Delete(directoryToRemove, true);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        GuiWidget.BreakInDebugger();
                                    }

                                    Directory.CreateDirectory(directoryToRemove);

                                    ApplicationController.Instance.Library.NotifyContainerChanged();
                                }
                            },
                                "You are switching to a different thumbnail rendering mode. If you want, your current thumbnails can be removed and recreated in the new style. You can switch back and forth at any time. There will be some processing overhead while the new thumbnails are created.\n\nDo you want to rebuild your existing thumbnails now?".Localize(),
                                "Rebuild Thumbnails Now".Localize(),
                                StyledMessageBox.MessageType.YES_NO,
                                "Rebuild".Localize());
                        });
                    }
                };

                this.AddSettingsRow(
                    new SettingsItem(
                        "Thumbnails".Localize(),
                        thumbnailsModeDropList,
                        theme));

                // TextSize
                if (!double.TryParse(UserSettings.Instance.get(UserSettingsKey.ApplicationTextSize), out double currentTexSize))
                {
                    currentTexSize = 1.0;
                }

                double sliderThumbWidth = 10 * GuiWidget.DeviceScale;
                double sliderWidth      = 100 * GuiWidget.DeviceScale;
                var    textSizeSlider   = new SolidSlider(new Vector2(), sliderThumbWidth, .7, 1.4)
                {
                    Name               = "Text Size Slider",
                    Margin             = new BorderDouble(5, 0),
                    Value              = currentTexSize,
                    HAnchor            = HAnchor.Stretch,
                    VAnchor            = VAnchor.Center,
                    TotalWidthInPixels = sliderWidth,
                };

                var optionalContainer = new FlowLayoutWidget()
                {
                    VAnchor = VAnchor.Center | VAnchor.Fit,
                    HAnchor = HAnchor.Fit
                };

                TextWidget sectionLabel = null;

                var textSizeApplyButton = new TextButton("Apply".Localize(), theme)
                {
                    VAnchor         = VAnchor.Center,
                    BackgroundColor = theme.SlightShade,
                    Visible         = false,
                    Margin          = new BorderDouble(right: 6)
                };
                textSizeApplyButton.Click += (s, e) =>
                {
                    GuiWidget.DeviceScale = textSizeSlider.Value;
                    ApplicationController.Instance.ReloadAll();
                };
                optionalContainer.AddChild(textSizeApplyButton);

                textSizeSlider.ValueChanged += (s, e) =>
                {
                    double textSizeNew = textSizeSlider.Value;
                    UserSettings.Instance.set(UserSettingsKey.ApplicationTextSize, textSizeNew.ToString("0.0"));
                    sectionLabel.Text           = "Text Size".Localize() + $" : {textSizeNew:0.0}";
                    textSizeApplyButton.Visible = textSizeNew != currentTexSize;
                };

                var section = new SettingsItem(
                    "Text Size".Localize() + $" : {currentTexSize:0.0}",
                    textSizeSlider,
                    theme,
                    optionalContainer);

                sectionLabel = section.Children <TextWidget>().FirstOrDefault();

                this.AddSettingsRow(section);
            }
#endif

            AddMenuItem("Forums".Localize(), () => ApplicationController.Instance.LaunchBrowser("https://forums.matterhackers.com/category/20/mattercontrol"));
            AddMenuItem("Wiki".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://wiki.mattercontrol.com"));
            AddMenuItem("Guides and Articles".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://www.matterhackers.com/topic/mattercontrol"));
            AddMenuItem("Release Notes".Localize(), () => ApplicationController.Instance.LaunchBrowser("http://wiki.mattercontrol.com/Release_Notes"));
            AddMenuItem("Report a Bug".Localize(), () => ApplicationController.Instance.LaunchBrowser("https://github.com/MatterHackers/MatterControl/issues"));

            var updateMatterControl = new SettingsItem("Check For Update".Localize(), theme);
            updateMatterControl.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    UpdateControlData.Instance.CheckForUpdate();
                    DialogWindow.Show <CheckForUpdatesPage>();
                });
            };
            this.AddSettingsRow(updateMatterControl);

            this.AddChild(new SettingsItem("Theme".Localize(), new GuiWidget(), theme));
            this.AddChild(this.GetThemeControl(theme));

            var aboutMatterControl = new SettingsItem("About".Localize() + " " + ApplicationController.Instance.ProductName, theme);
            if (IntPtr.Size == 8)
            {
                // Push right
                aboutMatterControl.AddChild(new HorizontalSpacer());

                // Add x64 adornment
                var blueBox = new FlowLayoutWidget()
                {
                    Margin      = new BorderDouble(10, 0),
                    Padding     = new BorderDouble(2),
                    Border      = new BorderDouble(1),
                    BorderColor = theme.Colors.PrimaryAccentColor,
                    VAnchor     = VAnchor.Center | VAnchor.Fit,
                };
                blueBox.AddChild(new TextWidget("64", pointSize: 8, textColor: theme.Colors.PrimaryAccentColor));

                aboutMatterControl.AddChild(blueBox);
            }
            aboutMatterControl.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() => DialogWindow.Show <AboutPage>());
            };
            this.AddSettingsRow(aboutMatterControl);
        }
Ejemplo n.º 15
0
        public HardwareTabPage(ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.theme   = theme;
            this.Padding = 0;
            this.HAnchor = HAnchor.Stretch;
            this.VAnchor = VAnchor.Stretch;

            var toolbar = new Toolbar(theme.TabbarPadding, theme.CreateSmallResetButton())
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
                Padding = theme.ToolbarPadding
            };

            theme.ApplyBottomBorder(toolbar);

            toolbar.AddChild(new TextButton("Inventory".Localize(), theme)
            {
                Padding     = new BorderDouble(6, 0),
                MinimumSize = new Vector2(0, theme.ButtonHeight),
                Selectable  = false
            });

            this.AddChild(toolbar);

            var horizontalSplitter = new Splitter()
            {
                SplitterDistance   = UserSettings.Instance.LibraryViewWidth,
                SplitterSize       = theme.SplitterWidth,
                SplitterBackground = theme.SplitterBackground,
                HAnchor            = HAnchor.Stretch,
                VAnchor            = VAnchor.Stretch,
            };

            horizontalSplitter.DistanceChanged += (s, e) =>
            {
                UserSettings.Instance.LibraryViewWidth = horizontalSplitter.SplitterDistance;
            };

            this.AddChild(horizontalSplitter);

            var treeView = new HardwareTreeView(theme)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
                Width   = 300,
                Margin  = 5
            };

            treeView.NodeMouseDoubleClick += (s, e) =>
            {
                if (e is MouseEventArgs mouseEvent &&
                    s is GuiWidget clickedWidget &&
                    mouseEvent.Button == MouseButtons.Left &&
                    mouseEvent.Clicks == 2)
                {
                    if (treeView?.SelectedNode.Tag is PrinterInfo printerInfo)
                    {
                        ApplicationController.Instance.OpenPrinter(printerInfo);
                    }
                }
            };

            treeView.NodeMouseClick += (s, e) =>
            {
                if (e is MouseEventArgs mouseEvent &&
                    s is GuiWidget clickedWidget &&
                    mouseEvent.Button == MouseButtons.Right)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        var popupMenu = new PopupMenu(ApplicationController.Instance.MenuTheme);

                        var openMenuItem    = popupMenu.CreateMenuItem("Open".Localize());
                        openMenuItem.Click += (s2, e2) =>
                        {
                            if (treeView?.SelectedNode.Tag is PrinterInfo printerInfo)
                            {
                                ApplicationController.Instance.OpenPrinter(printerInfo);
                            }
                        };

                        popupMenu.CreateSeparator();

                        var deleteMenuItem    = popupMenu.CreateMenuItem("Delete".Localize());
                        deleteMenuItem.Click += (s2, e2) =>
                        {
                            if (treeView.SelectedNode.Tag is PrinterInfo printerInfo)
                            {
                                // Delete printer
                                StyledMessageBox.ShowMessageBox(
                                    (deletePrinter) =>
                                {
                                    if (deletePrinter)
                                    {
                                        ProfileManager.Instance.DeletePrinter(printerInfo.ID);
                                    }
                                },
                                    "Are you sure you want to delete printer '{0}'?".Localize().FormatWith(printerInfo.Name),
                                    "Delete Printer?".Localize(),
                                    StyledMessageBox.MessageType.YES_NO,
                                    "Delete Printer".Localize());
                            }
                        };

                        popupMenu.ShowMenu(clickedWidget, mouseEvent);
                    });
                }
            };

            treeView.ScrollArea.HAnchor = HAnchor.Stretch;

            treeView.AfterSelect += (s, e) =>
            {
                if (treeView.SelectedNode.Tag is PrinterInfo printerInfo)
                {
                    horizontalSplitter.Panel2.CloseChildren();
                    horizontalSplitter.Panel2.AddChild(new PrinterDetails(printerInfo, theme, true)
                    {
                        HAnchor = HAnchor.MaxFitOrStretch,
                        VAnchor = VAnchor.Stretch,
                        Padding = theme.DefaultContainerPadding
                    });
                }
            };
            horizontalSplitter.Panel1.AddChild(treeView);

            horizontalSplitter.Panel2.AddChild(new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
            });
        }
        public bool IsValid()
        {
            try
            {
                if (LayerHeight > NozzleDiameter)
                {
                    string error    = "'Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("Layer Height = {0}\nNozzle Diameter = {1}".Localize(), LayerHeight, NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }
                else if (FirstLayerHeight > NozzleDiameter)
                {
                    string error    = "First Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("First Layer Height = {0}\nNozzle Diameter = {1}".Localize(), FirstLayerHeight, NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FirstLayerExtrusionWidth > NozzleDiameter * 4)
                {
                    string error    = "First Layer Extrusion Width' must be less than or equal to the 'Nozzle Diameter' * 4.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}\nNozzle Diameter = {1}".Localize(), GetActiveValue("first_layer_extrusion_width"), NozzleDiameter);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FirstLayerExtrusionWidth <= 0)
                {
                    string error    = "First Layer Extrusion Width' must be greater than 0.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}".Localize(), GetActiveValue("first_layer_extrusion_width"));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (MinFanSpeed > 100)
                {
                    string error    = "The Min Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), MinFanSpeed);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling' (Advanced display)".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (MaxFanSpeed > 100)
                {
                    string error    = "The Max Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), MaxFanSpeed);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling' (Advanced display)".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (ExtruderCount < 1)
                {
                    string error    = "The Extruder Count must be at least 1.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), ExtruderCount);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Printer' -> 'Features' (Advanced display)".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (FillDensity < 0 || FillDensity > 1)
                {
                    string error    = "The Fill Density must be between 0 and 1 inclusive.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), FillDensity);
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Infill'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                string normalSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Speed'".Localize();
                // If the given speed is part of the current slice engine then check that it is greater than 0.
                if (!ValidateGoodSpeedSettingGreaterThan0("bridge_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("external_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("first_layer_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("gap_fill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("small_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("support_material_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("top_solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("travel_speed", normalSpeedLocation))
                {
                    return(false);
                }

                string retractSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Filament' -> 'Retraction'".Localize();
                if (!ValidateGoodSpeedSettingGreaterThan0("retract_speed", retractSpeedLocation))
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
                string stackTraceNoBackslashRs = e.StackTrace.Replace("\r", "");
                ContactFormWindow.Open("Parse Error while slicing".Localize(), e.Message + stackTraceNoBackslashRs);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 17
0
 void MustSelectPrinterMessage(object state)
 {
     StyledMessageBox.ShowMessageBox(null, pleaseSelectPrinterMessage, pleaseSelectPrinterTitle);
 }
Ejemplo n.º 18
0
        private void GeneratePrinterOverflowMenu(PopupMenu popupMenu, ThemeConfig theme)
        {
            var menuActions = new List <NamedAction>()
            {
                new NamedAction()
                {
                    Icon      = StaticData.Instance.LoadIcon("memory_16x16.png", 16, 16).SetToColor(theme.TextColor),
                    Title     = "Configure EEProm".Localize(),
                    Action    = configureEePromButton_Click,
                    IsEnabled = () => printer.Connection.IsConnected
                }
            };

            menuActions.Add(new NamedBoolAction()
            {
                Title       = "Show Printer".Localize(),
                Action      = () => { },
                GetIsActive = () => printer.ViewState.ConfigurePrinterVisible,
                SetIsActive = (value) => printer.ViewState.ConfigurePrinterVisible = value
            });
            var printerType = printer.Settings.Slicer.PrinterType;

            if (printerType == PrinterType.FFF)
            {
                menuActions.Add(new NamedBoolAction()
                {
                    Title       = "Show Controls".Localize(),
                    Action      = () => { },
                    GetIsActive = () => printer.ViewState.ControlsVisible,
                    SetIsActive = (value) => printer.ViewState.ControlsVisible = value,
                });
                menuActions.Add(new NamedBoolAction()
                {
                    Title       = "Show Terminal".Localize(),
                    Action      = () => { },
                    GetIsActive = () => printer.ViewState.TerminalVisible,
                    SetIsActive = (value) => printer.ViewState.TerminalVisible = value,
                });
            }
            menuActions.Add(new ActionSeparator());
            menuActions.Add(new NamedAction()
            {
                Title  = "Import Presets".Localize(),
                Action = () =>
                {
                    AggContext.FileDialogs.OpenFileDialog(
                        new OpenFileDialogParams("settings files|*.printer"),
                        (dialogParams) =>
                    {
                        if (!string.IsNullOrEmpty(dialogParams.FileName))
                        {
                            DialogWindow.Show(new ImportSettingsPage(dialogParams.FileName, printer));
                        }
                    });
                }
            });
            menuActions.Add(new NamedAction()
            {
                Title  = "Export Printer".Localize(),
                Action = () => UiThread.RunOnIdle(() =>
                {
                    ApplicationController.Instance.ExportAsMatterControlConfig(printer);
                }),
                Icon = StaticData.Instance.LoadIcon("cube_export.png", 16, 16).SetToColor(theme.TextColor),
            });
            menuActions.Add(new ActionSeparator());
            menuActions.Add(new NamedAction()
            {
                Title  = "Calibrate Printer".Localize(),
                Action = () => UiThread.RunOnIdle(() =>
                {
                    UiThread.RunOnIdle(() =>
                    {
                        DialogWindow.Show(new PrinterCalibrationWizard(printer, theme));
                    });
                }),
                Icon = StaticData.Instance.LoadIcon("compass.png", 16, 16).SetToColor(theme.TextColor)
            });
            menuActions.Add(new ActionSeparator());
            menuActions.Add(new NamedAction()
            {
                Title  = "Update Settings...".Localize(),
                Action = () =>
                {
                    DialogWindow.Show(new UpdateSettingsPage(printer));
                },
                Icon = StaticData.Instance.LoadIcon("fa-refresh_14.png", 16, 16).SetToColor(theme.TextColor)
            });
            menuActions.Add(new NamedAction()
            {
                Title  = "Restore Settings...".Localize(),
                Action = () =>
                {
                    DialogWindow.Show(new PrinterProfileHistoryPage(printer));
                }
            });
            menuActions.Add(new NamedAction()
            {
                Title  = "Reset to Defaults...".Localize(),
                Action = () =>
                {
                    StyledMessageBox.ShowMessageBox(
                        (revertSettings) =>
                    {
                        if (revertSettings)
                        {
                            printer.Settings.ClearUserOverrides();
                            printer.Settings.ResetSettingsForNewProfile();
                            // this is user driven
                            printer.Settings.Save();
                            printer.Settings.Helpers.PrintLevelingData.SampledPositions.Clear();

                            ApplicationController.Instance.ReloadAll().ConfigureAwait(false);
                        }
                    },
                        "Resetting to default values will remove your current overrides and restore your original printer settings.\nAre you sure you want to continue?".Localize(),
                        "Revert Settings".Localize(),
                        StyledMessageBox.MessageType.YES_NO);
                }
            });
            menuActions.Add(new ActionSeparator());
            menuActions.Add(new NamedAction()
            {
                Title  = "Delete Printer".Localize(),
                Action = () =>
                {
                    StyledMessageBox.ShowMessageBox(
                        (doDelete) =>
                    {
                        if (doDelete)
                        {
                            ProfileManager.Instance.DeletePrinter(printer.Settings.ID);
                        }
                    },
                        "Are you sure you want to delete printer '{0}'?".Localize().FormatWith(printer.Settings.GetValue(SettingsKey.printer_name)),
                        "Delete Printer?".Localize(),
                        StyledMessageBox.MessageType.YES_NO,
                        "Delete Printer".Localize());
                },
            });

            theme.CreateMenuItems(popupMenu, menuActions);
        }
Ejemplo n.º 19
0
        private FlowLayoutWidget GetThumbnailRenderingControl()
        {
            FlowLayoutWidget buttonRow = new FlowLayoutWidget();

            buttonRow.HAnchor = HAnchor.ParentLeftRight;
            buttonRow.Margin  = new BorderDouble(top: 4);

            TextWidget settingsLabel = new TextWidget("Thumbnail Rendering".Localize());

            settingsLabel.AutoExpandBoundsToText = true;
            settingsLabel.TextColor = ActiveTheme.Instance.PrimaryTextColor;
            settingsLabel.VAnchor   = VAnchor.ParentTop;

            FlowLayoutWidget optionsContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);

            optionsContainer.Margin = new BorderDouble(bottom: 6);

            DropDownList interfaceOptionsDropList = new DropDownList("Development", maxHeight: 200);

            interfaceOptionsDropList.HAnchor = HAnchor.ParentLeftRight;

            optionsContainer.AddChild(interfaceOptionsDropList);
            optionsContainer.Width = 200;

            interfaceOptionsDropList.AddItem("Flat".Localize(), "orthographic");
            interfaceOptionsDropList.AddItem("3D".Localize(), "raytraced");

            List <string> acceptableUpdateFeedTypeValues = new List <string>()
            {
                "orthographic", "raytraced"
            };
            string currentThumbnailRenderingMode = UserSettings.Instance.get(UserSettingsKey.ThumbnailRenderingMode);

            if (acceptableUpdateFeedTypeValues.IndexOf(currentThumbnailRenderingMode) == -1)
            {
                if (!UserSettings.Instance.IsTouchScreen)
                {
                    UserSettings.Instance.set(UserSettingsKey.ThumbnailRenderingMode, "orthographic");
                }
                else
                {
                    UserSettings.Instance.set(UserSettingsKey.ThumbnailRenderingMode, "raytraced");
                }
            }

            interfaceOptionsDropList.SelectedValue     = UserSettings.Instance.get(UserSettingsKey.ThumbnailRenderingMode);
            interfaceOptionsDropList.SelectionChanged += (sender, e) =>
            {
                string thumbnailRenderingMode = ((DropDownList)sender).SelectedValue;
                if (thumbnailRenderingMode != UserSettings.Instance.get(UserSettingsKey.ThumbnailRenderingMode))
                {
                    UserSettings.Instance.set(UserSettingsKey.ThumbnailRenderingMode, thumbnailRenderingMode);

                    // Ask if the user would like to rebuild all their thumbnails
                    Action <bool> removeThumbnails = (bool shouldRebuildThumbnails) =>
                    {
                        if (shouldRebuildThumbnails)
                        {
                            string directoryToRemove = PartThumbnailWidget.ThumbnailPath();
                            try
                            {
                                if (Directory.Exists(directoryToRemove))
                                {
                                    Directory.Delete(directoryToRemove, true);
                                }
                            }
                            catch (Exception)
                            {
                                GuiWidget.BreakInDebugger();
                            }
                        }

                        ApplicationController.Instance.ReloadAll();
                    };

                    UiThread.RunOnIdle(() =>
                    {
                        StyledMessageBox.ShowMessageBox(removeThumbnails, rebuildThumbnailsMessage, rebuildThumbnailsTitle, StyledMessageBox.MessageType.YES_NO, "Rebuild".Localize());
                    });
                }
            };

            buttonRow.AddChild(settingsLabel);
            buttonRow.AddChild(new HorizontalSpacer());
            buttonRow.AddChild(optionsContainer);
            return(buttonRow);
        }
Ejemplo n.º 20
0
        private void GeneratePrinterOverflowMenu(PopupMenu popupMenu, ThemeConfig theme)
        {
            var menuActions = new List <NamedAction>()
            {
                new NamedAction()
                {
                    Icon      = AggContext.StaticData.LoadIcon("memory_16x16.png", 16, 16, theme.InvertIcons),
                    Title     = "Configure EEProm".Localize(),
                    Action    = configureEePromButton_Click,
                    IsEnabled = () => printer.Connection.IsConnected
                },
                new NamedBoolAction()
                {
                    Title       = "Show Controls".Localize(),
                    Action      = () => { },
                    GetIsActive = () => printer.ViewState.ControlsVisible,
                    SetIsActive = (value) => printer.ViewState.ControlsVisible = value
                },
                new NamedBoolAction()
                {
                    Title       = "Show Terminal".Localize(),
                    Action      = () => { },
                    GetIsActive = () => printer.ViewState.TerminalVisible,
                    SetIsActive = (value) => printer.ViewState.TerminalVisible = value
                },
                new NamedBoolAction()
                {
                    Title       = "Configure Printer".Localize(),
                    Action      = () => { },
                    GetIsActive = () => printer.ViewState.ConfigurePrinterVisible,
                    SetIsActive = (value) => printer.ViewState.ConfigurePrinterVisible = value
                },
                new ActionSeparator(),
                new NamedAction()
                {
                    Title  = "Import Presets".Localize(),
                    Action = () =>
                    {
                        AggContext.FileDialogs.OpenFileDialog(
                            new OpenFileDialogParams("settings files|*.printer"),
                            (dialogParams) =>
                        {
                            if (!string.IsNullOrEmpty(dialogParams.FileName))
                            {
                                DialogWindow.Show(new ImportSettingsPage(dialogParams.FileName, printer));
                            }
                        });
                    }
                },
                new NamedAction()
                {
                    Title  = "Export All Settings".Localize(),
                    Action = () =>
                    {
                        printer.Settings.Helpers.ExportAsMatterControlConfig();
                    }
                },
                new ActionSeparator(),
                new NamedAction()
                {
                    Title  = "Restore Settings".Localize(),
                    Action = () =>
                    {
                        DialogWindow.Show <PrinterProfileHistoryPage>();
                    }
                },
                new NamedAction()
                {
                    Title  = "Reset to Defaults".Localize(),
                    Action = () =>
                    {
                        StyledMessageBox.ShowMessageBox(
                            (revertSettings) =>
                        {
                            if (revertSettings)
                            {
                                bool onlyReloadSliceSettings = true;
                                if (printer.Settings.GetValue <bool>(SettingsKey.print_leveling_required_to_print) &&
                                    printer.Settings.GetValue <bool>(SettingsKey.print_leveling_enabled))
                                {
                                    onlyReloadSliceSettings = false;
                                }

                                printer.Settings.ClearUserOverrides();
                                printer.Settings.Save();

                                if (onlyReloadSliceSettings)
                                {
                                    printer?.Bed.GCodeRenderer?.Clear3DGCode();
                                }
                                else
                                {
                                    ApplicationController.Instance.ReloadAll();
                                }
                            }
                        },
                            "Resetting to default values will remove your current overrides and restore your original printer settings.\nAre you sure you want to continue?".Localize(),
                            "Revert Settings".Localize(),
                            StyledMessageBox.MessageType.YES_NO);
                    }
                },
                new ActionSeparator(),
                new NamedAction()
                {
                    Title  = "Delete Printer".Localize(),
                    Action = () =>
                    {
                        StyledMessageBox.ShowMessageBox(
                            (doDelete) =>
                        {
                            if (doDelete)
                            {
                                ProfileManager.Instance.DeleteActivePrinter(true);
                            }
                        },
                            "Are you sure you want to delete your currently selected printer?".Localize(),
                            "Delete Printer?".Localize(),
                            StyledMessageBox.MessageType.YES_NO,
                            "Delete Printer".Localize());
                    }
                }
            };

            theme.CreateMenuItems(popupMenu, menuActions);
        }
        public PrinterConnectButton(PrinterConfig printer, ThemeConfig theme)
        {
            this.printer = printer;
            this.HAnchor = HAnchor.Left | HAnchor.Fit;
            this.VAnchor = VAnchor.Fit;
            this.Margin  = 0;
            this.Padding = 0;

            connectButton = new TextIconButton(
                "Connect".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                Name           = "Connect to printer button",
                ToolTipText    = "Connect to the currently selected printer".Localize(),
                MouseDownColor = theme.ToolbarButtonDown,
            };
            connectButton.Click += (s, e) =>
            {
                if (connectButton.Enabled)
                {
                    ApplicationController.Instance.ConnectToPrinter(printer);
                }
            };
            this.AddChild(connectButton);

            theme.ApplyPrimaryActionStyle(connectButton);

            // add the cancel stop button
            cancelConnectButton = new TextIconButton(
                "Cancel".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                ToolTipText     = "Stop trying to connect to the printer.".Localize(),
                BackgroundColor = theme.ToolbarButtonBackground,
                HoverColor      = theme.ToolbarButtonHover,
                MouseDownColor  = theme.ToolbarButtonDown,
            };
            cancelConnectButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                printer.CancelPrint();
                cancelConnectButton.Enabled = false;
            });
            this.AddChild(cancelConnectButton);

            disconnectButton = new TextIconButton(
                "Disconnect".Localize(),
                AggContext.StaticData.LoadIcon("connect.png", 14, 14, theme.InvertIcons),
                theme)
            {
                Name            = "Disconnect from printer button",
                Visible         = false,
                ToolTipText     = "Disconnect from current printer".Localize(),
                BackgroundColor = theme.ToolbarButtonBackground,
                HoverColor      = theme.ToolbarButtonHover,
                MouseDownColor  = theme.ToolbarButtonDown,
            };
            disconnectButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                if (printer.Connection.Printing)
                {
                    StyledMessageBox.ShowMessageBox(
                        (bool disconnectCancel) =>
                    {
                        if (disconnectCancel)
                        {
                            printer.Connection.Stop(false);
                            printer.Connection.Disable();
                        }
                    },
                        "WARNING: Disconnecting will stop the current print.\n\nAre you sure you want to disconnect?".Localize(),
                        "Disconnect and stop the current print?".Localize(),
                        StyledMessageBox.MessageType.YES_NO,
                        "Disconnect".Localize(),
                        "Stay Connected".Localize());
                }
                else
                {
                    printer.Connection.Disable();
                }
            });
            this.AddChild(disconnectButton);

            foreach (var child in Children)
            {
                child.VAnchor = VAnchor.Center;
                child.Cursor  = Cursors.Hand;
                child.Margin  = theme.ButtonSpacing;
            }

            // Register listeners
            printer.Connection.CommunicationStateChanged += Connection_CommunicationStateChanged;

            this.SetVisibleStates();
        }
Ejemplo n.º 22
0
        public HardwareTreeView(ThemeConfig theme)
            : base(theme)
        {
            rootColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit
            };
            this.AddChild(rootColumn);

            // Printers
            printersNode = new TreeNode(theme)
            {
                Text             = "Printers".Localize(),
                HAnchor          = HAnchor.Stretch,
                AlwaysExpandable = true,
                Image            = AggContext.StaticData.LoadIcon("printer.png", 16, 16, theme.InvertIcons)
            };
            printersNode.TreeView = this;

            var forcedHeight = 20;
            var mainRow      = printersNode.Children.FirstOrDefault();

            mainRow.HAnchor = HAnchor.Stretch;
            mainRow.AddChild(new HorizontalSpacer());

            // add in the create printer button
            var createPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-add-circle_18.png", 18, 18, theme.InvertIcons), theme)
            {
                Name        = "Create Printer",
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing.Clone(left: theme.ButtonSpacing.Right),
                ToolTipText = "Create Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight
            };

            createPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                if (ApplicationController.Instance.AnyPrintTaskRunning)
                {
                    StyledMessageBox.ShowMessageBox("Please wait until the print has finished and try again.".Localize(), "Can't add printers while printing".Localize());
                }
                else
                {
                    DialogWindow.Show(PrinterSetup.GetBestStartPage(PrinterSetup.StartPageOptions.ShowMakeModel));
                }
            });
            mainRow.AddChild(createPrinter);

            // add in the import printer button
            var importPrinter = new IconButton(AggContext.StaticData.LoadIcon("md-import_18.png", 18, 18, theme.InvertIcons), theme)
            {
                VAnchor     = VAnchor.Center,
                Margin      = theme.ButtonSpacing,
                ToolTipText = "Import Printer".Localize(),
                Height      = forcedHeight,
                Width       = forcedHeight,
                Name        = "Import Printer Button"
            };

            importPrinter.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                AggContext.FileDialogs.OpenFileDialog(
                    new OpenFileDialogParams(
                        "settings files|*.ini;*.printer;*.slice"),
                    (result) =>
                {
                    if (!string.IsNullOrEmpty(result.FileName) &&
                        File.Exists(result.FileName))
                    {
                        //simpleTabs.RemoveTab(simpleTabs.ActiveTab);
                        if (ProfileManager.ImportFromExisting(result.FileName))
                        {
                            string importPrinterSuccessMessage = "You have successfully imported a new printer profile. You can find '{0}' in your list of available printers.".Localize();
                            DialogWindow.Show(
                                new ImportSucceeded(
                                    importPrinterSuccessMessage.FormatWith(Path.GetFileNameWithoutExtension(result.FileName))));
                        }
                        else
                        {
                            StyledMessageBox.ShowMessageBox("Oops! Settings file '{0}' did not contain any settings we could import.".Localize().FormatWith(Path.GetFileName(result.FileName)), "Unable to Import".Localize());
                        }
                    }
                });
            });
            mainRow.AddChild(importPrinter);

            rootColumn.AddChild(printersNode);

            HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
            this.Invalidate();

            // Filament
            var materialsNode = new TreeNode(theme)
            {
                Text             = "Materials".Localize(),
                AlwaysExpandable = true,
                Image            = AggContext.StaticData.LoadIcon("filament.png", 16, 16, theme.InvertIcons)
            };

            materialsNode.TreeView = this;

            rootColumn.AddChild(materialsNode);

            // Register listeners
            PrinterSettings.AnyPrinterSettingChanged += Printer_SettingChanged;

            // Rebuild the treeview anytime the Profiles list changes
            ProfileManager.ProfilesListChanged.RegisterEvent((s, e) =>
            {
                HardwareTreeView.CreatePrinterProfilesTree(printersNode, theme);
                this.Invalidate();
            }, ref unregisterEvents);
        }
Ejemplo n.º 23
0
        public static GuiWidget PrintProgressWidget(PrinterConfig printer, ThemeConfig theme)
        {
            var bodyRow = new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Top | VAnchor.Fit,
                //BackgroundColor = new Color(theme.Colors.PrimaryBackgroundColor, 128),
                MinimumSize = new Vector2(275, 140),
            };

            // Progress section
            var expandingContainer = new HorizontalSpacer()
            {
                VAnchor = VAnchor.Fit | VAnchor.Center
            };

            bodyRow.AddChild(expandingContainer);

            var progressContainer = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                VAnchor = VAnchor.Center | VAnchor.Fit,
                HAnchor = HAnchor.Stretch,
            };

            expandingContainer.AddChild(progressContainer);

            var progressDial = new ProgressDial(theme)
            {
                HAnchor = HAnchor.Center,
                Height  = 200 * DeviceScale,
                Width   = 200 * DeviceScale
            };

            progressContainer.AddChild(progressDial);

            var bottomRow = new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit
            };

            progressContainer.AddChild(bottomRow);

            var timeContainer = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Center | HAnchor.Fit,
                Margin  = 3
            };

            bottomRow.AddChild(timeContainer);

            // we can only reslice on 64 bit, because in 64 bit we always have the gcode loaded
            if (IntPtr.Size == 8)
            {
                var resliceButton = new TextButton("Re-Slice", theme)
                {
                    HAnchor = HAnchor.Right,
                    VAnchor = VAnchor.Center,
                    Margin  = new BorderDouble(0, 0, 7, 0),
                    Name    = "Re-Slice Button"
                };
                bool activelySlicing = false;
                resliceButton.Click += (s, e) =>
                {
                    resliceButton.Enabled = false;
                    UiThread.RunOnIdle(async() =>
                    {
                        bool doSlicing = !activelySlicing && printer.Bed.EditContext.SourceItem != null;
                        if (doSlicing)
                        {
                            var errors = printer.ValidateSettings();
                            if (errors.Any(err => err.ErrorLevel == ValidationErrorLevel.Error))
                            {
                                doSlicing = false;
                                ApplicationController.Instance.ShowValidationErrors("Slicing Error".Localize(), errors);
                            }
                        }

                        if (doSlicing)
                        {
                            activelySlicing = true;
                            if (bottomRow.Name == null)
                            {
                                bottomRow.Name = printer.Bed.EditContext.GCodeFilePath(printer);
                            }

                            await ApplicationController.Instance.Tasks.Execute("Saving".Localize(), printer, printer.Bed.SaveChanges);

                            // start up a new slice on a background thread
                            await ApplicationController.Instance.SliceItemLoadOutput(
                                printer,
                                printer.Bed.Scene,
                                printer.Bed.EditContext.GCodeFilePath(printer));

                            // Switch to the 3D layer view if on Model view
                            if (printer.ViewState.ViewMode == PartViewMode.Model)
                            {
                                printer.ViewState.ViewMode = PartViewMode.Layers3D;
                            }

                            // when it is done queue it to the change to gcode stream
                            var message2 = "Would you like to switch to the new G-Code? Before you switch, check that your are seeing the changes you expect.".Localize();
                            var caption2 = "Switch to new G-Code?".Localize();
                            StyledMessageBox.ShowMessageBox(async(clickedOk2) =>
                            {
                                if (clickedOk2)
                                {
                                    if (printer.Connection != null &&
                                        (printer.Connection.Printing || printer.Connection.Paused))
                                    {
                                        printer.Connection.SwitchToGCode(printer.Bed.EditContext.GCodeFilePath(printer));
                                        bottomRow.Name = printer.Bed.EditContext.GCodeFilePath(printer);
                                    }
                                }
                                else
                                {
                                    await ApplicationController.Instance.SliceItemLoadOutput(
                                        printer,
                                        printer.Bed.Scene,
                                        bottomRow.Name);
                                }
                                activelySlicing       = false;
                                resliceButton.Enabled = true;
                            }, message2, caption2, StyledMessageBox.MessageType.YES_NO, "Switch".Localize(), "Cancel".Localize());
                        }
                        else
                        {
                            resliceButton.Enabled = true;
                        }
                    });
                };
                bottomRow.AddChild(resliceButton);
            }

            timeContainer.AddChild(new ImageWidget(AggContext.StaticData.LoadIcon("fa-clock_24.png", theme.InvertIcons))
            {
                VAnchor = VAnchor.Center
            });

            var timeWidget = new TextWidget("", pointSize: 22, textColor: theme.TextColor)
            {
                AutoExpandBoundsToText = true,
                Margin  = new BorderDouble(10, 0, 0, 0),
                VAnchor = VAnchor.Center,
            };

            timeContainer.AddChild(timeWidget);

            var runningInterval = UiThread.SetInterval(
                () =>
            {
                int secondsPrinted = printer.Connection.SecondsPrinted;
                int hoursPrinted   = (int)(secondsPrinted / (60 * 60));
                int minutesPrinted = (secondsPrinted / 60 - hoursPrinted * 60);

                secondsPrinted = secondsPrinted % 60;

                // TODO: Consider if the consistency of a common time format would look and feel better than changing formats based on elapsed duration
                timeWidget.Text = (hoursPrinted <= 0) ? $"{minutesPrinted}:{secondsPrinted:00}" : $"{hoursPrinted}:{minutesPrinted:00}:{secondsPrinted:00}";

                progressDial.LayerIndex          = printer.Connection.CurrentlyPrintingLayer;
                progressDial.LayerCompletedRatio = printer.Connection.RatioIntoCurrentLayer;
                progressDial.CompletedRatio      = printer.Connection.PercentComplete / 100;

                switch (printer.Connection.CommunicationState)
                {
                case CommunicationStates.PreparingToPrint:
                case CommunicationStates.Printing:
                case CommunicationStates.Paused:
                    bodyRow.Visible = true;
                    break;

                default:
                    bodyRow.Visible = false;
                    break;
                }
            }, 1);

            bodyRow.Closed += (s, e) => UiThread.ClearInterval(runningInterval);

            bodyRow.Visible = false;

            return(bodyRow);
        }
Ejemplo n.º 24
0
 void MustSelectPrinterMessage(object state)
 {
     StyledMessageBox.ShowMessageBox("You must select a printer before you can export printable files.", "You must select a printer");
 }
Ejemplo n.º 25
0
        public bool IsValid()
        {
            try
            {
                if (GetValue <double>(SettingsKey.layer_height) > GetValue <double>(SettingsKey.nozzle_diameter))
                {
                    string error    = "'Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("Layer Height = {0}\nNozzle Diameter = {1}".Localize(), GetValue <double>(SettingsKey.layer_height), GetValue <double>(SettingsKey.nozzle_diameter));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }
                else if (GetValue <double>(SettingsKey.first_layer_height) > GetValue <double>(SettingsKey.nozzle_diameter))
                {
                    string error    = "'First Layer Height' must be less than or equal to the 'Nozzle Diameter'.".Localize();
                    string details  = string.Format("First Layer Height = {0}\nNozzle Diameter = {1}".Localize(), GetValue <double>(SettingsKey.first_layer_height), GetValue <double>(SettingsKey.nozzle_diameter));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Layers/Surface'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                // Print recovery can only work with a manually leveled or software leveled bed. Hardware leveling does not work.
                if (GetValue <bool>(SettingsKey.recover_is_enabled))
                {
                    string   location   = "Location: 'Settings & Controls' -> 'Settings' -> 'Printer' -> 'Print Recovery' -> 'Enable Recovery'".Localize();
                    string[] startGCode = GetValue("start_gcode").Replace("\\n", "\n").Split('\n');
                    foreach (string startGCodeLine in startGCode)
                    {
                        if (startGCodeLine.StartsWith("G29"))
                        {
                            string error   = "Start G-Code cannot contain G29 if Print Recovery is enabled.".Localize();
                            string details = "Your Start G-Code should not contain a G29 if you are planning on using Print Recovery. Change your start G-Code or turn off Print Recovery".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }

                        if (startGCodeLine.StartsWith("G30"))
                        {
                            string error   = "Start G-Code cannot contain G30 if Print Leveling is enabled.".Localize();
                            string details = "Your Start G-Code should not contain a G30 if you are planning on using Print Recovery. Change your start G-Code or turn off Print Recovery".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }
                    }
                }

                // If we have print leveling turned on then make sure we don't have any leveling commands in the start gcode.
                if (GetValue <bool>(SettingsKey.print_leveling_enabled))
                {
                    string   location   = "Location: 'Settings & Controls' -> 'Settings' -> 'Printer' -> 'Custom G-Code' -> 'Start G-Code'".Localize();
                    string[] startGCode = GetValue("start_gcode").Replace("\\n", "\n").Split('\n');
                    foreach (string startGCodeLine in startGCode)
                    {
                        if (startGCodeLine.StartsWith("G29"))
                        {
                            string error   = "Start G-Code cannot contain G29 if Print Leveling is enabled.".Localize();
                            string details = "Your Start G-Code should not contain a G29 if you are planning on using print leveling. Change your start G-Code or turn off print leveling".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }

                        if (startGCodeLine.StartsWith("G30"))
                        {
                            string error   = "Start G-Code cannot contain G30 if Print Leveling is enabled.".Localize();
                            string details = "Your Start G-Code should not contain a G30 if you are planning on using print leveling. Change your start G-Code or turn off print leveling".Localize();
                            StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                            return(false);
                        }
                    }
                }

                if (GetValue <double>(SettingsKey.first_layer_extrusion_width) > GetValue <double>(SettingsKey.nozzle_diameter) * 4)
                {
                    string error    = "'First Layer Extrusion Width' must be less than or equal to the 'Nozzle Diameter' * 4.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}\nNozzle Diameter = {1}".Localize(), GetValue(SettingsKey.first_layer_extrusion_width), GetValue <double>(SettingsKey.nozzle_diameter));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <double>(SettingsKey.first_layer_extrusion_width) <= 0)
                {
                    string error    = "'First Layer Extrusion Width' must be greater than 0.".Localize();
                    string details  = string.Format("First Layer Extrusion Width = {0}".Localize(), GetValue(SettingsKey.first_layer_extrusion_width));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Extrusion' -> 'First Layer'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <double>(SettingsKey.min_fan_speed) > 100)
                {
                    string error    = "The Minimum Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetValue <double>(SettingsKey.min_fan_speed));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <double>("max_fan_speed") > 100)
                {
                    string error    = "The Maximum Fan Speed can only go as high as 100%.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetValue <double>("max_fan_speed"));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Cooling'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <int>(SettingsKey.extruder_count) < 1)
                {
                    string error    = "The Extruder Count must be at least 1.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetValue <int>(SettingsKey.extruder_count));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'Printer' -> 'Features'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <double>(SettingsKey.fill_density) < 0 || GetValue <double>(SettingsKey.fill_density) > 1)
                {
                    string error    = "The Fill Density must be between 0 and 1.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetValue <double>(SettingsKey.fill_density));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Infill'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(false);
                }

                if (GetValue <double>(SettingsKey.fill_density) == 1 &&
                    GetValue("infill_type") != "LINES")
                {
                    string error    = "Solid Infill works best when set to LINES.".Localize();
                    string details  = string.Format("It is currently set to {0}.".Localize(), GetValue("infill_type"));
                    string location = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Infill Type'".Localize();
                    StyledMessageBox.ShowMessageBox(null, string.Format("{0}\n\n{1}\n\n{2}", error, details, location), "Slice Error".Localize());
                    return(true);
                }


                string normalSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'General' -> 'Speed'".Localize();
                // If the given speed is part of the current slice engine then check that it is greater than 0.
                if (!ValidateGoodSpeedSettingGreaterThan0("bridge_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("external_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("first_layer_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("gap_fill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("small_perimeter_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("support_material_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("top_solid_infill_speed", normalSpeedLocation))
                {
                    return(false);
                }
                if (!ValidateGoodSpeedSettingGreaterThan0("travel_speed", normalSpeedLocation))
                {
                    return(false);
                }

                string retractSpeedLocation = "Location: 'Settings & Controls' -> 'Settings' -> 'Filament' -> 'Filament' -> 'Retraction'".Localize();
                if (!ValidateGoodSpeedSettingGreaterThan0("retract_speed", retractSpeedLocation))
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
                string stackTraceNoBackslashRs = e.StackTrace.Replace("\r", "");
                ContactFormWindow.Open("Parse Error while slicing".Localize(), e.Message + stackTraceNoBackslashRs);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 26
0
        private void Initialize()
        {
            CLAPI  instance = CLAPI.GetInstance();
            string path     = FLScriptEditor.Settings.KernelPath;

            StartupSequence.loaderForm.SetStatus("Discovering Files in Path: " + path);
            string[] files = IOManager.DirectoryExists(path) ? IOManager.GetFiles(path, "*.cl") : new string[0];

            if (files.Length == 0)
            {
                DialogResult res = StyledMessageBox.Show(
                    "Error",
                    "No Files found at path: " + path,
                    MessageBoxButtons.AbortRetryIgnore,
                    SystemIcons.Error
                    );
                if (res == DialogResult.Retry)
                {
                    Initialize();
                    return;
                }

                if (res == DialogResult.Abort)
                {
                    StartupSequence.loaderForm.DialogResult = DialogResult.Abort;
                    StartupSequence.loaderForm.Close();
                    return;
                }

                if (res == DialogResult.Ignore)
                {
                    StartupSequence.loaderForm.DialogResult = DialogResult.OK;
                }
            }

            KernelDatabase dataBase             = new KernelDatabase(DataVectorTypes.Uchar1);
            List <CLProgramBuildResult> results = new List <CLProgramBuildResult>();
            bool throwEx     = false;
            int  kernelCount = 0;
            int  fileCount   = 0;

            if (FLScriptEditor.Settings.ExperimentalKernelLoading)
            {
                try
                {
                    string    source = TextProcessorAPI.PreprocessSource(files, new Dictionary <string, bool>());
                    CLProgram prog   = dataBase.AddProgram(instance, source, "./", false, out CLProgramBuildResult res);
                    throwEx |= !res;
                    if (res)
                    {
                        kernelCount += prog.ContainedKernels.Count;
                    }

                    results.Add(res);
                    StartupSequence.loaderForm.SetStatus($"File Loaded(Kernels Loaded): ({kernelCount})");
                }
                catch (Exception e)
                {
                    throw new SoftException(e);
                }
            }
            else
            {
                foreach (string file in files)
                {
                    StartupSequence.loaderForm.SetStatus(
                        $"[{fileCount}/{files.Length}]Loading: {file} ({kernelCount})"
                        );
                    try
                    {
                        CLProgram prog = dataBase.AddProgram(instance, file, false, out CLProgramBuildResult res);
                        kernelCount += prog.ContainedKernels.Count;
                        throwEx     |= !res;
                        results.Add(res);
                    }
                    catch (Exception e)
                    {
                        StartupSequence.loaderForm.Log("ERROR: " + e.Message, Color.Red);

                        throw e; //Let the Exception Viewer Catch that
                    }

                    fileCount++;
                }
            }


            StartupSequence.loaderForm.SetStatus("Loading Finished");
            StartupSequence.loaderForm.Log("Loading Finished", Color.White);
            StartupSequence.loaderForm.Log("Kernels Loaded: " + kernelCount, Color.White);

            if (throwEx)
            {
                DialogResult res =
                    StyledMessageBox.Show(
                        "OpenCL Build Errors",
                        "There are errors in one or more OpenCL kernels. Do you want to open the OpenCL Build Excepion Viewer?",
                        MessageBoxButtons.YesNoCancel,
                        SystemIcons.Warning
                        );
                if (res == DialogResult.Cancel)
                {
                    StartupSequence.loaderForm.DialogResult = DialogResult.Abort;
                    StartupSequence.loaderForm.Close();
                }
                else if (res == DialogResult.Yes)
                {
                    BuildExceptionViewer bvr = new BuildExceptionViewer(new CLBuildException(results));
                    if (bvr.ShowDialog() == DialogResult.Retry)
                    {
                        dataBase.Dispose();
                        Initialize();
                    }
                }
            }

            FLInstructionSet iset    = FLInstructionSet.CreateWithBuiltInTypes(dataBase);
            BufferCreator    creator = BufferCreator.CreateWithBuiltInTypes();
            FLParser         parser  = new FLParser(iset, creator, new WorkItemRunnerSettings(true, 2));

            StartupSequence.FlContainer = new FLDataContainer(instance, iset, creator, parser);
        }