public MacroDetailPage(GCodeMacro gcodeMacro, PrinterSettings printerSettings)
        {
            // Form validation fields
            MHTextEditWidget macroNameInput;
            MHTextEditWidget macroCommandInput;
            TextWidget       macroCommandError;
            TextWidget       macroNameError;

            this.HeaderText      = "Edit Macro".Localize();
            this.printerSettings = printerSettings;

            var elementMargin = new BorderDouble(top: 3);

            contentRow.Padding += 3;

            contentRow.AddChild(new TextWidget("Macro Name".Localize() + ":", 0, 0, 12)
            {
                TextColor = theme.Colors.PrimaryTextColor,
                HAnchor   = HAnchor.Stretch,
                Margin    = new BorderDouble(0, 0, 0, 1)
            });

            contentRow.AddChild(macroNameInput = new MHTextEditWidget(GCodeMacro.FixMacroName(gcodeMacro.Name))
            {
                HAnchor = HAnchor.Stretch
            });

            contentRow.AddChild(macroNameError = new TextWidget("Give the macro a name".Localize() + ".", 0, 0, 10)
            {
                TextColor = theme.Colors.PrimaryTextColor,
                HAnchor   = HAnchor.Stretch,
                Margin    = elementMargin
            });

            contentRow.AddChild(new TextWidget("Macro Commands".Localize() + ":", 0, 0, 12)
            {
                TextColor = theme.Colors.PrimaryTextColor,
                HAnchor   = HAnchor.Stretch,
                Margin    = new BorderDouble(0, 0, 0, 1)
            });

            macroCommandInput = new MHTextEditWidget(gcodeMacro.GCode, pixelHeight: 120, multiLine: true, typeFace: ApplicationController.GetTypeFace(NamedTypeFace.Liberation_Mono))
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch
            };
            macroCommandInput.ActualTextEditWidget.VAnchor = VAnchor.Stretch;
            macroCommandInput.DrawFromHintedCache();
            contentRow.AddChild(macroCommandInput);

            contentRow.AddChild(macroCommandError = new TextWidget("This should be in 'G-Code'".Localize() + ".", 0, 0, 10)
            {
                TextColor = theme.Colors.PrimaryTextColor,
                HAnchor   = HAnchor.Stretch,
                Margin    = elementMargin
            });

            var container = new FlowLayoutWidget
            {
                Margin  = new BorderDouble(0, 5),
                HAnchor = HAnchor.Stretch
            };

            contentRow.AddChild(container);

            var addMacroButton = theme.CreateDialogButton("Save".Localize());

            addMacroButton.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    if (ValidateMacroForm())
                    {
                        // SaveActiveMacro
                        gcodeMacro.Name  = macroNameInput.Text;
                        gcodeMacro.GCode = macroCommandInput.Text;

                        if (!printerSettings.Macros.Contains(gcodeMacro))
                        {
                            printerSettings.Macros.Add(gcodeMacro);
                            printerSettings.Save();
                        }

                        this.DialogWindow.ChangeToPage(new MacroListPage(printerSettings));
                    }
                });
            };

            this.AddPageAction(addMacroButton);

            // Define field validation
            var validationMethods        = new ValidationMethods();
            var stringValidationHandlers = new FormField.ValidationHandler[] { validationMethods.StringIsNotEmpty };

            formFields = new List <FormField>
            {
                new FormField(macroNameInput, macroNameError, stringValidationHandlers),
                new FormField(macroCommandInput, macroCommandError, stringValidationHandlers)
            };
        }
 public string CachePath(string cacheId, int width, int height)
 {
     return(ApplicationController.CacheablePath(
                Path.Combine("Thumbnails", "Content"),
                $"{cacheId}-{width}x{height}.png"));
 }
        private static PopupMenu CreatePopupMenu()
        {
            var menuTheme = ApplicationController.Instance.MenuTheme;

            var popupMenu = new PopupMenu(menuTheme)
            {
                MinimumSize = new Vector2(300, 0)
            };

            var linkIcon = StaticData.Instance.LoadIcon("fa-link_16.png", 16, 16, menuTheme.InvertIcons);

            PopupMenu.MenuItem menuItem;

            menuItem        = popupMenu.CreateMenuItem("Help".Localize(), StaticData.Instance.LoadIcon("help_page.png", 16, 16, menuTheme.InvertIcons));
            menuItem.Click += (s, e) => ApplicationController.Instance.ShowApplicationHelp("Docs");

            menuItem        = popupMenu.CreateMenuItem("Interface Tour".Localize(), StaticData.Instance.LoadIcon("tour.png", 16, 16, menuTheme.InvertIcons));
            menuItem.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    DialogWindow.Show <Tour.WelcomePage>();
                });
            };

            if (Application.EnableNetworkTraffic)
            {
                popupMenu.CreateSeparator();

                menuItem        = popupMenu.CreateMenuItem("Check For Update".Localize(), StaticData.Instance.LoadIcon("update.png", 16, 16, menuTheme.InvertIcons));
                menuItem.Click += (s, e) => UiThread.RunOnIdle(() =>
                {
                    UpdateControlData.Instance.CheckForUpdate();
                    DialogWindow.Show <CheckForUpdatesPage>();
                });
            }

            popupMenu.CreateSeparator();

            menuItem        = popupMenu.CreateMenuItem("Settings".Localize(), StaticData.Instance.LoadIcon("fa-cog_16.png", 16, 16, menuTheme.InvertIcons));
            menuItem.Click += (s, e) => DialogWindow.Show <ApplicationSettingsPage>();
            menuItem.Name   = "Settings MenuItem";

            popupMenu.CreateSeparator();

            ImageBuffer indicatorIcon = null;

            if (IntPtr.Size == 8)
            {
                indicatorIcon = StaticData.Instance.LoadIcon("x64.png", 16, 16, menuTheme.InvertIcons);
            }

            popupMenu.CreateSubMenu("Community".Localize(), menuTheme, (modifyMenu) =>
            {
                menuItem        = modifyMenu.CreateMenuItem("Forums".Localize(), linkIcon);
                menuItem.Click += (s, e) => ApplicationController.LaunchBrowser("https://forums.matterhackers.com/category/20/mattercontrol");

                menuItem        = modifyMenu.CreateMenuItem("Guides and Articles".Localize(), linkIcon);
                menuItem.Click += (s, e) => ApplicationController.LaunchBrowser("https://www.matterhackers.com/topic/mattercontrol");

                menuItem        = modifyMenu.CreateMenuItem("Support".Localize(), linkIcon);
                menuItem.Click += (s, e) => ApplicationController.LaunchBrowser("https://www.matterhackers.com/mattercontrol/support");

                menuItem        = modifyMenu.CreateMenuItem("Release Notes".Localize(), linkIcon);
                menuItem.Click += (s, e) => ApplicationController.LaunchBrowser("https://www.matterhackers.com/mattercontrol/support/release-notes");

                modifyMenu.CreateSeparator();

                menuItem        = modifyMenu.CreateMenuItem("Report a Bug".Localize(), StaticData.Instance.LoadIcon("feedback.png", 16, 16, menuTheme.InvertIcons));
                menuItem.Click += (s, e) => ApplicationController.LaunchBrowser("https://github.com/MatterHackers/MatterControl/issues");
            }, StaticData.Instance.LoadIcon("feedback.png", 16, 16, menuTheme.InvertIcons));

            popupMenu.CreateSeparator();

            var imageBuffer = new ImageBuffer(18, 18);

            // x64 indicator icon
            if (IntPtr.Size == 8)
            {
                var graphics = imageBuffer.NewGraphics2D();
                graphics.Clear(menuTheme.BackgroundColor);
                graphics.Rectangle(imageBuffer.GetBoundingRect(), menuTheme.PrimaryAccentColor);
                graphics.DrawString("64", imageBuffer.Width / 2, imageBuffer.Height / 2, 8, Agg.Font.Justification.Center, Agg.Font.Baseline.BoundsCenter, color: menuTheme.PrimaryAccentColor);
            }

            menuItem        = popupMenu.CreateMenuItem("About".Localize() + " MatterControl", imageBuffer);
            menuItem.Click += (s, e) => ApplicationController.Instance.ShowAboutPage();
            return(popupMenu);
        }
