File size: 19,323 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
// interfaces for host interaction
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Tear off class.
/// </summary>
internal class DisplayCellsHost : DisplayCells
{
internal DisplayCellsHost(PSHostRawUserInterface rawUserInterface)
{
_rawUserInterface = rawUserInterface;
}
internal override int Length(string str, int offset)
{
if (string.IsNullOrEmpty(str))
{
return 0;
}
if (offset < 0 || offset >= str.Length)
{
throw PSTraceSource.NewArgumentException(nameof(offset));
}
try
{
var valueStrDec = new ValueStringDecorated(str);
if (valueStrDec.IsDecorated)
{
str = valueStrDec.ToString(OutputRendering.PlainText);
}
int length = 0;
for (; offset < str.Length; offset++)
{
length += _rawUserInterface.LengthInBufferCells(str[offset]);
}
return length;
}
catch
{
// thrown when external host rawui is not implemented, in which case
// we will fallback to the default value.
return base.Length(str, offset);
}
}
internal override int Length(char character)
{
try
{
return _rawUserInterface.LengthInBufferCells(character);
}
catch
{
// thrown when external host rawui is not implemented, in which case
// we will fallback to the default value.
return base.Length(character);
}
}
private readonly PSHostRawUserInterface _rawUserInterface;
}
/// <summary>
/// Implementation of the LineOutput interface on top of Console and RawConsole.
/// </summary>
internal sealed class ConsoleLineOutput : LineOutput
{
#region tracer
[TraceSource("ConsoleLineOutput", "ConsoleLineOutput")]
internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput");
#endregion tracer
/// <summary>
/// The default buffer cell calculation already works for the PowerShell console host and Visual studio code host.
/// </summary>
private static readonly HashSet<string> s_psHost = new(StringComparer.Ordinal) { "ConsoleHost", "Visual Studio Code Host" };
#region LineOutput implementation
/// <summary>
/// The # of columns is just the width of the screen buffer (not the
/// width of the window)
/// </summary>
/// <value></value>
internal override int ColumnNumber
{
get
{
CheckStopProcessing();
PSHostRawUserInterface raw = _console.RawUI;
// IMPORTANT NOTE: we subtract one because
// we want to make sure the console's last column
// is never considered written. This causes the writing
// logic to always call WriteLine(), making sure a CR
// is inserted.
try
{
return _forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width;
}
catch
{
// thrown when external host rawui is not implemented, in which case
// we will fallback to the default value.
}
return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber;
}
}
/// <summary>
/// The # of rows is the # of rows visible in the window (and not the # of
/// rows in the screen buffer)
/// </summary>
/// <value></value>
internal override int RowNumber
{
get
{
CheckStopProcessing();
PSHostRawUserInterface raw = _console.RawUI;
try
{
return raw.WindowSize.Height;
}
catch
{
// thrown when external host rawui is not implemented, in which case
// we will fallback to the default value.
}
return _fallbackRawConsoleRowNumber;
}
}
/// <summary>
/// Write a line to the output device.
/// </summary>
/// <param name="s">Line to write.</param>
internal override void WriteLine(string s)
{
CheckStopProcessing();
// delegate the action to the helper,
// that will properly break the string into
// screen lines
_writeLineHelper.WriteLine(s, this.ColumnNumber);
}
internal override DisplayCells DisplayCells
{
get
{
CheckStopProcessing();
if (_displayCellsHost != null)
{
return _displayCellsHost;
}
// fall back if we do not have a Msh host specific instance
return _displayCellsDefault;
}
}
#endregion
/// <summary>
/// Constructor for the ConsoleLineOutput.
/// </summary>
/// <param name="host">PSHostUserInterface to wrap.</param>
/// <param name="paging">True if we require prompting for page breaks.</param>
/// <param name="errorContext">Error context to throw exceptions.</param>
internal ConsoleLineOutput(PSHost host, bool paging, TerminatingErrorContext errorContext)
{
if (host == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(host));
}
if (errorContext == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(errorContext));
}
_console = host.UI;
_errorContext = errorContext;
if (paging)
{
tracer.WriteLine("paging is needed");
// If we need to do paging, instantiate a prompt handler that will take care of the screen interaction
string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt);
_prompt = new PromptHandler(promptString, this);
}
if (!s_psHost.Contains(host.Name) && _console.RawUI is not null)
{
// set only if we have a valid raw interface
tracer.WriteLine("there is a valid raw interface");
_displayCellsHost = new DisplayCellsHost(_console.RawUI);
}
// instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called
WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine);
WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite);
if (_forceNewLine)
{
_writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, null, this.DisplayCells);
}
else
{
_writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells);
}
}
/// <summary>
/// Callback to be called when ILineOutput.WriteLine() is called by WriteLineHelper.
/// </summary>
/// <param name="s">String to write.</param>
private void OnWriteLine(string s)
{
// Do any default transcription.
_console.TranscribeResult(s);
switch (this.WriteStream)
{
case WriteStreamType.Error:
_console.WriteErrorLine(s);
break;
case WriteStreamType.Warning:
_console.WriteWarningLine(s);
break;
case WriteStreamType.Verbose:
_console.WriteVerboseLine(s);
break;
case WriteStreamType.Debug:
_console.WriteDebugLine(s);
break;
default:
// If the host is in "transcribe only"
// mode (due to an implicitly added call to Out-Default -Transcribe),
// then don't call the actual host API.
if (!_console.TranscribeOnly)
{
_console.WriteLine(s);
}
break;
}
LineWrittenEvent();
}
/// <summary>
/// Callback to be called when ILineOutput.Write() is called by WriteLineHelper
/// This is called when the WriteLineHelper needs to write a line whose length
/// is the same as the width of the screen buffer.
/// </summary>
/// <param name="s">String to write.</param>
private void OnWrite(string s)
{
switch (this.WriteStream)
{
case WriteStreamType.Error:
_console.WriteErrorLine(s);
break;
case WriteStreamType.Warning:
_console.WriteWarningLine(s);
break;
case WriteStreamType.Verbose:
_console.WriteVerboseLine(s);
break;
case WriteStreamType.Debug:
_console.WriteDebugLine(s);
break;
default:
_console.Write(s);
break;
}
LineWrittenEvent();
}
/// <summary>
/// Called when a line was written to console.
/// </summary>
private void LineWrittenEvent()
{
// check to avoid reentrancy from the prompt handler
// writing during the PromptUser() call
if (_disableLineWrittenEvent)
return;
// if there is no prompting, we are done
if (_prompt == null)
return;
// increment the count of lines written to the screen
_linesWritten++;
// check if we need to put out a prompt
if (this.NeedToPrompt)
{
// put out the prompt
_disableLineWrittenEvent = true;
PromptHandler.PromptResponse response = _prompt.PromptUser(_console);
_disableLineWrittenEvent = false;
switch (response)
{
case PromptHandler.PromptResponse.NextPage:
{
// reset the counter, since we are starting a new page
_linesWritten = 0;
}
break;
case PromptHandler.PromptResponse.NextLine:
{
// roll back the counter by one, since we allow one more line
_linesWritten--;
}
break;
case PromptHandler.PromptResponse.Quit:
// 1021203-2005/05/09-JonN
// HaltCommandException will cause the command
// to stop, but not be reported as an error.
throw new HaltCommandException();
}
}
}
/// <summary>
/// Check if we need to put out a prompt.
/// </summary>
/// <value>true if we need to prompt</value>
private bool NeedToPrompt
{
get
{
// NOTE: we recompute all the time to take into account screen resizing
int rawRowNumber = this.RowNumber;
if (rawRowNumber <= 0)
{
// something is wrong, there is no real estate, we suppress prompting
return false;
}
// the prompt will occupy some lines, so we need to subtract them form the total
// screen line count
int computedPromptLines = _prompt.ComputePromptLines(this.DisplayCells, this.ColumnNumber);
int availableLines = this.RowNumber - computedPromptLines;
if (availableLines <= 0)
{
tracer.WriteLine("No available Lines; suppress prompting");
// something is wrong, there is no real estate, we suppress prompting
return false;
}
return _linesWritten >= availableLines;
}
}
#region Private Members
/// <summary>
/// Object to manage prompting.
/// </summary>
private sealed class PromptHandler
{
/// <summary>
/// Prompt handler with the given prompt.
/// </summary>
/// <param name="s">Prompt string to be used.</param>
/// <param name="cmdlet">The Cmdlet using this prompt handler.</param>
internal PromptHandler(string s, ConsoleLineOutput cmdlet)
{
if (string.IsNullOrEmpty(s))
throw PSTraceSource.NewArgumentNullException(nameof(s));
_promptString = s;
_callingCmdlet = cmdlet;
}
/// <summary>
/// Determine how many rows the prompt should take.
/// </summary>
/// <param name="cols">Current number of columns on the screen.</param>
/// <param name="displayCells">String manipulation helper.</param>
/// <returns></returns>
internal int ComputePromptLines(DisplayCells displayCells, int cols)
{
// split the prompt string into lines
_actualPrompt = StringManipulationHelper.GenerateLines(displayCells, _promptString, cols, cols);
return _actualPrompt.Count;
}
/// <summary>
/// Options returned by the PromptUser() call.
/// </summary>
internal enum PromptResponse
{
NextPage,
NextLine,
Quit
}
/// <summary>
/// Do the actual prompting.
/// </summary>
/// <param name="console">PSHostUserInterface instance to prompt to.</param>
internal PromptResponse PromptUser(PSHostUserInterface console)
{
// NOTE: assume the values passed to ComputePromptLines are still valid
// write out the prompt line(s). The last one will not have a new line
// at the end because we leave the prompt at the end of the line
for (int k = 0; k < _actualPrompt.Count; k++)
{
if (k < (_actualPrompt.Count - 1))
console.WriteLine(_actualPrompt[k]); // intermediate line(s)
else
console.Write(_actualPrompt[k]); // last line
}
while (true)
{
_callingCmdlet.CheckStopProcessing();
KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho);
char key = ki.Character;
if (key == 'q' || key == 'Q')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.Quit;
}
else if (key == ' ')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.NextPage;
}
else if (key == '\r')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.NextLine;
}
}
}
/// <summary>
/// Cached string(s) valid during a sequence of ComputePromptLines()/PromptUser()
/// </summary>
private StringCollection _actualPrompt;
/// <summary>
/// Prompt string as passed at initialization.
/// </summary>
private readonly string _promptString;
/// <summary>
/// The cmdlet that uses this prompt helper.
/// </summary>
private readonly ConsoleLineOutput _callingCmdlet = null;
}
/// <summary>
/// Flag to force new lines in CMD.EXE by limiting the
/// usable width to N-1 (e.g. 80-1) and forcing a call
/// to WriteLine()
/// </summary>
private readonly bool _forceNewLine = true;
/// <summary>
/// Use this if IRawConsole is null;
/// </summary>
private readonly int _fallbackRawConsoleColumnNumber = 80;
/// <summary>
/// Use this if IRawConsole is null;
/// </summary>
private readonly int _fallbackRawConsoleRowNumber = 40;
private readonly WriteLineHelper _writeLineHelper;
/// <summary>
/// Handler to prompt the user for page breaks
/// if this handler is not null, we have prompting.
/// </summary>
private readonly PromptHandler _prompt = null;
/// <summary>
/// Counter for the # of lines written when prompting is on.
/// </summary>
private long _linesWritten = 0;
/// <summary>
/// Flag to avoid reentrancy on prompting.
/// </summary>
private bool _disableLineWrittenEvent = false;
/// <summary>
/// Reference to the PSHostUserInterface interface we use.
/// </summary>
private readonly PSHostUserInterface _console = null;
/// <summary>
/// Msh host specific string manipulation helper.
/// </summary>
private readonly DisplayCells _displayCellsHost;
/// <summary>
/// Reference to error context to throw Msh exceptions.
/// </summary>
private readonly TerminatingErrorContext _errorContext = null;
#endregion
}
}
|