Skip to content

Discussion: PowerShell needs to support 24bit color. Where? How? #2381

Closed

Description

@Jaykul

Since the Windows console now has 24bit color support, it seems obvious to me that PowerShell needs to build support for that in the same release timeframe.

As a reminder, 24-bit color means 256 values each for red, green, blue -- without an alpha channel.

For the sake of argument, let's assume that at a minimum, Write-Host needs to support Foreground and Background colors as 24bit values ...

What should the syntax be for 24bit color?

The most obvious suggestion is the HTML #rrggbb syntax -- but that would be a comment. We could pass it as a quoted string, but we could also choose to accept simple unadorned rrggbb ...

A richer choice would be to add a [Color] type, which would allow for syntax like: [color]"336699" or even RGB values like [color](51, 102, 153) or even [color]@{h=210; s=50; l=40} (all of which represent the same color)...

Any other thoughts?

Where should colors work?

The most obvious place where this is definitely needed is in the Write-Host command.

However, I would also like support in the colors that are specified for $Host.PrivateData ... where I think it would be particularly helpful to be able to pick colors that are not one of the 16 colors, and of course, it would be wonderful if the core 16 colors could be available there as well, so that we could theme our console by just setting those values ;-)

Additionally, we need to be able to support colors in format files, perhaps we need foreground/background settings on the table/row/column/cell elements, or perhaps we just need a function like Get-AnsiCode, or a property on a type like the aforementioned [Color] so we could put the VT escape sequences into a string, like: Write-Host "$(([color](51, 102, 153)).Foreground)This is blue$([Color]::reset) and this isn't" ...

Finally, many modules (like PSReadLine and PowerLine) need to support colors, and I would really like them to all support the same syntax for setting colors (and/or the same Color type).

Have I missed anything?

Is there a better syntax? Other commands or classes that need colors? Do you wish I would just go off and do this in a module instead of asking for it in the core shell? Please speak up here!