Example #4
0
        /// <summary>
        /// Download an image from the web into the specified ImageSequence
        /// </summary>
        /// <param name="uri"></param>
        public static void RetrieveImageSquenceAsync(ImageSequence imageSequenceToLoadInto,
                                                     string uriToLoad,
                                                     Action doneLoading = null)
        {
            var asyncImageSequence = new ImageSequence();

            var longHash    = uriToLoad.GetLongHashCode();
            var pngFileName = ApplicationController.CacheablePath("Images", longHash.ToString() + ".png");
            var gifFileName = ApplicationController.CacheablePath("Images", longHash.ToString() + ".gif");

            if (File.Exists(pngFileName))
            {
                try
                {
                    Task.Run(() =>
                    {
                        AggContext.StaticData.LoadImageSequenceData(new StreamReader(pngFileName).BaseStream, asyncImageSequence);
                        UiThread.RunOnIdle(() =>
                        {
                            imageSequenceToLoadInto.Copy(asyncImageSequence);
                            imageSequenceToLoadInto.Invalidate();
                            doneLoading?.Invoke();
                        });
                    });

                    return;
                }
                catch
                {
                }
            }
            else if (File.Exists(gifFileName))
            {
                Task.Run(() =>
                {
                    try
                    {
                        AggContext.StaticData.LoadImageSequenceData(new StreamReader(gifFileName).BaseStream, asyncImageSequence);
                        if (asyncImageSequence.NumFrames > 0)
                        {
                            UiThread.RunOnIdle(() =>
                            {
                                imageSequenceToLoadInto.Copy(asyncImageSequence);
                                imageSequenceToLoadInto.Invalidate();
                                doneLoading?.Invoke();
                            });
                        }
                        else
                        {
                            DownloadImageAsync(imageSequenceToLoadInto, uriToLoad, doneLoading, asyncImageSequence, pngFileName, gifFileName);
                        }
                    }
                    catch
                    {
                        DownloadImageAsync(imageSequenceToLoadInto, uriToLoad, doneLoading, asyncImageSequence, pngFileName, gifFileName);
                    }
                });

                return;
            }

            DownloadImageAsync(imageSequenceToLoadInto, uriToLoad, doneLoading, asyncImageSequence, pngFileName, gifFileName);
        }
        private void AddGeneralPannel(GuiWidget settingsColumn)
        {
            var generalPanel = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
            };

            var configureIcon = StaticData.Instance.LoadIcon("fa-cog_16.png", 16, 16).SetToColor(theme.TextColor);

            var generalSection = new SectionWidget("General".Localize(), generalPanel, theme, expandingContent: false)
            {
                Name    = "General Section",
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
            };

            settingsColumn.AddChild(generalSection);

            theme.ApplyBoxStyle(generalSection);

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

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

            var printer = ApplicationController.Instance.ActivePrinters.FirstOrDefault();

            // TODO: Sort out how handle this better on Android and in a multi-printer setup
            if (printer != null)
            {
                this.AddSettingsRow(
                    new SettingsItem(
                        "Camera Monitoring".Localize(),
                        theme,
                        new SettingsItem.ToggleSwitchConfig()
                {
                    Checked      = printer.Settings.GetValue <bool>(SettingsKey.publish_bed_image),
                    ToggleAction = (itemChecked) =>
                    {
                        printer.Settings.SetValue(SettingsKey.publish_bed_image, itemChecked ? "1" : "0");
                    }
                },
                        previewButton,
                        StaticData.Instance.LoadIcon("camera-24x24.png", 24, 24))
                {
                    Enabled = printer.Settings.PrinterSelected
                },
                    generalPanel
                    );
            }
#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 (ApplicationController.ChangeToPrintNotification != null)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        ApplicationController.ChangeToPrintNotification(this.DialogWindow);
                    });
                }
            };

            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,
                    StaticData.Instance.LoadIcon("notify-24x24.png", 16, 16).SetToColor(theme.TextColor)),
                generalPanel);

            // 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")
                        {
#if DEBUG
                            AppContext.Platform.GenerateLocalizationValidationFile();
#endif
                        }

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

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

#if !__ANDROID__
            // ThumbnailRendering
            var thumbnailsModeDropList = new MHDropDownList("", theme, maxHeight: 200 * GuiWidget.DeviceScale);
            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[] thumbnails = new string[]
                                {
                                    ApplicationController.CacheablePath(
                                        Path.Combine("Thumbnails", "Content"), ""),
                                    ApplicationController.CacheablePath(
                                        Path.Combine("Thumbnails", "Library"), "")
                                };
                                foreach (var directoryToRemove in thumbnails)
                                {
                                    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),
                generalPanel);
#endif

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

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

            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) => UiThread.RunOnIdle(() =>
            {
                GuiWidget.DeviceScale = textSizeSlider.Value;
                ApplicationController.Instance.ReloadAll().ConfigureAwait(false);
            });
            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 != currentTextSize;
            };

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

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

            this.AddSettingsRow(textSizeRow, generalPanel);

            var themeSection = CreateThemePanel(theme);
            settingsColumn.AddChild(themeSection);
            theme.ApplyBoxStyle(themeSection);
        }
