예제 #1
0
        public PowerShellRawUI(PowerShellConsoleModel model)
        {
            _model = model;

            ForegroundColor = ConsoleColor.White;
            BackgroundColor = ConsoleColor.Black;
            CursorPosition = new Coordinates(0, 0);
        }
 public ScriptingHostRawUserInterface(ApplicationSettings settings)
 {
     Output = new OutputBuffer();
     backgroundColor = settings.BackgroundColor;
     foregroundColor = settings.ForegroundColor;
     cursorPosition = new Coordinates(0, 0);
     windowPosition = new Coordinates(0, 0);
     cursorSize = 1;
     bufferSize = new Size(settings.HostWidth, Int32.MaxValue);
     windowSize = bufferSize;
 }
예제 #3
0
		internal ProgressPane(ConsoleHostUserInterface ui)
		{
			this.location = new Coordinates(0, 0);
			if (ui != null)
			{
				this.ui = ui;
				this.rawui = ui.RawUI;
				return;
			}
			else
			{
				throw new ArgumentNullException("ui");
			}
		}
예제 #4
0
		internal void Show()
		{
			BufferCell[,] bufferCellArray = this.progressRegion;
			if (bufferCellArray != null)
			{
				int length = bufferCellArray.GetLength(0);
				int num = bufferCellArray.GetLength(1);
				this.location = this.rawui.WindowPosition;
				this.location.X = 0;
				this.location.Y = Math.Min(this.location.Y + 2, this.bufSize.Height);
				this.savedRegion = this.rawui.GetBufferContents(new Rectangle(this.location.X, this.location.Y, this.location.X + num - 1, this.location.Y + length - 1));
				this.rawui.SetBufferContents(this.location, bufferCellArray);
				return;
			}
			else
			{
				return;
			}
		}
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     throw new NotImplementedException();
 }
예제 #6
0
		public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
		{
			throw new NotSupportedException(Resources.PSHostRawUserInterfaceSetBufferContentsNotSupported);
		}
