private void communicationStateChanged(object sender, EventArgs args) { UiThread.RunOnIdle(() => updateControls(false)); }
private void onPrinterStatusChanged(object sender, EventArgs e) { SetVisibleControls(); UiThread.RunOnIdle(this.Invalidate); }
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.Colors.PrimaryTextColor, 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.Colors.PrimaryTextColor, VAnchor = VAnchor.Bottom }; autoUppercase.CheckedStateChanged += (s, e) => { UserSettings.Instance.Fields.SetBool(UserSettingsKey.TerminalAutoUppercase, autoUppercase.Checked); }; headerRow.AddChild(autoUppercase); // Body var bodyRow = new FlowLayoutWidget(); bodyRow.AnchorAll(); this.AddChild(bodyRow); textScrollWidget = new TextScrollWidget(printer, printer.Connection.TerminalLog.PrinterLines) { BackgroundColor = theme.Colors.SecondaryBackgroundColor, TextColor = theme.Colors.PrimaryTextColor, HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Stretch, Margin = 0, Padding = new BorderDouble(3, 0) }; bodyRow.AddChild(textScrollWidget); bodyRow.AddChild(new TextScrollBar(textScrollWidget, 15)); // 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("", 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 = 0; 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(); }
public void SetBreadCrumbs(LibraryProvider previousLibraryProvider, LibraryProvider currentLibraryProvider) { LibraryProvider displayingProvider = currentLibraryProvider; this.CloseAndRemoveAllChildren(); List <LibraryProvider> parentProviderList = new List <LibraryProvider>(); while (currentLibraryProvider != null) { parentProviderList.Add(currentLibraryProvider); currentLibraryProvider = currentLibraryProvider.ParentLibraryProvider; } bool haveFilterRunning = displayingProvider.KeywordFilter != null && displayingProvider.KeywordFilter != ""; bool first = true; for (int i = parentProviderList.Count - 1; i >= 0; i--) { LibraryProvider parentLibraryProvider = parentProviderList[i]; if (!first) { GuiWidget separator = new TextWidget(">", textColor: ActiveTheme.Instance.PrimaryTextColor); separator.VAnchor = VAnchor.ParentCenter; separator.Margin = new BorderDouble(0); this.AddChild(separator); } Button gotoProviderButton = navigationButtonFactory.Generate(parentLibraryProvider.Name); gotoProviderButton.Name = "Bread Crumb Button " + parentLibraryProvider.Name; if (first) { gotoProviderButton.Margin = new BorderDouble(0, 0, 3, 0); } else { gotoProviderButton.Margin = new BorderDouble(3, 0); } gotoProviderButton.Click += (sender2, e2) => { UiThread.RunOnIdle(() => { SwitchToLibraryProvider(parentLibraryProvider); }); }; this.AddChild(gotoProviderButton); first = false; } if (haveFilterRunning) { GuiWidget separator = new TextWidget(">", textColor: ActiveTheme.Instance.PrimaryTextColor); separator.VAnchor = VAnchor.ParentCenter; separator.Margin = new BorderDouble(0); this.AddChild(separator); Button searchResultsButton = null; if (ActiveTheme.Instance.IsTouchScreen) { searchResultsButton = navigationButtonFactory.Generate("Search Results".Localize(), "icon_search_32x32.png"); } else { searchResultsButton = navigationButtonFactory.Generate("Search Results".Localize(), "icon_search_24x24.png"); } searchResultsButton.Name = "Bread Crumb Button " + "Search Results"; searchResultsButton.Margin = new BorderDouble(3, 0); this.AddChild(searchResultsButton); } // while all the buttons don't fit in the control if (this.Parent != null && this.Parent.Width > 0 && this.Children.Count > 4 && this.GetChildrenBoundsIncludingMargins().Width > this.Parent.Width) { // lets take out the > and put in a ... this.RemoveChild(1); GuiWidget separator = new TextWidget("...", textColor: ActiveTheme.Instance.PrimaryTextColor); separator.VAnchor = VAnchor.ParentCenter; separator.Margin = new BorderDouble(3, 0); this.AddChild(separator, 1); while (this.GetChildrenBoundsIncludingMargins().Width > this.Parent.Width && this.Children.Count > 4) { this.RemoveChild(3); this.RemoveChild(2); } } }
public override Task Rebuild() { this.DebugDepth("Rebuild"); bool valuesChanged = false; // ensure we have good values StartPercent = agg_basics.Clamp(StartPercent, 0, 100, ref valuesChanged); if (Diameter < 1 || Diameter > 100000) { if (Diameter == double.MaxValue) { var aabb = this.GetAxisAlignedBoundingBox(); // uninitialized set to a reasonable value Diameter = (int)aabb.XSize; } Diameter = Math.Min(100000, Math.Max(1, Diameter)); valuesChanged = true; } MinSidesPerRotation = agg_basics.Clamp(MinSidesPerRotation, 3, 360, ref valuesChanged); var rebuildLocks = this.RebuilLockAll(); return(ApplicationController.Instance.Tasks.Execute( "Curve".Localize(), null, (reporter, cancellationToken) => { var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox(); var radius = Diameter / 2; var circumference = MathHelper.Tau * radius; double numRotations = sourceAabb.XSize / circumference; double numberOfCuts = numRotations * MinSidesPerRotation; double cutSize = sourceAabb.XSize / numberOfCuts; double cutPosition = sourceAabb.MinXYZ.X + cutSize; var cuts = new List <double>(); for (int i = 0; i < numberOfCuts; i++) { cuts.Add(cutPosition); cutPosition += cutSize; } var rotationCenter = new Vector3(sourceAabb.MinXYZ.X + (sourceAabb.MaxXYZ.X - sourceAabb.MinXYZ.X) * (StartPercent / 100), BendCcw ? sourceAabb.MaxXYZ.Y + radius : sourceAabb.MinXYZ.Y - radius, sourceAabb.Center.Z); var curvedChildren = new List <IObject3D>(); var status = new ProgressStatus(); foreach (var sourceItem in SourceContainer.VisibleMeshes()) { var originalMesh = sourceItem.Mesh; status.Status = "Copy Mesh".Localize(); reporter.Report(status); var transformedMesh = originalMesh.Copy(CancellationToken.None); var itemMatrix = sourceItem.WorldMatrix(SourceContainer); // transform into this space transformedMesh.Transform(itemMatrix); if (SplitMesh) { status.Status = "Split Mesh".Localize(); reporter.Report(status); // split the mesh along the x axis transformedMesh.SplitOnPlanes(Vector3.UnitX, cuts, cutSize / 8); } for (int i = 0; i < transformedMesh.Vertices.Count; i++) { var position = transformedMesh.Vertices[i]; var angleToRotate = ((position.X - rotationCenter.X) / circumference) * MathHelper.Tau - MathHelper.Tau / 4; var distanceFromCenter = rotationCenter.Y - position.Y; if (!BendCcw) { angleToRotate = -angleToRotate; distanceFromCenter = -distanceFromCenter; } var rotatePosition = new Vector3Float(Math.Cos(angleToRotate), Math.Sin(angleToRotate), 0) * distanceFromCenter; rotatePosition.Z = position.Z; transformedMesh.Vertices[i] = rotatePosition + new Vector3Float(rotationCenter.X, radius + sourceAabb.MaxXYZ.Y, 0); } // transform back into item local space transformedMesh.Transform(Matrix4X4.CreateTranslation(-rotationCenter) * itemMatrix.Inverted); if (SplitMesh) { status.Status = "Merge Vertices".Localize(); reporter.Report(status); transformedMesh.MergeVertices(.1); } transformedMesh.CalculateNormals(); var curvedChild = new Object3D() { Mesh = transformedMesh }; curvedChild.CopyWorldProperties(sourceItem, SourceContainer, Object3DPropertyFlags.All, false); curvedChild.Visible = true; curvedChild.Translate(new Vector3(rotationCenter)); if (!BendCcw) { curvedChild.Translate(0, -sourceAabb.YSize - Diameter, 0); } curvedChildren.Add(curvedChild); } RemoveAllButSource(); this.SourceContainer.Visible = false; this.Children.Modify((list) => { list.AddRange(curvedChildren); }); UiThread.RunOnIdle(() => { rebuildLocks.Dispose(); Invalidate(InvalidateType.DisplayValues); Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children)); }); return Task.CompletedTask; })); }
public void TriggerReload(object sender, EventArgs e) { UiThread.RunOnIdle(Reload); }
public void MoveFromToolTipToToolTip() { TempData tempData = new TempData(); SystemWindow systemWindow = CreateTwoChildWindow(tempData); // move into the first widget systemWindow.OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, 11, 11, 0)); UiThread.InvokePendingActions(); // sleep long enough to show the tool tip Thread.Sleep((int)(ToolTipManager.InitialDelay * 1000 + minMsToBias)); UiThread.InvokePendingActions(); // make sure the tool tip came up Assert.IsTrue(systemWindow.Children.Count == 3); Assert.IsTrue(tempData.showCount == 1); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == toolTip1Text); // move off the first widget systemWindow.OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, 29, 29, 0)); Thread.Sleep(minMsTimeToRespond); // sleep enough for the tool tip to want to respond UiThread.InvokePendingActions(); // make sure the first tool tip went away Assert.IsTrue(systemWindow.Children.Count == 2); Assert.IsTrue(tempData.popCount == 1); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == ""); // sleep long enough to clear the fast move time Thread.Sleep((int)(ToolTipManager.ReshowDelay * 1000 * 2)); UiThread.InvokePendingActions(); // make sure the first tool still gone Assert.IsTrue(systemWindow.Children.Count == 2); Assert.IsTrue(tempData.popCount == 1); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == ""); // move onto the other widget systemWindow.OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, 31, 31, 0)); Thread.Sleep(minMsTimeToRespond); // sleep enough for the tool tip to want to respond UiThread.InvokePendingActions(); // make sure the first tool tip still gone Assert.IsTrue(systemWindow.Children.Count == 2); Assert.IsTrue(tempData.popCount == 1); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == ""); // wait 1/2 long enough for the second tool tip to come up Thread.Sleep((int)(ToolTipManager.InitialDelay * 1000 / 2 + minMsToBias)); UiThread.InvokePendingActions(); // make sure the second tool tip not showing Assert.IsTrue(systemWindow.Children.Count == 2); Assert.IsTrue(tempData.popCount == 1); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == ""); // wait 1/2 long enough for the second tool tip to come up Thread.Sleep((int)(ToolTipManager.AutoPopDelay * 1000 / 2 + minMsToBias)); UiThread.InvokePendingActions(); // make sure the tool tip 2 came up Assert.IsTrue(systemWindow.Children.Count == 3); Assert.IsTrue(tempData.showCount == 2); Assert.IsTrue(systemWindow.ToolTipManager.CurrentText == toolTip2Text); }
private void GeneratePrinterOverflowMenu(PopupMenu popupMenu, ThemeConfig theme) { var menuActions = new List <NamedAction>() { new NamedAction() { Icon = StaticData.Instance.LoadIcon("memory_16x16.png", 16, 16, theme.InvertIcons), 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, theme.InvertIcons), }); 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, theme.InvertIcons) }); 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, theme.InvertIcons) }); 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); }
public PrinterActionsBar(PrinterConfig printer, PrinterTabPage printerTabPage, ThemeConfig theme) : base(theme) { this.printer = printer; this.printerTabPage = printerTabPage; this.HAnchor = HAnchor.Stretch; this.VAnchor = VAnchor.Fit; var defaultMargin = theme.ButtonSpacing; var printerType = printer.Settings.Slicer.PrinterType; if (printerType == PrinterType.FFF) { // add the reset button first (if there is one) if (printer.Settings.GetValue <bool>(SettingsKey.show_reset_connection)) { var resetConnectionButton = new TextIconButton( "Reset".Localize(), StaticData.Instance.LoadIcon("e_stop.png", 14, 14, theme.InvertIcons), theme) { ToolTipText = "Reboots the firmware on the controller".Localize(), Margin = defaultMargin }; resetConnectionButton.Click += (s, e) => { UiThread.RunOnIdle(printer.Connection.RebootBoard); }; this.AddChild(resetConnectionButton); } this.AddChild(new PrinterConnectButton(printer, theme)); // add the start print button GuiWidget startPrintButton; this.AddChild(startPrintButton = new PrintPopupMenu(printer, theme) { Margin = theme.ButtonSpacing }); void SetPrintButtonStyle(object s, EventArgs e) { switch (printer.Connection.CommunicationState) { case CommunicationStates.FinishedPrint: case CommunicationStates.Connected: theme.ApplyPrimaryActionStyle(startPrintButton); break; default: theme.RemovePrimaryActionStyle(startPrintButton); break; } } // make sure the buttons state is set correctly printer.Connection.CommunicationStateChanged += SetPrintButtonStyle; startPrintButton.Closed += (s, e) => printer.Connection.CommunicationStateChanged -= SetPrintButtonStyle; // and set the style right now SetPrintButtonStyle(this, null); } else { var exportButton = new ExportSlaPopupMenu(printer, theme) { Margin = theme.ButtonSpacing }; // add the SLA export button this.AddChild(exportButton); theme.ApplyPrimaryActionStyle(exportButton); } this.AddChild(new SliceButton(printer, printerTabPage, theme) { Name = "Generate Gcode Button", Margin = theme.ButtonSpacing, }); // Add vertical separator this.AddChild(new ToolbarSeparator(theme.GetBorderColor(50), theme.SeparatorMargin) { VAnchor = VAnchor.Absolute, Height = theme.ButtonHeight, }); var buttonGroupB = new ObservableCollection <GuiWidget>(); var iconPath = Path.Combine("ViewTransformControls", "model.png"); modelViewButton = new RadioIconButton(StaticData.Instance.LoadIcon(iconPath, 16, 16, theme.InvertIcons), theme) { SiblingRadioButtonList = buttonGroupB, Name = "Model View Button", Checked = printer?.ViewState.ViewMode == PartViewMode.Model || printer == null, ToolTipText = "Model View".Localize(), BackgroundRadius = theme.ButtonRadius, Margin = theme.ButtonSpacing }; modelViewButton.Click += SwitchModes_Click; buttonGroupB.Add(modelViewButton); AddChild(modelViewButton); viewModes.Add(PartViewMode.Model, modelViewButton); iconPath = Path.Combine("ViewTransformControls", "gcode_3d.png"); layers3DButton = new RadioIconButton(StaticData.Instance.LoadIcon(iconPath, 16, 16, theme.InvertIcons), theme) { SiblingRadioButtonList = buttonGroupB, Name = "Layers3D Button", Checked = printer?.ViewState.ViewMode == PartViewMode.Layers3D, ToolTipText = "3D Layer View".Localize(), BackgroundRadius = theme.ButtonRadius, Margin = theme.ButtonSpacing }; layers3DButton.Click += SwitchModes_Click; buttonGroupB.Add(layers3DButton); viewModes.Add(PartViewMode.Layers3D, layers3DButton); if (!UserSettings.Instance.IsTouchScreen) { this.AddChild(layers3DButton); } iconPath = Path.Combine("ViewTransformControls", "gcode_2d.png"); layers2DButton = new RadioIconButton(StaticData.Instance.LoadIcon(iconPath, 16, 16, theme.InvertIcons), theme) { SiblingRadioButtonList = buttonGroupB, Name = "Layers2D Button", Checked = printer?.ViewState.ViewMode == PartViewMode.Layers2D, ToolTipText = "2D Layer View".Localize(), BackgroundRadius = theme.ButtonRadius, Margin = theme.ButtonSpacing, }; layers2DButton.Click += SwitchModes_Click; buttonGroupB.Add(layers2DButton); this.AddChild(layers2DButton); viewModes.Add(PartViewMode.Layers2D, layers2DButton); this.AddChild(new HorizontalSpacer()); if (printerType == PrinterType.FFF) { int hotendCount = printer.Settings.Helpers.HotendCount(); for (int extruderIndex = 0; extruderIndex < hotendCount; extruderIndex++) { this.AddChild(new TemperatureWidgetHotend(printer, extruderIndex, theme, hotendCount) { Margin = new BorderDouble(right: 10) }); } if (printer.Settings.GetValue <bool>(SettingsKey.has_heated_bed)) { this.AddChild(new TemperatureWidgetBed(printer, theme)); } // Register listeners printer.Connection.ConnectionSucceeded += CheckForPrintRecovery; // if we are already connected than check if there is a print recovery right now if (printer.Connection.CommunicationState == CommunicationStates.Connected) { CheckForPrintRecovery(null, null); } } this.OverflowButton.Name = "Printer Overflow Menu"; this.OverflowButton.ToolTipText = "Printer Options".Localize(); this.ExtendOverflowMenu = (popupMenu) => { this.GeneratePrinterOverflowMenu(popupMenu, ApplicationController.Instance.MenuTheme); }; printer.ViewState.ViewModeChanged += (s, e) => { if (viewModes[e.ViewMode] is RadioIconButton activeButton && viewModes[e.PreviousMode] is RadioIconButton previousButton && !buttonIsBeingClicked) { // Show slide to animation from previous to current, on completion update view to current by setting active.Checked previousButton.SlideToNewState( activeButton, this, () => { activeButton.Checked = true; }, theme); } }; }
private void onOpenPartViewClick(object sender, EventArgs e) { UiThread.RunOnIdle(() => openPartView()); }
private void onRemoveLinkClick(object sender, EventArgs e) { UiThread.RunOnIdle(RemoveThisFromPrintLibrary); }
public MacroDetailPage(GCodeMacro gcodeMacro, PrinterSettings printerSettings) { // Form validation fields MHTextEditWidget macroNameInput; MHTextEditWidget macroCommandInput; WrappedTextWidget macroCommandError; WrappedTextWidget 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.TextColor, HAnchor = HAnchor.Stretch, Margin = new BorderDouble(0, 0, 0, 1) }); contentRow.AddChild(macroNameInput = new MHTextEditWidget(GCodeMacro.FixMacroName(gcodeMacro.Name), theme) { HAnchor = HAnchor.Stretch }); contentRow.AddChild(macroNameError = new WrappedTextWidget("Give the macro a name".Localize() + ".", 10) { TextColor = theme.TextColor, Margin = elementMargin }); contentRow.AddChild(new TextWidget("Macro Commands".Localize() + ":", 0, 0, 12) { TextColor = theme.TextColor, HAnchor = HAnchor.Stretch, Margin = new BorderDouble(0, 0, 0, 1) }); macroCommandInput = new MHTextEditWidget(gcodeMacro.GCode, theme, 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 WrappedTextWidget("This should be in 'G-Code'".Localize() + ".", 10) { TextColor = theme.TextColor, Margin = elementMargin }); var container = new FlowLayoutWidget { Margin = new BorderDouble(0, 5), HAnchor = HAnchor.Stretch }; contentRow.AddChild(container); var saveMacroButton = theme.CreateDialogButton("Save".Localize()); saveMacroButton.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.NotifyMacrosChanged(); printerSettings.Save(); this.DialogWindow.ChangeToPage(new MacroListPage(printerSettings)); } }); }; this.AddPageAction(saveMacroButton); // 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) }; }
private void addToQueueButton_Click(object sender, EventArgs mouseEvent) { UiThread.RunOnIdle(AddItemsToQueue); }
public void CreateCopyInQueue() { // Guard for single item selection if (this.queueDataView.SelectedItems.Count != 1) { return; } var queueRowItem = this.queueDataView.SelectedItems[0]; var printItemWrapper = queueRowItem.PrintItemWrapper; int thisIndexInQueue = QueueData.Instance.GetIndex(printItemWrapper); if (thisIndexInQueue != -1 && File.Exists(printItemWrapper.FileLocation)) { string libraryDataPath = ApplicationDataStorage.Instance.ApplicationLibraryDataPath; if (!Directory.Exists(libraryDataPath)) { Directory.CreateDirectory(libraryDataPath); } string newCopyFilename; int infiniteBlocker = 0; do { newCopyFilename = Path.Combine(libraryDataPath, Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(printItemWrapper.FileLocation))); newCopyFilename = Path.GetFullPath(newCopyFilename); infiniteBlocker++; } while (File.Exists(newCopyFilename) && infiniteBlocker < 100); File.Copy(printItemWrapper.FileLocation, newCopyFilename); string newName = printItemWrapper.Name; if (!newName.Contains(" - copy")) { newName += " - copy"; } else { int index = newName.LastIndexOf(" - copy"); newName = newName.Substring(0, index) + " - copy"; } int copyNumber = 2; string testName = newName; string[] itemNames = QueueData.Instance.GetItemNames(); // figure out if we have a copy already and increment the number if we do while (true) { if (itemNames.Contains(testName)) { testName = "{0} {1}".FormatWith(newName, copyNumber); copyNumber++; } else { break; } } newName = testName; PrintItem newPrintItem = new PrintItem(); newPrintItem.Name = newName; newPrintItem.FileLocation = newCopyFilename; newPrintItem.ReadOnly = printItemWrapper.PrintItem.ReadOnly; newPrintItem.Protected = printItemWrapper.PrintItem.Protected; UiThread.RunOnIdle(AddPartCopyToQueue, new PartToAddToQueue() { PrintItem = newPrintItem, InsertAfterIndex = thisIndexInQueue + 1 }); } }
public PresetListItem(SlicePresetsWindow windowController, DataStorage.SliceSettingsCollection preset) { this.preset = preset; this.BackgroundColor = RGBA_Bytes.White; this.HAnchor = HAnchor.ParentLeftRight; this.Margin = new BorderDouble(6, 0, 6, 3); this.Padding = new BorderDouble(3); LinkButtonFactory linkButtonFactory = new LinkButtonFactory(); linkButtonFactory.fontSize = 10; int maxLabelWidth = 300; TextWidget materialLabel = new TextWidget(preset.Name, pointSize: 14); materialLabel.EllipsisIfClipped = true; materialLabel.VAnchor = Agg.UI.VAnchor.ParentCenter; materialLabel.MinimumSize = new Vector2(maxLabelWidth, materialLabel.Height); materialLabel.Width = maxLabelWidth; Button materialEditLink = linkButtonFactory.Generate("edit"); materialEditLink.VAnchor = Agg.UI.VAnchor.ParentCenter; materialEditLink.Click += (sender, e) => { UiThread.RunOnIdle((state) => { windowController.ChangeToSlicePresetDetail(preset); }); }; Button materialRemoveLink = linkButtonFactory.Generate("remove"); materialRemoveLink.Margin = new BorderDouble(left: 4); materialRemoveLink.VAnchor = Agg.UI.VAnchor.ParentCenter; materialRemoveLink.Click += (sender, e) => { UiThread.RunOnIdle((state) => { //Unwind this setting if it is currently active if (ActivePrinterProfile.Instance.ActivePrinter != null) { if (preset.Id == ActivePrinterProfile.Instance.ActiveQualitySettingsID) { ActivePrinterProfile.Instance.ActiveQualitySettingsID = 0; } string[] activeMaterialPresets = ActivePrinterProfile.Instance.ActivePrinter.MaterialCollectionIds.Split(','); for (int i = 0; i < activeMaterialPresets.Count(); i++) { int index = 0; Int32.TryParse(activeMaterialPresets[i], out index); if (preset.Id == index) { ActivePrinterProfile.Instance.SetMaterialSetting(i + 1, 0); } } } preset.Delete(); windowController.ChangeToSlicePresetList(); ActiveSliceSettings.Instance.LoadAllSettings(); ApplicationWidget.Instance.ReloadAdvancedControlsPanel(); }); }; this.AddChild(materialLabel); this.AddChild(new HorizontalSpacer()); this.AddChild(materialEditLink); this.AddChild(materialRemoveLink); this.Height = 35; }
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(); }
public void ThemeChanged(object sender, EventArgs e) { UiThread.RunOnIdle(Reload); }
public void SetContainer(ILibraryContainer currentContainer) { this.CloseChildren(); var backButton = new IconButton(StaticData.Instance.LoadIcon(Path.Combine("Library", "back.png"), 20, 20).SetToColor(theme.TextColor), theme) { VAnchor = VAnchor.Fit | VAnchor.Center, Enabled = currentContainer.Parent != null, Name = "Library Up Button", ToolTipText = "Click to go back".Localize(), Margin = theme.ButtonSpacing, MinimumSize = new Vector2(theme.ButtonHeight, theme.ButtonHeight) }; backButton.Click += (s, e) => { NavigateBack(); }; this.AddChild(backButton); bool firstItem = true; if (this.Width < 250) { var containerButton = new LinkLabel((libraryContext.ActiveContainer.Name == null ? "?" : libraryContext.ActiveContainer.Name), theme) { Name = "Bread Crumb Button " + libraryContext.ActiveContainer.Name, VAnchor = VAnchor.Center, Margin = theme.ButtonSpacing, TextColor = theme.TextColor }; this.AddChild(containerButton); } else { var extraSpacing = (theme.ButtonSpacing).Clone(left: theme.ButtonSpacing.Right * .4); foreach (var container in currentContainer.AncestorsAndSelf().Reverse()) { if (!firstItem) { // Add path separator this.AddChild(new TextWidget("/", pointSize: theme.DefaultFontSize + 1, textColor: theme.TextColor) { VAnchor = VAnchor.Center, Margin = extraSpacing.Clone(top: 2) }); } // Create a button for each container var containerButton = new LinkLabel(container.Name, theme) { Name = "Bread Crumb Button " + container.Name, VAnchor = VAnchor.Center, Margin = theme.ButtonSpacing.Clone(top: 1), TextColor = theme.TextColor }; containerButton.Click += (s, e) => { UiThread.RunOnIdle(() => libraryContext.ActiveContainer = container); }; this.AddChild(containerButton); firstItem = false; } var childrenWidth = this.GetChildrenBoundsIncludingMargins().Width; // while all the buttons don't fit in the control if (this.Parent != null && this.Width > 0 && this.Children.Count > 4 && childrenWidth > (this.Width - 20)) { // lets take out the > and put in a ... var removedWidth = this.RemoveChild(1).Width; var separator = new TextWidget("...", textColor: theme.TextColor) { VAnchor = VAnchor.Center, Margin = new BorderDouble(right: 5) }; removedWidth -= this.AddChild(separator, 1).Width; while (childrenWidth - removedWidth > this.Width - 20 && this.Children.Count > 4) { removedWidth += this.RemoveChild(3).Width; removedWidth += this.RemoveChild(2).Width; } UiThread.RunOnIdle(() => this.Width = this.Width + 1); } } }
public void AddElements() { Title = LocalizedString.Get("Design Add-ons"); FlowLayoutWidget topToBottom = new FlowLayoutWidget(FlowDirection.TopToBottom); topToBottom.AnchorAll(); topToBottom.Padding = new BorderDouble(3, 0, 3, 5); FlowLayoutWidget headerRow = new FlowLayoutWidget(FlowDirection.LeftToRight); headerRow.HAnchor = HAnchor.ParentLeftRight; headerRow.Margin = new BorderDouble(0, 3, 0, 0); headerRow.Padding = new BorderDouble(0, 3, 0, 3); { string elementHeaderLabelBeg = LocalizedString.Get("Select a Design Tool"); string elementHeaderLabelFull = string.Format("{0}:", elementHeaderLabelBeg); string elementHeaderLabel = elementHeaderLabelFull; TextWidget elementHeader = new TextWidget(string.Format(elementHeaderLabel), pointSize: 14); elementHeader.TextColor = ActiveTheme.Instance.PrimaryTextColor; elementHeader.HAnchor = HAnchor.ParentLeftRight; elementHeader.VAnchor = Agg.UI.VAnchor.ParentBottom; headerRow.AddChild(elementHeader); } topToBottom.AddChild(headerRow); GuiWidget presetsFormContainer = new GuiWidget(); { presetsFormContainer.HAnchor = HAnchor.ParentLeftRight; presetsFormContainer.VAnchor = VAnchor.ParentBottomTop; presetsFormContainer.BackgroundColor = ActiveTheme.Instance.SecondaryBackgroundColor; } FlowLayoutWidget pluginRowContainer = new FlowLayoutWidget(FlowDirection.TopToBottom); pluginRowContainer.AnchorAll(); presetsFormContainer.AddChild(pluginRowContainer); unlockButtonFactory.Margin = new BorderDouble(10, 0); if (ActiveTheme.Instance.IsDarkTheme) { unlockButtonFactory.normalFillColor = new RGBA_Bytes(0, 0, 0, 100); unlockButtonFactory.normalBorderColor = new RGBA_Bytes(0, 0, 0, 100); unlockButtonFactory.hoverFillColor = new RGBA_Bytes(0, 0, 0, 50); unlockButtonFactory.hoverBorderColor = new RGBA_Bytes(0, 0, 0, 50); } else { unlockButtonFactory.normalFillColor = new RGBA_Bytes(0, 0, 0, 50); unlockButtonFactory.normalBorderColor = new RGBA_Bytes(0, 0, 0, 50); unlockButtonFactory.hoverFillColor = new RGBA_Bytes(0, 0, 0, 100); unlockButtonFactory.hoverBorderColor = new RGBA_Bytes(0, 0, 0, 100); } foreach (CreatorInformation creatorInfo in RegisteredCreators.Instance.Creators) { FlowLayoutWidget pluginListingContainer = new FlowLayoutWidget(); pluginListingContainer.HAnchor = Agg.UI.HAnchor.ParentLeftRight; pluginListingContainer.BackgroundColor = RGBA_Bytes.White; pluginListingContainer.Padding = new BorderDouble(0); pluginListingContainer.Margin = new BorderDouble(6, 0, 6, 6); ClickWidget pluginRow = new ClickWidget(); pluginRow.Margin = new BorderDouble(6, 0, 6, 0); pluginRow.Height = 38; pluginRow.HAnchor = Agg.UI.HAnchor.ParentLeftRight; FlowLayoutWidget macroRow = new FlowLayoutWidget(); macroRow.AnchorAll(); macroRow.BackgroundColor = RGBA_Bytes.White; if (creatorInfo.iconPath != "") { ImageBuffer imageBuffer = LoadImage(creatorInfo.iconPath); ImageWidget imageWidget = new ImageWidget(imageBuffer); imageWidget.VAnchor = Agg.UI.VAnchor.ParentCenter; macroRow.AddChild(imageWidget); } bool userHasPermission; if (!creatorInfo.paidAddOnFlag) { userHasPermission = true; } else { userHasPermission = creatorInfo.permissionFunction(); } string addOnDescription; addOnDescription = creatorInfo.description; TextWidget buttonLabel = new TextWidget(addOnDescription, pointSize: 14); buttonLabel.Margin = new BorderDouble(left: 10); buttonLabel.VAnchor = Agg.UI.VAnchor.ParentCenter; macroRow.AddChild(buttonLabel); if (!userHasPermission) { TextWidget demoLabel = new TextWidget("(demo)", pointSize: 10); demoLabel.Margin = new BorderDouble(left: 4); demoLabel.VAnchor = Agg.UI.VAnchor.ParentCenter; macroRow.AddChild(demoLabel); } FlowLayoutWidget hSpacer = new FlowLayoutWidget(); hSpacer.HAnchor = Agg.UI.HAnchor.ParentLeftRight; macroRow.AddChild(hSpacer); CreatorInformation callCorrectFunctionHold = creatorInfo; pluginRow.Click += (sender, e) => { if (RegisteredCreators.Instance.Creators.Count > 0) { callCorrectFunctionHold.functionToLaunchCreator(null, null); } UiThread.RunOnIdle(CloseOnIdle); }; pluginRow.Cursor = Cursors.Hand; macroRow.Selectable = false; pluginRow.AddChild(macroRow); pluginListingContainer.AddChild(pluginRow); if (!userHasPermission) { Button unlockButton = unlockButtonFactory.Generate("Unlock"); unlockButton.Margin = new BorderDouble(0); unlockButton.Cursor = Cursors.Hand; unlockButton.Click += (sender, e) => { callCorrectFunctionHold.unlockFunction(); }; pluginListingContainer.AddChild(unlockButton); } pluginRowContainer.AddChild(pluginListingContainer); if (callCorrectFunctionHold.unlockRegisterFunction != null) { callCorrectFunctionHold.unlockRegisterFunction(TriggerReload, ref unregisterEvents); } } topToBottom.AddChild(presetsFormContainer); BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor; Button cancelPresetsButton = textImageButtonFactory.Generate(LocalizedString.Get("Cancel")); cancelPresetsButton.Click += (sender, e) => { UiThread.RunOnIdle(CloseOnIdle); }; FlowLayoutWidget buttonRow = new FlowLayoutWidget(); buttonRow.HAnchor = HAnchor.ParentLeftRight; buttonRow.Padding = new BorderDouble(0, 3); GuiWidget hButtonSpacer = new GuiWidget(); hButtonSpacer.HAnchor = HAnchor.ParentLeftRight; buttonRow.AddChild(hButtonSpacer); buttonRow.AddChild(cancelPresetsButton); topToBottom.AddChild(buttonRow); AddChild(topToBottom); }
private bool about_Click() { UiThread.RunOnIdle(AboutWindow.Show); return(true); }
public override Task Rebuild() { this.DebugDepth("Rebuild"); UpdateHistogramDisplay(); bool propertyUpdated = false; var minSeparation = .01; var rangeStart = RangeStart.Value(this); var rangeEnd = RangeEnd.Value(this); if (rangeStart < 0 || rangeStart > 1 || rangeEnd < 0 || rangeEnd > 1 || rangeStart > rangeEnd - minSeparation) { rangeStart = Math.Max(0, Math.Min(1 - minSeparation, rangeStart)); rangeEnd = Math.Max(0, Math.Min(1, rangeEnd)); if (rangeStart > rangeEnd - minSeparation) { // values are overlapped or too close together if (rangeEnd < 1 - minSeparation) { // move the end up whenever possible rangeEnd = rangeStart + minSeparation; } else { // move the end to the end and the start up rangeEnd = 1; RangeStart = 1 - minSeparation; } } propertyUpdated = true; } var rebuildLock = RebuildLock(); // now create a long running task to process the image return(ApplicationController.Instance.Tasks.Execute( "Calculate Path".Localize(), null, (reporter, cancellationToken) => { var progressStatus = new ProgressStatus(); this.GenerateMarchingSquaresAndLines( (progress0to1, status) => { progressStatus.Progress0To1 = progress0to1; progressStatus.Status = status; reporter.Report(progressStatus); }, Image, ThresholdFunction); if (propertyUpdated) { UpdateHistogramDisplay(); this.Invalidate(InvalidateType.Properties); } UiThread.RunOnIdle(() => { rebuildLock.Dispose(); Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Path)); }); return Task.CompletedTask; })); }
private bool ImportSettingsMenu_Click() { UiThread.RunOnIdle(() => WizardWindow.Show <ImportSettingsPage>("ImportSettingsPage", "Import Settings Page")); return(true); }
public void ReloadAdvancedControlsPanelTrigger(object sender, EventArgs e) { UiThread.RunOnIdle(ReloadAdvancedControlsPanel); }
private DropDownMenu GetSliceOptionsMenuDropList() { DropDownMenu sliceOptionsMenuDropList; sliceOptionsMenuDropList = new DropDownMenu("Profile".Localize() + "... ") { HoverColor = new RGBA_Bytes(0, 0, 0, 50), NormalColor = new RGBA_Bytes(0, 0, 0, 0), BorderColor = new RGBA_Bytes(ActiveTheme.Instance.SecondaryTextColor, 100), BackgroundColor = new RGBA_Bytes(0, 0, 0, 0), BorderWidth = 1, MenuAsWideAsItems = false, AlignToRightEdge = true, }; sliceOptionsMenuDropList.Name = "Slice Settings Options Menu"; sliceOptionsMenuDropList.VAnchor |= VAnchor.ParentCenter; sliceOptionsMenuDropList.AddItem("Import".Localize()).Selected += (s, e) => { ImportSettingsMenu_Click(); }; sliceOptionsMenuDropList.AddItem("Export".Localize()).Selected += (s, e) => { WizardWindow.Show <ExportSettingsPage>("ExportSettingsPage", "Export Settings"); }; MenuItem settingsHistory = sliceOptionsMenuDropList.AddItem("Restore Settings".Localize()); settingsHistory.Selected += (s, e) => { WizardWindow.Show <PrinterProfileHistoryPage>("PrinterProfileHistory", "Restore Settings"); }; settingsHistory.Enabled = !string.IsNullOrEmpty(AuthenticationData.Instance.ActiveSessionUsername); sliceOptionsMenuDropList.AddItem("Reset to Defaults".Localize()).Selected += (s, e) => { UiThread.RunOnIdle(ResetToDefaults); }; return(sliceOptionsMenuDropList); }
public void Show() { UiThread.Invoke(() => ViewModelManager.ShowViewModel(this)); }
void DoneButton_Click(object sender, MouseEventArgs mouseEvent) { UiThread.RunOnIdle(DoDoneButton_Click); }
public override void OnLoad(EventArgs args) { filterOutput.Checked = UserSettings.Instance.Fields.GetBool(UserSettingsKey.TerminalFilterOutput, false); UiThread.RunOnIdle(manualCommandTextEdit.Focus); base.OnLoad(args); }
public override void OnDraw(Graphics2D graphics2D) { totalDrawTime.Restart(); GuiWidget.DrawCount = 0; using (new PerformanceTimer("Draw Timer", "MC Draw")) { base.OnDraw(graphics2D); } totalDrawTime.Stop(); millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds); if (ShowMemoryUsed) { long memory = GC.GetTotalMemory(false); this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, widgetsDrawn = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount); if (DoCGCollectEveryDraw) { GC.Collect(); } } if (firstDraw) { firstDraw = false; foreach (string arg in commandLineArgs) { string argExtension = Path.GetExtension(arg).ToUpper(); if (argExtension.Length > 1 && MeshFileIo.ValidFileExtensions().Contains(argExtension)) { QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg)))); } } TerminalWindow.ShowIfLeftOpen(); #if false { SystemWindow releaseNotes = new SystemWindow(640, 480); string releaseNotesFile = Path.Combine("C:/Users/LarsBrubaker/Downloads", "test1.html"); string releaseNotesContent = StaticData.Instance.ReadAllText(releaseNotesFile); HtmlWidget content = new HtmlWidget(releaseNotesContent, RGBA_Bytes.Black); content.AddChild(new GuiWidget(HAnchor.AbsolutePosition, VAnchor.ParentBottomTop)); content.VAnchor |= VAnchor.ParentTop; content.BackgroundColor = RGBA_Bytes.White; releaseNotes.AddChild(content); releaseNotes.BackgroundColor = RGBA_Bytes.Cyan; UiThread.RunOnIdle((state) => { releaseNotes.ShowAsSystemWindow(); }, 1); } #endif AfterFirstDraw?.Invoke(); if (false && UserSettings.Instance.get("SoftwareLicenseAccepted") != "true") { UiThread.RunOnIdle(() => WizardWindow.Show <LicenseAgreementPage>("SoftwareLicense", "Software License Agreement")); } if (ActiveSliceSettings.ProfileData.Profiles.Count == 0) { // Start the setup wizard if no profiles exist UiThread.RunOnIdle(() => WizardWindow.Show()); } } //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds); //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D); }
private MatterControlApplication(double width, double height) : base(width, height) { Name = "MatterControl"; // set this at startup so that we can tell next time if it got set to true in close UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1; this.commandLineArgs = Environment.GetCommandLineArgs(); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; bool forceSofwareRendering = false; for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++) { string command = commandLineArgs[currentCommandIndex]; string commandUpper = command.ToUpper(); switch (commandUpper) { case "FORCE_SOFTWARE_RENDERING": forceSofwareRendering = true; GL.ForceSoftwareRendering(); break; case "CLEAR_CACHE": AboutWidget.DeleteCacheData(); break; case "SHOW_MEMORY": ShowMemoryUsed = true; break; case "DO_GC_COLLECT_EVERY_DRAW": ShowMemoryUsed = true; DoCGCollectEveryDraw = true; break; case "CREATE_AND_SELECT_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string argument = commandLineArgs[currentCommandIndex]; string[] printerData = argument.Split(','); if (printerData.Length >= 2) { Printer ActivePrinter = new Printer(); ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]); ActivePrinter.Make = printerData[0]; ActivePrinter.Model = printerData[1]; if (printerData.Length == 3) { ActivePrinter.ComPort = printerData[2]; } PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter); test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model); ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter; } } break; case "CONNECT_TO_PRINTER": if (currentCommandIndex + 1 <= commandLineArgs.Length) { PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter(); } break; case "START_PRINT": if (currentCommandIndex + 1 <= commandLineArgs.Length) { bool hasBeenRun = false; currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath))); PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) => { if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected) { hasBeenRun = true; PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible(); } }, ref unregisterEvent); } } break; case "SLICE_AND_EXPORT_GCODE": if (currentCommandIndex + 1 <= commandLineArgs.Length) { currentCommandIndex++; string fullPath = commandLineArgs[currentCommandIndex]; QueueData.Instance.RemoveAll(); if (!string.IsNullOrEmpty(fullPath)) { string fileName = Path.GetFileNameWithoutExtension(fullPath); PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath)); QueueData.Instance.AddItem(printItemWrapper); SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper); ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper); exportForTest.ExportGcodeCommandLineUtility(fileName); } } break; } if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper())) { // If we are the only instance running then do nothing. // Else send these to the running instance so it can load them. } } //WriteTestGCodeFile(); #if !DEBUG if (File.Exists("RunUnitTests.txt")) #endif { #if IS_WINDOWS_FORMS if (!Clipboard.IsInitialized) { Clipboard.SetSystemClipboard(new WindowsFormsClipboard()); } #endif // you can turn this on to debug some bounds issues //GuiWidget.DebugBoundsUnderMouse = true; } GuiWidget.DefaultEnforceIntegerBounds = true; if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen) { TextWidget.GlobalPointSizeScaleRatio = 1.3; } using (new PerformanceTimer("Startup", "MainView")) { this.AddChild(ApplicationController.Instance.MainView); } this.MinimumSize = minSize; this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off #if false // this is to test freeing gcodefile memory Button test = new Button("test"); test.Click += (sender, e) => { //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile(); //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode"); SystemWindow window = new SystemWindow(100, 100); window.ShowAsSystemWindow(); }; allControls.AddChild(test); #endif this.AnchorAll(); if (!forceSofwareRendering) { UseOpenGL = true; } string version = "1.5"; Title = "MatterControl {0}".FormatWith(version); if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0) { Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra); } UiThread.RunOnIdle(CheckOnPrinter); string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition"); if (desktopPosition != null && desktopPosition != "") { string[] sizes = desktopPosition.Split(','); //If the desktop position is less than -10,-10, override int xpos = Math.Max(int.Parse(sizes[0]), -10); int ypos = Math.Max(int.Parse(sizes[1]), -10); DesktopPosition = new Point2D(xpos, ypos); } }
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(() => { 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); }