Example #6
0
        public TerminalWidget(PrinterConfig printer, ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.printer = printer;
            this.Name    = "TerminalWidget";
            this.Padding = new BorderDouble(5, 0);

            // Header
            var headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight)
            {
                HAnchor = HAnchor.Left | HAnchor.Stretch,
                Padding = new BorderDouble(0, 8)
            };

            this.AddChild(headerRow);

            headerRow.AddChild(CreateVisibilityOptions(theme));

            autoUppercase = new CheckBox("Auto Uppercase".Localize(), textSize: theme.DefaultFontSize)
            {
                Margin    = new BorderDouble(left: 25),
                Checked   = UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalAutoUppercase, true),
                TextColor = theme.TextColor,
                VAnchor   = VAnchor.Center
            };
            autoUppercase.CheckedStateChanged += (s, e) =>
            {
                UserSettings.Instance.Fields.SetBool(UserSettingsKey.TerminalAutoUppercase, autoUppercase.Checked);
            };
            headerRow.AddChild(autoUppercase);

            // Body
            var bodyRow = new FlowLayoutWidget()
            {
                Margin  = new BorderDouble(bottom: 4),
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch
            };

            this.AddChild(bodyRow);

            textScrollWidget = new TextScrollWidget(printer, printer.Connection.TerminalLog)
            {
                BackgroundColor = theme.MinimalShade,
                TextColor       = theme.TextColor,
                HAnchor         = HAnchor.Stretch,
                VAnchor         = VAnchor.Stretch,
                Margin          = 0,
                Padding         = new BorderDouble(3, 0)
            };
            bodyRow.AddChild(textScrollWidget);
            bodyRow.AddChild(new TextScrollBar(textScrollWidget, 15)
            {
                ThumbColor      = theme.AccentMimimalOverlay,
                BackgroundColor = theme.SlightShade,
                Margin          = 0
            });

            textScrollWidget.LineFilterFunction = lineData =>
            {
                var line       = lineData.Line;
                var output     = lineData.Direction == TerminalLine.MessageDirection.ToPrinter;
                var outputLine = line;

                var lineWithoutChecksum = GCodeFile.GetLineWithoutChecksum(line);

                // and set this as the output if desired
                if (output &&
                    !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowChecksum, true))
                {
                    outputLine = lineWithoutChecksum;
                }

                if (!output &&
                    lineWithoutChecksum == "ok" &&
                    !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowOks, true))
                {
                    return(null);
                }
                else if (output &&
                         lineWithoutChecksum.StartsWith("M105") &&
                         !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowTempRequests, true))
                {
                    return(null);
                }
                else if (output &&
                         (lineWithoutChecksum.StartsWith("G0 ") || lineWithoutChecksum.StartsWith("G1 ")) &&
                         !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowMovementRequests, true))
                {
                    return(null);
                }
                else if (!output &&
                         (lineWithoutChecksum.StartsWith("T") || lineWithoutChecksum.StartsWith("ok T")) &&
                         !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowTempResponse, true))
                {
                    return(null);
                }
                else if (!output &&
                         lineWithoutChecksum == "wait" &&
                         !UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowWaitResponse, false))
                {
                    return(null);
                }

                if (UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalShowInputOutputMarks, true))
                {
                    switch (lineData.Direction)
                    {
                    case TerminalLine.MessageDirection.FromPrinter:
                        outputLine = "→ " + outputLine;
                        break;

                    case TerminalLine.MessageDirection.ToPrinter:
                        outputLine = "← " + outputLine;
                        break;

                    case TerminalLine.MessageDirection.ToTerminal:
                        outputLine = "* " + outputLine;
                        break;
                    }
                }

                return(outputLine);
            };

            // Input Row
            var inputRow = new FlowLayoutWidget(FlowDirection.LeftToRight)
            {
                BackgroundColor = this.BackgroundColor,
                HAnchor         = HAnchor.Stretch,
                Margin          = new BorderDouble(bottom: 2)
            };

            this.AddChild(inputRow);

            manualCommandTextEdit = new MHTextEditWidget("", theme, typeFace: ApplicationController.GetTypeFace(NamedTypeFace.Liberation_Mono))
            {
                Margin  = new BorderDouble(right: 3),
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Bottom
            };
            manualCommandTextEdit.ActualTextEditWidget.EnterPressed += (s, e) =>
            {
                SendManualCommand();
            };
            manualCommandTextEdit.ActualTextEditWidget.KeyDown += (s, keyEvent) =>
            {
                bool changeToHistory = false;
                if (keyEvent.KeyCode == Keys.Up)
                {
                    commandHistoryIndex--;
                    if (commandHistoryIndex < 0)
                    {
                        commandHistoryIndex = 0;
                    }

                    changeToHistory = true;
                }
                else if (keyEvent.KeyCode == Keys.Down)
                {
                    commandHistoryIndex++;
                    if (commandHistoryIndex > commandHistory.Count - 1)
                    {
                        commandHistoryIndex = commandHistory.Count - 1;
                    }
                    else
                    {
                        changeToHistory = true;
                    }
                }
                else if (keyEvent.KeyCode == Keys.Escape)
                {
                    manualCommandTextEdit.Text = "";
                }

                if (changeToHistory && commandHistory.Count > 0)
                {
                    manualCommandTextEdit.Text = commandHistory[commandHistoryIndex];
                }
            };
            inputRow.AddChild(manualCommandTextEdit);

            // Footer
            var toolbarPadding = theme.ToolbarPadding;
            var footerRow      = new FlowLayoutWidget
            {
                HAnchor = HAnchor.Stretch,
                Padding = new BorderDouble(0, toolbarPadding.Bottom, toolbarPadding.Right, toolbarPadding.Top)
            };

            this.AddChild(footerRow);

            var sendButton = theme.CreateDialogButton("Send".Localize());

            sendButton.Margin = theme.ButtonSpacing;
            sendButton.Click += (s, e) =>
            {
                SendManualCommand();
            };
            footerRow.AddChild(sendButton);

            var clearButton = theme.CreateDialogButton("Clear".Localize());

            clearButton.Margin = theme.ButtonSpacing;
            clearButton.Click += (s, e) =>
            {
                printer.Connection.TerminalLog.Clear();
            };

            footerRow.AddChild(clearButton);

            var exportButton = theme.CreateDialogButton("Export".Localize());

            exportButton.Margin = theme.ButtonSpacing;
            exportButton.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    AggContext.FileDialogs.SaveFileDialog(
                        new SaveFileDialogParams("Save as Text|*.txt")
                    {
                        Title             = "MatterControl: Terminal Log",
                        ActionButtonLabel = "Export",
                        FileName          = "print_log.txt"
                    },
                        (saveParams) =>
                    {
                        if (!string.IsNullOrEmpty(saveParams.FileName))
                        {
                            string filePathToSave = saveParams.FileName;

                            if (filePathToSave != null && filePathToSave != "")
                            {
                                try
                                {
                                    textScrollWidget.WriteToFile(filePathToSave);
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    Debug.Print(ex.Message);

                                    printer.Connection.TerminalLog.WriteLine("");
                                    printer.Connection.TerminalLog.WriteLine("WARNING: Write Failed!".Localize());
                                    printer.Connection.TerminalLog.WriteLine("Can't access".Localize() + " " + filePathToSave);
                                    printer.Connection.TerminalLog.WriteLine("");

                                    UiThread.RunOnIdle(() =>
                                    {
                                        StyledMessageBox.ShowMessageBox(ex.Message, "Couldn't save file".Localize());
                                    });
                                }
                            }
                        }
                    });
                });
            };
            footerRow.AddChild(exportButton);

            footerRow.AddChild(new HorizontalSpacer());

            this.AnchorAll();
        }
