PowerLine.psm1

#!/usr/bin/env powershell
using namespace System.Collections.Generic
using namespace PoshCode.Pansies

$script:PowerLineRoot = $PSScriptRoot

if($PSVersionTable.PSVersion -lt "6.0") {
    Add-Type -Path $PSScriptRoot\lib\net451\PowerLine.dll
} else {
    Add-Type -Path $PSScriptRoot\lib\netstandard1.6\PowerLine.dll
}

if(!$PowerLinePrompt) {
    [PowerLine.Prompt]$Script:PowerLinePrompt = @(,@(
        @{ bg = "Cyan";     fg = "White"; text = { $MyInvocation.HistoryId } },
        @{ bg = "DarkBlue"; fg = "White"; text = { Get-SegmentedPath } }
    ))
}
function Add-PowerLineBlock {
    <#
        .Synopsis
            Insert a PowerLine block into the $PowerLinePrompt
        .Description
            Allows changing the foreground and background colors based on elevation or success.
 
            Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not.
        .Example
            New-PowerLineBlock (Get-Elapsed) -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
 
            This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error.
    #>

    [CmdletBinding(DefaultParameterSetName="Error")]
    param(
        # The text, object, or scriptblock to show as output
        [Parameter(Position=0, Mandatory=$true)]
        [Alias("Text")]
        $Object,

        # The foreground color to use when the last command succeeded
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [RgbColor]$ErrorBackgroundColor,

        # The line to insert the block to. Index starts at 0.
        # If the number is out of range, a new line will be added to the prompt
        # Defaults to -1 (the last line).
        [int]$Line = -1,

        # The column to insert the block to (Left or Right aligned).
        # Defaults to the Left column
        [ValidateSet("Left","Right")]
        [string]$Column = "Left",

        # The position in column to insert the block to. The left-aligned column is 0, the right-aligned column is 1.
        # Defaults to append at the end.
        [ValidateSet(-1,0,1)]
        [int]$InsertAt = -1
    )
    $Parameters = @{} + $PSBoundParameters
    # Remove the position parameters:
    $null = $Parameters.Remove("Line")
    $null = $Parameters.Remove("Column")
    $null = $Parameters.Remove("InsertAt")

    $blocks = [PowerLine.TextFactory]$Parameters

    if($Line -gt ($global:PowerLinePrompt.Lines.Count - 1)) {
        $null = $global:PowerLinePrompt.Add((New-Object PowerLine.Line))
        $Line = -1
    }

    [int]$Column = if($Column -eq "Left") { 0 } else { 1 }
    if($Column -gt ($global:PowerLinePrompt.Lines[$Line].Columns.Count - 1)) {
        $null = $global:PowerLinePrompt.Lines[$Line].Columns.Add((New-Object PowerLine.Column))
    }

    if($InsertAt -lt 0 -or $InsertAt -gt $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Count) {
        $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Add($blocks)
    } else {
        $global:PowerLinePrompt.Lines[$Line].Columns[$Column].Blocks.Insert($InsertAt,$blocks)
    }
}
function Get-Elapsed {
    <#
    .Synopsis
        Get the time span elapsed during the execution of command (by default the previous command)
    .Description
        Calls Get-History to return a single command and returns the difference between the Start and End execution time
    #>

    [CmdletBinding()]
    param(
        # The command ID to get the execution time for (defaults to the previous command)
        [Parameter()]
        [int]$Id,

        # A Timespan format pattern such as "{0:ss\.ffff}"
        [Parameter()]
        [string]$Format = "{0:h\:mm\:ss\.ffff}"
    )
    $null = $PSBoundParameters.Remove("Format")
    $LastCommand = Get-History -Count 1 @PSBoundParameters
    if(!$LastCommand) { return "" }
    $Duration = $LastCommand.EndExecutionTime - $LastCommand.StartExecutionTime
    $Format -f $Duration
}
function Get-SegmentedPath {
    <#
    .Synopsis
        Gets PowerLine Blocks for each folder in the path
    .Description
        Returns an array of hashtables which can be cast to PowerLine Blocks.
        Includes support for limiting the number of segments or total length of the path, but defaults to 3 segments max
    #>

    [CmdletBinding(DefaultParameterSetName="Segments")]
    param(
        # The path to segment. Defaults to $pwd
        [Parameter(Position=0)]
        [string]
        $Path = $pwd,

        # The maximum number of segments. Defaults to 3
        [Parameter(ParameterSetName="Segments")]
        $SegmentLimit = 3,

        # The maximum length. Defaults to 0 (no max)
        [Parameter(ParameterSetName="Length")]
        [int]
        $LengthLimit = 0,

        # The foreground color to use when the last command succeeded
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [RgbColor]$ErrorBackgroundColor
    )

    $buffer = @()

    if($Path.ToLower().StartsWith($Home.ToLower())) {
        $Path = '~' + $Path.Substring($Home.Length)
    }
    Write-Verbose $Path
    while($Path) {
        $buffer += if($Path -eq "~") {
            @{ Object = $Path }
        } else {
            @{ Object = Split-Path $Path -Leaf }
        }
        $Path = Split-Path $Path

        Write-Verbose $Path

        if($Path -and $SegmentLimit -le $buffer.Count) {
            if($buffer.Count -gt 1) {
                $buffer[-1] = @{ Object = [char]0x2026; }
            } else {
                $buffer += @{ Object = [char]0x2026; }
            }
            break
        }

        if($LengthLimit) {
            $CurrentLength = ($buffer.Object | Measure-Object Length -Sum).Sum + $buffer.Count - 1
            $Tail = if($Path) { 2 } else { 0 }

            if($LengthLimit -lt $CurrentLength + $Tail) {
                if($buffer.Count -gt 1) {
                    $buffer[-1] = @{ Object = [char]0x2026; }
                } else {
                    $buffer += @{ Object = [char]0x2026; }
                }
                break
            }
        }
    }
    [Array]::Reverse($buffer)

    foreach($output in $buffer) {

        # Always set the defaults first, if they're provided
        if($PSBoundParameters.ContainsKey("ForegroundColor")) {
            $output.ForegroundColor = $ForegroundColor
        }
        if($PSBoundParameters.ContainsKey("BackgroundColor")) {
            $output.BackgroundColor = $BackgroundColor
        }

        # If it's elevated, and they passed the elevated color ...
        if(Test-Elevation) {
            if($PSBoundParameters.ContainsKey("ElevatedForegroundColor")) {
                $output.ForegroundColor = $ElevatedForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor")) {
                $output.BackgroundColor = $ElevatedBackgroundColor
            }
        }

        # If it failed, and they passed an error color ...
        if(!(Test-Success)) {
            if($PSBoundParameters.ContainsKey("ErrorForegroundColor")) {
                $output.ForegroundColor = $ErrorForegroundColor
            }
            if($PSBoundParameters.ContainsKey("ErrorBackgroundColor")) {
                $output.BackgroundColor = $ErrorBackgroundColor
            }
        }
    }
    $buffer
}
function Get-ShortenedPath {
    [CmdletBinding()]
    param(
        [Parameter(Position=0)]
        [string]
        $Path = $pwd,

        [Parameter()]
        [switch]
        $RelativeToHome,

        [Parameter()]
        [int]
        $MaximumLength = [int]::MaxValue,

        [Parameter()]
        [switch]
        $SingleCharacterSegment        
    )

    if ($MaximumLength -le 0) {
        return [string]::Empty
    }

    if ($RelativeToHome -and $Path.ToLower().StartsWith($Home.ToLower())) {
        $Path = '~' + $Path.Substring($Home.Length)
    }

    if (($MaximumLength -gt 0) -and ($Path.Length -gt $MaximumLength)) {
        $Path = $Path.Substring($Path.Length - $MaximumLength)
        if ($Path.Length -gt 3) {
            $Path = "..." + $Path.Substring(3)
        }
    }

    # Credit: http://www.winterdom.com/powershell/2008/08/13/mypowershellprompt.html
    if ($SingleCharacterSegment) {
        # Remove prefix for UNC paths
        $Path = $Path -replace '^[^:]+::', ''
        # handle paths starting with \\ and . correctly
        $Path = ($Path -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
    }

    $Path
}
set-alias New-PowerLineBlock New-TextFactory
function New-TextFactory {
    <#
        .Synopsis
            Create PowerLine.TextFactory with variable background colors
        .Description
            Allows changing the foreground and background colors based on elevation or success.
 
            Tests elevation fist, and then whether the last command was successful, so if you pass separate colors for each, the Elevated*Color will be used when PowerShell is running as administrator and there is no error. The Error*Color will be used whenever there's an error, whether it's elevated or not.
        .Example
            New-TextFactory (Get-Elapsed) -ForegroundColor White -BackgroundColor DarkBlue -ErrorBackground DarkRed -ElevatedForegroundColor Yellow
 
            This example shows the time elapsed executing the last command in White on a DarkBlue background, but switches the text to yellow if elevated, and the background to red on error.
    #>

    [CmdletBinding(DefaultParameterSetName="Error")]
    param(
        # The text, object, or scriptblock to show as output
        [Alias("Text")]
        [AllowNull()][AllowEmptyString()]
        [Parameter(Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)] # , Mandatory=$true
        $Object,

        # The foreground color to use when the last command succeeded
        [Alias("Foreground", "Fg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ForegroundColor,

        # The background color to use when the last command succeeded
        [Alias("Background", "Bg")]
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$BackgroundColor,

        # The foreground color to use when the process is elevated (running as administrator)
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ElevatedForegroundColor,

        # The background color to use when the process is elevated (running as administrator)
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ElevatedBackgroundColor,

        # The foreground color to use when the last command failed
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ErrorForegroundColor,

        # The background color to use when the last command failed
        [Parameter(ValueFromPipelineByPropertyName)]
        [RgbColor]$ErrorBackgroundColor
    )
    $output = [PowerLine.TextFactory]@{
        Object = $Object
    }
    # Always set the defaults first, if they're provided
    if($PSBoundParameters.ContainsKey("ForegroundColor")) {
        $output.DefaultForegroundColor = $ForegroundColor
    }
    if($PSBoundParameters.ContainsKey("BackgroundColor")) {
        $output.DefaultBackgroundColor = $BackgroundColor
    }

    # If it's elevated, and they passed the elevated color ...
    if(Test-Elevation) {
        if($PSBoundParameters.ContainsKey("ElevatedForegroundColor")) {
            $output.DefaultForegroundColor = $ElevatedForegroundColor
        }
        if($PSBoundParameters.ContainsKey("ElevatedBackgroundColor")) {
            $output.DefaultBackgroundColor = $ElevatedBackgroundColor
        }
    }

    # If it failed, and they passed an error color ...
    if(!(Test-Success)) {
        if($PSBoundParameters.ContainsKey("ErrorForegroundColor")) {
            $output.DefaultForegroundColor = $ErrorForegroundColor
        }
        if($PSBoundParameters.ContainsKey("ErrorBackgroundColor")) {
            $output.DefaultBackgroundColor = $ErrorBackgroundColor
        }
    }

    $output.GetText()
}
function Set-PowerLinePrompt {
    #.Synopsis
    # Set the default PowerLine prompt function which uses the $PowerLinePrompt variable
    #.Description
    # Overwrites the current prompt function with one that uses the PowerLinePrompt variable
    # Note that this doesn't try to preserve any changes already made to the prompt by modules like ZLocation
    #.Example
    # Set-PowerLinePrompt -CurrentDirectory
    #
    # Sets the powerline prompt and activates and option supported by this prompt function to update the .Net environment with the current directory each time the prompt runs.
    #.Example
    # Set-PowerLinePrompt -PowerLineFont
    #
    # Sets the powerline prompt using the actual PowerLine font characters, and ensuring that we're using the default characters. Note that you can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator...
    #.Example
    # Set-PowerLinePrompt -ResetSeparators
    #
    # Sets the powerline prompt and forces the use of "safe" separator characters. You can still change the characters used to separate blocks in the PowerLine output after running this, by setting the static members of [PowerLine.Prompt] like Separator and ColorSeparator...
    #.Example
    # Set-PowerLinePrompt -UseAnsiEscapes
    #
    # Sets the powerline prompt and forces the use of ANSI escape sequences in the string output (rather than Write-Host) to change colors, regardless of what we're able to detect about the console.
    [CmdletBinding(DefaultParameterSetName="PowerLine")]
    param(
        # A script which outputs a string used to update the Window Title each time the prompt is run
        [scriptblock]$Title,

        # Keep the .Net Current Directory in sync with PowerShell's
        [switch]$CurrentDirectory,

        # If true, set the [PowerLine.Prompt] static members to extended characters from PowerLine fonts
        [Parameter(ParameterSetName="PowerLine")]
        [switch]$PowerLineFont,

        # If true, set the [PowerLine.Prompt] static members to characters available in Consolas and Courier New
        [Parameter(ParameterSetName="Reset")]
        [switch]$ResetSeparators,

        # If true, override the default testing for ANSI consoles and force the use of Escape Sequences rather than Write-Host
        [Parameter()]
        [switch]$UseAnsiEscapes = $($Host.UI.SupportsVirtualTerminal -or $Env:ConEmuANSI -eq "ON"),

        # If true, adds ENABLE_VIRTUAL_TERMINAL_PROCESSING to the console output mode. Useful on PowerShell versions that don't restore the console
        [Parameter()]
        [switch]$RestoreVirtualTerminal
    )
    if($null -eq $script:OldPrompt) {
        $script:OldPrompt = $function:global:prompt
        $MyInvocation.MyCommand.Module.OnRemove = {
            $function:global:prompt = $script:OldPrompt
        }
    }
    if($PSBoundParameters.ContainsKey("Title")) {
        $global:PowerLinePrompt.Title = $Title
    }
    if($PSBoundParameters.ContainsKey("CurrentDirectory")) {
        $global:PowerLinePrompt.SetCurrentDirectory = $CurrentDirectory
    }

    $global:PowerLinePrompt.UseAnsiEscapes = $UseAnsiEscapes
    $global:PowerLinePrompt.RestoreVirtualTerminal = $RestoreVirtualTerminal


    if($ResetSeparators -or ($PSBoundParameters.ContainsKey("PowerLineFont") -and !$PowerLineFont) ) {
        # Use characters that at least work in Consolas
        [PowerLine.Prompt]::ColorSeparator  = [char]0x258C
        [PowerLine.Prompt]::ReverseColorSeparator = [char]0x2590
        [PowerLine.Prompt]::Separator  = [char]0x25BA
        [PowerLine.Prompt]::ReverseSeparator = [char]0x25C4
        [PowerLine.Prompt]::Branch   = [char]0x00A7
        [PowerLine.Prompt]::Gear     = [char]0x263C
    }
    if($PowerLineFont) {
        # Make sure we're using the PowerLine custom use extended characters:
        [PowerLine.Prompt]::ColorSeparator = [char]0xe0b0
        [PowerLine.Prompt]::ReverseColorSeparator = [char]0xe0b2
        [PowerLine.Prompt]::Separator = [char]0xe0b1
        [PowerLine.Prompt]::ReverseSeparator = [char]0xe0b3
        [PowerLine.Prompt]::Branch   = [char]0xE0A0
        [PowerLine.Prompt]::Gear     = [char]0x26EF
    }

    $function:global:prompt =  {

        # FIRST, make a note if there was an error in the previous command
        [bool]$script:LastSuccess = $?

        try {
            if($global:PowerLinePrompt.Title) {
                $Host.UI.RawUI.WindowTitle = [System.Management.Automation.LanguagePrimitives]::ConvertTo( (& $global:PowerLinePrompt.Title), [string] )
            }
            if($global:PowerLinePrompt.SetCurrentDirectory) {
                # Make sure Windows & .Net know where we are
                # They can only handle the FileSystem, and not in .Net Core
                [System.IO.Directory]::SetCurrentDirectory( (Get-Location -PSProvider FileSystem).ProviderPath )
            }
        } catch {}

        if ($global:PowerLinePrompt.RestoreVirtualTerminal) {
            [PoshCode.Pansies.Console.WindowsHelper]::EnableVirtualTerminalProcessing()
        }
        $global:PowerLinePrompt.ToString($Host.UI.RawUI.BufferSize.Width)
    }
}
function Test-Elevation {
    <#
    .Synopsis
        Get a value indicating whether the process is elevated (running as administrator)
    #>

    [CmdletBinding()]
    param()

    [Security.Principal.WindowsIdentity]::GetCurrent().Owner -eq 'S-1-5-32-544'
}
function Test-Success {
    <#
    .Synopsis
        Get a value indicating whether the last command succeeded or not
    #>

    [CmdletBinding()]
    param()

    $script:LastSuccess
}