Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Pansies.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Pansies", "Pansies.csproj", "{9037884B-464E-7D76-D4CA-093F85B25B46}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9037884B-464E-7D76-D4CA-093F85B25B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9037884B-464E-7D76-D4CA-093F85B25B46}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9037884B-464E-7D76-D4CA-093F85B25B46}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9037884B-464E-7D76-D4CA-093F85B25B46}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B791020B-78E4-4968-B1D3-1EB8DB93C7C8}
EndGlobalSection
EndGlobal
26 changes: 26 additions & 0 deletions Source/Assembly/ColorSpaceConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using PoshCode.Pansies.ColorSpaces;
using PoshCode.Pansies.ColorSpaces.Conversions;

namespace PoshCode.Pansies
{
/// <summary>
/// Provides helpers for configuring color space defaults exposed to PowerShell consumers.
/// </summary>
public static class ColorSpaceConfiguration
{
public static IXyz GetWhiteReference()
{
return XyzConverter.GetWhiteReference();
}

public static void SetWhiteReference(IXyz whiteReference)
{
XyzConverter.SetWhiteReference(whiteReference);
}

public static void ResetWhiteReference()
{
XyzConverter.ResetWhiteReference();
}
}
}
65 changes: 59 additions & 6 deletions Source/Assembly/ColorSpaces/Conversions/XyzConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,70 @@ namespace PoshCode.Pansies.ColorSpaces.Conversions
{
internal static class XyzConverter
{
private static readonly object WhiteReferenceLock = new object();
private static readonly Xyz DefaultWhiteReference = new Xyz
{
X = 95.047,
Y = 100.000,
Z = 108.883
};

#region Constants/Helper methods for Xyz related spaces
internal static IXyz WhiteReference { get; private set; } // TODO: Hard-coded!
internal static IXyz WhiteReference { get; private set; }
internal const double Epsilon = 0.008856; // Intent is 216/24389
internal const double Kappa = 903.3; // Intent is 24389/27

static XyzConverter()
{
WhiteReference = new Xyz
ResetWhiteReference();
}

public static IXyz GetWhiteReference()
{
lock (WhiteReferenceLock)
{
return Clone(WhiteReference ?? DefaultWhiteReference);
}
}

public static void SetWhiteReference(IXyz whiteReference)
{
if (whiteReference is null)
{
throw new ArgumentNullException(nameof(whiteReference));
}

lock (WhiteReferenceLock)
{
WhiteReference = Clone(whiteReference);
}
}

public static void ResetWhiteReference()
{
lock (WhiteReferenceLock)
{
WhiteReference = Clone(DefaultWhiteReference);
}
}

private static Xyz Clone(IXyz source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}

if (source is Xyz xyz)
{
return new Xyz(xyz.X, xyz.Y, xyz.Z);
}

return new Xyz
{
X = 95.047,
Y = 100.000,
Z = 108.883
X = source.X,
Y = source.Y,
Z = source.Z
};
}

Expand Down Expand Up @@ -72,4 +125,4 @@ private static double PivotRgb(double n)
return (n > 0.04045 ? Math.Pow((n + 0.055) / 1.055, 2.4) : n / 12.92) * 100.0;
}
}
}
}
239 changes: 239 additions & 0 deletions Source/Assembly/Commands/ExpandVariableCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Text;

namespace PoshCode.Pansies.Commands
{
[Cmdlet("Expand", "Variable", DefaultParameterSetName = ParameterSetContent)]
[OutputType(typeof(string))]
public sealed class ExpandVariableCommand : PSCmdlet
{
private const string ParameterSetPath = "Path";
private const string ParameterSetContent = "Content";

[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSetPath)]
[Alias("PSPath")]
public string Path { get; set; } = string.Empty;

[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ParameterSetContent)]
public string Content { get; set; } = string.Empty;

[Parameter]
public SwitchParameter Unescaped { get; set; }

/// <summary>
/// Specifies which drives to use for variable expansion. Each drive represents a different source or type of variable:
/// <list type="bullet">
/// <item><term>bg</term><description>Background color variables.</description></item>
/// <item><term>emoji</term><description>Emoji variables.</description></item>
/// <item><term>esc</term><description>Escape sequence variables.</description></item>
/// <item><term>extra</term><description>Extra or custom variables.</description></item>
/// <item><term>fg</term><description>Foreground color variables.</description></item>
/// <item><term>nf</term><description>Nerd Font icon variables.</description></item>
/// <item><term>variable</term><description>Standard PowerShell variables.</description></item>
/// </list>
/// By specifying one or more drives, you control which sources are used during variable expansion.
/// </summary>
[Parameter]
public string[] Drive { get; set; } = new[] { "bg", "emoji", "esc", "extra", "fg", "nf", "variable" };

[Parameter(ParameterSetName = ParameterSetPath)]
public SwitchParameter InPlace { get; set; }

[Parameter(ParameterSetName = ParameterSetPath)]
public SwitchParameter Passthru { get; set; }

protected override void ProcessRecord()
{
if (ParameterSetName == ParameterSetContent)
{
var result = ExpandVariable(Content ?? string.Empty, "Content");

if (result != null)
{
WriteObject(result);
}

return;
}

var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out var providerInfo);

foreach (var resolvedPath in resolvedPaths)
{
var fullName = BuildProviderQualifiedPath(providerInfo, resolvedPath);
var value = GetVariableValue(fullName);
var replacement = ExpandVariable(value?.ToString() ?? string.Empty, fullName);

if (replacement is null)
{
continue;
}

var isVariableProvider = string.Equals(providerInfo.Name, "Variable", StringComparison.OrdinalIgnoreCase);
var passthruPath = fullName;

if (isVariableProvider && fullName.IndexOf(':') < 0)
{
passthruPath = providerInfo.Name + ":" + fullName;
}

if (InPlace)
{
if (isVariableProvider)
{
var variableName = passthruPath;

var providerSeparator = variableName.IndexOf(':');

if (providerSeparator >= 0)
{
variableName = variableName.Substring(providerSeparator + 1);
}

var variable = SessionState.PSVariable.Get(variableName);

if (variable != null)
{
variable.Value = replacement;
SessionState.PSVariable.Set(variable);
}
else
{
SessionState.PSVariable.Set(variableName, replacement);
}
}
else
{
SessionState.InvokeProvider.Item.Set(passthruPath, replacement);
}

if (Passthru)
{
if (isVariableProvider)
{
WriteObject(replacement);
}
else
{
WriteObject(SessionState.InvokeProvider.Item.Get(passthruPath), true);
}
}
}
else
{
WriteObject(replacement);
}
}
}

private static string BuildProviderQualifiedPath(ProviderInfo providerInfo, string path)
{
if (providerInfo.Name == "Variable" || providerInfo.Name == "FileSystem" || path.Contains(':'))
{
return path;
}

return $"{providerInfo.Name}:{path}";
}

private string ExpandVariable(string code, string source)
{
var replacements = new List<TextReplacement>();
var ast = Parser.ParseInput(code, source, out _, out var errors);

if (errors.Length > 0)
{
WriteError(new ErrorRecord(
new ParseException($"{errors.Length} Parse Errors in {source}, cannot expand."),
"ParseErrors",
ErrorCategory.InvalidOperation,
source));

return null;
}

var drives = new HashSet<string>(Drive, StringComparer.OrdinalIgnoreCase);

var variables = ast
.FindAll(node => node is VariableExpressionAst, searchNestedScriptBlocks: true)
.OfType<VariableExpressionAst>()
.Where(variable => ShouldExpand(variable, drives));

foreach (var variable in variables)
{
try
{
var replacement = GetVariableValue(variable.VariablePath.UserPath)?.ToString() ?? string.Empty;

if (!Unescaped)
{
replacement = replacement.ToPsEscapedString();
}

if (variable.Parent is ExpandableStringExpressionAst)
{
replacements.Add(new TextReplacement(replacement, variable.Extent));
}
else
{
replacements.Add(new TextReplacement("\"" + replacement + "\"", variable.Extent));
}
}
catch
{
WriteWarning($"VariableNotFound: '{variable.VariablePath.UserPath}' at {source}:{variable.Extent.StartLineNumber}:{variable.Extent.StartColumnNumber}");
}
}

var builder = new StringBuilder(code);

foreach (var replacement in replacements.OrderByDescending(r => r.StartOffset))
{
builder.Remove(replacement.StartOffset, replacement.Length)
.Insert(replacement.StartOffset, replacement.Text);
}

return builder.ToString();
}

private bool ShouldExpand(VariableExpressionAst variable, HashSet<string> drives)
{
if (!variable.VariablePath.IsDriveQualified)
{
return drives.Contains("variable");
}

return drives.Contains(variable.VariablePath.DriveName ?? "variable");
}

private sealed class TextReplacement
{
public TextReplacement(string text, IScriptExtent extent)
{
Text = text;
StartOffset = extent.StartOffset;
EndOffset = extent.EndOffset;
}

public string Text { get; }

public int StartOffset { get; }

public int EndOffset { get; }

public int Length => EndOffset - StartOffset;
}

private sealed class ParseException : Exception
{
public ParseException(string message)
: base(message)
{
}
}
}
}
14 changes: 14 additions & 0 deletions Source/Assembly/Commands/RestoreCursorPosition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Management.Automation;

namespace PoshCode.Pansies.Commands
{
[Cmdlet("Restore", "CursorPosition")]
public sealed class RestoreCursorPositionCommand : Cmdlet
{
protected override void EndProcessing()
{
Console.Write("\u001b8");
}
}
}
Loading