Skip to content
44 changes: 27 additions & 17 deletions src/Spinner.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ public function spin(Closure $callback): mixed
return $this->renderStatically($callback);
}

$this->hideCursor();

$originalAsync = pcntl_async_signals(true);

pcntl_signal(SIGINT, function () {
Expand All @@ -56,6 +54,7 @@ public function spin(Closure $callback): mixed
});

try {
$this->hideCursor();
$this->render();

$pid = pcntl_fork();
Expand All @@ -71,24 +70,33 @@ public function spin(Closure $callback): mixed
} else {
$result = $callback();

posix_kill($pid, SIGHUP);
pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);

$this->eraseRenderedLines();
$this->showCursor();
$this->resetTerminal($originalAsync, $pid);

return $result;
}
} catch (\Throwable $e) {
$this->showCursor();
pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);
$this->resetTerminal($originalAsync, $pid ?? null);

throw $e;
}
}

/**
* Reset the terminal.
*/
protected function resetTerminal(bool $originalAsync, ?int $pid): void
{
if ($pid) {
posix_kill($pid, SIGHUP);
}

pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);

$this->eraseRenderedLines();
$this->showCursor();
}

/**
* Render a static version of the spinner.
*
Expand All @@ -101,13 +109,15 @@ protected function renderStatically(Closure $callback): mixed
{
$this->static = true;

$this->hideCursor();
$this->render();

$result = $callback();
try {
$this->hideCursor();
$this->render();

$this->eraseRenderedLines();
$this->showCursor();
$result = $callback();
} finally {
$this->eraseRenderedLines();
$this->showCursor();
}

return $result;
}
Expand Down