*/ private array $wins = []; private ?Desktop $desk = null; public float $scale = 2.0; /** the screen's scale, before the zoom of the menu */ private float $base = 2.0; /** @var array{0: int, 1: int, 2: int, 3: int} the screen: x, y, w, h */ private array $screen = [0, 0, 1920, 1080]; private string $pressedIn = ''; private float $lastDown = -10; /** the press being held is the second of a double click (decided when pressed: the release of ONE click is not a double) */ private bool $downDouble = false; private float $clock = 0; private string $engineMode = ''; private bool $minimized = false; private ?SkinWindow $under = null; /** the windows are above the others (menu: Toujours au-dessus); SDL cannot change it on a window: they are made again */ private bool $onTop = true; private bool $videoFull = false; /** @var array{0: int, 1: int} the dialog's window */ private array $dialogSize = [760, 640]; /** seconds since the keyboard focus left WinZik (Alt+Tab): its menus go */ private float $away = 0.0; private bool $hadFocus = false; private float $screenCheck = 99.0; /** this frame redraws the windows (30 a second) */ private bool $drawNow = true; /** seconds left during which every window is drawn at each frame (after the pointer, a key) */ private float $burst = 1.0; private float $drawClock = 0.0; public function __construct(private Engine $engine, string $zoom = 'auto') { self::$trace = in_array(getenv('WINZIK_TRACE'), ['1', '2'], true); // the click that brings WinZik to the front is a click too (SDL drops a press within 10 ms of the focus by default: // the first click on WinZik coming from another program was lost) \SDL_SetHint('SDL_MOUSE_FOCUS_CLICKTHROUGH', '1'); // every screen of the computer: WinZik's desktop covers them all, each window lives on the one under its middle $this->useMonitors(self::findMonitors()); self::trace('screens: ' . json_encode($this->monitors)); // the skins are 258 pixels wide: x2 on a 1080p screen, x3 on a 4K one, x1.5 under 900 lines (the main screen's) $this->scale = $this->base = is_numeric($zoom) && (float)$zoom > 0 ? (float)$zoom : self::baseScale($this->monitors[0]); // the close button / Alt+F4 / "Close window" of the task bar on one of the windows (SDL says nothing else: // its 'quit' comes only when the last window closes, and the engine's hidden one stays) $engine->ownWindowClose = true; // the dialogs (Options, YouTube...) are each a window of the computer as big as they are: nothing around them \JumPHP\Gui\Form::$dialogFillsView = true; $engine->input->on('window-close', fn (int $id) => $this->closed($id)); $engine->input->on('key', function (): void { $this->burst = 0.4; // a key: every window drawn at once (what it changed shows) }); $this->listenMouse(); // the player back from the task bar: every window of WinZik with it, in the same frame $engine->input->on('window', function (int $event, int $a = 0, int $b = 0, int $id = 0): void { if (self::$trace && in_array($event, [\SDL_WINDOWEVENT_FOCUS_GAINED, \SDL_WINDOWEVENT_FOCUS_LOST, \SDL_WINDOWEVENT_ENTER, \SDL_WINDOWEVENT_LEAVE], true)) { $names = [\SDL_WINDOWEVENT_FOCUS_GAINED => 'focus+', \SDL_WINDOWEVENT_FOCUS_LOST => 'focus-', \SDL_WINDOWEVENT_ENTER => 'enter', \SDL_WINDOWEVENT_LEAVE => 'leave']; self::trace('window ' . $names[$event] . ' ' . $id . ' (' . $this->windowNamed($id) . ')'); } if ($event === \SDL_WINDOWEVENT_FOCUS_GAINED) { $this->activated($id); } if ($this->minimized && $this->desk !== null && isset($this->wins['main']) && $id === $this->wins['main']['id'] && in_array($event, [\SDL_WINDOWEVENT_RESTORED, \SDL_WINDOWEVENT_SHOWN, \SDL_WINDOWEVENT_MAXIMIZED, \SDL_WINDOWEVENT_FOCUS_GAINED], true)) { $this->minimized = false; $this->desk->fromTray(); } }); } private float $lastRaise = -10.0; /** * A window of WinZik activated (Alt+Tab, the task bar, a click): every window of WinZik comes in front with it, it * last (it keeps the keyboard). Raising them activates them too: what follows a raise for a moment is not an activation. */ /** a window of WinZik activated: every window raised at the next frame, unless a click caused it (raiseLater) */ private int $activatedId = 0; /** when the mouse was last pressed on a window of WinZik (real time) */ private float $lastPress = 0.0; private float $activatedAt = 0.0; private function activated(int $id): void { // not now: the activation of a click comes just before its press (same moment): raising the other windows took the // focus from the window pressed, and SDL stopped following the mouse out of it (a window dragged quickly let go // of the pointer, its release lost) $this->activatedId = $id; $this->activatedAt = microtime(true); } /** Each frame: an activation without a click (Alt+Tab, the task bar) brings every window of WinZik to the front. */ private function raiseLater(): void { if ($this->activatedId === 0 || microtime(true) - $this->activatedAt < 0.05) { return; } $id = $this->activatedId; $this->activatedId = 0; if ($this->pressedIn !== '' || microtime(true) - $this->lastPress < 0.5) { return; // a click: the window manager raised the window clicked, the others are above anyway } $focused = null; foreach ($this->wins as $n) { if ($n['id'] === $id) { $focused = $n; } } if ($focused === null || $this->clock - $this->lastRaise < 0.6) { return; } $this->lastRaise = $this->clock; foreach ($this->wins as $name => $n) { if ($n['shown'] && $n['id'] !== $id && !str_starts_with($name, 'menu')) { \SDL_RaiseWindow($n['win']); } } \SDL_RaiseWindow($focused['win']); } /** Every window of WinZik in front (a second WinZik started: this one comes back). */ public function raise(): void { if ($this->minimized && isset($this->wins['main'])) { \SDL_RestoreWindow($this->wins['main']['win']); $this->minimized = false; } foreach ($this->wins as $n) { if ($n['shown']) { \SDL_RaiseWindow($n['win']); } } } /** A window of WinZik closed by the system: the player = quit, the others hide, the engine's = its dialog closes. */ public function closed(int $id): void { $engineWin = $this->engine->sdl->getWindow()?->getWindow(); if ($engineWin !== null && $id === (int)\SDL_GetWindowID($engineWin)) { $top = $this->engine->scenes->current(); if ($top instanceof SplashScene || $top === null) { $this->desk !== null ? $this->desk->wz()->quit() : $this->engine->quit(); } elseif (!$top instanceof MainForm) { $this->engine->scenes->pop(); } return; } $desk = $this->desk; foreach ($this->wins as $name => $n) { if ($n['id'] !== $id || $desk === null) { continue; } $wz = $desk->wz(); match ($name) { 'main' => $wz->quit(), 'playlist' => $desk->togglePlaylist(), 'eq' => $wz->toggleEq(), 'lyrics' => $wz->toggleLyrics(), 'compact' => $wz->toggleCompact(), 'menu', 'menu2' => $desk->close(), // the copies of the lyrics bar on the other screens and the card follow their own window / option: no // key of their own in the settings (ui['lyrics#0'] was saved in winzik.json) 'card' => null, default => str_starts_with($name, 'lyrics#') ? null : $wz->ui[$name]['visible'] = false, }; } } /** The desktop version: an executable or `bin/jumphp run` with a screen (not a browser, not the tests). */ public static function wanted(): bool { return Platform::isDesktop() && !Platform::isWasm() && !Platform::isHeadless() && !Platform::isPhoneApp() && function_exists('SDL_CreateWindow') && function_exists('SDL_GetMouseFocus') && getenv('WINZIK_ONE_WINDOW') !== '1'; } /** @var list the screens (x, y, w, h in screen pixels), the main one first */ private array $monitors = [[0, 0, 1920, 1080]]; /** @return list the screens (the main one first): xrandr's on X11, else SDL's displays */ private static function findMonitors(): array { // WINZIK_SCREENS="x,y,w,h;x,y,w,h": the screens given (tests on a virtual screen: Xvfb has no real monitors) $given = (string)getenv('WINZIK_SCREENS'); if ($given !== '') { $list = []; foreach (explode(';', $given) as $part) { $v = array_map('intval', explode(',', $part)); if (count($v) === 4 && $v[2] > 0 && $v[3] > 0) { $list[] = [$v[0], $v[1], $v[2], $v[3]]; } } if ($list !== []) { return $list; } } // X11: xrandr says what each screen SHOWS. SDL says the size of its mode, which is wrong with a scaled screen (a // 2560x1600 panel showing 1707x1067 of the desktop, 1.5 times bigger: WinZik went past the edges) $xr = PHP_OS_FAMILY === 'Linux' && getenv('DISPLAY') ? self::parseXrandr((string)@shell_exec((is_executable('/usr/bin/timeout') ? 'timeout 3 ' : '') . 'xrandr --listmonitors 2>/dev/null')) : []; if ($xr !== []) { return $xr; } $found = []; $n = function_exists('SDL_GetNumVideoDisplays') ? (int)\SDL_GetNumVideoDisplays() : 0; for ($i = 0; $i < max(1, $n); $i++) { $r = new \SDL_Rect(0, 0, 0, 0); if (function_exists('SDL_GetDisplayBounds') && \SDL_GetDisplayBounds($i, $r) === 0 && $r->w > 0) { $found[] = [(int)$r->x, (int)$r->y, (int)$r->w, (int)$r->h]; } } // Windows: the main screen is the one at 0, 0 (its zoom of 125 %, 150 %... is in these sizes: SDL is not "DPI // aware", Windows gives it the same scaled pixels for the screens and for the windows) usort($found, fn (array $a, array $b) => ($a[0] === 0 && $a[1] === 0 ? 0 : 1) <=> ($b[0] === 0 && $b[1] === 0 ? 0 : 1)); return $found !== [] ? $found : [[0, 0, 1920, 1080]]; } /** * " 0: +*HDMI-A-0 2560/798x1080/334+0+768 HDMI-A-0" lines: each screen (x, y, w, h), the main one (*) first. * @return list */ public static function parseXrandr(string $out): array { $xr = []; foreach (explode("\n", $out) as $line) { if (preg_match('#^\s*\d+:\s*\+?(\*?)\S+\s+(\d+)/\d+x(\d+)/\d+\+(-?\d+)\+(-?\d+)#', $line, $m) && (int)$m[2] > 0) { $mon = [(int)$m[4], (int)$m[5], (int)$m[2], (int)$m[3]]; $m[1] === '*' ? array_unshift($xr, $mon) : $xr[] = $mon; } } return $xr; } /** The scale of WinZik on a screen: the skins are 258 pixels wide (x2 on 1080 lines, x3 on 4K, x1.5 under 900). */ private static function baseScale(array $monitor): float { return max(1.0, min(4.0, floor($monitor[3] / 520 * 2) / 2)); } /** The bounding box of the screens (WinZik's desktop covers them all). */ private function useMonitors(array $monitors): void { $this->monitors = $monitors; $x0 = min(array_map(fn ($m) => $m[0], $monitors)); $y0 = min(array_map(fn ($m) => $m[1], $monitors)); $x1 = max(array_map(fn ($m) => $m[0] + $m[2], $monitors)); $y1 = max(array_map(fn ($m) => $m[1] + $m[3], $monitors)); $this->screen = [$x0, $y0, $x1 - $x0, $y1 - $y0]; } private ?\App\Media\Process $xrandr = null; private float $xrandrAt = 0.0; private float $monitorCheck = 0.0; /** * Every few seconds, the screens again (a laptop docked or not, a screen plugged, a resolution changed): when they * changed, every window keeps its place on the screen it was on, then goes inside a screen. */ private function watchMonitors(float $dt): void { if (PHP_OS_FAMILY !== 'Linux' || !getenv('DISPLAY') || (string)getenv('WINZIK_SCREENS') !== '') { $this->monitorCheck += $dt; if ($this->monitorCheck > 3) { $this->monitorCheck = 0.0; $found = self::findMonitors(); if ($found !== $this->monitors) { $this->monitorsChanged($found); } } return; } if ($this->xrandr !== null) { $this->xrandr->poll(); if (!$this->xrandr->done()) { // never waited for: a stuck xrandr (an X server that hangs) is stopped after 5 s, forgotten after 10 s $age = microtime(true) - $this->xrandrAt; if ($age > 10) { $this->xrandr->cleanup(); $this->xrandr = null; } elseif ($age > 5) { $this->xrandr->kill(); } return; } $found = self::parseXrandr($this->xrandr->output()); $this->xrandr->cleanup(); $this->xrandr = null; if ($found !== [] && $found !== $this->monitors) { $this->monitorsChanged($found); } return; } $this->monitorCheck += $dt; if ($this->monitorCheck > 3) { $this->monitorCheck = 0.0; $this->xrandr = \App\Media\Process::start(['xrandr', '--listmonitors'], sys_get_temp_dir()); $this->xrandrAt = microtime(true); } } /** @param list $found */ private function monitorsChanged(array $found): void { self::trace('screens: ' . json_encode($found)); $desk = $this->desk; $old = []; $windows = $desk !== null ? array_filter([$desk->main, $desk->playlist, $desk->eq, $desk->video], fn ($w) => $w !== null) : []; foreach ($windows as $w) { $old[spl_object_id($w)] = [$this->screen[0] + $w->x * $this->scale, $this->screen[1] + $w->y * $this->scale]; } $this->useMonitors($found); $this->base = self::baseScale($found[0]); if ($desk !== null) { // the scale as the zoom of the menu makes it everywhere else (Desktop::effectiveScale: whole or half steps) $desk->baseScale = $this->base; $desk->scale = $this->scale = Desktop::effectiveScale($this->base, $desk->zoomPct()); foreach ($windows as $w) { [$sx, $sy] = $old[spl_object_id($w)]; $w->x = ($sx - $this->screen[0]) / $this->scale; $w->y = ($sy - $this->screen[1]) / $this->scale; } $desk->followMain(); } else { $this->scale = $this->base; } $this->engineMode = ''; // the splash / a dialog placed again } /** * The screen of a point, or the nearest one when it is between screens. * @return array{0: float, 1: float, 2: float, 3: float} in desktop pixels */ private function nearestMonitor(float $dx, float $dy): array { $best = null; $bestD = INF; foreach ($this->screensInDesk() as $m) { $nx = max($m[0], min($dx, $m[0] + $m[2])); $ny = max($m[1], min($dy, $m[1] + $m[3])); $d = ($nx - $dx) ** 2 + ($ny - $dy) ** 2; if ($d < $bestD) { $bestD = $d; $best = $m; } } return $best ?? $this->monitorAt(-1e9, -1e9); } /** * Every window of WinZik whole on one screen (never past an edge, never across two): the player and the list docked * under it as one block; a block taller than its screen gets a shorter list. */ private function fitWindows(Desktop $desk): void { $wz = $desk->wz(); $main = $desk->main; $list = $desk->playlist; $docked = $main !== null && $list !== null && $list->visible() && $wz->ui['playlist']['attached']; $blocks = []; if ($main !== null && $main->visible()) { $blocks[] = [$main, $docked ? $list : null]; } if ($list !== null && $list->visible() && !$docked) { $blocks[] = [$list, null]; } foreach ([$desk->eq, $desk->video] as $w) { if ($w !== null && $w->visible() && !($w === $desk->video && (bool)($wz->ui['video']['full'] ?? false))) { $blocks[] = [$w, null]; } } $player = null; // the player's block once placed: the others brought back do not go over it foreach ($blocks as [$w, $under]) { $bw = max($w->width(), $under?->width() ?? 0); $bh = $w->height() + ($under?->height() ?? 0); [$mx, $my, $mw, $mh] = $this->nearestMonitor($w->x + $bw / 2, $w->y + min($bh, 40) / 2); $tall = $under ?? ($w === $list ? $list : null); if ($bh > $mh && $tall instanceof \App\Gui\PlaylistWindow) { // too tall for this screen: the list loses lines $rows = max(\App\Gui\PlaylistWindow::MIN_ROWS, $tall->rows() - (int)ceil(($bh - $mh) / \App\Gui\PlaylistWindow::ROW_HEIGHT)); if ($rows !== $tall->rows()) { $wz->ui['playlist']['rows'] = $rows; $bh = $w->height() + ($under?->height() ?? 0); } } $x = max($mx, min($w->x, $mx + $mw - $bw)); $y = max($my, min($w->y, $my + $mh - min($bh, $mh))); $moved = abs($x - $w->x) > 0.01 || abs($y - $w->y) > 0.01; if ($moved && $player !== null && $w !== $main && $x < $player[0] + $player[2] && $x + $bw > $player[0] && $y < $player[1] + $player[3] && $y + $bh > $player[1]) { // brought back onto the player: beside it (left, else right), on the same screen if ($player[0] - $bw >= $mx) { $x = $player[0] - $bw; } elseif ($player[0] + $player[2] + $bw <= $mx + $mw) { $x = $player[0] + $player[2]; } } if ($w === $main) { $player = [$x, $y, $bw, $bh]; } if ($moved) { $w->x = $x; $w->y = $y; $w->remember(); if ($under !== null) { $desk->followMain(); } } } } /** The screen the mouse is on now (the splash shows there), null when it cannot be known. */ private function pointerMonitor(): ?array { if (PHP_OS_FAMILY === 'Linux' && getenv('DISPLAY')) { $out = (string)@shell_exec('xdotool getmouselocation --shell 2>/dev/null'); self::trace('pointer: ' . str_replace("\n", ' ', trim($out))); if (preg_match('/X=(-?\d+)\s+Y=(-?\d+)/', $out, $m)) { return $this->monitorAt(((int)$m[1] - $this->screen[0]) / $this->scale, ((int)$m[2] - $this->screen[1]) / $this->scale); } } return null; } /** * The screen under a point of WinZik's desktop (desktop pixels), the main one when it is on none. * @return array{0: float, 1: float, 2: float, 3: float} that screen in desktop pixels */ public function monitorAt(float $dx, float $dy): array { $sx = $this->screen[0] + $dx * $this->scale; $sy = $this->screen[1] + $dy * $this->scale; $pick = $this->monitors[0]; foreach ($this->monitors as $m) { if ($sx >= $m[0] && $sx < $m[0] + $m[2] && $sy >= $m[1] && $sy < $m[1] + $m[3]) { $pick = $m; break; } } return [($pick[0] - $this->screen[0]) / $this->scale, ($pick[1] - $this->screen[1]) / $this->scale, $pick[2] / $this->scale, $pick[3] / $this->scale]; } public function screenCount(): int { return count($this->monitors); } /** @return list every screen, in desktop pixels */ public function screensInDesk(): array { return array_map(fn ($m) => [($m[0] - $this->screen[0]) / $this->scale, ($m[1] - $this->screen[1]) / $this->scale, $m[2] / $this->scale, $m[3] / $this->scale], $this->monitors); } /** true: the point is on a screen (not in the holes between screens of different sizes) */ public function onAScreen(float $dx, float $dy): bool { $sx = $this->screen[0] + $dx * $this->scale; $sy = $this->screen[1] + $dy * $this->scale; foreach ($this->monitors as $m) { if ($sx >= $m[0] && $sx < $m[0] + $m[2] && $sy >= $m[1] && $sy < $m[1] + $m[3]) { return true; } } return false; } /** The screen of the player (its middle): the lyrics, a film on the whole screen, the splash and dialogs go there. */ public function playerMonitor(): array { $main = $this->desk?->main; return $main !== null ? $this->monitorAt($main->x + $main->width() / 2, $main->y + 20) : $this->monitorAt(-1e9, -1e9); } public function screenWidth(): float { return (float)$this->screen[2]; } public function screenHeight(): float { return (float)$this->screen[3]; } public function attach(Desktop $desk): void { $this->desk = $desk; $desk->native = $this; $desk->baseScale = $this->base; $desk->scale = $this->scale = Desktop::effectiveScale($this->base, $desk->zoomPct()); } public function windowUnderPointer(): ?SkinWindow { return $this->under; } /** the helpers ended (quitting): none starts again */ private bool $stopped = false; /** * Quitting: the helpers of the desktop end with WinZik (the icon of the notification area, the watcher of the window * in front, xrandr); they do not start again after. Again: nothing. */ public function stop(): void { $this->stopped = true; $this->trayFailed = true; $this->tray?->close(); $this->tray = null; $this->foreground?->stop(); $this->foreground = null; $this->xrandr?->stop(); $this->xrandr?->cleanup(); $this->xrandr = null; } /** the icon in the notification area while WinZik is reduced there (JumPHP\Native\SystemTray) */ private ?\JumPHP\Native\SystemTray $tray = null; /** Réduire: the player goes to the task bar, the other windows hide (they come back with it). */ public function minimize(): void { // Réduire dans la barre (2001: the systray icon of winster4.bas): every window hidden, the icon of the // notification area brings them back; without one (no tray on this desktop), the player goes to the task bar $this->ensureTray(); if ($this->tray === null && isset($this->wins['main'])) { \SDL_MinimizeWindow($this->wins['main']['win']); $this->minimized = true; } } /** the notification area has no icon of ours (none here, or its helper failed): not tried again */ private bool $trayFailed = false; /** The icon of WinZik in the notification area, ALWAYS there (compact bar, lyrics only, reduced: WinZik is never lost). */ /** the icon's helper: when it was started, when it may start again, how many times it ended at once */ private float $trayStarted = 0.0; private float $trayRetryAt = 0.0; private int $trayFails = 0; private function ensureTray(): void { if ($this->tray !== null || $this->trayFailed || $this->clock < $this->trayRetryAt) { return; } $this->trayStarted = $this->clock; $this->tray = \JumPHP\Native\SystemTray::show('WinZik', $this->engine->config->path('assets/icon.png'), ['show' => 'Afficher WinZik', 'play' => 'Play / Pause', 'next' => 'Suivant', 'compact' => 'Mode compact', 'quit' => 'Quitter'], true); $this->trayFailed = $this->tray === null; } private ?Foreground $foreground = null; /** * Form4.Timer1: the compact bar on the title bar of the window in front (another program's), at its right before * its buttons; it follows it. Without that window (or that helper), it stays where it is. */ private function followForeground(Desktop $desk): void { $wz = $desk->wz(); if ($this->stopped || !($wz->options['compactFollow'] ?? true) || $desk->compact === null) { $this->foreground?->stop(); $this->foreground = null; return; } // always watched (not only in the mini bar): the window of another program in front is known BEFORE the mini // bar is asked for, which then goes onto it at once $this->foreground ??= new Foreground($wz->storagePath('tmp/logs')); $r = $this->foreground->rect(); if (!$wz->ui['compact']['active'] || $r === null || $this->pressedIn === 'compact') { return; } [$right, $top] = self::onTitleBar($r, $this->scale, (int)($wz->options['compactDx'] ?? 0), (int)($wz->options['compactDy'] ?? 0)); $desk->compact->x = ($right - $this->screen[0]) / $this->scale; $desk->compact->y = max(0, ($top - $this->screen[1]) / $this->scale); } /** * Where the mini bar goes on the title bar of a window ([x, y, w, h, title bar height], screen pixels, at the zoom * $scale): its buttons (the bar FOLDED) in the middle of the title bar, before its buttons, moved by the offset of the * settings ($dx / $dy, + or -: each title bar has its buttons elsewhere). Its height unfolded never counts (it was * centred on it: the bar went up as it unfolded, down as it folded): the title shows under the buttons, it stays. * @param array{0: int|float, 1: int|float, 2: int|float, 3: int|float, 4: int|float} $r * @return array{0: float, 1: float} */ public static function onTitleBar(array $r, float $scale, int $dx, int $dy): array { [$bw, $bh] = [CompactWindow::WIDTH * $scale, CompactWindow::FOLDED * $scale]; [$x, $y, $w, , $title] = $r; $top = $title >= $bh ? $y - $title + ($title - $bh) / 2 : $y + 6; // in its title bar (or its own drawn header) $right = $x + $w - $bw - ($title > 0 ? 150 : 170); // before its buttons return [(float)($right + $dx), (float)($top + $dy)]; } /** when the menu of the icon was opened (it closes alone if the pointer never comes onto it: a click elsewhere is not seen) */ private float $trayMenuAt = -1.0; /** the last moment the pointer was over a menu of WinZik */ private float $menuHovered = -10.0; private function pollTray(Desktop $desk): void { if ($this->trayMenuAt >= 0) { if ($desk->menu() === null) { $this->trayMenuAt = -1.0; } elseif ($this->clock - $this->trayMenuAt > 4 && $this->clock - $this->menuHovered > 4) { $desk->close(); $this->trayMenuAt = -1.0; } } $this->ensureTray(); if ($this->tray === null) { return; } $wz = $desk->wz(); $heard = false; foreach ($this->tray->poll() as $event) { $heard = true; if (preg_match('/^context (-?\d+) (-?\d+)$/', $event, $m)) { // a right click on the icon: WinZik's own menu at the point clicked (to the left near the right edge, // upwards near the bottom) $desk->openTrayMenu(((int)$m[1] - $this->screen[0]) / $this->scale, ((int)$m[2] - $this->screen[1]) / $this->scale); $this->trayMenuAt = $this->clock; continue; } match ($event) { // the icon clicked: the whole of WinZik, in front (out of the tray, of the compact bar, of lyrics only) 'activate', 'show' => $this->showEverything($desk), 'play' => $wz->togglePause(), 'next' => $wz->next(), 'compact' => $wz->toggleCompact(), 'quit' => $wz->quit(), default => null, }; } if (!$this->tray->alive()) { // the helper ended: after a click (zenity), a new icon at once; ended by itself (no tray here, no Python // module): again later, later and later (it was started again at every frame: a process 16 times a second) $this->tray->close(); $this->tray = null; if (!$heard) { $this->trayFails = $this->clock - $this->trayStarted < 5 ? $this->trayFails + 1 : 0; $this->trayRetryAt = $this->clock + min(60.0, 2.0 ** $this->trayFails); $this->trayFailed = $this->trayFails >= 4; } } } /** * WinZik started again while it runs (or its icon asked for): every window back (out of the tray, of the mini * bar, of lyrics only), in front, and on the screen of the mouse when the player is on another one. */ public function wakeUp(): void { $desk = $this->desk; if ($desk === null) { return; } $this->showEverything($desk); $main = $desk->main; $here = $this->pointerMonitor(); if ($main === null || $here === null) { return; } $there = $this->playerMonitor(); if (abs($here[0] - $there[0]) > 0.5 || abs($here[1] - $there[1]) > 0.5) { // the player (and its list) in the middle of this screen; fitWindows keeps it whole $list = $desk->playlist; $docked = $list !== null && $list->visible() && $desk->wz()->ui['playlist']['attached']; $bw = max($main->width(), $docked ? $list->width() : 0); $bh = $main->height() + ($docked ? $list->height() : 0); $main->x = $here[0] + max(0, ($here[2] - $bw) / 2); $main->y = $here[1] + max(0, ($here[3] - $bh) / 2); $main->remember(); $desk->followMain(); } } private function showEverything(Desktop $desk): void { $wz = $desk->wz(); $desk->fromTray(); $wz->ui['lyricsOnly'] = false; if ($wz->ui['compact']['active']) { $wz->toggleCompact(); } $this->lastRaise = -10.0; $this->raise(); } // each frame ------------------------------------------------------------------------------------------ /** WINZIK_TRACE=1: every frame's length and every mouse event on stderr (to measure how quick the clicks are) */ public static bool $trace = false; public static function trace(string $line): void { if (self::$trace) { fwrite(STDERR, sprintf("[%.3f] %s\n", microtime(true), $line)); } } private float $frameStart = 0.0; /** @var array trace: sums over the last 5 seconds */ private array $stats = []; private function stat(string $name, float $seconds): void { $this->stats[$name] = ($this->stats[$name] ?? 0.0) + $seconds; $this->stats["max $name"] = max($this->stats["max $name"] ?? 0.0, $seconds); } public function frame(float $dt): void { if (self::$trace) { $now = microtime(true); if ($this->frameStart > 0 && $now - $this->frameStart > 0.050) { self::trace(sprintf('slow frame gap %.0f ms', ($now - $this->frameStart) * 1000)); } if ($this->frameStart > 0) { $this->stat('gap', $now - $this->frameStart); $this->stats['frames'] = ($this->stats['frames'] ?? 0) + 1; } if (($this->stats['since'] ?? 0) === 0) { $this->stats['since'] = $now; } elseif ($now - $this->stats['since'] > 5) { $f = max(1, $this->stats['frames'] ?? 1); $line = sprintf('stats %d frames: php %.1f Mo (pic %.1f);', $f, memory_get_usage() / 1e6, memory_get_peak_usage() / 1e6); foreach (['gap', 'step', 'draw', 'shell'] as $k) { $line .= sprintf(' %s avg %.1f max %.1f ms;', $k, ($this->stats[$k] ?? 0) / $f * 1000, ($this->stats["max $k"] ?? 0) * 1000); } self::trace($line); $this->stats = ['since' => $now]; } $this->frameStart = $now; $shellStart = $now; } $this->clock += $dt; $this->watchMonitors($dt); $this->engineWindow(); $desk = $this->desk; if ($desk === null || !($this->engine->scenes->current() instanceof MainForm || $this->dialogOnTop())) { $this->hideAll(); return; } $wz = $desk->wz(); if ($this->minimized && isset($this->wins['main']) && (\SDL_GetWindowFlags($this->wins['main']['win']) & self::MINIMIZED) === 0) { // the player came back from the task bar $this->minimized = false; $desk->fromTray(); } $this->pollTray($desk); // Alt+Tab to another program (or a click on it): the menus of WinZik go away if ($desk->menu() !== null) { $focus = \SDL_GetKeyboardFocus(); $ours = false; if ($focus) { $fid = (int)\SDL_GetWindowID($focus); foreach ($this->wins as $n) { $ours = $ours || $n['id'] === $fid; } } $this->hadFocus = $this->hadFocus || $ours; $this->away = $ours ? 0.0 : $this->away + $dt; if ($this->hadFocus && $this->away > 0.25 && $this->pressedIn === '') { $desk->close(); $this->away = 0.0; } } else { $this->away = 0.0; $this->hadFocus = false; } $this->followForeground($desk); // the film on the whole screen goes above everything: its window is made again with that flag $videoFull = (bool)($wz->ui['video']['full'] ?? false); if ($videoFull !== $this->videoFull && isset($this->wins['video'])) { self::freeWindow($this->wins['video']); unset($this->wins['video']); } $this->videoFull = $videoFull; // a dialog (YouTube, Options...) open: WinZik's windows come down from "always on top" (the dialog above them) $onTop = (bool)($wz->options['onTop'] ?? true) && !$this->dialogOnTop() && !in_array($this->engineMode, ['dialog', 'editor', 'full'], true); // a window on no screen (a screen unplugged, the first start on a computer whose screens have holes): to the main one $this->screenCheck += $dt; if ($this->screenCheck > 1.0 && $desk->main !== null) { $this->screenCheck = 0.0; $main = $desk->main; if (!$this->onAScreen($main->x + $main->width() / 2, $main->y + 10)) { [$mx, $my] = $this->monitorAt(-1e9, -1e9); $main->x = $mx + 12; $main->y = $my + 12; $main->remember(); $desk->followMain(); } } if ($onTop !== $this->onTop) { $this->onTop = $onTop; $this->destroyAll(); } // the zoom of the menu / Ctrl + wheel: every window of WinZik at its new size (their texts drawn at it) $zoomed = Desktop::effectiveScale($this->base, $desk->zoomPct()); if (abs($zoomed - $this->scale) > 0.001) { $this->scale = $desk->scale = $zoomed; } $this->burst = max(0.0, $this->burst - $dt); if ($this->desk !== null && $this->desk->revealing()) { $this->burst = 0.1; // unrolling / rolling up: every frame } $this->drawClock += $dt; $this->drawNow = $this->drawClock >= 1 / 30 - 0.002; if ($this->drawNow) { $this->drawClock = 0.0; } $pointer = $this->pointer(); $this->raiseLater(); // the keys (Escape, F, the keys of 2001...) go to the desktop of WinZik: its windows are the computer's, the form // never gave it the focus (only a click on a widget does) $top = $this->engine->scenes->current(); if ($top instanceof MainForm && $top->focused() === null) { $top->setFocus($desk); } $t = microtime(true); $desk->step($dt, $pointer); $this->fitWindows($desk); if (self::$trace) { $this->stat('step', microtime(true) - $t); $t = microtime(true); } foreach ($desk->windows() as $window) { $this->show($window, $window->visible() || ($window->id() === 'main' && $wz->ui['tray'] && $this->tray === null)); } $this->menuWindow($desk->menu()); $this->otherLyrics($desk); $this->freeHidden(); // a dialog, the editor, A propos: above WinZik's windows (shown after it: the window manager put them above it; // one of them clicked: the dialog comes back in front once the click is over) if (in_array($this->engineMode, ['dialog', 'editor', 'full'], true) && $this->pressedIn === '' && !$this->engineAbove) { $focus = \SDL_GetKeyboardFocus(); $fid = $focus ? (int)\SDL_GetWindowID($focus) : 0; $this->engineAbove = $fid !== 0 && $this->windowNamed($fid) !== '' && !str_starts_with($this->windowNamed($fid), 'menu'); } if ($this->engineAbove && in_array($this->engineMode, ['dialog', 'editor', 'full'], true)) { $win = $this->engine->sdl->getWindow()?->getWindow(); if ($win !== null) { \SDL_RaiseWindow($win); } } $this->engineAbove = false; if (self::$trace) { $this->stat('draw', microtime(true) - $t); $this->stat('shell', microtime(true) - ($shellStart ?? $t)); } } /** A dialog over the player: the windows of WinZik stay on screen (the music goes on). */ private function dialogOnTop(): bool { $top = $this->engine->scenes->current(); return $top !== null && !$top instanceof FullScreen && !$top instanceof MainForm && $top->isOverlay(); } /** The engine's window: the splash alone, hidden under the player, a framed window for dialogs and editors, the whole screen for Lock and A propos. */ /** a window of WinZik appeared this frame (a dialog open is raised above it again) */ private bool $engineAbove = false; /** @var array{0: float, 1: float, 2: float, 3: float}|null the screen the splash shows on (chosen once) */ private ?array $splashMonitor = null; /** * The splash's window on a screen of that size (pixels): about 40 % of its width, whatever its resolution or its * zoom (1707 pixels: x1.5; 2560: x2.25; 1366: x1.25), never more than half its height. * @return array{0: int, 1: int, 2: bool} */ public static function splashSize(int $sw, int $sh): array { $k = round(min($sw * 0.4 / 489, $sh * 0.5 / 153) * 4) / 4; $k = max(0.75, $k); return [(int)round(489 * $k), (int)round(153 * $k), false]; } private function engineWindow(): void { $win = $this->engine->sdl->getWindow()?->getWindow(); if ($win === null) { return; } $top = $this->engine->scenes->current(); $mode = match (true) { $top instanceof SplashScene => 'splash', $top instanceof FullScreen => 'full', $top instanceof MainForm => 'hidden', $this->dialogOnTop() => 'dialog', default => 'editor', }; // the splash: on the screen of the mouse (the active one); the dialogs and Lock / A propos: on the player's if ($mode === 'splash' && $this->engineMode !== 'splash') { $this->splashMonitor = $this->pointerMonitor() ?? $this->playerMonitor(); } [$mx, $my, $mw, $mh] = $mode === 'splash' && $this->splashMonitor !== null ? $this->splashMonitor : $this->playerMonitor(); [$sx, $sy, $sw, $sh] = [(int)round($this->screen[0] + $mx * $this->scale), (int)round($this->screen[1] + $my * $this->scale), (int)round($mw * $this->scale), (int)round($mh * $this->scale)]; if ($mode === 'dialog' && $top instanceof \JumPHP\Gui\Form) { // as big as the dialog (it grows: the results of a search): the window follows it [$dw, $dh] = array_map(fn ($v) => (int)ceil($v), $top->dialogSize($sw * 0.9, $sh * 0.9)); if ($mode === $this->engineMode && [$dw, $dh] !== $this->dialogSize) { $this->dialogSize = [$dw, $dh]; \SDL_SetWindowSize($win, $dw, $dh); \SDL_SetWindowPosition($win, $sx + intdiv($sw - $dw, 2), $sy + intdiv($sh - $dh, 2)); } $this->dialogSize = [$dw, $dh]; } if ($mode === $this->engineMode) { return; } if ($this->engineMode === 'full') { \SDL_SetWindowFullscreen($win, 0); // out of the system's full screen first (its size and place come back) } $this->engineMode = $mode; [$w, $h, $bordered] = match ($mode) { 'splash' => self::splashSize($sw, $sh), 'full' => [$sw, $sh, false], 'dialog' => [$this->dialogSize[0], $this->dialogSize[1], true], 'editor' => [min($sw - 40, 1180), min($sh - 80, 820), true], default => [0, 0, true], }; if ($mode === 'hidden') { // hidden, and tiny: the engine still draws its (empty) view each frame, 64 x 64 costs nothing \SDL_SetWindowSize($win, 64, 64); \SDL_HideWindow($win); return; } \SDL_SetWindowBordered($win, $bordered); \SDL_SetWindowSize($win, $w, $h); \SDL_SetWindowPosition($win, $mode === 'full' ? $sx : $sx + intdiv($sw - $w, 2), $mode === 'full' ? $sy : $sy + intdiv($sh - $h, 2)); \SDL_ShowWindow($win); if ($mode === 'full') { // A propos, Lock: the system's full screen of that screen (the task bar goes under it, the window manager // keeps a mere window of the screen's size under its panels) \SDL_SetWindowFullscreen($win, \SDL_WINDOW_FULLSCREEN_DESKTOP); } \SDL_RaiseWindow($win); } // the windows of WinZik ------------------------------------------------------------------------------ private function show(SkinWindow $window, bool $visible): void { $id = $window->id(); // while they unroll / roll up (Desktop::revealed), each window slides in from the left (out to the left): it // keeps its size and moves (resizing the windows of the computer and their pictures each frame was slow); // its height follows its own animations (the player's bottom part, the compact bar) $revealed = $this->desk !== null ? $this->desk->revealed($window) : $window->width(); $w = (int)round($window->width() * $this->scale); $h = (int)round($window->height() * $this->scale); if ($revealed * $this->scale < 1) { $visible = false; } $x = $this->screen[0] + (int)round(($window->x - ($window->width() - $revealed)) * $this->scale); $y = $this->screen[1] + (int)round($window->y * $this->scale); if (!isset($this->wins[$id])) { if (!$visible) { return; } // the compact bar (on other programs' title bars), the lyrics, the menu and a film on the whole screen are always above $above = $this->onTop || in_array($id, ['compact', 'menu', 'menu2', 'lyrics'], true) || ($id === 'video' && (bool)($this->desk?->wz()->ui['video']['full'] ?? false)); // ONE application for the system: the player is in the task bar, every other window is a tool window of // WinZik (no entry of its own in the task bar, the dock, Alt+Tab), the menu a real popup menu $kind = match ($id) { 'main' => 0, // the lyrics too: outside the window manager, which keeps its windows off the panels (the bar covers the task bar) // the mini bar too: on another program's title bar, ALWAYS above it (a window of the window manager lost // its "above" once hidden and shown again: it went under the window it sits on) 'menu', 'menu2', 'lyrics', 'card', 'compact' => self::POPUP_MENU | self::SKIP_TASKBAR, // a tool window of WinZik; while a dialog is open (onTop off), a plain one: the window manager keeps the // tool windows of a program above its other windows, the dialog went under the play list default => str_starts_with($id, 'lyrics#') ? self::POPUP_MENU | self::SKIP_TASKBAR : ($this->onTop ? self::UTILITY : 0) | self::SKIP_TASKBAR, }; $flags = self::BORDERLESS | self::HIDDEN | ($above ? self::ALWAYS_ON_TOP : 0) | $kind; $win = \SDL_CreateWindow('WinZik', $x, $y, max(1, $w), max(1, $h), $flags); // no vsync: five windows each waiting for the screen's refresh made a frame wait five times (12 images a second) $renderer = new Renderer($win, max(1, $w), max(1, $h), false); $root = defined('JUMPHP_ROOT') ? (string)JUMPHP_ROOT : (string)getcwd(); $this->wins[$id] = ['win' => $win, 'id' => (int)\SDL_GetWindowID($win), 'r' => $renderer, 'tex' => new NativeTextures($renderer->getRenderer(), $root), 'w' => $w, 'h' => $h, 'x' => $x, 'y' => $y, 'shown' => false]; // the same name and icon on every window: whatever shows them, they are WinZik's $icon = $this->desk?->wz()->skin->image('ico'); $surface = $icon !== null ? @\IMG_Load($icon) : null; if ($surface) { \SDL_SetWindowIcon($win, $surface); // SDL keeps its own copy \SDL_FreeSurface($surface); } \SDL_SetWindowTitle($win, $id === 'main' ? 'WinZik' : 'WinZik - ' . $id); } $n = &$this->wins[$id]; if (!$visible) { if ($n['shown'] && !($id === 'main' && $this->minimized)) { \SDL_HideWindow($n['win']); $n['shown'] = false; $n['hiddenAt'] = $this->clock; } unset($n); return; } $resized = $w !== $n['w'] || $h !== $n['h']; if ($resized && $this->pressedIn === $id && microtime(true) - ($n['resizedAt'] ?? 0.0) < 0.05) { // being resized by the pointer: the window of the computer follows 20 times a second (each resize goes // through the window manager and makes the picture again: at every frame it was slow, the clicks went wrong); // its last picture stays meanwhile, the release gives its final size unset($n); return; } if ($resized) { $n['resizedAt'] = microtime(true); \SDL_SetWindowSize($n['win'], max(1, $w), max(1, $h)); $n['r']->resizeView(max(1, $w), max(1, $h)); [$n['w'], $n['h']] = [$w, $h]; } if ($x !== $n['x'] || $y !== $n['y']) { \SDL_SetWindowPosition($n['win'], $x, $y); [$n['x'], $n['y']] = [$x, $y]; } // drawn before it shows (no black window for a frame: they all appear together, at once); then 30 times a // second (the pictures of a film are 25, the title moves 5 times a second): half the work of 60 // drawn when it is due (each window its own pace: the player with its visualizer 30 times a second, the play list // a few times...), at once after the pointer or a key (every window for a moment: a click changes others too) $due = $this->drawNow && ($this->burst > 0 || $this->clock - ($n['drawnAt'] ?? -1.0) >= $window->redrawEvery() - 0.002); if ($due || !$n['shown'] || $resized) { $this->draw($n, fn (Canvas $c) => $window->render($c)); $n['drawnAt'] = $this->clock; } if (!$n['shown']) { \SDL_ShowWindow($n['win']); $n['shown'] = true; $this->engineAbove = true; // a dialog open: it is raised again above this window (frame) if (in_array($id, ['menu', 'menu2', 'compact'], true)) { \SDL_RaiseWindow($n['win']); // above the player even when it was clicked last (same layer) } $this->draw($n, fn (Canvas $c) => $window->render($c)); } unset($n); } /** @param array{r: Renderer, tex: NativeTextures} $n @param callable(Canvas): void $paint */ private function draw(array $n, callable $paint, float $ox = 0, float $oy = 0): void { $t0 = self::$trace ? microtime(true) : 0.0; $r = $n['r']; $r->beginFrame('#000000'); $c = new Canvas($r, null); $c->native = $n['tex']; $c->scale = $this->scale; $c->skin = $this->desk?->wz()->skin; $c->at($ox, $oy); $paint($c); $r->endFrame(); if (self::$trace && microtime(true) - $t0 > 0.012) { self::trace(sprintf('draw took %.0f ms', (microtime(true) - $t0) * 1000)); } } /** * A window hidden for 15 s (the equalizer, the film, a card, a menu...): its renderer and its pictures freed (made * again when it shows: at once). The player stays (its taskbar entry). */ private function freeHidden(): void { foreach ($this->wins as $id => $n) { if ($id !== 'main' && !$n['shown'] && $this->clock - ($n['hiddenAt'] ?? $this->clock) > 15) { self::freeWindow($n); unset($this->wins[$id]); } } } /** * A window of the computer closed with everything it holds: its pictures and texts (and their fonts) first, then its * renderer, then the window (only the window destroyed, the renderer and its textures stayed: they leaked at every * dialog opened or closed). * @param array{win: mixed, r: Renderer, tex: NativeTextures} $n */ private static function freeWindow(array $n): void { $n['tex']->destroy(); $n['r']->destroy(); \SDL_DestroyWindow($n['win']); } /** Every window of WinZik closed (they are made again at the next frame, with the new flags). */ private function destroyAll(): void { foreach ($this->wins as $n) { self::freeWindow($n); } $this->wins = []; $this->under = null; $this->pressedIn = ''; } private function hideAll(): void { foreach ($this->wins as $id => $n) { if ($n['shown']) { \SDL_HideWindow($n['win']); $this->wins[$id]['shown'] = false; } } } /** The right click menu (and its submenu) as one window of the computer. */ /** The lyrics on every screen (the bar's option): the other screens get a copy of the bar, at their bottom. */ private function otherLyrics(Desktop $desk): void { $bar = $desk->lyrics; $all = $bar !== null && $bar->visible() && (bool)($desk->wz()->options['lyricsAllScreens'] ?? false) && count($this->monitors) > 1; $player = $this->playerMonitor(); foreach ($this->screensInDesk() as $i => $m) { $id = 'lyrics#' . $i; $same = abs($m[0] - $player[0]) < 0.5 && abs($m[1] - $player[1]) < 0.5; if (!$all || $same) { if (isset($this->wins[$id]) && $this->wins[$id]['shown']) { \SDL_HideWindow($this->wins[$id]['win']); $this->wins[$id]['shown'] = false; } continue; } $this->show(new class($desk->wz(), $desk, $bar, $m, $id) extends SkinWindow { /** @param array{0: float, 1: float, 2: float, 3: float} $m */ public function __construct($wz, $desk, private \App\Gui\LyricsBar $bar, private array $m, private string $name) { parent::__construct($wz, $desk); $this->x = $m[0]; $this->y = $m[1] + $m[3] - $bar->height(); } public function id(): string { return $this->name; } public function width(): float { return $this->m[2]; } public function height(): float { return $this->bar->height(); } public function visible(): bool { return true; } public function render(Canvas $c): void { $this->bar->monitorOverride = $this->m; $this->bar->render($c); $this->bar->monitorOverride = null; } }, true); } } /** The right click menu and its submenu: each a window of the computer, as big as it (nothing grey around). */ private function menuWindow(?PopupMenu $menu): void { foreach (['menu' => $menu, 'menu2' => $menu?->child] as $id => $m) { if ($m === null) { if (isset($this->wins[$id]) && $this->wins[$id]['shown']) { \SDL_HideWindow($this->wins[$id]['win']); $this->wins[$id]['shown'] = false; } continue; } $this->show(new class($this->desk?->wz(), $this->desk, $m, $id) extends SkinWindow { public function __construct($wz, $desk, private PopupMenu $menu, private string $name) { parent::__construct($wz, $desk); [$this->x, $this->y] = [$menu->x, $menu->y]; } public function id(): string { return $this->name; } public function width(): float { return PopupMenu::WIDTH; } public function height(): float { return $this->menu->height(); } public function visible(): bool { return true; } public function render(Canvas $c): void { $saved = [$c->ox, $c->oy]; $c->at(-$this->x, -$this->y); [$withChild, $shadow] = [$this->menu->withChild, $this->menu->shadow]; [$this->menu->withChild, $this->menu->shadow] = [false, false]; $this->menu->render($c); [$this->menu->withChild, $this->menu->shadow] = [$withChild, $shadow]; $c->at($saved[0], $saved[1]); } }, true); } } // the pointer ---------------------------------------------------------------------------------------- /** @var list the mouse events of this frame, in their order: type, button, x, y, window id */ private array $mouseEvents = []; /** the window the mouse is in (SDL's ENTER / LEAVE, in the order of the events), 0: none of ours */ private int $mouseWinId = 0; /** @var array{0: float, 1: float}|null where the pointer was last (desktop pixels) */ private ?array $lastPointer = null; /** The engine gives every mouse event in its order (InputManager 'mouse-event'): none is lost between two frames. */ private function listenMouse(): void { $this->engine->input->on('window', function (int $event, int $a = 0, int $b = 0, int $id = 0): void { if ($event === \SDL_WINDOWEVENT_ENTER) { $this->mouseWinId = $id; } elseif ($event === \SDL_WINDOWEVENT_LEAVE && $this->mouseWinId === $id) { $this->mouseWinId = 0; } }); $this->engine->input->on('mouse-event', function (string $type, int $button, float $x, float $y): void { $this->mouseEvents[] = [$type, $button, $x, $y, $this->mouseWinId]; $this->burst = 0.4; if (str_starts_with($this->windowNamed($this->mouseWinId), 'menu')) { $this->menuHovered = $this->clock; } if (self::$trace && ($type !== 'move' || getenv('WINZIK_TRACE') === '2')) { self::trace("event $type $button " . round($x) . ',' . round($y) . ' win ' . $this->mouseWinId . ' (' . $this->windowNamed($this->mouseWinId) . ')'); } }); } private function windowNamed(int $sdlId): string { foreach ($this->wins as $name => $n) { if ($n['id'] === $sdlId && $n['shown']) { return $name; } } return ''; } /** * Every mouse event of the frame, in its order, to the window it happened in (a press and what follows it, to the * window pressed: SDL keeps the mouse there). @return array{0: float, 1: float}|null where the pointer is (desktop pixels) */ private function pointer(): ?array { $desk = $this->desk; $events = $this->mouseEvents; $this->mouseEvents = []; if ($desk === null) { return null; } if ($this->mouseWinId === 0 && $events === [] && ($focus = \SDL_GetMouseFocus())) { $this->mouseWinId = (int)\SDL_GetWindowID($focus); // before the first ENTER of the session } foreach ($events as [$type, $button, $x, $y, $winId]) { $in = $this->pressedIn !== '' && ($type === 'move' || $type === 'up') ? $this->pressedIn : $this->windowNamed($winId); if ($in === '' || !isset($this->wins[$in])) { continue; } // where we put the window (SDL's own position comes back late while it moves) $dx = ($this->wins[$in]['x'] - $this->screen[0] + $x) / $this->scale; $dy = ($this->wins[$in]['y'] - $this->screen[1] + $y) / $this->scale; $window = null; foreach ($desk->windows() as $w) { if ($w->id() === $in) { $window = $w; } } $target = str_starts_with($in, 'menu') ? null : $window; if ($type === 'down' && $button === 1) { $now = microtime(true); // the real time (the frames' clock lags after a slow frame) $this->lastPress = $now; $double = $now - $this->lastDown < 0.4; $this->downDouble = $double; $this->lastDown = $double ? -10 : $now; // a third click starts again (not a double once more) $this->pressedIn = $in; $desk->nativePointer('down', $dx, $dy, $target, $double); } elseif ($type === 'down' && $button === 3) { $desk->nativePointer('right', $dx, $dy, $window); } elseif ($type === 'up' && $button === 1 && $this->pressedIn !== '') { $desk->nativePointer('up', $dx, $dy, $target, $this->downDouble); $this->pressedIn = ''; } elseif ($type === 'move') { if ($this->pressedIn !== '') { $desk->nativePointer('drag', $dx, $dy, $target); } $this->lastPointer = [$dx, $dy]; } elseif ($type === 'wheel' && $window !== null) { $desk->nativePointer('wheel', $dx, $dy, $window, false, $y); } if ($type !== 'wheel') { $this->lastPointer = [$dx, $dy]; } } $in = $this->pressedIn !== '' ? $this->pressedIn : $this->windowNamed($this->mouseWinId); if ($in === '') { $this->under = null; return null; } $this->under = null; foreach ($desk->windows() as $w) { if ($w->id() === $in) { $this->under = $w; } } return $this->lastPointer; } }