예제 #7
0
        /// <summary>
        /// Executes the native command once all of the input has been gathered.
        /// </summary>
        /// <exception cref="PipelineStoppedException">
        /// The pipeline is stopping
        /// </exception>
        /// <exception cref="ApplicationFailedException">
        /// The native command could not be run
        /// </exception>
        internal override void Complete()
        {
            // Indicate whether we need to consider redirecting the output/error of the current native command.
            // Usually a windows program which is the last command in a pipeline can be executed as 'background' -- we don't need to capture its output/error streams.
            bool background;

            // Figure out if we're going to run this process "standalone" i.e. without
            // redirecting anything. This is a bit tricky as we always run redirected so
            // we have to see if the redirection is actually being done at the topmost level or not.

            //Calculate if input and output are redirected.
            bool redirectOutput;
            bool redirectError;
            bool redirectInput;

            CalculateIORedirection(out redirectOutput, out redirectError, out redirectInput);

            // Find out if it's the only command in the pipeline.
            bool soloCommand = this.Command.MyInvocation.PipelineLength == 1;

            // Get the start info for the process. 
            ProcessStartInfo startInfo = GetProcessStartInfo(redirectOutput, redirectError, redirectInput, soloCommand);

            if (this.Command.Context.CurrentPipelineStopping)
            {
                throw new PipelineStoppedException();
            }

            // If a problem occurred in running the program, this exception will
            // be set and should be rethrown at the end of the try/catch block...
            Exception exceptionToRethrow = null;
            Host.Coordinates startPosition = new Host.Coordinates();
            bool scrapeHostOutput = false;

            try
            {
                // If this process is being run standalone, tell the host, which might want
                // to save off the window title or other such state as might be tweaked by 
                // the native process
                if (!redirectOutput)
                {
                    this.Command.Context.EngineHostInterface.NotifyBeginApplication();

                    // Also, store the Raw UI coordinates so that we can scrape the screen after
                    // if we are transcribing.
                    try
                    {
                        if (this.Command.Context.EngineHostInterface.UI.IsTranscribing)
                        {
                            scrapeHostOutput = true;
                            startPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition;
                            startPosition.X = 0;
                        }
                    }
                    catch (Host.HostException)
                    {
                        // The host doesn't support scraping via its RawUI interface
                        scrapeHostOutput = false;
                    }
                }

                //Start the process. If stop has been called, throw exception.
                //Note: if StopProcessing is called which this method has the lock,
                //Stop thread will wait for nativeProcess to start.
                //If StopProcessing gets the lock first, then it will set the stopped
                //flag and this method will throw PipelineStoppedException when it gets
                //the lock.
                lock (_sync)
                {
                    if (_stopped)
                    {
                        throw new PipelineStoppedException();
                    }

                    try
                    {
                        _nativeProcess = new Process();
                        _nativeProcess.StartInfo = startInfo;
                        _nativeProcess.Start();
                    }
                    catch (Win32Exception)
                    {
#if CORECLR             // Shell doesn't exist on OneCore, so a file cannot be associated with an executable,
                        // and we cannot run an executable as 'ShellExecute' either.
                        throw;
#else
                        // See if there is a file association for this command. If so
                        // then we'll use that. If there's no file association, then
                        // try shell execute...
                        string executable = FindExecutable(startInfo.FileName);
                        bool notDone = true;
                        if (!String.IsNullOrEmpty(executable))
                        {
                            if (IsConsoleApplication(executable))
                            {
                                // Allocate a console if there isn't one attached already...
                                ConsoleVisibility.AllocateHiddenConsole();
                            }

                            string oldArguments = startInfo.Arguments;
                            string oldFileName = startInfo.FileName;
                            startInfo.Arguments = "\"" + startInfo.FileName + "\" " + startInfo.Arguments;
                            startInfo.FileName = executable;
                            try
                            {
                                _nativeProcess.Start();
                                notDone = false;
                            }
                            catch (Win32Exception)
                            {
                                // Restore the old filename and arguments to try shell execute last...
                                startInfo.Arguments = oldArguments;
                                startInfo.FileName = oldFileName;
                            }
                        }
                        // We got here because there was either no executable found for this 
                        // file or we tried to launch the exe and it failed. In either case
                        // we will try launching one last time using ShellExecute...
                        if (notDone)
                        {
                            if (soloCommand && startInfo.UseShellExecute == false)
                            {
                                startInfo.UseShellExecute = true;
                                startInfo.RedirectStandardInput = false;
                                startInfo.RedirectStandardOutput = false;
                                startInfo.RedirectStandardError = false;
                                _nativeProcess.Start();
                            }
                            else
                            {
                                throw;
                            }
                        }
#endif
                    }
                }

                if (this.Command.MyInvocation.PipelinePosition < this.Command.MyInvocation.PipelineLength)
                {
                    // Never background unless you're at the end of a pipe.
                    // Something like
                    //    ls | notepad | sort.exe
                    // should block until the notepad process is terminated.
                    background = false;
                }
                else
                {
                    background = true;
                    if (startInfo.UseShellExecute == false)
                    {
                        background = IsWindowsApplication(_nativeProcess.StartInfo.FileName);
                    }
                }

                try
                {
                    //If input is redirected, start input to process.
                    if (startInfo.RedirectStandardInput)
                    {
                        NativeCommandIOFormat inputFormat = NativeCommandIOFormat.Text;
                        if (_isMiniShell)
                        {
                            inputFormat = ((MinishellParameterBinderController)NativeParameterBinderController).InputFormat;
                        }
                        lock (_sync)
                        {
                            if (!_stopped)
                            {
                                _inputWriter.Start(_nativeProcess, inputFormat);
                            }
                        }
                    }

                    if (background == false)
                    {
                        //if output is redirected, start reading output of process.
                        if (startInfo.RedirectStandardOutput || startInfo.RedirectStandardError)
                        {
                            lock (_sync)
                            {
                                if (!_stopped)
                                {
                                    _outputReader = new ProcessOutputReader(_nativeProcess, Path, redirectOutput, redirectError);
                                    _outputReader.Start();
                                }
                            }
                            if (_outputReader != null)
                            {
                                ProcessOutputHelper();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    StopProcessing();
                    throw;
                }
                finally
                {
                    if (background == false)
                    {
                        //Wait for process to exit
                        _nativeProcess.WaitForExit();

                        //Wait for input writer to finish.
                        _inputWriter.Done();

                        //Wait for outputReader to finish
                        if (_outputReader != null)
                        {
                            _outputReader.Done();
                        }

                        // Capture screen output if we are transcribing
                        if (this.Command.Context.EngineHostInterface.UI.IsTranscribing &&
                            scrapeHostOutput)
                        {
                            Host.Coordinates endPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition;
                            endPosition.X = this.Command.Context.EngineHostInterface.UI.RawUI.BufferSize.Width - 1;

                            // If the end position is before the start position, then capture the entire buffer.
                            if (endPosition.Y < startPosition.Y)
                            {
                                startPosition.Y = 0;
                            }

                            Host.BufferCell[,] bufferContents = this.Command.Context.EngineHostInterface.UI.RawUI.GetBufferContents(
                                new Host.Rectangle(startPosition, endPosition));

                            StringBuilder lineContents = new StringBuilder();
                            StringBuilder bufferText = new StringBuilder();

                            for (int row = 0; row < bufferContents.GetLength(0); row++)
                            {
                                if (row > 0)
                                {
                                    bufferText.Append(Environment.NewLine);
                                }

                                lineContents.Clear();
                                for (int column = 0; column < bufferContents.GetLength(1); column++)
                                {
                                    lineContents.Append(bufferContents[row, column].Character);
                                }

                                bufferText.Append(lineContents.ToString().TrimEnd(Utils.Separators.SpaceOrTab));
                            }

                            this.Command.Context.InternalHost.UI.TranscribeResult(bufferText.ToString());
                        }

                        this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, _nativeProcess.ExitCode);
                        if (_nativeProcess.ExitCode != 0)
                            this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
                    }
                }
            }
            catch (Win32Exception e)
            {
                exceptionToRethrow = e;
            } // try
            catch (PipelineStoppedException)
            {
                // If we're stopping the process, just rethrow this exception...
                throw;
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                exceptionToRethrow = e;
            }
            finally
            {
                if (!redirectOutput)
                {
                    this.Command.Context.EngineHostInterface.NotifyEndApplication();
                }
                // Do the clean up...
                CleanUp();
            }

            // An exception was thrown while attempting to run the program
            // so wrap and rethrow it here...
            if (exceptionToRethrow != null)
            {
                // It's a system exception so wrap it in one of ours and re-throw.
                string message = StringUtil.Format(ParserStrings.ProgramFailedToExecute,
                    this.NativeCommandName, exceptionToRethrow.Message,
                    this.Command.MyInvocation.PositionMessage);
                ApplicationFailedException appFailedException = new ApplicationFailedException(message, exceptionToRethrow);

                // There is no need to set this exception here since this exception will eventually be caught by pipeline processor.
                // this.commandRuntime.PipelineProcessor.ExecutionFailed = true;

                throw appFailedException;
            }
        }
예제 #8
0
        public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
        {
            // TODO: REIMPLEMENT PSHostRawUserInterface.ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
            throw new NotImplementedException("The ScrollBufferContents method is not (yet) implemented!");

            //if (_control.Dispatcher.CheckAccess())
            //{
            //    _control.ScrollBufferContents(source, destination, clip, fill);
            //}
            //else
            //{
            //   _control.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
            //    {
            //        _control.ScrollBufferContents(source, destination, clip, fill);
            //    });
            //}
        }
 /// <summary>
 /// Scrolls the contents of the console buffer.
 /// </summary>
 /// <param name="source">The source rectangle to scroll.</param>
 /// <param name="destination">The destination coordinates by which to scroll.</param>
 /// <param name="clip">The rectangle inside which the scrolling will be clipped.</param>
 /// <param name="fill">The cell with which the buffer will be filled.</param>
 public override void ScrollBufferContents(
     Rectangle source, 
     Coordinates destination, 
     Rectangle clip, 
     BufferCell fill)
 {
     Logger.Write(
         LogLevel.Warning,
         "PSHostRawUserInterface.ScrollBufferContents was called");
 }
예제 #10
0
        /// <summary>
        ///
        /// Handle backspace with proper cursor adjustment for ReadLineSafe
        ///
        /// </summary>
        /// <param name="originalCursorPosition">
        /// 
        /// it is the cursor position where ReadLineSafe begins
        /// 
        /// </param>
        /// <exception cref="HostException">
        /// 
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// 
        /// </exception>

        private void WriteBackSpace(Coordinates originalCursorPosition)
        {
            Coordinates cursorPosition = _rawui.CursorPosition;
            if (cursorPosition == originalCursorPosition)
            {
                // at originalCursorPosition, don't move
                return;
            }

            if (cursorPosition.X == 0)
            {
                if (cursorPosition.Y <= originalCursorPosition.Y)
                {
                    return;
                }
                // BufferSize.Width is 1 larger than cursor position
                cursorPosition.X = _rawui.BufferSize.Width - 1;
                cursorPosition.Y--;
                BlankAtCursor(cursorPosition);
            }
            else if (cursorPosition.X > 0)
            {
                cursorPosition.X--;
                BlankAtCursor(cursorPosition);
            }
            // do nothing if cursorPosition.X is left of screen
        }
예제 #11
0
        /// <summary>
        /// Get the character at the cursor when the user types 'tab' in the middle of line.
        /// </summary>
        /// <param name="cursorPosition">the cursor position where 'tab' is hit</param>
        /// <returns></returns>
        private char GetCharacterUnderCursor(Coordinates cursorPosition)
        {
            Rectangle region = new Rectangle(0, cursorPosition.Y, RawUI.BufferSize.Width - 1, cursorPosition.Y);
            BufferCell[,] content = RawUI.GetBufferContents(region);

            for (int index = 0, column = 0; column <= cursorPosition.X; index++)
            {
                BufferCell cell = content[0, index];
                if (cell.BufferCellType == BufferCellType.Complete || cell.BufferCellType == BufferCellType.Leading)
                {
                    if (column == cursorPosition.X)
                    {
                        return cell.Character;
                    }

                    column += ConsoleControl.LengthInBufferCells(cell.Character);
                }
            }

            Dbg.Assert(false, "the character at the cursor should be retrieved, never gets to here");
            return '\0';
        }
예제 #12
0
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
 }
예제 #13
0
 /// <summary>
 /// Copies a given character to a region of the screen buffer based 
 /// on the coordinates of the region. This method is not implemented. 
 /// The call fails with an exception.
 /// </summary>
 /// <param name="origin">The coordnates of the region.</param>
 /// <param name="contents">A BufferCell structure that defines the fill character.</param>
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     throw new NotImplementedException("The SetBufferContents() method is not implemented by MyRawUserInterface.");
 }
예제 #14
0
 /// <summary>
 /// Crops a region of the screen buffer. This functionality is not 
 /// implemented. The call fails with an exception.
 /// </summary>
 /// <param name="source">A Rectangle structure that identifies the 
 /// region of the screen to be scrolled.</param>
 /// <param name="destination">A Coordinates structure that 
 /// identifies the upper-left coordinates of the region of the 
 /// screen to receive the source region contents.</param>
 /// <param name="clip">A Rectangle structure that identifies the 
 /// region of the screen to include in the operation.</param>
 /// <param name="fill">A BufferCell structure that identifies the 
 /// character and attributes to be used to fill all cells within 
 /// the intersection of the source rectangle and clip rectangle 
 /// that are left "empty" by the move.</param>
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
     throw new NotImplementedException("The ScrollBufferContents() method is not implemented by MyRawUserInterface.");
 }
예제 #15
0
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
     if (this.externalRawUI == null)
     {
         this.ThrowNotInteractive();
     }
     this.externalRawUI.ScrollBufferContents(source, destination, clip, fill);
 }
 public override void ScrollBufferContents(System.Management.Automation.Host.Rectangle source, System.Management.Automation.Host.Coordinates destination, System.Management.Automation.Host.Rectangle clip, System.Management.Automation.Host.BufferCell fill)
 {
     // throw new NotImplementedException();
 }
예제 #17
0
        ScrollBufferContents
        (
            Rectangle source,
            Coordinates destination,
            Rectangle clip,
            BufferCell fill
        )
        {
            if (_externalRawUI == null)
            {
                ThrowNotInteractive();
            }

            _externalRawUI.ScrollBufferContents(source, destination, clip, fill);
        }
예제 #18
0
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
 }
예제 #19
0
        /// <summary>
        ///
        /// Handle writing print token with proper cursor adjustment for ReadLineSafe
        ///
        /// </summary>
        /// <param name="printToken">
        /// 
        /// token output for each char input. It must be a one-char string
        /// 
        /// </param>
        /// <param name="originalCursorPosition">
        /// 
        /// it is the cursor position where ReadLineSafe begins
        /// 
        /// </param>
        /// <exception cref="HostException">
        /// 
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// 
        /// </exception>

        private void WritePrintToken(
            string printToken,
            ref Coordinates originalCursorPosition)
        {
            Dbg.Assert(!string.IsNullOrEmpty(printToken),
                "Calling WritePrintToken with printToken being null or empty");
            Dbg.Assert(printToken.Length == 1,
                "Calling WritePrintToken with printToken's Length being " + printToken.Length);
            Size consoleBufferSize = _rawui.BufferSize;
            Coordinates currentCursorPosition = _rawui.CursorPosition;

            // if the cursor is currently at the lower right corner, this write will cause the screen buffer to
            // scroll up. So, it is necessary to adjust the original cursor position one row up.
            if (currentCursorPosition.Y >= consoleBufferSize.Height - 1 && // last row
                currentCursorPosition.X >= consoleBufferSize.Width - 1)  // last column
            {
                if (originalCursorPosition.Y > 0)
                {
                    originalCursorPosition.Y--;
                }
            }
            WriteToConsole(printToken, false);
        }
 /// <summary>
 /// Scroll buffer contents.
 /// </summary>
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
     _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.ScrollBufferContents, new object[] { source, destination, clip, fill });
 }
예제 #21
0
 /// <summary>
 /// Blank out at and move rawui.CursorPosition to <paramref name="cursorPosition"/>
 /// </summary>
 /// <param name="cursorPosition">Position to blank out</param>
 private void BlankAtCursor(Coordinates cursorPosition)
 {
     _rawui.CursorPosition = cursorPosition;
     WriteToConsole(" ", true);
     _rawui.CursorPosition = cursorPosition;
 }
 /// <summary>
 /// Set buffer contents.
 /// </summary>
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetBufferContents2, new object[] { origin, contents });
 }
 /// <summary>
 /// Sets the contents of the buffer at the given coordinate.
 /// </summary>
 /// <param name="origin">The coordinate at which the buffer will be changed.</param>
 /// <param name="contents">The new contents for the buffer at the given coordinate.</param>
 public override void SetBufferContents(
     Coordinates origin, 
     BufferCell[,] contents)
 {
     Logger.Write(
         LogLevel.Warning,
         "PSHostRawUserInterface.SetBufferContents was called");
 }
예제 #24
0
 public abstract void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill);
예제 #25
0
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     // TODO: REIMPLEMENT PSHostRawUserInterface.SetBufferContents(Coordinates origin, BufferCell[,] contents)
     throw new NotImplementedException("The SetBufferContents method is not (yet) implemented!");
     //if (_control.Dispatcher.CheckAccess())
     // {
     //     _control.SetBufferContents(origin, contents);
     // }
     // else
     // {
     //    _control.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate
     //     {
     //         _control.SetBufferContents(origin, contents);
     //     });
     // }
 }
예제 #26
0
 public abstract void SetBufferContents(Coordinates origin, BufferCell[,] contents);
예제 #27
0
		public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
		{
			throw new NotSupportedException(Resources.PSHostRawUserInterfaceScrollBufferContentsNotSupported);
		}
 /// <summary>
 /// This functionality is not currently implemented. The call fails with an exception.
 /// </summary>
 /// <param name="source">Unused</param>
 /// <param name="destination">Unused</param>
 /// <param name="clip">Unused</param>
 /// <param name="fill">Unused</param>
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
     throw new NotImplementedException("The method or operation is not implemented.");
 }
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip,
                                           BufferCell fill)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// This functionality is not currently implemented. The call fails with an exception.
 /// </summary>
 /// <param name="origin">Unused</param>
 /// <param name="contents">Unused</param>
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     throw new NotImplementedException("The method or operation is not implemented.");
 }
예제 #31
0
        SetBufferContents(Coordinates origin, BufferCell[,] contents)
        {
            if (_externalRawUI == null)
            {
                ThrowNotInteractive();
            }

            _externalRawUI.SetBufferContents(origin, contents);
        }
 public override void SetBufferContents(System.Management.Automation.Host.Coordinates origin, System.Management.Automation.Host.BufferCell[,] contents)
 {
     return(null);
     // throw new NotImplementedException();
 }