Skip to content

Instantly share code, notes, and snippets.

@vertexvaar
Created June 26, 2018 16:00
Show Gist options
  • Save vertexvaar/3c45898d0207ae05cde7cdefe65c5e86 to your computer and use it in GitHub Desktop.
Save vertexvaar/3c45898d0207ae05cde7cdefe65c5e86 to your computer and use it in GitHub Desktop.
<?php
/**
* http://www.termsys.demon.co.uk/vtansi.htm#cursor
*
* Class Cursor
*/
class Cursor
{
/**
* @var array
*/
protected $positon = [
'row' => 0,
'col' => 0,
];
protected $savedPosition = [
'row' => 0,
'col' => 0,
];
protected $highestPosition = [
'row' => 0,
'col' => 0,
];
private function update()
{
$this->highestPosition['row'] = max($this->highestPosition['row'], $this->positon['row']);
$this->highestPosition['col'] = max($this->highestPosition['col'], $this->positon['col']);
}
public function end()
{
$this->moveToLineStart();
while ($this->highestPosition['row'] > $this->positon['row']) {
$this->moveDown();
}
}
public function moveAbsolute(int $row, int $col)
{
$this->positon['row'] = $row;
$this->positon['col'] = $col;
echo "\e[{$row};{$col}H";
}
public function savePosition()
{
$this->savedPosition = $this->positon;
echo "\e[s";
}
public function restorePosition()
{
$this->positon = $this->savedPosition;
echo "\e[u";
}
public function moveUp($lines = 1)
{
if (($this->positon['row'] - $lines) < 0) {
return false;
}
$this->positon['row'] -= $lines;
$this->update();
echo "\e[{$lines}A";
}
public function moveDown($lines = 1)
{
$this->positon['row'] += $lines;
$this->update();
echo "\e[{$lines}B";
}
public function moveLeft($lines = 1)
{
if (($this->positon['col'] - $lines) < 0) {
return false;
}
$this->positon['col'] -= $lines;
$this->update();
echo "\e[{$lines}D";
}
public function moveRight($lines = 1)
{
$this->positon['col'] += $lines;
$this->update();
echo "\e[{$lines}A";
}
public function draw($chars)
{
$newlines = substr_count($chars, PHP_EOL);
$this->positon['row'] += $newlines;
$this->positon['col'] += mb_strlen($chars);
$this->update();
foreach (preg_split('//u', $chars, null, PREG_SPLIT_NO_EMPTY) as $char) {
usleep(rand(10000, 200000));
echo $char;
}
}
public function moveToLineStart()
{
$this->moveLeft($this->positon['col']);
$this->positon['col'] = 0;
}
}
$cursor = new Cursor();
$cursor->draw('XXXXX' . PHP_EOL);
$cursor->savePosition();
$cursor->draw('XXXXX' . PHP_EOL);
$cursor->restorePosition();
$cursor->draw('X---X' . PHP_EOL);
$cursor->moveToLineStart();
$cursor->moveUp();
$cursor->moveUp();
$cursor->draw('0---0' . PHP_EOL);
$cursor->moveAbsolute(1, 1);
$cursor->draw('X');
$cursor->moveAbsolute(1, 3);
$cursor->draw('X');
$cursor->moveAbsolute(10, 30);
$cursor->draw('X');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment