Files
UVtools/UVtools.Core/Operations/OperationScripting.cs
T
Tiago Conceição c800f887d2 v3.4.2
- **Core:**
   - (Add) Getter `FileFormat.DisplayPixelCount` Gets the display total number of pixels (ResolutionX * ResolutionY)
   - (Add) Getter `Layer.NonZeroPixelRatio` Gets the ratio between non zero pixels and display number of pixels
   - (Add) Getter `Layer.NonZeroPixelPercentage` Gets the percentage of non zero pixels relative to the display number of pixels
   - (Add) Getter `Layer.PreviousHeightLayer()` Gets the previous layer with a different height from the current, returns null if no previous layer
   - (Add) Getter `Layer.NextHeightLayer()` Gets the next layer with a different height from the current, returns null if no next layer
   - (Add) Method `Layer.GetPreviousLayerWithAtLeastPixelCountOf()` Gets the previous layer matching at least a number of pixels, returns null if no previous layer
   - (Add) Method `Layer.GetNextLayerWithAtLeastPixelCountOf()` Gets the next layer matching at least a number of pixels, returns null if no next layer
   - (Add) Method `Operation.GetRoiOrVolumeBounds()` returns the selected ROI rectangle or model volume bounds rectangle
   - (Add) Documentation around `Operation` methods
   - (Fix) Open files in partial mode when the resolution is not defined would cause a `NullPointerException` (#474)
- **Suggestion: Wait time before cure**
   - (Add) Proportional maximum time change: Sets the maximum allowed time difference relative to the previous layer (#471)
   - (Add) Proportional mass get modes: Previous, Average and Maximum relative to a defined height (#471)
   - (Change) Proportional set type sets fallback time to the first layer
   - (Fix) Proportional set type was taking current layer mass instead of looking to the previous cured layer (#471)
- **Tools:**
   - **Edit print parameters:**
      - (Change) Incorporate the unit label into the numeric input box
      - (Change) Allow TSMC speeds to be 0 as minimum value (#472)
   - (Fix) PCB Exposure: The thumbnail has random noise around the image
- **Settings:**
   - (Add) Tools: "Always prompt for confirmation before execute the operation"
   - (Fix) Changing layer compression method when no file is loaded would cause a error
- **UI:**
   - (Add) Holding Shift key while drag and drop a .uvtop file will try to execute the operation without showing the window or prompt
   - (Add) Drag and drop a .cs or .csx file into UVtools will load and show the scripting dialog with the file selected
- (Add) Errors that crash application will now show an report window with the crash information and able to fast report them
- (Add) "Version" key and value on registry to tell the current installed version (Windows MSI only)
- (Upgrade) AvaloniaUI from 0.10.13 to 0.10.14
- (Upgrade) .NET from 6.0.4 to 6.0.5
2022-05-16 01:25:21 +01:00

198 lines
6.0 KiB
C#

/*
* GNU AFFERO GENERAL PUBLIC LICENSE
* Version 3, 19 November 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using UVtools.Core.FileFormats;
using UVtools.Core.Scripting;
namespace UVtools.Core.Operations;
[Serializable]
public sealed class OperationScripting : Operation
{
#region Members
public event EventHandler? OnScriptReload;
private string? _filePath;
private string? _scriptText;
private ScriptState? _scriptState;
#endregion
#region Overrides
public override bool CanRunInPartialMode => true;
//public override bool CanHaveProfiles => false;
public override string IconClass => "fas fa-code";
public override string Title => "Scripting";
public override string Description =>
$"Run external scripts to manipulate the loaded file.\n" +
$"The scripts have wide access to your system and able to do modifications, read/write files, etc. " +
$"Make sure to run only the scripts you trust! Or run UVtools in a sandbox while executing this.";
public override string ConfirmationText =>
$"run the {ScriptGlobals?.Script.Name} script from layers {LayerIndexStart} through {LayerIndexEnd}?";
public override string ProgressTitle =>
$"Scripting from layers {LayerIndexStart} through {LayerIndexEnd}";
public override string ProgressAction => "Scripted layers";
public override string? ValidateInternally()
{
if (!CanExecute)
{
if (ScriptGlobals is not null && About.Version.CompareTo(ScriptGlobals.Script.MinimumVersionToRun) >= 0)
{
return
$"Unable to run due {About.Software} version {About.VersionStr} is lower than required {ScriptGlobals.Script.MinimumVersionToRun}\n" +
$"Please update {About.Software} in order to run this script.";
}
return "Script is not loaded.";
}
var scriptValidation = _scriptState!.ContinueWithAsync<string?>("return ScriptValidate();").Result;
return scriptValidation.ReturnValue;
}
public override string ToString()
{
var result = $"[{Path.GetFileName(_filePath)}]" + LayerRangeString;
if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
return result;
}
#endregion
#region Enums
#endregion
#region Properties
[XmlIgnore]
public ScriptGlobals? ScriptGlobals { get; private set; }
public string? FilePath
{
get => _filePath;
set
{
if (value is null)
{
RaiseAndSetIfChanged(ref _filePath, null);
}
else
{
if (!value.EndsWith(".csx") && !value.EndsWith(".cs")) return;
if (!File.Exists(value)) return;
if (!RaiseAndSetIfChanged(ref _filePath, value)) return;
}
RaisePropertyChanged(nameof(HaveFile));
}
}
[XmlIgnore]
public string? ScriptText
{
get => _scriptText;
set => RaiseAndSetIfChanged(ref _scriptText, value);
}
public bool CanExecute => !string.IsNullOrWhiteSpace(_filePath) && _scriptState is not null && ScriptGlobals is not null && About.Version.CompareTo(ScriptGlobals.Script.MinimumVersionToRun) >= 0;
public bool HaveFile => !string.IsNullOrWhiteSpace(_filePath);
/*public override string ToString()
{
var result = $"[{_infillType}] [Wall: {_wallThickness}px] [B: {_infillBrightness}px] [T: {_infillThickness}px] [S: {_infillSpacing}px]" + LayerRangeString;
if (!string.IsNullOrEmpty(ProfileName)) result = $"{ProfileName}: {result}";
return result;
}*/
#endregion
#region Constructor
public OperationScripting() { }
public OperationScripting(FileFormat slicerFile) : base(slicerFile)
{ }
#endregion
#region Equality
private bool Equals(OperationScripting other)
{
return _filePath == other._filePath;
}
public override bool Equals(object? obj)
{
return ReferenceEquals(this, obj) || obj is OperationScripting other && Equals(other);
}
public override int GetHashCode()
{
return (_filePath != null ? _filePath.GetHashCode() : 0);
}
#endregion
#region Methods
public void ReloadScriptFromFile(string? filePath = null)
{
if (!string.IsNullOrWhiteSpace(filePath)) FilePath = filePath;
if (string.IsNullOrWhiteSpace(_filePath) || !File.Exists(_filePath)) return;
ReloadScriptFromText(File.ReadAllText(_filePath));
}
public void ReloadScriptFromText(string? text = null)
{
if (!string.IsNullOrWhiteSpace(text)) ScriptText = text;
if (string.IsNullOrWhiteSpace(_scriptText)) return;
ScriptText = ScriptParser.ParseScriptFromText(_scriptText);
ScriptGlobals = new ScriptGlobals { SlicerFile = SlicerFile, Operation = this };
_scriptState = CSharpScript.RunAsync(_scriptText,
ScriptOptions.Default.AddReferences(typeof(About).Assembly).WithAllowUnsafe(true),
ScriptGlobals).Result;
var result = _scriptState.ContinueWithAsync("ScriptInit();").Result;
RaisePropertyChanged(nameof(CanExecute));
OnScriptReload?.Invoke(this, EventArgs.Empty);
}
protected override bool ExecuteInternally(OperationProgress progress)
{
if (ScriptGlobals is null || _scriptState is null) return false;
ScriptGlobals.Progress = progress;
var scriptExecute = _scriptState.ContinueWithAsync<bool>("return ScriptExecute();").Result;
return !progress.Token.IsCancellationRequested && scriptExecute.ReturnValue;
}
#endregion
}