| 1 | /*++ |
| 2 | |
| 3 | Copyright (c) Microsoft. All rights reserved. |
| 4 | |
| 5 | Module Name: |
| 6 | |
| 7 | Terminal.cpp |
| 8 | |
| 9 | Abstract: |
| 10 | |
| 11 | Implementation of Terminal. |
| 12 | |
| 13 | --*/ |
| 14 | #include "precomp.h" |
| 15 | #include "Terminal.h" |
| 16 | |
| 17 | namespace wsl::windows::wslc { |
| 18 | |
| 19 | using namespace wsl::windows::common::vt; |
| 20 | |
| 21 | Terminal::Terminal() : |
| 22 | m_out(GetStdHandle(STD_OUTPUT_HANDLE), stdout), m_err(GetStdHandle(STD_ERROR_HANDLE), stderr), m_in(GetStdHandle(STD_INPUT_HANDLE), stdin) |
| 23 | { |
| 24 | } |
| 25 | |
| 26 | Terminal::Terminal(FILE* outFile, bool outVtEnabled, FILE* errFile, bool errVtEnabled, FILE* inFile, bool inInteractive) : |
| 27 | m_out(outFile, outVtEnabled), m_err(errFile, errVtEnabled), m_in(inFile, inInteractive) |
| 28 | { |
| 29 | } |
| 30 | |
| 31 | std::wstring_view Terminal::LevelPrefix(Level level) const noexcept |
| 32 | { |
| 33 | if (!IsColorEnabled(level)) |
| 34 | { |
| 35 | return {}; |
| 36 | } |
| 37 | |
| 38 | switch (level) |
| 39 | { |
| 40 | case Level::Warning: |
| 41 | return Format::Fg::BrightYellow.Get(); |
| 42 | case Level::Error: |
| 43 | return Format::Fg::BrightRed.Get(); |
| 44 | default: |
| 45 | return {}; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | bool Terminal::IsVTEnabled(Level level) const noexcept |
| 50 | { |
| 51 | return ChannelFor(level).IsVTEnabled(); |
| 52 | } |
| 53 | |
| 54 | bool Terminal::IsColorEnabled(Level level) const noexcept |
| 55 | { |
| 56 | return ChannelFor(level).IsVTEnabled() && !m_noColor; |
| 57 | } |
| 58 | |
| 59 | std::optional<int> Terminal::GetConsoleWidth(Level level) const |
| 60 | { |
| 61 | return ChannelFor(level).GetConsoleWidth(); |
| 62 | } |
| 63 | |
| 64 | std::wstring Terminal::PromptForLine(Level level, std::wstring_view label, bool mask) |
| 65 | { |
| 66 | // Write the label without a trailing newline so the cursor stays inline (matching |
| 67 | // Docker's prompt behavior), then flush so it reaches the user before the blocking read. |
| 68 | Write(level, L"{}", label); |
| 69 | ChannelFor(level).Flush(); |
| 70 | |
| 71 | const bool willMask = mask && m_in.IsInteractive(); |
| 72 | auto line = m_in.ReadLine(mask); |
| 73 | |
| 74 | // When echo was masked the user's Enter was not echoed, so advance the line here. |
| 75 | if (willMask) |
| 76 | { |
| 77 | Write(level, L"\n"); |
| 78 | } |
| 79 | |
| 80 | return line.value_or(std::wstring{}); |
| 81 | } |
| 82 | |
| 83 | } // namespace wsl::windows::wslc |