Activity

  1. bobfrankly commented on Sep 28, 2016

    @bobfrankly

    I feel like a [color] type supporting RGB and HSL would be the most functional option, and agree that Write-Host is the obvious target for this. I would already be using it if it was available.

  2. added
    Issue-Discussion
    on Sep 28, 2016
  3. joeyaiello commented on Sep 29, 2016

    @joeyaiello
    Contributor

    This all looks pretty sound to me. Support casting multiple string and collection formats into a [Color] type.

    If you're ready to implement this, Joel Bennett (@Jaykul), feel free to submit it as an RFC.

  4. rkeithhill commented on Sep 29, 2016

    @rkeithhill
    Collaborator

    If folks want to use 24-bit color with Write-Host then it seems that PowerShell and/or .NET Core would have to adapt. Right now System.ConsoleColor is an enum defined as:

        [Serializable]
        public enum ConsoleColor
        {
            Black = 0,
            DarkBlue = 1,
            DarkGreen = 2,
            DarkCyan = 3,
            DarkRed = 4,
            DarkMagenta = 5,
            DarkYellow = 6,
            Gray = 7,
            DarkGray = 8,
            Blue = 9,
            Green = 10,
            Cyan = 11,
            Red = 12,
            Magenta = 13,
            Yellow = 14,
            White = 15
        }
    

    Where the int values identify a index in the current 16-color palette for the console.

    In the blog post announcing 24-bit color support for the Windows Console, they mentioned they have not updated the Console property page to support 24-bit color yet. It would be good to know what they have planned especially when it comes to surfacing this functionality through Win32 API and/or .NET Core.

    That said, I could imagine new parameter sets on Write-Host with new parameters like -Background and -Foreground (or maybe -Back/ForegroundTrueColor) that are of type System.Drawing.Color. PowerShell already knows how to convert int values to that type:

    97> [System.Drawing.Color]0xff0000
    
    
    R             : 255
    G             : 0
    B             : 0
    A             : 0
    IsKnownColor  : False
    IsEmpty       : False
    IsNamedColor  : False
    IsSystemColor : False
    Name          : ff0000
    

    And this type supports known color names:

    98> [System.Drawing.Color]::AliceBlue
    
    
    R             : 240
    G             : 248
    B             : 255
    A             : 255
    IsKnownColor  : True
    IsEmpty       : False
    IsNamedColor  : True
    IsSystemColor : False
    Name          : AliceBlue
    

    It has methods to return Hue, Saturation and Brightness. Unfortunately, I don't see a ctor or static method to construct an object from those values.

    Now for coloring strings not using Write-Host, then a class to help with the ANSI esc sequence would be very nice to have. Not sure what exactly that would look like but we should take a peek to see what the folks in the node community (chalk, ansi-256-colors, ansi-escapes) have done. I could see the community building modules to provide this functionality. No need for integration into PowerShell Core AFAICT.

  5. rkeithhill commented on Sep 29, 2016

    @rkeithhill
    Collaborator

    Doh! Looks like System.Drawing.Color is available only in .NET Core App >= 1.1. I assume PowerShell Core is currently .NET Core App 1.0?

  6. rkeithhill commented on Sep 29, 2016

    @rkeithhill
    Collaborator

    Also, FWIW I would want to specify unnamed colors like so 0xe90c1b but I think it would be easy to make most approaches accept this as it is the actual color value.

  7. Jaykul commented on Sep 29, 2016

    @Jaykul
    ContributorAuthor

    I suppose that using the existing type (that most of us are familiar with) is worth putting up with the useless alpha value, especially since it can already cast 0xrrggbb and names.

    I assume that PowerShell will update it's .Net Core eventually, but we could always just copy the code from the CoreFx repo. We could also add the type adapters or constructors or From___ methods etc. -- there are MIT licensed conversion routines on Colourful (and also ColorMine).

    We also need an XtermConsoleColor table. We could use that in place of the ConsoleColor since the first 16 of the Xterm color table are the same as the basic 16 ...

    However, the crucial part is a we also need to be able to map RGB values to the XtermConsoleColors, and even to the basic 16, because, you know ... not every terminal supports full color. I have to think about how to do that right. Colourful has a few difference implementations, but this would need to be fast...

    And yes, Keith Hill (@rkeithhill), there is, in fact, no API or anything that allows using the new colors in the Console currently, except VT ANSI escape sequences ... and that's really the only way I can see to implement it in format files anyway -- unless we extend them to support a color attribute all over the place.

    I'm ok with that. In fact I have already used them in file table formats the hard way, and that's how I implemented colors for PowerLine obviously.

  8. joeyaiello commented on Sep 29, 2016

    @joeyaiello
    Contributor

    Keith Hill (@rkeithhill) thanks for the heads up on Core's type. That seems like the way to go.

    we could always just copy the code from the CoreFx repo.

    I'd much rather we upgrade PowerShell Core to use .NET Core 1.1. Unless we're absolutely blocked and something is critical on a short time-span, we should avoid duplicating code as a general rule of thumb.

  9. lzybkr commented on Sep 29, 2016

    @lzybkr
    Contributor

    Regarding the Win32 API - we shouldn't care, it's not portable. That said, I believe the plan is no 24bit color support in the api, escapes sequences are the new api.

    There is mapping support in conhost to support the screen scraping apis which only have 4 bit color support. Maybe it's possible to use that code somehow, but maybe the right api is to report errors if the terminal doesn't support the colors you ask for.

  10. Jaykul commented on Sep 30, 2016

    @Jaykul
    ContributorAuthor

    Well Jason Shirk (@lzybkr), I think the right thing to do is probably to (copy what chalk does in this situation and) convert down. They use a javascript color-convert library for that, which has a nice simple down-sampling algorithm.

    Or just borrow from ObscureWare/Console.Core

  11. added
    Up-for-Grabs
    on Oct 25, 2016
  12. be5invis commented on Oct 26, 2016

    @be5invis

    Jason Shirk (@lzybkr)

    Just a mention, Example code used to produce colors:

    bool EnableVTMode()
    {
        // Set output mode to handle virtual terminal sequences
        HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
        if (hOut == INVALID_HANDLE_VALUE)
        {
            return false;
        }
    
        DWORD dwMode = 0;
        if (!GetConsoleMode(hOut, &dwMode))
        {
            return false;
        }
    
        dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        if (!SetConsoleMode(hOut, dwMode))
        {
            return false;
        }
        return true;
    }
    int __cdecl wmain(int argc, WCHAR* argv[])
    {   
        argc; // unused
        argv; // unused
        //First, enable VT mode
        bool fSuccess = EnableVTMode();
        if (!fSuccess)
        {
            printf("Unable to enter VT processing mode. Quitting.\n");
            return -1;
        }
        int red = 0; // set these to whatever
        int green = 0;
        int blue = 0;
        printf("\x1b[38;2;%d;%d;%dm", red, green, blue); // produces RGB foreground
        printf("\x1b[48;2;%d;%d;%dm", red, green, blue); // produces RGB background
    
        int index = 0;
        printf("\x1b[38;5;%dm", index); // produces xterm color table index foreground
        printf("\x1b[48;5;%dm", index); // produces xterm color table index background
    }

    cc. Mike Griese (@zadjii-msft)

  13. zadjii-msft commented on Oct 27, 2016

    @zadjii-msft

    Just to add my comments, I'm backing up Jason Shirk (@lzybkr) on what he said. We're not going to extend the Console API to add support for this. That just creates another API that .NET and others would have to try and translate manually when they port to other platforms. Emitting VT sequences is the new standard for console features (and it has been for decades, Windows is finally on the train).

    It's also notoriously tricky to determine what kind of actual color support a particular terminal provides. Most terminals set themselves as TERM=xterm, but then also support all the way to 24-bit color, while some applications like tmux only support 256color. I haven't found a good way to pick which of the sequences to go with, or determine what's possible, so I usually stick to just emitting xterm table sequences.

    That's my 2 cents.

  14. Jaykul commented on Mar 7, 2017

    @Jaykul
    ContributorAuthor

    Hey, Jason Shirk (@lzybkr) and Mike Griese (@zadjii-msft) -- I'm working on research for this, and was looking at related console APIs and the IShellLink API.

    Do either of you know if it's possible to determine (from within a PowerShell instance) whether a process was launched from a link or not, and if so, which link? That is, specifically, the "link" one was launched from, so as to change the properties (for future instances) the way the property dialog does?

    For instance, this MSDN page documents new shell features which have registry settings... unless the shell was launched from a shortcut. How could I tell this was the case?

  15. 17 remaining items

  16. rkeithhill commented on Jun 6, 2018

    @rkeithhill
    Collaborator

    9Rune5 This exists. Install the DirColors module for the PSGallery. It even supports a LS_COLORS style configuration.

  17. Jaykul commented on Dec 11, 2018

    @Jaykul
    ContributorAuthor

    UPDATE: As of Windows 10 build 18298, when you open the properties page of any Console window, you’ll notice an additional “Terminal” tab -- which among other things, allows one to set the default ForegroundColor and BackgroundColor to RGB values which are separate from the 16 color "ConsoleColor" palette.

    If these are set, then the PowerShell $Host.UI.RawUI values BackgroundColor and ForegroundColor are just plain wrong, and basically impossible to get right, since they only allow setting to ConsoleColor values (i.e. 0-16)

    By adding this setting, the Windows team has really thrown down the gauntlet on support for VT and RGB values instead of ConsoleColors -- there's no possible value for the current [ConsoleColor] properties that won't be wrong.

  18. ExE-Boss commented on Apr 19, 2019

    @ExE-Boss

    I use the Pansies module, which allows for using objects to store ANSI escape sequence data.

  19. Jaykul commented on May 16, 2019

    @Jaykul
    ContributorAuthor

    Joey Aiello (@joeyaiello) regarding your comments on the community call -- color is NOT something you can leave to the terminal. The terminal is built on top of the console. It supports and uses RGB color values and the XTerm 216-color (web-safe palette) but there's no API for them except VT escape sequences.

    PowerShell currently only supports the base 16 "ConsoleColors" for any of it's color parameters and properties, and switching to RGB requires using the VT escape sequences, which is not backwards-compatible with older versions of Windows.

    For instance, see what happens when the default foreground color is changed, in my stream:
    https://www.twitch.tv/videos/424738436?t=00h05m36s

  20. Delta456 commented on Oct 11, 2020

    @Delta456

    Currently with the latest release of Powershell 7. I can do 24 bit color via echo but it doesn't via os.system function of Python or print().

    pwsh_community

    I am working on Powershell 7 24 bit support of my module and I am stuck on this limitation :c Will love to see this fully supported.

  21. daxian-dbw commented on Nov 10, 2021

    @daxian-dbw
    Member

    Given that the new $PSStyle in 7.2 supports generating VT sequences for RGB color representation, can we consider this feature request done? /cc Steve Lee (@SteveL-MSFT)
    Example:

    image

  22. Jaykul commented on Nov 11, 2021

    @Jaykul
    ContributorAuthor

    Given that the new $PSStyle in 7.2 supports generating VT sequences for RGB color representation, can we consider this feature request done?

    Sure. It's not (in my opinion) a great implementation, still does not feel fully featured -- but since it's released, obviously the answer to how PowerShell will support color is:

    1. There is a built-in $PSStyles object with Foreground and Background properties that have nested FromRgb helper functions to generate full RGB ANSI escape sequences...
    2. The built-in $PSStyles object includes a few hashtables of arbitrary colors they can theme
    3. Users can figure out whether their terminal supports full RGB, 16 colors, or 256 colors and set $PSStyle colors appropriately as they wish in their profile on every load.

    It could be a lot more usable. In particular, burying the support for FromRgb in properties of the $PSStyle object is obscure, and not supporting that syntax directly on Write-Host is disappointing, and I'm frustrated that you broke all existing code that changed colors on warnings/errors etc. #16441

  23. ghost closed this as completedon Nov 12, 2021
  24. poidah commented on Feb 6, 2023

    @poidah

    This is definately NOT fixed...

    Please, just add HEX values as an option and be done with it.

    Do not make this harder than it needs to be just so you can show off how much you know.

    You can show off by making this as easy as possible for the use-user (coder) :)

    Link to related post

  25. Diom commented on Mar 1, 2023

    @Diom

    I agree with Peter Vincent (@poidah) and Joel Bennett (@Jaykul) ... this is not a good solution.
    I already know how to use ANSI escape code, and I know how to create variables with the escape codes. This solution is barely better than escape code, and requires me to pollute the message string with markup (or write a filter that does it)

    I want a solution that does Write-Host "hi" -ForegroundColor "#AFA" and can automatically fallback to plain output when the terminal does not support the colors.

  26. Jaykul commented on Oct 28, 2023

    @Jaykul
    ContributorAuthor

    I want a solution that does Write-Host "hi" -ForegroundColor "#AFA" and can automatically fallback to plain output when the terminal does not support the colors.

    Come help build Pansies

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-DiscussionResolution-FixedUp-for-GrabsWG-Interactive-Console

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions