예제 #1
0
 /// <summary>
 /// 当接收到标准输出或标准错误时调用
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnOutputReceived(OutputReceivedEventArgs e)
 {
     Task.Run(() =>
     {
         OutputReceived?.Invoke(this, e);
     });
 }
예제 #2
0
        /// <summary>
        /// To be called by view when ready
        /// </summary>
        public async Task <TerminalResponse> StartShellProcessAsync(ShellProfile shellProfile, TerminalSize size, SessionType sessionType, string termState)
        {
            if (!_requireShellProcessStart && !string.IsNullOrEmpty(termState))
            {
                OutputReceived?.Invoke(this, Encoding.UTF8.GetBytes(termState));
            }

            _trayProcessCommunicationService.SubscribeForTerminalOutput(Id, t => OutputReceived?.Invoke(this, t));

            if (_requireShellProcessStart)
            {
                var response = await _trayProcessCommunicationService
                               .CreateTerminalAsync(Id, size, shellProfile, sessionType).ConfigureAwait(false);

                if (response.Success)
                {
                    _fallbackTitle = response.Name;
                    SetTitle(_fallbackTitle);
                }
                return(response);
            }
            else
            {
                return(await _trayProcessCommunicationService.PauseTerminalOutputAsync(Id, false));
            }
        }
예제 #3
0
        /// <summary>
        /// 处理并触发OutputReceived事件时发生
        /// </summary>
        /// <param name="src"></param>
        /// <param name="isError"></param>
        private void RaiseOutputReceived(DataReceivedEventArgs src, bool isError = false)
        {
            if (src.Data == null)
            {
                return;
            }
            if (src.Data == "")
            {
                return;
            }
            var match = Regex.Match(src.Data, exitCodePattern);

            if (match.Success)
            {
                leastShellExitCode = int.Parse(match.Result("${code}"));
                return;
            }
            if (!isError)
            {
                _builder.AppendOut(src.Data);
            }
            else
            {
                _builder.AppendError(src.Data);
            }
            OutputReceived?.Invoke(this, new OutputReceivedEventArgs(src, isError));
        }
 protected virtual void OnOutputReceived(byte[] output)
 {
     OutputReceived?.Invoke(this, new OutputReceivedArgs()
     {
         data = output
     });
 }
예제 #5
0
        public void WriteOutput(string jobId, string output)
        {
            jobId  = rgxUrl.Replace(jobId, "");
            output = rgxPwd.Replace(output, (m) => m.Groups[1] + " ****");
            OutputReceived?.Invoke(this, new DownloadOutputEventArgs(jobId, output));
#if DEBUG
            System.Diagnostics.Debug.WriteLine(output);
#endif
        }
예제 #6
0
 private void OnProcessOutput(object sender, DataReceivedEventArgs e)
 {
     lock (_lock)
     {
         OutputReceived?.Invoke(this, e.Data);
         if (_hasExited && _localProcess.StandardOutput.EndOfStream)
         {
             Closed?.Invoke(this, _localProcess.ExitCode);
         }
     }
 }
예제 #7
0
        /// <summary>
        /// to be called by view when ready
        /// </summary>
        /// <param name="shellProfile"></param>
        /// <param name="size"></param>
        /// <param name="sessionType"></param>
        public async Task StartShellProcess(ShellProfile shellProfile, TerminalSize size, SessionType sessionType)
        {
            _trayProcessCommunicationService.SubscribeForTerminalOutput(Id, t => OutputReceived?.Invoke(this, t));
            var response = await _trayProcessCommunicationService.CreateTerminal(Id, size, shellProfile, sessionType).ConfigureAwait(true);

            if (response.Success)
            {
                FallbackTitle = response.ShellExecutableName;
                SetTitle(FallbackTitle);
            }
        }
예제 #8
0
 private void OnOutputReceived(DataReceivedEventArgs srcArgs, bool isErr = false)
 {
     if (isErr)
     {
         outputBuilder.AppendError(srcArgs.Data);
     }
     else
     {
         outputBuilder.AppendOut(srcArgs.Data);
     }
     OutputReceived?.Invoke(this, new OutputReceivedEventArgs(srcArgs, isErr));
 }
예제 #9
0
        private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            lock (_processLock)
            {
                if (_cancellationToken.IsCancellationRequested && !_process.HasExited)
                {
                    _process.Kill();
                    return;
                }
            }

            OutputReceived?.Invoke(sender, e);
        }
예제 #10
0
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public ICommandResult Execute(string fileName, string args)
        {
            lock (_executingLock)
            {
                if (isDisposed)
                {
                    throw new ObjectDisposedException(nameof(HestExecutor));
                }
                //输出构造器
                outputBuilder.Clear();
                //记录开始时间
                DateTime start = DateTime.Now;
                //开始进程
                currentProcess = Process.Start(GetStartInfo(fileName, args));

                //监听
                currentProcess.OutputDataReceived += (s, e) =>
                {
                    outputBuilder.AppendOut(e.Data);
                    OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false));
                };
                currentProcess.ErrorDataReceived += (s, e) =>
                {
                    outputBuilder.AppendError(e.Data);
                    OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true));
                };
                currentProcess.BeginOutputReadLine();
                currentProcess.BeginErrorReadLine();

                //触发事件
                CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args));

                //等待进程结束
                currentProcess.WaitForExit();
                currentProcess.CancelErrorRead();
                currentProcess.CancelOutputRead();

                //记录结束时间
                DateTime end = DateTime.Now;
                //构造结果对象
                var result = new HestExecutorResult()
                {
                    ExitCode = currentProcess.ExitCode, Output = outputBuilder.Result
                };
                //触发结束事件
                CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start));
                //返回结果
                return(result);
            };
        }
예제 #11
0
            /// <summary>Handler for all strings written to StdOut</summary>
            /// <param name="sendingProcess"></param>
            /// <param name="outLine"></param>
            private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
            {
                if (outLine.Data == null)
                    finished = true;

                else if (!string.IsNullOrWhiteSpace(outLine.Data))
                {
                    OutputReceived?.Invoke(this, outLine);

                    output.Append(outLine.Data + Environment.NewLine);
                    if (WriteToConsole)
                        Console.WriteLine(outLine.Data);
                }
            }
예제 #12
0
        private void ReceiveOutput(IEnumerable <TerminalCode> codes)
        {
            lock (_bufferSync)
            {
                TerminalCode lastCode = new TerminalCode(TerminalCodeType.DummyCode);
                foreach (var code in codes)
                {
                    ProcessTerminalCode(code, lastCode);
                    lastCode = code;
                }
            }

            OutputReceived?.Invoke(this, EventArgs.Empty);
        }
예제 #13
0
        private void OutputThread()
        {
            while (IsRunning)
            {
                _outputReceivedEvent.WaitOne();

                while (IsRunning && _outputQueue.TryDequeue(out DataReceivedEventArgs data))
                {
                    OutputReceived?.Invoke(this, data);
                }

                _outputReceivedEvent.Reset();
            }
        }
예제 #14
0
        public void StartWithEvents()
        {
            Process.StartInfo.CreateNoWindow         = true;
            Process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            Process.StartInfo.UseShellExecute        = false;
            Process.StartInfo.RedirectStandardError  = true;
            Process.StartInfo.RedirectStandardOutput = true;
            Process.EnableRaisingEvents = true;
            Process.ErrorDataReceived  += (s, e) => OutputReceived?.Invoke(this, e.Data ?? "");
            Process.OutputDataReceived += (s, e) => OutputReceived?.Invoke(this, e.Data ?? "");
            Process.Exited += (s, e) => Exited?.Invoke(this, new EventArgs());

            Process.Start();
            Process.BeginErrorReadLine();
            Process.BeginOutputReadLine();
        }
예제 #15
0
        public void SendOutput(string line)
        {
            if (string.IsNullOrEmpty(line))
            {
                return;
            }

            Task.Run(() =>
            {
                OutputReceived?.Invoke(this, line);

                lock (this)
                {
                    _outputCache.AppendLine(line);
                    if (_logWriter != null)
                    {
                        _logWriter.WriteLine(line);
                    }
                }
            });
        }
예제 #16
0
 public MiFlashBatExecuteProcess(string batFileName, DeviceSerialNumber serial)
 {
     this.StartInfo = new ProcessStartInfo()
     {
         UseShellExecute        = false,
         CreateNoWindow         = true,
         Arguments              = $"/q /c {batFileName} {serial.ToFullSerial()}",
         FileName               = "cmd.exe",
         WorkingDirectory       = AdbConstants.toolsPath,
         RedirectStandardError  = true,
         RedirectStandardOutput = true,
     };
     Logger.Warn(this, $"file path:{StartInfo.Arguments}");
     OutputDataReceived += (s, e) =>
     {
         OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false));
     };
     ErrorDataReceived += (s, e) =>
     {
         OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true));
     };
 }
예제 #17
0
        /// <summary>
        /// 触发OutputReceived事件
        /// </summary>
        /// <param name="e"></param>
        private void OnOutputReceived(OutputReceivedEventArgs e)
        {
            if (e.Text == null || e.Text == "")
            {
                return;
            }
            var m = Regex.Match(e.Text, @"^___ec(?<code>-?\d+)$");

            if (Regex.IsMatch(e.Text, @"^.+;\u0020echo\u0020___ec\$\?$"))
            {
                return;
            }
            if (m.Success)
            {
                builder.ExitCode = Convert.ToInt32(m.Result("${code}"));
                return;
            }
            if (_isEnableRead)
            {
                builder.AppendOut(e.Text);
            }
            OutputReceived?.Invoke(this, e);
        }
예제 #18
0
        private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data == null)
            {
                return;
            }

            OutputReceived?.Invoke(this, new EventArgs <string>(e.Data));

            if (e.Data.StartsWith(_serviceStartedMessage))
            {
                var address = new Uri(e.Data.Substring(_serviceStartedMessage.Length));
                ServiceUri = address;
                OnServiceStarted();
            }

            if (e.Data.StartsWith(_serviceFailedMessage))
            {
                var crashFilePath = e.Data.Substring(_serviceFailedMessage.Length);
                var crashDetails  = File.ReadAllText(crashFilePath);
                var exception     = JsonConvert.DeserializeObject <SerializableException>(crashDetails);
                OnServiceFailed(exception);
            }
        }
예제 #19
0
 private void RaiseOutputReceivedEvent(string category, string data)
 {
     OutputReceived?.Invoke(this, new DebugeeOutputEventArgs(category, data));
 }
예제 #20
0
 void IDebugUnixShellCommandCallback.OnOutputLine(string line)
 {
     OutputReceived?.Invoke(this, line);
 }
예제 #21
0
        public void Run()
        {
            _localProcess                     = new System.Diagnostics.Process();
            _localProcess.StartInfo           = processStartInfo;
            _localProcess.Exited             += OnProcessExited;
            _localProcess.EnableRaisingEvents = true;
            _localProcess.Start();

            _stdoutWriter   = new StreamWriter(_localProcess.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: false);
            _processReader  = new StreamReader(_localProcess.StandardOutput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), false, BUFMAX, false);
            _outputReadTask = System.Threading.Tasks.Task.Run(() => ReadLoop(_processReader, _cancellationSource.Token, (line) => { OutputReceived?.Invoke(this, line); }));

            _localProcess.ErrorDataReceived += OnErrorOutput;
            _localProcess.Exited            += OnProcessExited;
            _localProcess.BeginErrorReadLine();
        }
예제 #22
0
        public LocalRawCommandRunner(string command, string arguments)
        {
            _processStartInfo = new ProcessStartInfo(command, arguments);
            _processStartInfo.RedirectStandardError  = true;
            _processStartInfo.RedirectStandardInput  = true;
            _processStartInfo.RedirectStandardOutput = true;
            _processStartInfo.UseShellExecute        = false;
            _processStartInfo.CreateNoWindow         = true;

            _localProcess         = System.Diagnostics.Process.Start(_processStartInfo);
            _localProcess.Exited += OnProcessExited;
            _localProcess.EnableRaisingEvents = true;

            _stdoutWriter  = new StreamWriter(_localProcess.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: false);
            _processReader = new StreamReader(_localProcess.StandardOutput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: false);
            _processError  = new StreamReader(_localProcess.StandardError.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), detectEncodingFromByteOrderMarks: false);

            System.Threading.Tasks.Task.Run(() => ReadLoop(_processReader, _cancellationSource.Token, (msg) => { OutputReceived?.Invoke(this, msg); }));
            System.Threading.Tasks.Task.Run(() => ReadLoop(_processError, _cancellationSource.Token, (msg) => { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(new Exception(msg))); }));
        }
예제 #23
0
 private void OnProcessOutput(object sender, DataReceivedEventArgs e)
 {
     OutputReceived?.Invoke(this, e.Data + '\n');
 }
예제 #24
0
 /// <summary>
 /// 触发输出事件
 /// </summary>
 /// <param name="e"></param>
 /// <param name="isErr"></param>
 protected virtual void RaiseOutputReceived(DataReceivedEventArgs e, bool isErr)
 {
     callback?.Invoke(new OutputReceivedEventArgs(e, isErr));
     OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, isErr));
 }
예제 #25
0
 private void OnOutputReceived(object sender, OutputReceivedEventArgs e)
 {
     OutputReceived?.Invoke(sender, e?.Output);
 }
예제 #26
0
 protected virtual void OnOutputReceived(ProgramOutputReceivedEventArgs e)
 {
     OutputReceived?.Invoke(this, e);
 }