Example #7
0
        public static SystemWindow LoadRootWindow(int width, int height)
        {
            timer = Stopwatch.StartNew();

            if (false)
            {
                // set the default font
                AggContext.DefaultFont           = ApplicationController.GetTypeFace(NamedTypeFace.Nunito_Regular);
                AggContext.DefaultFontBold       = ApplicationController.GetTypeFace(NamedTypeFace.Nunito_Bold);
                AggContext.DefaultFontItalic     = ApplicationController.GetTypeFace(NamedTypeFace.Nunito_Italic);
                AggContext.DefaultFontBoldItalic = ApplicationController.GetTypeFace(NamedTypeFace.Nunito_Bold_Italic);
            }

            var systemWindow = new RootSystemWindow(width, height);

            var overlay = new GuiWidget()
            {
                BackgroundColor = AppContext.Theme.BackgroundColor,
            };

            overlay.AnchorAll();

            systemWindow.AddChild(overlay);

            var mutedAccentColor = AppContext.Theme.SplashAccentColor;

            var spinner = new LogoSpinner(overlay, rotateX: -0.05)
            {
                MeshColor = mutedAccentColor
            };

            progressPanel = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                Position    = new Vector2(0, height * .25),
                HAnchor     = HAnchor.Center | HAnchor.Fit,
                VAnchor     = VAnchor.Fit,
                MinimumSize = new Vector2(400, 100),
                Margin      = new BorderDouble(0, 0, 0, 200)
            };
            overlay.AddChild(progressPanel);

            progressPanel.AddChild(statusText = new TextWidget("", textColor: AppContext.Theme.TextColor)
            {
                MinimumSize            = new Vector2(200, 30),
                HAnchor                = HAnchor.Center,
                AutoExpandBoundsToText = true
            });

            progressPanel.AddChild(progressBar = new ProgressBar()
            {
                FillColor   = mutedAccentColor,
                BorderColor = Color.Gray,                 // theme.BorderColor75,
                Height      = 11,
                Width       = 230,
                HAnchor     = HAnchor.Center,
                VAnchor     = VAnchor.Absolute
            });

            AppContext.RootSystemWindow = systemWindow;

            // hook up a keyboard watcher to rout keys when not handled by children

            systemWindow.KeyPressed += SystemWindow_KeyPressed;

            systemWindow.KeyDown += (s, keyEvent) =>
            {
                var view3D            = systemWindow.Descendants <View3DWidget>().Where((v) => v.ActuallyVisibleOnScreen()).FirstOrDefault();
                var printerTabPage    = systemWindow.Descendants <PrinterTabPage>().Where((v) => v.ActuallyVisibleOnScreen()).FirstOrDefault();
                var offsetDist        = 50;
                var arrowKeyOperation = keyEvent.Shift ? TrackBallTransformType.Translation : TrackBallTransformType.Rotation;

                var gcode2D = systemWindow.Descendants <GCode2DWidget>().Where((v) => v.ActuallyVisibleOnScreen()).FirstOrDefault();

                if (keyEvent.KeyCode == Keys.F1)
                {
                    ApplicationController.Instance.ActivateHelpTab();
                }

                if (EnableF5Collect &&
                    keyEvent.KeyCode == Keys.F5)
                {
                    GC.Collect();
                    systemWindow.Invalidate();
                }

                if (!keyEvent.Handled &&
                    gcode2D != null)
                {
                    switch (keyEvent.KeyCode)
                    {
                    case Keys.Oemplus:
                    case Keys.Add:
                        if (keyEvent.Control)
                        {
                            // Zoom out
                            gcode2D.Zoom(1.2);
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.OemMinus:
                    case Keys.Subtract:
                        if (keyEvent.Control)
                        {
                            // Zoom in
                            gcode2D.Zoom(.8);
                            keyEvent.Handled = true;
                        }

                        break;
                    }
                }

                if (!keyEvent.Handled &&
                    view3D != null)
                {
                    switch (keyEvent.KeyCode)
                    {
                    case Keys.C:
                        if (keyEvent.Control)
                        {
                            view3D.Scene.Copy();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.P:
                        if (keyEvent.Control)
                        {
                            view3D.PushToPrinterAndPrint();
                        }

                        break;

                    case Keys.X:
                        if (keyEvent.Control)
                        {
                            view3D.Scene.Cut();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.Y:
                        if (keyEvent.Control)
                        {
                            view3D.Scene.UndoBuffer.Redo();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.A:
                        if (keyEvent.Control)
                        {
                            view3D.SelectAll();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.S:
                        if (keyEvent.Control)
                        {
                            view3D.Save();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.V:
                        if (keyEvent.Control)
                        {
                            view3D.sceneContext.Paste();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.Oemplus:
                    case Keys.Add:
                        if (keyEvent.Control)
                        {
                            // Zoom out
                            Offset3DView(view3D, new Vector2(0, offsetDist), TrackBallTransformType.Scale);
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.OemMinus:
                    case Keys.Subtract:
                        if (keyEvent.Control)
                        {
                            // Zoom in
                            Offset3DView(view3D, new Vector2(0, -offsetDist), TrackBallTransformType.Scale);
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.Z:
                        if (keyEvent.Control)
                        {
                            if (keyEvent.Shift)
                            {
                                view3D.Scene.Redo();
                            }
                            else
                            {
                                // undo last operation
                                view3D.Scene.Undo();
                            }

                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.Insert:
                        if (keyEvent.Shift)
                        {
                            view3D.sceneContext.Paste();
                            keyEvent.Handled = true;
                        }

                        break;

                    case Keys.Delete:
                    case Keys.Back:
                        view3D.Scene.DeleteSelection();
                        keyEvent.Handled          = true;
                        keyEvent.SuppressKeyPress = true;
                        break;

                    case Keys.Escape:
                        if (view3D.CurrentSelectInfo.DownOnPart)
                        {
                            view3D.CurrentSelectInfo.DownOnPart = false;

                            view3D.Scene.SelectedItem.Matrix = view3D.TransformOnMouseDown;

                            keyEvent.Handled          = true;
                            keyEvent.SuppressKeyPress = true;
                        }

                        foreach (var interactionVolume in view3D.InteractionLayer.InteractionVolumes)
                        {
                            interactionVolume.CancelOperation();
                        }

                        break;

                    case Keys.Left:
                        if (keyEvent.Control &&
                            printerTabPage != null &&
                            !printerTabPage.sceneContext.ViewState.ModelView)
                        {
                            // Decrement slider
                            printerTabPage.LayerFeaturesIndex -= 1;
                        }
                        else
                        {
                            if (view3D.sceneContext.Scene.SelectedItem is IObject3D object3D)
                            {
                                NudgeItem(view3D, object3D, ArrowDirection.Left, keyEvent);
                            }
                            else
                            {
                                // move or rotate view left
                                Offset3DView(view3D, new Vector2(-offsetDist, 0), arrowKeyOperation);
                            }
                        }

                        keyEvent.Handled          = true;
                        keyEvent.SuppressKeyPress = true;
                        break;

                    case Keys.Right:
                        if (keyEvent.Control &&
                            printerTabPage != null &&
                            !printerTabPage.sceneContext.ViewState.ModelView)
                        {
                            // Increment slider
                            printerTabPage.LayerFeaturesIndex += 1;
                        }
                        else
                        {
                            if (view3D.sceneContext.Scene.SelectedItem is IObject3D object3D)
                            {
                                NudgeItem(view3D, object3D, ArrowDirection.Right, keyEvent);
                            }
                            else
                            {
                                // move or rotate view right
                                Offset3DView(view3D, new Vector2(offsetDist, 0), arrowKeyOperation);
                            }
                        }

                        keyEvent.Handled          = true;
                        keyEvent.SuppressKeyPress = true;
                        break;

                    case Keys.Up:
                        if (view3D.Printer != null &&
                            printerTabPage != null &&
                            view3D.Printer.ViewState.ViewMode != PartViewMode.Model)
                        {
                            printerTabPage.LayerScrollbar.Value += 1;
                        }
                        else
                        {
                            if (view3D.sceneContext.Scene.SelectedItem is IObject3D object3D)
                            {
                                NudgeItem(view3D, object3D, ArrowDirection.Up, keyEvent);
                            }
                            else
                            {
                                Offset3DView(view3D, new Vector2(0, offsetDist), arrowKeyOperation);
                            }
                        }

                        keyEvent.Handled          = true;
                        keyEvent.SuppressKeyPress = true;
                        break;

                    case Keys.Down:
                        if (view3D.Printer != null &&
                            printerTabPage != null &&
                            view3D.Printer.ViewState.ViewMode != PartViewMode.Model)
                        {
                            printerTabPage.LayerScrollbar.Value -= 1;
                        }
                        else
                        {
                            if (view3D.sceneContext.Scene.SelectedItem is IObject3D object3D)
                            {
                                NudgeItem(view3D, object3D, ArrowDirection.Down, keyEvent);
                            }
                            else
                            {
                                Offset3DView(view3D, new Vector2(0, -offsetDist), arrowKeyOperation);
                            }
                        }

                        keyEvent.Handled          = true;
                        keyEvent.SuppressKeyPress = true;
                        break;
                    }
                }
            };

            // Hook SystemWindow load and spin up MatterControl once we've hit first draw
            systemWindow.Load += (s, e) =>
            {
                // Show the End User License Agreement if it has not been shown (on windows it is shown in the installer)
                if (AggContext.OperatingSystem != OSType.Windows &&
                    UserSettings.Instance.get(UserSettingsKey.SoftwareLicenseAccepted) != "true")
                {
                    var eula = new LicenseAgreementPage(LoadMC)
                    {
                        Margin = new BorderDouble(5)
                    };

                    systemWindow.AddChild(eula);
                }
                else
                {
                    LoadMC();
                }
            };

            void LoadMC()
            {
                ReportStartupProgress(0.02, "First draw->RunOnIdle");

                // UiThread.RunOnIdle(() =>
                Task.Run(async() =>
                {
                    try
                    {
                        ReportStartupProgress(0.15, "MatterControlApplication.Initialize");

                        ApplicationController.LoadTranslationMap();

                        var mainView = await Initialize(systemWindow, (progress0To1, status) =>
                        {
                            ReportStartupProgress(0.2 + progress0To1 * 0.7, status);
                        });

                        ReportStartupProgress(0.9, "AddChild->MainView");
                        systemWindow.AddChild(mainView, 0);

                        ReportStartupProgress(1, "");
                        systemWindow.BackgroundColor = Color.Transparent;
                        overlay.Close();
                    }
                    catch (Exception ex)
                    {
                        UiThread.RunOnIdle(() =>
                        {
                            statusText.Visible = false;

                            var errorTextColor = Color.White;

                            progressPanel.Margin          = 0;
                            progressPanel.VAnchor         = VAnchor.Center | VAnchor.Fit;
                            progressPanel.BackgroundColor = Color.DarkGray;
                            progressPanel.Padding         = 20;
                            progressPanel.Border          = 1;
                            progressPanel.BorderColor     = Color.Red;

                            var theme = new ThemeConfig();

                            progressPanel.AddChild(
                                new TextWidget("Startup Failure".Localize() + ":", pointSize: theme.DefaultFontSize, textColor: errorTextColor));

                            progressPanel.AddChild(
                                new TextWidget(ex.Message, pointSize: theme.FontSize9, textColor: errorTextColor));

                            var closeButton = new TextButton("Close", theme)
                            {
                                BackgroundColor = theme.SlightShade,
                                HAnchor         = HAnchor.Right,
                                VAnchor         = VAnchor.Absolute
                            };
                            closeButton.Click += (s1, e1) =>
                            {
                                systemWindow.Close();
                            };

                            spinner.SpinLogo    = false;
                            progressBar.Visible = false;

                            progressPanel.AddChild(closeButton);
                        });
                    }

                    AppContext.IsLoading = false;
                });
            }

            ReportStartupProgress(0, "ShowAsSystemWindow");

            return(systemWindow);
        }
Example #8
0
 public string CachePath(string cacheId)
 {
     return(ApplicationController.CacheablePath(
                Path.Combine("Thumbnails", "Content"),
                $"{cacheId}.png"));
 }
Example #9
0
        public MarkdownEditPage(UIField uiField)
        {
            this.WindowTitle = "MatterControl - " + "Markdown Edit".Localize();
            this.HeaderText  = "Edit Page".Localize() + ":";

            var tabControl = new SimpleTabs(theme, new GuiWidget())
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
            };

            tabControl.TabBar.BackgroundColor = theme.TabBarBackground;
            tabControl.TabBar.Padding         = 0;

            contentRow.AddChild(tabControl);
            contentRow.Padding = 0;

            var editContainer = new GuiWidget()
            {
                HAnchor         = HAnchor.Stretch,
                VAnchor         = VAnchor.Stretch,
                Padding         = theme.DefaultContainerPadding,
                BackgroundColor = theme.BackgroundColor
            };

            editWidget = new MHTextEditWidget("", theme, multiLine: true, typeFace: ApplicationController.GetTypeFace(NamedTypeFace.Liberation_Mono))
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
                Name    = this.Name
            };
            editWidget.DrawFromHintedCache();
            editWidget.ActualTextEditWidget.VAnchor = VAnchor.Stretch;

            editContainer.AddChild(editWidget);

            markdownWidget = new MarkdownWidget(theme, true)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
                Margin  = 0,
                Padding = 0,
            };

            var previewTab = new ToolTab("Preview", "Preview".Localize(), tabControl, markdownWidget, theme, hasClose: false)
            {
                Name = "Preview Tab"
            };

            tabControl.AddTab(previewTab);

            var editTab = new ToolTab("Edit", "Edit".Localize(), tabControl, editContainer, theme, hasClose: false)
            {
                Name = "Edit Tab"
            };

            tabControl.AddTab(editTab);

            tabControl.ActiveTabChanged += (s, e) =>
            {
                if (tabControl.SelectedTabIndex == 1)
                {
                    markdownWidget.Markdown = editWidget.Text;
                }
            };

            tabControl.SelectedTabIndex = 0;

            var saveButton = theme.CreateDialogButton("Save".Localize());

            saveButton.Click += (s, e) =>
            {
                uiField.SetValue(
                    editWidget.Text.Replace("\n", "\\n"),
                    userInitiated: true);

                this.DialogWindow.CloseOnIdle();
            };
            this.AddPageAction(saveButton);

            var link = new LinkLabel("Markdown Help", theme)
            {
                Margin  = new BorderDouble(right: 20),
                VAnchor = VAnchor.Center
            };

            link.Click += (s, e) =>
            {
                ApplicationController.Instance.LaunchBrowser("https://guides.github.com/features/mastering-markdown/");
            };
            footerRow.AddChild(link, 0);
        }
Example #10
0
        public AboutPage()
            : base("Close".Localize())
        {
            this.WindowTitle = "About".Localize() + " " + ApplicationController.Instance.ProductName;
            this.MinimumSize = new Vector2(480 * GuiWidget.DeviceScale, 520 * GuiWidget.DeviceScale);
            this.WindowSize  = new Vector2(500 * GuiWidget.DeviceScale, 550 * GuiWidget.DeviceScale);

            contentRow.BackgroundColor = Color.Transparent;

            headerRow.Visible = false;

            var altHeadingRow = new GuiWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Absolute,
                Height  = 100,
            };

            contentRow.AddChild(altHeadingRow);

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

            var productTitle = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Center | HAnchor.Fit
            };

            productTitle.AddChild(new TextWidget("MatterControl".Localize(), textColor: theme.TextColor, pointSize: 20)
            {
                Margin = new BorderDouble(right: 3)
            });
            productTitle.AddChild(new TextWidget("TM".Localize(), textColor: theme.TextColor, pointSize: 7)
            {
                VAnchor = VAnchor.Top
            });

            altHeadingRow.AddChild(productInfo);
            productInfo.AddChild(productTitle);

            var spinnerPanel = new GuiWidget()
            {
                HAnchor = HAnchor.Absolute | HAnchor.Left,
                VAnchor = VAnchor.Absolute,
                Height  = 100,
                Width   = 100,
            };

            altHeadingRow.AddChild(spinnerPanel);
            var accentColor = theme.PrimaryAccentColor;

            var spinner = new LogoSpinner(spinnerPanel, 4, 0.2, 0, rotateX: 0);

            productInfo.AddChild(
                new TextWidget("Version".Localize() + " " + VersionInfo.Instance.BuildVersion, textColor: theme.TextColor, pointSize: theme.DefaultFontSize)
            {
                HAnchor = HAnchor.Center
            });

            productInfo.AddChild(
                new TextWidget("Developed By".Localize() + ": " + "MatterHackers", textColor: theme.TextColor, pointSize: theme.DefaultFontSize)
            {
                HAnchor = HAnchor.Center
            });

            contentRow.AddChild(
                new WrappedTextWidget(
                    "MatterControl is made possible by the team at MatterHackers and other open source software".Localize() + ":",
                    pointSize: theme.DefaultFontSize,
                    textColor: theme.TextColor)
            {
                Margin = new BorderDouble(0, 15)
            });

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

            var data = JsonConvert.DeserializeObject <List <LibraryLicense> >(StaticData.Instance.ReadAllText(Path.Combine("License", "license.json")));

            var linkIcon = StaticData.Instance.LoadIcon("fa-link_16.png", 16, 16, theme.InvertIcons);

            SectionWidget section = null;

            foreach (var item in data.OrderBy(i => i.Name))
            {
                var linkButton = new IconButton(linkIcon, theme);
                linkButton.Click += (s, e) => UiThread.RunOnIdle(() =>
                {
                    ApplicationController.LaunchBrowser(item.Url);
                });

                section = new SectionWidget(item.Title ?? item.Name, new LazyLicenseText(item.Name, theme), theme, linkButton, expanded: false)
                {
                    HAnchor = HAnchor.Stretch
                };
                licensePanel.AddChild(section);
            }

            // Apply a bottom border to the last time for balance
            if (section != null)
            {
                section.Border = section.Border.Clone(bottom: 1);
            }

            var scrollable = new ScrollableWidget(autoScroll: true)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch,
                Margin  = new BorderDouble(bottom: 10),
            };

            scrollable.ScrollArea.HAnchor = HAnchor.Stretch;
            scrollable.AddChild(licensePanel);
            contentRow.AddChild(scrollable);

            contentRow.AddChild(
                new TextWidget("Copyright © 2019 MatterHackers, Inc.", textColor: theme.TextColor, pointSize: theme.DefaultFontSize)
            {
                HAnchor = HAnchor.Center,
            });

            var siteLink = new LinkLabel("www.matterhackers.com", theme)
            {
                HAnchor   = HAnchor.Center,
                TextColor = theme.TextColor
            };

            siteLink.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                ApplicationController.LaunchBrowser("http://www.matterhackers.com");
            });
            contentRow.AddChild(siteLink);
        }
Example #11
0
        public TerminalWidget(PrinterConfig printer, ThemeConfig theme)
            : base(FlowDirection.TopToBottom)
        {
            this.printer = printer;
            this.Name    = "TerminalWidget";
            this.Padding = new BorderDouble(5, 0);

            // Header
            var headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight)
            {
                HAnchor = HAnchor.Left | HAnchor.Stretch,
                Padding = new BorderDouble(0, 8)
            };

            this.AddChild(headerRow);

            filterOutput = new CheckBox("Filter Output".Localize(), textSize: theme.DefaultFontSize)
            {
                TextColor = theme.TextColor,
                VAnchor   = VAnchor.Bottom,
            };
            filterOutput.CheckedStateChanged += (s, e) =>
            {
                if (filterOutput.Checked)
                {
                    textScrollWidget.SetLineStartFilter(new string[] { "<-wait", "<-ok", "<-T" });
                }
                else
                {
                    textScrollWidget.SetLineStartFilter(null);
                }

                UserSettings.Instance.Fields.SetBool(UserSettingsKey.TerminalFilterOutput, filterOutput.Checked);
            };
            headerRow.AddChild(filterOutput);

            autoUppercase = new CheckBox("Auto Uppercase".Localize(), textSize: theme.DefaultFontSize)
            {
                Margin    = new BorderDouble(left: 25),
                Checked   = UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalAutoUppercase, true),
                TextColor = theme.TextColor,
                VAnchor   = VAnchor.Bottom
            };
            autoUppercase.CheckedStateChanged += (s, e) =>
            {
                UserSettings.Instance.Fields.SetBool(UserSettingsKey.TerminalAutoUppercase, autoUppercase.Checked);
            };
            headerRow.AddChild(autoUppercase);

            // Body
            var bodyRow = new FlowLayoutWidget()
            {
                Margin  = new BorderDouble(bottom: 4),
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Stretch
            };

            this.AddChild(bodyRow);

            textScrollWidget = new TextScrollWidget(printer, printer.Connection.TerminalLog.PrinterLines)
            {
                BackgroundColor = theme.MinimalShade,
                TextColor       = theme.TextColor,
                HAnchor         = HAnchor.Stretch,
                VAnchor         = VAnchor.Stretch,
                Margin          = 0,
                Padding         = new BorderDouble(3, 0)
            };
            bodyRow.AddChild(textScrollWidget);
            bodyRow.AddChild(new TextScrollBar(textScrollWidget, 15)
            {
                ThumbColor      = theme.AccentMimimalOverlay,
                BackgroundColor = theme.SlightShade,
                Margin          = 0
            });

            // Input Row
            var inputRow = new FlowLayoutWidget(FlowDirection.LeftToRight)
            {
                BackgroundColor = this.BackgroundColor,
                HAnchor         = HAnchor.Stretch,
                Margin          = new BorderDouble(bottom: 2)
            };

            this.AddChild(inputRow);

            manualCommandTextEdit = new MHTextEditWidget("", theme, typeFace: ApplicationController.GetTypeFace(NamedTypeFace.Liberation_Mono))
            {
                Margin  = new BorderDouble(right: 3),
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Bottom
            };
            manualCommandTextEdit.ActualTextEditWidget.EnterPressed += (s, e) =>
            {
                SendManualCommand();
            };
            manualCommandTextEdit.ActualTextEditWidget.KeyDown += (s, keyEvent) =>
            {
                bool changeToHistory = false;
                if (keyEvent.KeyCode == Keys.Up)
                {
                    commandHistoryIndex--;
                    if (commandHistoryIndex < 0)
                    {
                        commandHistoryIndex = 0;
                    }
                    changeToHistory = true;
                }
                else if (keyEvent.KeyCode == Keys.Down)
                {
                    commandHistoryIndex++;
                    if (commandHistoryIndex > commandHistory.Count - 1)
                    {
                        commandHistoryIndex = commandHistory.Count - 1;
                    }
                    else
                    {
                        changeToHistory = true;
                    }
                }
                else if (keyEvent.KeyCode == Keys.Escape)
                {
                    manualCommandTextEdit.Text = "";
                }

                if (changeToHistory && commandHistory.Count > 0)
                {
                    manualCommandTextEdit.Text = commandHistory[commandHistoryIndex];
                }
            };
            inputRow.AddChild(manualCommandTextEdit);

            // Footer
            var toolbarPadding = theme.ToolbarPadding;
            var footerRow      = new FlowLayoutWidget
            {
                HAnchor = HAnchor.Stretch,
                Padding = new BorderDouble(0, toolbarPadding.Bottom, toolbarPadding.Right, toolbarPadding.Top)
            };

            this.AddChild(footerRow);

            var sendButton = theme.CreateDialogButton("Send".Localize());

            sendButton.Margin = theme.ButtonSpacing;
            sendButton.Click += (s, e) =>
            {
                SendManualCommand();
            };
            footerRow.AddChild(sendButton);

            var clearButton = theme.CreateDialogButton("Clear".Localize());

            clearButton.Margin = theme.ButtonSpacing;
            clearButton.Click += (s, e) =>
            {
                printer.Connection.TerminalLog.Clear();
            };
            footerRow.AddChild(clearButton);

            var exportButton = theme.CreateDialogButton("Export".Localize());

            exportButton.Margin = theme.ButtonSpacing;
            exportButton.Click += (s, e) =>
            {
                UiThread.RunOnIdle(() =>
                {
                    AggContext.FileDialogs.SaveFileDialog(
                        new SaveFileDialogParams("Save as Text|*.txt")
                    {
                        Title             = "MatterControl: Terminal Log",
                        ActionButtonLabel = "Export",
                        FileName          = "print_log.txt"
                    },
                        (saveParams) =>
                    {
                        if (!string.IsNullOrEmpty(saveParams.FileName))
                        {
                            string filePathToSave = saveParams.FileName;
                            if (filePathToSave != null && filePathToSave != "")
                            {
                                try
                                {
                                    textScrollWidget.WriteToFile(filePathToSave);
                                }
                                catch (UnauthorizedAccessException ex)
                                {
                                    Debug.Print(ex.Message);

                                    printer.Connection.TerminalLog.PrinterLines.Add("");
                                    printer.Connection.TerminalLog.PrinterLines.Add(writeFaildeWaring);
                                    printer.Connection.TerminalLog.PrinterLines.Add(cantAccessPath.FormatWith(filePathToSave));
                                    printer.Connection.TerminalLog.PrinterLines.Add("");

                                    UiThread.RunOnIdle(() =>
                                    {
                                        StyledMessageBox.ShowMessageBox(ex.Message, "Couldn't save file".Localize());
                                    });
                                }
                            }
                        }
                    });
                });
            };
            footerRow.AddChild(exportButton);

            footerRow.AddChild(new HorizontalSpacer());

            this.AnchorAll();
        }
