From 06d879853ce562de66991968500274b5a485d8b4 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Fri, 29 Apr 2016 02:25:57 +0200 Subject: [PATCH] Command and prompt style can be modified --- examples/simple.php | 2 ++ lib/LineRead.php | 29 +++++++++++++++++++++++++++-- lib/Shell.php | 19 ++++++++++++++++++- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/examples/simple.php b/examples/simple.php index 85bc09d..78b34ab 100644 --- a/examples/simple.php +++ b/examples/simple.php @@ -43,6 +43,8 @@ class MyShell extends Shell $lt = $t + 5; echo date("Y-m-d h:i:s")."\n"; } + $fg = ($this->seq % 7) + 1; + $this->setPromptStyle("3{$fg}"); } protected function onCommand($buffer) diff --git a/lib/LineRead.php b/lib/LineRead.php index a17d392..674933a 100644 --- a/lib/LineRead.php +++ b/lib/LineRead.php @@ -26,6 +26,10 @@ class LineRead protected $sttyOld; + protected $commandStyle; + + protected $promptStyle; + public function __construct() { stream_set_blocking(STDIN, false); @@ -58,7 +62,20 @@ class LineRead $prompt = $this->prompt; $buffer = $this->buffer; $cursor = strlen($this->prompt) + 1 + $this->posCursor - $this->posScroll; - fprintf(STDOUT, "\r\e[2K\e[32;1m%s\e[37m%s\e[%dG\e[0m", $prompt, $buffer, $cursor); + + $promptStyle = $this->styleToAnsi($this->promptStyle); + $commandStyle = $this->styleToAnsi($this->commandStyle); + $endStyle = "\e[0m"; + + fprintf(STDOUT, "\r\e[2K{$promptStyle}%s{$commandStyle}%s\e[%dG{$endStyle}", $prompt, $buffer, $cursor); + } + + protected function styleToAnsi($style) + { + if (!$style) { + return; + } + return "\e[0;".$style."m"; } protected function handleInput() @@ -137,10 +154,18 @@ class LineRead fprintf(STDERR, "\n%s\n", substr($code,1)); } } + + public function setCommandStyle($style) + { + $this->commandStyle = $style; + } - public function setPrompt($prompt) + public function setPrompt($prompt, $style=null) { $this->prompt = $prompt; + if ($style) { + $this->promptStyle = $style; + } } } diff --git a/lib/Shell.php b/lib/Shell.php index 778f6d9..89d35de 100644 --- a/lib/Shell.php +++ b/lib/Shell.php @@ -6,6 +6,11 @@ use NoccyLabs\Shell\LineRead; abstract class Shell { + + protected $promptStyle; + + protected $commandStyle; + public function __construct(array $config=[]) { $this->configure($config); @@ -71,14 +76,26 @@ abstract class Shell { } + public function setPromptStyle($style) + { + $this->promptStyle = $style; + } + + public function setCommandStyle($style) + { + $this->commandStyle = $style; + } + public function run() { $lineRead = new LineRead(); + + $lineRead->setCommandStyle($this->commandStyle); $this->running = true; do { - $lineRead->setPrompt($this->getPrompt()); + $lineRead->setPrompt($this->getPrompt(), $this->promptStyle); $buffer = $lineRead->update(); if ($buffer == "\x03") { $this->stop();