64 lines
2.6 KiB
PHP
64 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Extensions\Externals;
|
|
|
|
use JumPHP\Externals\Externals;
|
|
use JumPHP\Externals\RemoteFile;
|
|
use JumPHP\Renderer\Renderer;
|
|
use JumPHP\Scene\AbstractScene;
|
|
|
|
/**
|
|
* A file read like a disk: open() it, read() a few bytes anywhere (only their blocks come), then confirm reads it
|
|
* all with readAll() and its progress. The bar shows the blocks in the cache.
|
|
* Run: JUMPHP_SCENE='App\Extensions\Externals\ReadSample' bin/jumphp run externals-demo
|
|
*/
|
|
final class ReadSample extends AbstractScene
|
|
{
|
|
public const LABEL = 'Read a file by blocks: read(offset, length), readAll() with progress, the cache';
|
|
|
|
private ?RemoteFile $file = null;
|
|
private string $head = '';
|
|
private string $middle = '';
|
|
private float $progress = 0;
|
|
|
|
public function __construct(private Externals $externals)
|
|
{
|
|
}
|
|
|
|
public function enter(array $params = []): void
|
|
{
|
|
$this->head = $this->middle = '';
|
|
$this->progress = 0;
|
|
$this->externals->search('*.dat')->then(function (array $found): void {
|
|
if ($found === []) {
|
|
return;
|
|
}
|
|
$this->externals->open($found[0]->path)->then(function (RemoteFile $f): void {
|
|
$this->file = $f;
|
|
$f->read(0, 8)->then(fn (string $b) => $this->head = $b); // the first block only
|
|
$f->read(intdiv($f->size(), 2), 8)->then(fn (string $b) => $this->middle = $b); // one in the middle
|
|
});
|
|
});
|
|
}
|
|
|
|
public function update(float $dt): void
|
|
{
|
|
if ($this->file !== null && $this->actions()->isPressed('confirm')) {
|
|
$this->file->readAll(fn (float $p) => $this->progress = $p);
|
|
}
|
|
}
|
|
|
|
public function render(Renderer $r): void
|
|
{
|
|
$r->clear([10, 24, 24]);
|
|
$f = $this->file;
|
|
$this->font()->draw($r, $f === null ? 'OPENING...' : strtoupper($f->path()) . ' ' . $f->size() . ' B', 160, 10, 1, [255, 208, 64], 'center');
|
|
$this->font()->draw($r, 'START ' . strtoupper(bin2hex($this->head)), 20, 40, 1, [220, 255, 220]);
|
|
$this->font()->draw($r, 'MIDDLE ' . strtoupper(bin2hex($this->middle)), 20, 56, 1, [220, 255, 220]);
|
|
$ratio = $f?->cachedRatio() ?? 0.0;
|
|
$r->fillRect(20, 90, 280, 14, [30, 50, 50]);
|
|
$r->fillRect(20, 90, 280 * $ratio, 14, [80, 200, 140]);
|
|
$this->font()->draw($r, 'CACHED ' . (int) round($ratio * 100) . '% (READALL ' . (int) round($this->progress * 100) . '%)', 160, 112, 1, [200, 230, 230], 'center');
|
|
$this->font()->draw($r, 'CONFIRM: READ IT ALL', 160, 166, 1, [120, 160, 160], 'center');
|
|
}
|
|
}
|