Example #12
0
        private static void RetrieveText(string uriToLoad,
                                         string cacheFolder,
                                         Action <string> updateResult,
                                         Action <HttpRequestMessage> addHeaders = null)
        {
            var longHash = uriToLoad.GetLongHashCode();

            var appDataFileName = ApplicationController.CacheablePath(cacheFolder, longHash.ToString() + ".txt");

            string fileText = null;

            // first try the cache in the users applications folder
            if (File.Exists(appDataFileName))
            {
                try
                {
                    lock (locker)
                    {
                        fileText = File.ReadAllText(appDataFileName);
                    }

                    updateResult?.Invoke(fileText);
                }
                catch
                {
                }
            }
            else             // We could not find it in the application cache. Check if it is in static data.
            {
                var staticDataPath = Path.Combine(cacheFolder, longHash.ToString() + ".txt");

                if (StaticData.Instance.FileExists(staticDataPath))
                {
                    try
                    {
                        lock (locker)
                        {
                            fileText = StaticData.Instance.ReadAllText(staticDataPath);
                        }

                        updateResult?.Invoke(fileText);
                    }
                    catch
                    {
                    }
                }
            }

            // whether we find it or not check the web for the latest version
            Task.Run(async() =>
            {
                var requestMessage = new HttpRequestMessage(HttpMethod.Get, uriToLoad);
                addHeaders?.Invoke(requestMessage);
                using (var client = new HttpClient())
                {
                    using (HttpResponseMessage response = await client.SendAsync(requestMessage))
                    {
                        var text = await response.Content.ReadAsStringAsync();
                        if (!string.IsNullOrEmpty(text) &&
                            text != fileText)
                        {
                            File.WriteAllText(appDataFileName, text);
                            updateResult?.Invoke(text);
                        }
                    }
                }
            });
        }
