NL
apps/winzik / src / Gui / MainWindow.php · commit 6576d6f
<?phpnamespace App\Gui;use App\Media\Spectrum;use App\Audio\Player;use JumPHP\Gui\Pointer;/** * The player (Form1 of 2001): main.bmp, 258 pixels wide, 99 high (128 opened with the hidden button at the right of * the playlist button). Every control is where it was in winster.frm (its twips / 15). */final class MainWindow extends SkinWindow{    public const WIDTH = 258;    public const SHORT = 99;    public const TALL = 128;    /** the height while it opens or closes (Image3_Click: 25 twips a step) */    private float $shown = self::SHORT;    /** the position bar is held: the knob follows the pointer, the song moves when it is let go (Picture5) */    private ?float $seekTo = null;    /** dragging the title scrolls it by hand (Text4_MouseMove) */    private float $titleFrom = 0;    private int $titleShiftFrom = 0;    public function id(): string    {        return 'main';    }    public function width(): float    {        return self::WIDTH;    }    public function height(): float    {        return round($this->shown);    }    public function visible(): bool    {        return $this->wz->ui['main']['visible'] && !$this->wz->ui['compact']['active'] && !$this->wz->ui['lyricsOnly'] && !$this->wz->ui['tray'];    }    public function controls(): array    {        $vis = $this->wz->skin->vis;        // the visualizer (when the bottom part is open): a click, the next way to draw it        $visControl = $vis !== null && $this->shown > $vis[1] + 4 ? ['vis' => [(float)$vis[0], (float)$vis[1], (float)$vis[2], (float)$vis[3]]] : [];        return $visControl + [            'shuffle' => [0, 0, 25, 17],        // picture8 hd.gif / he.gif: Hasard            'info' => [0, 16, 25, 17],          // picture19: the tags (Form6)            'compact' => [224, 0, 17, 15],      // picture9 petit.gif (Command6)            'close' => [240, 0, 17, 17],        // picture17            'tray' => [224, 16, 17, 15],        // picture20            'lyrics' => [240, 16, 17, 15],      // picture18 (Command9)            'title' => [48, 0, 161, 12],        // Text4            'vu' => [24, 17, 201, 12],          // Image5: the bargraph on / off            'volume' => [0, 46, 117, 13],       // Image1 + picture2            'volumeLabel' => [0, 31, 70, 13],   // its label: WinZik's volume / the computer's            'balance' => [136, 46, 117, 13],    // picture7 + picture3            'position' => [0, 62, 256, 13],     // picture4 + picture5            'prev' => [64, 76, 25, 18],         // picture16 barr.gif            'pause' => [88, 76, 25, 18],        // picture13            'play' => [112, 76, 25, 18],        // picture11            'stop' => [136, 76, 25, 18],        // picture10            'next' => [160, 76, 25, 18],        // picture15            'playlist' => [184, 76, 25, 18],    // picture1 bpl.gif            'expand' => [232, 76, 25, 18],      // Image3: no picture, it opens the bottom of main.bmp            'time' => [0, 78, 58, 20],          // Label3..5: a click, the time left / gone by        ];    }    /** where the pointer is in the window (-1: away): over the position bar, the title says where a click goes */    private float $pointerX = -1;    public function hover(float $x, float $y): void    {        parent::hover($x, $y);        $this->pointerX = $x;    }    public function tip(string $control): string    {        return match ($control) {            'time' => $this->timeLeft() ? 'Clic : temps écoulé' : 'Clic : temps restant',            'volumeLabel' => $this->wz->volumeMode === 'system' ? 'Clic : volume de WinZik' : 'Clic : volume du système',            'vis' => 'Clic : visualiseur suivant',            'volume' => 'Molette : volume ± 5 %',            'balance' => 'Molette : ± 5 %, double-clic : au centre',            'position' => 'Molette : ± 5 secondes',            default => '',        };    }    /** the counter shows the time left in the song (a click on it), not the time gone by */    private function timeLeft(): bool    {        return (bool)($this->wz->options['timeLeft'] ?? false);    }    /**     * What the title stripe shows: the song scrolling; over the position bar, where a click there goes; the pointer a     * moment on a control whose meaning is not obvious, what it does.     */    public function titleShown(): string    {        $player = $this->wz->player;        $duration = $player->duration();        if (($this->seekTo !== null || ($this->hovered === 'position' && $this->pressed === '')) && $duration > 0 && $player->file !== null) {            $to = $this->seekTo ?? max(0, min(235, $this->pointerX - 6)) * $duration / 235;            return 'Aller à ' . self::clock($to) . ' / ' . self::clock($duration);        }        return $this->hint() ?: $this->wz->scrolledTitle();    }    private static function clock(float $seconds): string    {        $t = (int)floor($seconds);        return $t >= 3600 ? sprintf('%d:%02d:%02d', intdiv($t, 3600), intdiv($t, 60) % 60, $t % 60) : sprintf('%02d:%02d', intdiv($t, 60), $t % 60);    }    /** The wheel: on the volume, the balance or the position it moves them; elsewhere the volume. */    public function wheel(float $notches): bool    {        $wz = $this->wz;        $step = $notches > 0 ? 1 : -1;        match ($this->hovered) {            'balance' => $wz->setBalance($wz->player->balance + 5 * $step),            'position' => $wz->seek(max(0, $wz->player->position + 5 * $step)),            default => $wz->setVolumeValue($wz->volumeValue() + 5 * $step),        };        return true;    }    public const VIS_MODES = ['bars' => 'Barres', 'fire' => 'Barres de feu', 'scope' => 'Sinusoïde', 'waterfall' => 'Cascade',        'mirror' => 'Miroir', 'rain' => 'Pluie de points'];    /**     * The visualizer in the opened part (the skin's VIS.txt), what is heard: a click on it goes to the next way to draw     * it. Barres (a bar per band, its top falling back), Barres de feu (the bars in flames, sparks above), Sinusoïde     * (the sound itself, an oscilloscope), and three of WinZik's own: Cascade (the spectrum going by, a line a frame),     * Miroir (the bars up and down from the middle), Pluie de points (dots that fall, faster where it is loud).     */    private function visualizer(Canvas $c, float $shown): void    {        $vis = $this->wz->skin->vis;        if ($vis === null || $shown <= $vis[1] + 2) {            return;        }        [$x, $y, $w, $h] = $vis;        $h = min($h, $shown - $y - 1);        $colors = $this->wz->skin->colors;        $sp = $this->wz->spectrum;        $n = count($sp->bars);        $bw = ($w - ($n - 1)) / $n;        $c->fill($x, $y, $w, $h, [0, 0, 0, 120]);        $grade = fn (float $t): string => $t < 0.55 ? $colors['barGreenLeft'] : ($t < 0.8 ? $colors['barOrangeLeft'] : $colors['barRedLeft']);        switch ($this->wz->options['visMode'] ?? 'bars') {            case 'fire':                // the bars in flames: from deep red to yellow to white at the top, sparks where the peaks are                for ($i = 0; $i < $n; $i++) {                    $bx = $x + $i * ($bw + 1);                    $level = $sp->bars[$i] * $h;                    for ($row = 0; $row < $level; $row++) {                        $t = $row / max(1, $h);                        $flicker = 0.85 + 0.15 * sin($this->desk->clock * 23 + $i * 1.7 + $row);                        $r = 255;                        $g = (int)min(255, 40 + 230 * $t * $flicker);                        $b = (int)max(0, 255 * ($t - 0.75) * 3);                        $c->fill($bx, $y + $h - $row - 1, $bw, 1, [$r, $g, $b, (int)(150 + 105 * $t)]);                    }                    $peak = $sp->peaks[$i] * $h;                    if ($peak >= 1 && fmod($this->desk->clock * 7 + $i, 1.0) < 0.6) {                        $c->fill($bx + $bw / 2 - 0.5, $y + $h - $peak - 2, 1, 1, '#ffffa0');                    }                }                break;            case 'scope':                // the sound itself: a line through the 64 points, from left to right                $mid = $y + $h / 2;                $prev = null;                foreach ($sp->wave as $k => $v) {                    $px = $x + $k * ($w - 1) / 63;                    $py = $mid - max(-1.0, min(1.0, $v * 2.2)) * ($h / 2 - 1);                    if ($prev !== null) {                        for ($s = 0; $s <= 4; $s++) {                            $c->fill($prev[0] + ($px - $prev[0]) * $s / 4, $prev[1] + ($py - $prev[1]) * $s / 4, 1, 1, $colors['barGreenLeft']);                        }                    }                    $prev = [$px, $py];                }                break;            case 'waterfall':                // the spectrum going by: each line a moment (the newest at the bottom), its colour how loud each band was                $lines = count($sp->history);                $lh = max(1.0, $h / Spectrum::HISTORY);                foreach ($sp->history as $k => $levels) {                    $ly = $y + $h - ($lines - $k) * $lh;                    if ($ly < $y) {                        continue;                    }                    foreach ($levels as $i => $level) {                        if ($level > 0.05) {                            $c->fill($x + $i * ($bw + 1), $ly, $bw + 1, $lh, [(int)(255 * $level), (int)(255 * $level * $level), (int)(120 + 135 * (1 - $level)), (int)(60 + 195 * $level)]);                        }                    }                }                break;            case 'mirror':                // the bars up and down from the middle line, their tops shining                $mid = $y + $h / 2;                for ($i = 0; $i < $n; $i++) {                    $bx = $x + $i * ($bw + 1);                    $half = $sp->bars[$i] * $h / 2;                    $color = $grade($sp->bars[$i]);                    $c->fill($bx, $mid - $half, $bw, $half * 2, $color);                    $c->fill($bx, $mid - $half, $bw, 1, $colors['active']);                    $c->fill($bx, $mid + $half - 1, $bw, 1, $colors['active']);                }                $c->fill($x, $mid, $w, 1, [255, 255, 255, 60]);                break;            case 'rain':                // dots falling down each column, faster and brighter where the band is loud                $t = $this->desk->clock;                for ($i = 0; $i < $n; $i++) {                    $level = $sp->bars[$i];                    $bx = $x + $i * ($bw + 1) + $bw / 2 - 0.5;                    for ($d = 0; $d < 3; $d++) {                        $fall = fmod($t * (6 + 30 * $level) + $i * 3.7 + $d * $h / 3, $h);                        $alpha = (int)(70 + 185 * $level);                        $green = \JumPHP\Util\Color::of($colors['barGreenLeft']);                        $c->fill($bx, $y + $fall, 1.5, 1.5, $level > 0.6 ? [255, 255, 255, $alpha] : [$green->r, $green->g, $green->b, $alpha]);                    }                    $c->fill($x + $i * ($bw + 1), $y + $h - 1, $bw, 1, $grade($level));                }                break;            default:                for ($i = 0; $i < $n; $i++) {                    $bx = $x + $i * ($bw + 1);                    $level = $sp->bars[$i] * $h;                    // two pixel rows each: the bars of the screens of that time                    for ($row = 0; $row + 1 <= $level; $row += 2) {                        $c->fill($bx, $y + $h - $row - 1, $bw, 1, $grade($row / max(1, $h)));                    }                    $peak = $sp->peaks[$i] * $h;                    if ($peak >= 1) {                        $c->fill($bx, $y + $h - $peak - 1, $bw, 1, $colors['active']);                    }                }        }    }    public function dragsItself(string $control): bool    {        return in_array($control, ['volume', 'balance', 'position'], true);    }    public function update(float $dt): void    {        $target = $this->wz->ui['main']['expanded'] ? self::TALL : self::SHORT;        if ($this->shown != $target) {            $step = $dt * 110;            $this->shown = $this->shown < $target ? min($target, $this->shown + $step) : max($target, $this->shown - $step);            $this->desk->followMain();        }    }    /** playing: its visualizer, its light, its counter 30 times a second; else its scrolling title only */    public function redrawEvery(): float    {        return $this->wz->player->state === Player::PLAYING ? 1 / 30 : 1 / 6;    }    public function render(Canvas $c): void    {        $wz = $this->wz;        $skin = $wz->skin;        $h = $this->height();        if (!$c->image('main', 0, 0, self::WIDTH, $h, [0, 0, self::WIDTH, (int)$h])) {            $c->fill(0, 0, self::WIDTH, $h, '#404040');        }        $player = $wz->player;        $this->visualizer($c, $h);        // the bargraph (Label8..13) and its light (Shape1)        if ($wz->ui['vu']) {            $this->bar($c, $wz->vuLeft, -1);            $this->bar($c, $wz->vuRight, 1);            // the beat of the bass (learnt for each song); paused: it blinks slowly, as before            $beat = $player->state === Player::PLAYING ? $wz->spectrum->beat : ($player->state === Player::PAUSED && fmod($this->desk->clock, 1.0) < 0.5 ? 1.0 : 0.0);            $on = \JumPHP\Util\Color::of($skin->colors['barRedLeft']);            $mix = fn (int $dark, int $lit) => (int)round($dark + ($lit - $dark) * $beat);            $this->led($c, sprintf('#%02x%02x%02x', $mix(0x40, $on->r), $mix(0x10, $on->g), $mix(0x10, $on->b)));        }        // the scrolling title, its labels        $title = $this->titleShown();        $c->text($c->fit($title, 161, 7.5), 48, 1, 7.5, $skin->colors['title']);        if ($wz->working()) {            // something works in the background (Whisper, a download, the equalizer's sound, a film): a small loader            $c->spinner(203, 7, 3.6, $skin->colors['title'], $this->desk->clock);        }        $system = $wz->volumeMode === 'system';        $c->text(($system ? 'Système : ' : 'Volume : ') . $wz->volumeValue() . ' %', 1, 33, 7, $system ? '#60c0ff' : $skin->colors['volume']);        $kbps = $player->file !== null && $player->info->kbps > 0 ? sprintf('%03d', $player->info->kbps) : 'N/A';        $c->text($kbps, 118, 33, 7, $skin->colors['kbps']);        $c->text('Balance : ' . $player->balance . ' %', 252, 33, 7, $skin->colors['balance'], 'right');        // the sliders: their track pictures, then the knobs        $c->image('fbson', 0, 48);        if ($system) {            $c->fill(2, 50, 113, 6, [40, 140, 255, 110]);       // the computer's volume: its groove blue        }        $c->image('bson', $wz->volumeValue(), 48);              // the knob is at the volume (xc - 6)        $c->image('fbbal', 136, 48);        $c->image('bbal', 136 + 50 + $player->balance / 2, 48);        $c->image('fpos', 0, 64);        // the parts left out (the blanks, an intro): darker on the groove, its knob going over them        $length = $player->duration();        if ($player->file !== null && $length > 0 && $wz->skipBlanks()) {            [$start, $end] = $wz->bounds($player->file);            if ($start > 0) {                $c->fill(10, 66, min(235.0, $start * 235 / $length), 4, [0, 0, 0, 120]);            }            if ($end > 0 && $end < $length) {                $from = $end * 235 / $length;                $c->fill(10 + $from, 66, 235 - $from, 4, [0, 0, 0, 120]);            }        }        $c->image('bpos', $this->knob(), 64);        // the counter: hours, minutes, seconds (Label5, Label4, Label3; Fixedsys); the time left: "-0" for the hours        $t = (int)floor($this->seekTo ?? $player->position);        $left = $this->timeLeft() && $length > 0 && $player->file !== null;        if ($left) {            $t = (int)ceil(max(0.0, $length - ($this->seekTo ?? $player->position)));        }        $parts = [[intdiv($t, 3600), 0, 'hours'], [intdiv($t, 60) % 60, 18, 'minutes'], [$t % 60, 36, 'seconds']];        foreach ($parts as $k => [$value, $x, $color]) {            $digits = $k === 0 && $left ? '-' . min(9, $value) : sprintf('%02d', $value);            $c->text($digits, $x + 1, 84, 10, $skin->colors[$color], 'left', 'mono-bold.ttf');        }        // the buttons        $c->image($wz->playlist->shuffle ? 'he' : 'hd', 0, 0);        $c->image('info', 0, 16);        $c->image('petit', 224, 0);        $c->image('close', 240, 0, 17, 17);        $c->image('tray', 224, 16);        $c->image('lyr', 240, 16);        foreach (['prev' => 'barr', 'pause' => 'bpause', 'play' => 'bplay', 'stop' => 'bstop', 'next' => 'bav', 'playlist' => 'bpl'] as $id => $picture) {            [$x, $y] = $this->controls()[$id];            $c->image($picture, $x, $y);            $this->pushed($c, $id);        }        foreach (['shuffle', 'info', 'compact', 'close', 'tray', 'lyrics'] as $id) {            $this->pushed($c, $id);        }    }    /** The knob of the position bar: 0..235 pixels for the whole song (pp = 235 / duration). */    private function knob(): float    {        $player = $this->wz->player;        $duration = $player->duration();        $position = $this->seekTo ?? $player->position;        return $duration > 0 ? min(235, max(0, $position * 235 / $duration)) : 0;    }    /** One side of the bargraph: green, orange then red blocks from the middle outwards. */    private function bar(Canvas $c, float $level, int $side): void    {        $colors = $this->wz->skin->colors;        $blocks = 23;        $lit = (int)round(min(1, $level) * $blocks);        for ($i = 0; $i < $lit; $i++) {            $key = $i < 14 ? 'barGreen' : ($i < 19 ? 'barOrange' : 'barRed');            $color = $colors[$key . ($side < 0 ? 'Left' : 'Right')];            $x = $side < 0 ? 120 - ($i + 1) * 4 : 133 + $i * 4;            $c->fill($x, 19, 3, 8, $color);        }    }    private function led(Canvas $c, string $color): void    {        $c->fill(124, 49, 7, 7, $color);        $c->fill(125, 48, 5, 9, $color);        $c->fill(123, 50, 9, 5, $color);        $c->fill(125, 50, 2, 2, [255, 255, 255, 120]);    }    public function press(float $x, float $y, Pointer $p): bool    {        if (!parent::press($x, $y, $p)) {            return false;        }        $this->titleFrom = $x;        $this->titleShiftFrom = $this->wz->titleShift;        $this->drag($x, $y);        return true;    }    public function drag(float $x, float $y): void    {        $wz = $this->wz;        switch ($this->pressed) {            case 'volume':                $wz->setVolumeValue((int)round(max(6, min(106, $x)) - 6));    // Image1_MouseMove: xc - 6                break;            case 'balance':                $wz->setBalance((int)round((max(142, min(242, $x)) - 142 - 50) * 2));                break;            case 'position':                $duration = $wz->player->duration();                if ($duration > 0 && $wz->player->file !== null) {                    $knob = max(0, min(235, $x - 6));                    $this->seekTo = $knob * $duration / 235;                }                break;            case 'title':                $wz->titleShift = $this->titleShiftFrom - (int)round(($x - $this->titleFrom) / 4);                break;        }    }    public function release(float $x, float $y, bool $double): void    {        if ($this->pressed === 'position') {            if ($this->seekTo !== null) {                // Picture5_MouseUp: the song goes there and plays                $this->wz->seek($this->seekTo);                if ($this->wz->player->state !== Player::PLAYING) {                    $this->wz->play();                }            }            $this->seekTo = null;            $this->pressed = '';            return;        }        if (in_array($this->pressed, ['volume', 'balance', 'title'], true)) {            if ($this->pressed === 'balance' && $double) {                $this->wz->setBalance(0);       // a double click: back to the middle            }            $this->pressed = '';            return;        }        parent::release($x, $y, $double);    }    protected function clicked(string $id, bool $double): void    {        $wz = $this->wz;        if ($id === 'volumeLabel') {            $wz->toggleVolumeMode();            return;        }        if ($id === 'time') {            $this->wz->options['timeLeft'] = !$this->timeLeft();            $this->wz->notice($this->timeLeft() ? 'Compteur : temps restant' : 'Compteur : temps écoulé', 2);            $this->wz->touch();            return;        }        if ($id === 'vis') {            $modes = array_keys(self::VIS_MODES);            $at = (int)array_search($wz->options['visMode'] ?? 'bars', $modes, true);            $wz->options['visMode'] = $modes[($at + 1) % count($modes)];            $wz->notice('Visualiseur : ' . self::VIS_MODES[$wz->options['visMode']], 2);            $wz->touch();            return;        }        match ($id) {            'shuffle' => $wz->toggleShuffle(),            'info' => $this->desk->host()->openTags(),            'compact' => $wz->toggleCompact(),            'close' => $this->desk->quitWithEffect(),            'tray' => $this->desk->toTray(),            'lyrics' => $this->desk->lyricsOnly(),            'vu' => $wz->ui['vu'] = !$wz->ui['vu'],            'prev' => $wz->previous(),            'pause' => $wz->pause(),            'play' => $wz->play(),            'stop' => $wz->stop(),            'next' => $wz->next(),            'playlist' => $this->desk->togglePlaylist(),            'expand' => $this->toggleExpand(),            default => null,        };    }    private function toggleExpand(): void    {        $this->wz->ui['main']['expanded'] = !$this->wz->ui['main']['expanded'];        $this->wz->touch();    }    public function restore(): void    {        parent::restore();        $this->shown = $this->wz->ui['main']['expanded'] ? self::TALL : self::SHORT;    }}