예제 #27
0
 /// <summary>
 /// 触发输出事件
 /// </summary>
 /// <param name="e"></param>
 /// <param name="isErr"></param>
 private void RaiseOutputReceived(DataReceivedEventArgs e, bool isErr)
 {
     callback?.Invoke(new OutputReceivedEventArgs(e, isErr));
     OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, isErr));
 }
 protected void OnOutputReceived(OutputEventArgs e)
 {
     OutputReceived?.Invoke(this, e);
 }
예제 #29
0
 private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
 {
     outputBuilder !.AppendOut(e.Data);
     OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false));
 }
예제 #30
0
        /// <summary>
        /// Invokes youtube-dl with the specified parameters and options.
        /// </summary>
        /// <param name="urls">The video URLs to be passed to youtube-dl.</param>
        /// <param name="options">An OptionSet specifying the options to be passed to youtube-dl.</param>
        /// <param name="ct">A CancellationToken used to cancel the download.</param>
        /// <param name="progress">A progress provider used to get download progress information.</param>
        /// <returns>The exit code of the youtube-dl process.</returns>
        public async Task <int> RunAsync(string[] urls, OptionSet options,
                                         CancellationToken ct, IProgress <DownloadProgress> progress = null)
        {
            var tcs       = new TaskCompletionSource <int>();
            var process   = new Process();
            var startInfo = new ProcessStartInfo()
            {
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            if (!String.IsNullOrEmpty(PythonPath))
            {
                startInfo.FileName  = PythonPath;
                startInfo.Arguments = $"\"{ExecutablePath}\" {ConvertToArgs(urls, options)}";
            }
            else
            {
                startInfo.FileName  = ExecutablePath;
                startInfo.Arguments = ConvertToArgs(urls, options);
            }
            process.EnableRaisingEvents = true;
            process.StartInfo           = startInfo;
            var tcsOut = new TaskCompletionSource <bool>();
            // this variable is used for tracking download states
            bool isDownloading = false;

            process.OutputDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsOut.SetResult(true);
                    return;
                }
                Match match;
                if ((match = rgxProgress.Match(e.Data)).Success)
                {
                    if (match.Groups.Count > 1 && match.Groups[1].Length > 0)
                    {
                        float  progValue  = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100.0f;
                        Group  totalGroup = match.Groups["total"];
                        string total      = totalGroup.Success ? totalGroup.Value : null;
                        Group  speedGroup = match.Groups["speed"];
                        string speed      = speedGroup.Success ? speedGroup.Value : null;
                        Group  etaGroup   = match.Groups["eta"];
                        string eta        = etaGroup.Success ? etaGroup.Value : null;
                        progress?.Report(
                            new DownloadProgress(
                                DownloadState.Downloading, progress: progValue, totalDownloadSize: total, downloadSpeed: speed, eta: eta
                                )
                            );
                    }
                    else
                    {
                        progress?.Report(new DownloadProgress(DownloadState.Downloading));
                    }
                    isDownloading = true;
                }
                else if ((match = rgxPlaylist.Match(e.Data)).Success)
                {
                    var index = int.Parse(match.Groups[1].Value);
                    progress?.Report(new DownloadProgress(DownloadState.PreProcessing, index: index));
                    isDownloading = false;
                }
                else if (isDownloading && (match = rgxPost.Match(e.Data)).Success)
                {
                    progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1));
                    isDownloading = false;
                }
                Debug.WriteLine("[youtube-dl] " + e.Data);
                OutputReceived?.Invoke(this, e);
            };
            var tcsError = new TaskCompletionSource <bool>();

            process.ErrorDataReceived += (o, e) =>
            {
                if (e.Data == null)
                {
                    tcsError.SetResult(true);
                    return;
                }
                Debug.WriteLine("[youtube-dl ERROR] " + e.Data);
                progress?.Report(new DownloadProgress(DownloadState.Error, data: e.Data));
                ErrorReceived?.Invoke(this, e);
            };
            process.Exited += async(sender, args) =>
            {
                // Wait for output and error streams to finish
                await tcsOut.Task;
                await tcsError.Task;
                tcs.TrySetResult(process.ExitCode);
                process.Dispose();
            };
            ct.Register(() =>
            {
                if (!tcs.Task.IsCompleted)
                {
                    tcs.TrySetCanceled();
                }
                try { if (!process.HasExited)
                      {
                          process.KillTree();
                      }
                }
                catch { }
            });
            Debug.WriteLine("[youtube-dl] Arguments: " + process.StartInfo.Arguments);
            if (!await Task.Run(() => process.Start()))
            {
                tcs.TrySetException(new InvalidOperationException("Failed to start youtube-dl process."));
            }
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            progress?.Report(new DownloadProgress(DownloadState.PreProcessing));
            return(await tcs.Task);
        }