Example #13
0
        /// <summary>
        /// Download an image from the web into the specified ImageSequence
        /// </summary>
        /// <param name="uri"></param>
        public static void RetrieveImageSquenceAsync(ImageSequence imageSequenceToLoadInto, string uriToLoad)
        {
            var asyncImageSequence = new ImageSequence();

            var longHash    = uriToLoad.GetLongHashCode();
            var pngFileName = ApplicationController.CacheablePath("Images", longHash.ToString() + ".png");
            var gifFileName = ApplicationController.CacheablePath("Images", longHash.ToString() + ".gif");

            if (File.Exists(pngFileName))
            {
                try
                {
                    Task.Run(() =>
                    {
                        AggContext.StaticData.LoadImageSequenceData(new StreamReader(pngFileName).BaseStream, asyncImageSequence);
                        UiThread.RunOnIdle(() =>
                        {
                            imageSequenceToLoadInto.Copy(asyncImageSequence);
                            imageSequenceToLoadInto.Invalidate();
                        });
                    });

                    return;
                }
                catch
                {
                }
            }
            else if (File.Exists(gifFileName))
            {
                try
                {
                    Task.Run(() =>
                    {
                        AggContext.StaticData.LoadImageSequenceData(new StreamReader(gifFileName).BaseStream, asyncImageSequence);
                        UiThread.RunOnIdle(() =>
                        {
                            imageSequenceToLoadInto.Copy(asyncImageSequence);
                            imageSequenceToLoadInto.Invalidate();
                        });
                    });

                    return;
                }
                catch
                {
                }
            }

            WebClient client = new WebClient();

            client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
            {
                try                 // if we get a bad result we can get a target invocation exception. In that case just don't show anything
                {
                    Task.Run(() =>
                    {
                        // scale the loaded image to the size of the target image
                        byte[] raw    = e.Result;
                        Stream stream = new MemoryStream(raw);

                        AggContext.StaticData.LoadImageSequenceData(stream, asyncImageSequence);

                        if (asyncImageSequence.Frames.Count == 1)
                        {
                            // save the as png
                            AggContext.ImageIO.SaveImageData(pngFileName, asyncImageSequence.Frames[0]);
                        }
                        else                         // save original stream as gif
                        {
                            using (var writter = new FileStream(gifFileName, FileMode.Create))
                            {
                                stream.Position = 0;
                                stream.CopyTo(writter);
                            }
                        }

                        UiThread.RunOnIdle(() =>
                        {
                            imageSequenceToLoadInto.Copy(asyncImageSequence);
                            imageSequenceToLoadInto.Invalidate();
                        });
                    });
                }
                catch
                {
                }
            };

            try
            {
                client.DownloadDataAsync(new Uri(uriToLoad));
            }
            catch
            {
            }
        }
 public string CachePath(ILibraryItem libraryItem)
 {
     return(ApplicationController.CacheablePath(
                Path.Combine("Thumbnails", "Library"),
                $"{libraryItem.ID}.png"));
 }
Example #15
0
        public ApplicationSettingsPage()
        {
            this.AlwaysOnTopOfMain = true;
            this.WindowTitle       = this.HeaderText = "MatterControl " + "Settings".Localize();
            this.WindowSize        = new Vector2(700 * GuiWidget.DeviceScale, 600 * GuiWidget.DeviceScale);

            contentRow.Padding = contentRow.Padding.Clone(top: 0);

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

            contentRow.AddChild(generalPanel);

            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();
            };

            var printer = ApplicationController.Instance.ActivePrinter;

            this.AddSettingsRow(
                new SettingsItem(
                    "Camera Monitoring".Localize(),
                    theme,
                    new SettingsItem.ToggleSwitchConfig()
            {
                Checked      = printer.Settings.GetValue <bool>(SettingsKey.publish_bed_image),
                ToggleAction = (itemChecked) =>
                {
                    printer.Settings.SetValue(SettingsKey.publish_bed_image, itemChecked ? "1" : "0");
                }
            },
                    previewButton,
                    AggContext.StaticData.LoadIcon("camera-24x24.png", 24, 24)),
                generalPanel
                );
#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 (ApplicationController.ChangeToPrintNotification != null)
                {
                    UiThread.RunOnIdle(() =>
                    {
                        ApplicationController.ChangeToPrintNotification(this.DialogWindow);
                    });
                }
            };

            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", 16, 16, theme.InvertIcons)),
                generalPanel);

            // 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")
                        {
#if DEBUG
                            AppContext.Platform.GenerateLocalizationValidationFile();
#endif
                        }

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

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

#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[] thumbnails = new string[]
                                {
                                    ApplicationController.CacheablePath(
                                        Path.Combine("Thumbnails", "Content"), ""),
                                    ApplicationController.CacheablePath(
                                        Path.Combine("Thumbnails", "Library"), "")
                                };
                                foreach (var directoryToRemove in thumbnails)
                                {
                                    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),
                generalPanel);
#endif

            // TextSize
            if (!double.TryParse(UserSettings.Instance.get(UserSettingsKey.ApplicationTextSize), out double currentTextSize))
            {
                currentTextSize = 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              = currentTextSize,
                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 != currentTextSize;
            };

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

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

            this.AddSettingsRow(section, generalPanel);

            themeColorPanel = new ThemeColorPanel(theme)
            {
                HAnchor = HAnchor.Stretch
            };

            var droplist = new DropDownList("Custom", theme.Colors.PrimaryTextColor, maxHeight: 200, pointSize: theme.DefaultFontSize)
            {
                BorderColor = theme.GetBorderColor(75),
                Margin      = new BorderDouble(0, 0, 10, 0)
            };

            int i = 0;

            foreach (var item in AppContext.ThemeProviders)
            {
                var newItem = droplist.AddItem(item.Key);

                if (item.Value == themeColorPanel.ThemeProvider)
                {
                    droplist.SelectedIndex = i;
                }

                i++;
            }

            droplist.SelectionChanged += (s, e) =>
            {
                if (AppContext.ThemeProviders.TryGetValue(droplist.SelectedValue, out IColorTheme provider))
                {
                    themeColorPanel.ThemeProvider = provider;
                    UserSettings.Instance.set(UserSettingsKey.ThemeName, droplist.SelectedValue);
                }
            };

            var themeRow = new SettingsItem("Theme".Localize(), droplist, theme);
            generalPanel.AddChild(themeRow);
            generalPanel.AddChild(themeColorPanel);

            themeColorPanel.Border      = themeRow.Border;
            themeColorPanel.BorderColor = themeRow.BorderColor;
            themeRow.Border             = 0;

            var advancedPanel = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                Margin = new BorderDouble(2, 0)
            };

            var sectionWidget = new SectionWidget("Advanced".Localize(), advancedPanel, theme, serializationKey: "ApplicationSettings-Advanced", expanded: false)
            {
                Name    = "Advanced Section",
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
                Margin  = 0
            };
            contentRow.AddChild(sectionWidget);

            theme.ApplyBoxStyle(sectionWidget);

            sectionWidget.Margin = new BorderDouble(0, 10);

            // 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();
                    }
                }
            }),
                advancedPanel);

            var openCacheButton = new IconButton(AggContext.StaticData.LoadIcon("fa-link_16.png", 16, 16, theme.InvertIcons), theme)
            {
                ToolTipText = "Open Folder".Localize(),
            };
            openCacheButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                Process.Start(ApplicationDataStorage.ApplicationUserDataPath);
            });

            this.AddSettingsRow(
                new SettingsItem(
                    "Application Storage".Localize(),
                    openCacheButton,
                    theme),
                advancedPanel);

            var clearCacheButton = new HoverIconButton(AggContext.StaticData.LoadIcon("remove.png", 16, 16, theme.InvertIcons), theme)
            {
                ToolTipText = "Clear Cache".Localize(),
            };
            clearCacheButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                CacheDirectory.DeleteCacheData();
            });

            this.AddSettingsRow(
                new SettingsItem(
                    "Application Cache".Localize(),
                    clearCacheButton,
                    theme),
                advancedPanel);

            advancedPanel.Children <SettingsItem>().First().Border = new BorderDouble(0, 1);
        }
 public string CachePath(ILibraryItem libraryItem, int width, int height)
 {
     return(ApplicationController.CacheablePath(
                Path.Combine("Thumbnails", "Library"),
                CacheFilename(libraryItem, width, height)));
 }
Example #17
0
 public string CachePath(ILibraryItem libraryItem, int width, int height)
 {
     return(ApplicationController.CacheablePath(
                Path.Combine("Thumbnails", "Library"),
                $"{libraryItem.ID}-{width}x{height}.png"));
 }