<?phpnamespace App\Form;use App\Cryo\FreezeFile;use App\Cryo\LiveClient;use App\Cryo\Studio;use App\Gui\MemoryChart;use JumPHP\Gui\Button;use JumPHP\Gui\CheckBox;use JumPHP\Gui\Container;use JumPHP\Gui\Form;use JumPHP\Gui\Image;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\Radio;use JumPHP\Gui\TextBox;use JumPHP\Gui\Theme;use JumPHP\Native\FilePicker;use JumPHP\Util\Lang;/** * The main window: the snapshots on the left, one screen of analysis on the right, chosen with the radios of the * "nav" row (overview + alerts, leaks by site / class / stack, classes, node inspector, dominators, orphans, * duplicates, query, memory series, call stack of a freeze, Live link to a running script). Every list of nodes opens * the clicked node in the inspector. * Widgets: forms/MainForm.form.yaml. * * @property Image $logo * @property Label $heading * @property Label $subtitle * @property Button $demo * @property Button $open * @property CheckBox $dark * @property Container $nav * @property Radio $navOverview * @property Radio $navLeaks * @property Radio $navClasses * @property Radio $navInspector * @property Radio $navDominators * @property Radio $navOrphans * @property Radio $navDupes * @property Radio $navQuery * @property Radio $navSeries * @property Container $snapshotsPanel * @property ListBox $snapshots * @property Label $snapInfo * @property Label $backend * @property Container $analysis * @property Label $viewTitle * @property Container $pageOverview * @property Label $alertsTitle * @property ListBox $alerts * @property Label $alertDetail * @property ListBox $overviewRows * @property Container $pageLeaks * @property Label $byLabel * @property Radio $bySite * @property Radio $byClass * @property Radio $byStack * @property ListBox $rows * @property Label $detail * @property Label $sourceTitle * @property TextBox $source * @property Label $hookTitle * @property TextBox $hookSource * @property Label $pathInfo * @property Container $pageClasses * @property ListBox $classes * @property Label $instancesTitle * @property ListBox $instances * @property Container $pageInspector * @property Button $back * @property Label $nodeTitle * @property Button $pathButton * @property Label $nodeInfo * @property Label $outTitle * @property ListBox $outEdges * @property Label $inTitle * @property ListBox $inEdges * @property ListBox $pathRows * @property Container $pageDominators * @property ListBox $dominators * @property Container $pageOrphans * @property ListBox $orphans * @property Container $pageDupes * @property ListBox $dupes * @property Container $pageQuery * @property TextBox $queryText * @property Button $runQuery * @property Label $queryHelp * @property Label $queryStatus * @property ListBox $queryRows * @property Container $pageSeries * @property Button $openSeries * @property Button $demoSeries * @property Label $seriesName * @property MemoryChart $chart * @property Label $seriesInfo * @property Radio $navStack * @property Container $pageStack * @property Button $openFreeze * @property Button $demoFreeze * @property Label $freezeName * @property Label $freezeInfo * @property Label $framesTitle * @property ListBox $frames * @property Label $varsTitle * @property ListBox $frameVars * @property TextBox $frameSource * @property Radio $navLive * @property Container $pageLive * @property TextBox $liveUrl * @property TextBox $liveToken * @property Button $liveConnect * @property Button $liveSnapshot * @property Label $liveStatus * @property MemoryChart $liveChart * @property Label $liveCounters * @property Label $liveClassesTitle * @property ListBox $liveClasses * @property Label $liveHelp */final class MainForm extends Form{ /** screen => [radio id, page id] */ public const VIEWS = [ 'overview' => ['navOverview', 'pageOverview'], 'leaks' => ['navLeaks', 'pageLeaks'], 'classes' => ['navClasses', 'pageClasses'], 'inspector' => ['navInspector', 'pageInspector'], 'dominators' => ['navDominators', 'pageDominators'], 'orphans' => ['navOrphans', 'pageOrphans'], 'dupes' => ['navDupes', 'pageDupes'], 'query' => ['navQuery', 'pageQuery'], 'series' => ['navSeries', 'pageSeries'], 'stack' => ['navStack', 'pageStack'], 'live' => ['navLive', 'pageLive'], ]; private Studio $studio; private bool $userFiles = false; private string $view = 'leaks'; /** @var list<array{text: string, key: string, row: array<string, mixed>}> */ private array $leakRows = []; /** @var list<array{text: string, alert: array<string, mixed>}> */ private array $alertRows = []; /** @var list<array{text: string, class: string}> */ private array $classRows = []; /** @var array<string, list<array{text: string, node: ?int}>> list id => its rows (a click opens the node) */ private array $nodeLists = []; private ?int $node = null; private string $previous = 'classes'; private string $seriesPath = ''; private string $freezePath = ''; private ?FreezeFile $freeze = null; private ?LiveClient $live = null; private int $liveShown = -1; private string $liveMessage = ''; protected function loaded(array $params = []): void { $this->studio = new Studio($this->engine->config->path('assets/demo')); $this->userFiles = false; $this->node = null; $this->previous = 'classes'; $this->nodeLists = []; $this->seriesPath = $this->engine->config->path('assets/demo/' . Studio::DEMO_SERIES); $this->freezePath = $this->engine->config->path('assets/demo/' . Studio::DEMO_FREEZE); $this->freeze = null; $this->live?->disconnect(); $this->live = new LiveClient(fn (string $method, string $url, array $headers, float $timeout) => $this->engine->http()->request($method, $url, null, $headers, $timeout)); $this->liveShown = -1; $this->liveMessage = ''; $url = $this->engine->options->get('live_url'); if (is_string($url) && $url !== '') { $this->liveUrl->text = $url; } $this->backend->text = Lang::t('Reader: {name}', ['name' => Studio::backend()]); $this->view = isset($params['view'], self::VIEWS[$params['view']]) ? (string)$params['view'] : 'leaks'; $this->studio->loadDemo(); $this->showView($this->view, false); $this->refreshSnapshots(count(Studio::DEMO) - 1); } // header ------------------------------------------------------------------------------------------------------ public function onDemoClick(Button $sender): void { $this->userFiles = false; $this->studio->loadDemo(); $this->seriesPath = $this->engine->config->path('assets/demo/' . Studio::DEMO_SERIES); $this->refreshSnapshots(count(Studio::DEMO) - 1); } public function onOpenClick(Button $sender): void { FilePicker::open(['title' => 'Open .cryo', 'multiple' => true, 'filters' => ['Cryo snapshots, series, freezes' => ['cryo', 'cryom', 'cryf']]]) ->then(fn (mixed $files) => $this->openFiles($files === null ? [] : (array)$files)); } /** Snapshots (.cryo) join the list (the first one replaces the demo); a series (.cryom) goes to the Series screen, a freeze (.cryf) to the Stack screen. @param list<string> $files */ public function openFiles(array $files): void { $errors = []; $snapshots = []; foreach ($files as $file) { if (str_ends_with(strtolower($file), '.cryom')) { $this->openSeries($file); } elseif (str_ends_with(strtolower($file), '.cryf')) { $this->openFreeze($file); } else { $snapshots[] = $file; } } if ($snapshots === []) { return; } $this->leaveDemo(); foreach ($snapshots as $file) { try { $this->studio->add($file); } catch (\Throwable $e) { $errors[] = basename($file) . ': ' . $e->getMessage(); } } $this->node = null; $this->refreshSnapshots($this->studio->count() - 1); if ($errors !== []) { $this->viewTitle->text = implode("\n", $errors) . "\n" . $this->viewTitle->text; } } /** The first file of the visitor (opened, or taken Live) replaces the demo. */ private function leaveDemo(): void { if (!$this->userFiles) { $this->studio->clear(); $this->userFiles = true; } } public function onDarkChange(CheckBox $sender, bool $checked): void { $this->theme->colors = $checked ? Theme::DARK : Theme::LIGHT; $this->root->background = $this->theme->colors['background']; } // snapshots --------------------------------------------------------------------------------------------------- public function onSnapshotChange(ListBox $sender, int $index, string $item): void { $info = $this->studio->info($index); $this->snapInfo->text = $info === null ? '' : Lang::t('Epoch {epoch} · {objects} objects ({tracked} with a site) · {orphans} orphans · {nodes} nodes · {edges} edges · {bytes} · PHP {php}', [ 'epoch' => $info['epoch'], 'objects' => $info['objects'], 'tracked' => $info['objects_with_site'], 'orphans' => $info['orphans'], 'nodes' => $info['nodes'], 'edges' => $info['edges'], 'bytes' => Studio::bytes($info['bytes']), 'php' => self::phpVersion((int)$info['php_version_id']), ]); $this->refreshView(); } private function refreshSnapshots(int $select): void { $this->snapshots->items = $this->studio->snapshotLines(); $this->snapshots->selected = -1; if ($this->studio->count() > 0) { $this->snapshots->select(max(0, $select)); } else { $this->snapInfo->text = ''; $this->refreshView(); } } // navigation -------------------------------------------------------------------------------------------------- /** The screen shown: a key of VIEWS. */ public function view(): string { return $this->view; } public function onNavChange(Radio $sender, bool $checked): void { if (!$checked) { return; } foreach (self::VIEWS as $view => [$radio]) { if ($radio === $sender->id) { $this->showView($view); } } } /** Shows a screen: its radio checked, its page visible, its content up to date. */ public function showView(string $view, bool $refresh = true): void { $this->view = $view; foreach (self::VIEWS as $name => [$radio, $page]) { $this->widget($radio)->props['checked'] = $name === $view; $this->widget($page)->visible = $name === $view; } $this->invalidate(); if ($refresh) { $this->refreshView(); } } /** Opens a node in the inspector (Back returns to the screen it came from). */ public function inspect(int $node): void { if ($this->view !== 'inspector') { $this->previous = $this->view; } $this->node = $node; $this->pathRows->items = []; $this->showView('inspector'); } private function refreshView(): void { $index = $this->snapshots->selected; match ($this->view) { 'overview' => $this->showOverview($index), 'classes' => $this->showClasses($index), 'inspector' => $this->showNode($index), 'dominators' => $this->showNodeList('dominators', Lang::t('Nodes that retain the most memory (dominator tree): retained size, node'), $this->studio->dominatorRows($index)), 'orphans' => $this->showNodeList('orphans', Lang::t('Objects kept alive only by uncollected cycles, by class'), $this->studio->orphanRows($index)), 'dupes' => $this->showNodeList('dupes', Lang::t('Strings and arrays stored several times with the same content'), $this->studio->dupeRows($index)), 'query' => $this->runQuery(), 'series' => $this->showSeries(), 'stack' => $this->showStack(), 'live' => $this->showLive(), default => $this->showLeaks(), }; } /** @param list<array{text: string, node: ?int}> $rows */ private function showNodeList(string $list, string $title, array $rows): void { $this->viewTitle->text = $title; $this->nodeLists[$list] = $rows; /** @var ListBox $box */ $box = $this->widget($list); $box->props['selected'] = -1; $box->items = $rows === [] ? [Lang::t('(none)')] : array_column($rows, 'text'); if ($rows === []) { $this->nodeLists[$list] = [['text' => '', 'node' => null]]; } } /** A click on a line of a list of nodes (instances, dominators, orphans, duplicates, query, roots) opens it. */ public function onNodeRowChange(ListBox $sender, int $index, string $item): void { $node = $this->nodeLists[$sender->id][$index]['node'] ?? null; if ($node !== null) { $sender->props['selected'] = -1; $this->inspect($node); } } // overview ---------------------------------------------------------------------------------------------------- private function showOverview(int $index): void { $this->viewTitle->text = Lang::t('Overview of the selected snapshot'); $this->alertRows = $this->studio->alertRows($index); $this->alerts->props['selected'] = -1; $this->alerts->items = $this->alertRows === [] ? [Lang::t('No alert')] : array_column($this->alertRows, 'text'); $this->alertDetail->text = $this->alertRows === [] ? '' : Lang::t('Click an alert to see what keeps it alive'); $this->nodeLists['overviewRows'] = $this->studio->overviewRows($index); $this->overviewRows->props['selected'] = -1; $this->overviewRows->items = array_column($this->nodeLists['overviewRows'], 'text'); } public function onAlertChange(ListBox $sender, int $index, string $item): void { $a = $this->alertRows[$index]['alert'] ?? null; if ($a === null) { return; } $lines = [Studio::shortMessage((string)$a['message']) . ' · ' . Studio::bytes($a['bytes'])]; if (is_array($a['path'] ?? null)) { $lines[] = Lang::t('Path: {path}', ['path' => Studio::pathLine($a['path'])]); } if (is_string($a['site'] ?? null)) { $lines[] = Lang::t('Site: {site}', ['site' => Studio::shortSite($a['site'])]); } $this->alertDetail->text = implode("\n", $lines); } public function onOverviewRowChange(ListBox $sender, int $index, string $item): void { $this->onNodeRowChange($sender, $index, $item); } // leaks ------------------------------------------------------------------------------------------------------- /** The grouping of the delta: 'site', 'class' or 'stack'. */ public function by(): string { return match (true) { $this->byClass->checked => 'class', $this->byStack->checked => 'stack', default => 'site', }; } public function onByChange(Radio $sender, bool $checked): void { if ($checked && $this->view === 'leaks') { $this->showLeaks(); } } private function showLeaks(): void { $this->viewTitle->text = $this->studio->count() < 2 ? Lang::t('Open at least 2 snapshots of the same process to compare them') : Lang::t('Objects created per interval and still alive ({n} snapshots)', ['n' => $this->studio->count()]); $this->leakRows = $this->studio->deltaRows($this->by()); $this->rows->props['selected'] = -1; $this->rows->items = array_column($this->leakRows, 'text'); foreach ([$this->detail, $this->source, $this->hookSource, $this->pathInfo] as $w) { $w->text = ''; } if ($this->leakRows !== []) { $this->rows->select(0); } } public function onRowChange(ListBox $sender, int $index, string $item): void { $r = $this->leakRows[$index] ?? null; if ($r === null) { return; } $by = $this->by(); $site = $this->studio->siteOf($by, $r['key']); $hook = $r['row']['hooked_by'] ?? null; $lines = []; if ($site !== null) { $s = Studio::parseSite($site); $lines[] = Lang::t($r['row']['growing'] ? 'Leak: {function}() keeps every object it creates at line {line}' : '{function}(), line {line}', ['function' => $s['function'], 'line' => $s['line']]); } if (is_string($hook)) { $h = Studio::parseSite($hook); $lines[] = Lang::t('Hooked by line {line}: {function}()', ['line' => $h['line'], 'function' => $h['function']]); } $this->detail->text = implode("\n", $lines); $this->source->text = $this->studio->sourceExcerpt($site, 2); $this->hookSource->text = is_string($hook) ? $this->studio->sourceExcerpt($hook, 2) : Lang::t('(write site unknown: cryo.track_alloc=site or stack)'); $explain = $site === null ? null : $this->studio->explain($site); $paths = $explain['paths'] ?? []; $this->pathInfo->text = $paths === [] ? '' : Lang::t('Typical path ({n} of the survivors): {path}', ['n' => $paths[0]['count'], 'path' => Studio::pathLine($paths[0]['path'])]); } // classes ----------------------------------------------------------------------------------------------------- private function showClasses(int $index): void { $this->viewTitle->text = Lang::t('Objects per class, by retained size'); $this->classRows = $this->studio->classRows($index); $this->classes->props['selected'] = -1; $this->classes->items = array_column($this->classRows, 'text'); $this->instancesTitle->text = Lang::t('Click a class to list its instances'); $this->instances->items = []; $this->nodeLists['instances'] = []; } public function onClassChange(ListBox $sender, int $index, string $item): void { $class = $this->classRows[$index]['class'] ?? null; if ($class === null) { return; } $this->nodeLists['instances'] = $this->studio->instanceRows($this->snapshots->selected, $class, 1000); $this->instances->props['selected'] = -1; $this->instances->scrollY = 0; $this->instances->items = array_column($this->nodeLists['instances'], 'text'); $this->instancesTitle->text = Lang::t('{n} instances of {class}: click one to inspect it', ['n' => count($this->nodeLists['instances']), 'class' => $class]); } // inspector --------------------------------------------------------------------------------------------------- /** The node shown by the inspector, null when none. */ public function inspected(): ?int { return $this->node; } private function showNode(int $index): void { $this->viewTitle->text = Lang::t('Node inspector'); $this->outEdges->props['selected'] = -1; $this->inEdges->props['selected'] = -1; $this->pathRows->props['selected'] = -1; $n = $this->node === null ? null : $this->studio->node($index, $this->node); $this->pathButton->enabled = $n !== null; if ($n === null) { $this->nodeTitle->text = $this->node === null ? Lang::t('Click a node in a list (classes, dominators, query...) to inspect it') : Lang::t('No node #{node} in this snapshot', ['node' => $this->node]); $this->nodeInfo->text = ''; $this->outEdges->items = []; $this->inEdges->items = []; $this->pathRows->items = []; $this->nodeLists['outEdges'] = $this->nodeLists['inEdges'] = $this->nodeLists['pathRows'] = []; return; } $retained = $this->studio->retained($index, (int)$n['node']); $this->nodeTitle->text = sprintf('#%d %s (%s) ', $n['node'], $n['class'] ?? $n['type'], $n['type']) . Lang::t('{size}, retained {retained}', [ 'size' => Studio::bytes($n['size']), 'retained' => $retained === null ? '?' : Studio::bytes($retained)]); $info = []; $info[] = Lang::t('Created at: {site}', ['site' => $n['site'] ?? '?']) . (isset($n['epoch']) ? ' (epoch ' . $n['epoch'] . ')' : ''); $info[] = Lang::t('Written at: {site}', ['site' => $n['write'] ?? '?']); if (is_array($n['stack'] ?? null) && $n['stack'] !== []) { $info[] = Lang::t('Stack: {stack}', ['stack' => implode(' ← ', array_map(Studio::shortSite(...), $n['stack']))]); } foreach ($n['roots'] ?? [] as $rt) { $info[] = Lang::t('Root: {kind} {name}', ['kind' => $rt['kind'], 'name' => $rt['name']]); } $this->nodeInfo->text = implode("\n", $info); $this->nodeLists['outEdges'] = array_map(fn (array $e) => ['text' => sprintf('%s → #%d %s', $e['name'], $e['node'], $e['class'] ?? $e['type']), 'node' => (int)$e['node']], $n['out']); $this->nodeLists['inEdges'] = array_map(fn (array $e) => ['text' => sprintf('#%d %s → %s', $e['node'], $e['class'] ?? $e['type'], $e['name']), 'node' => (int)$e['node']], $n['in']); $this->outEdges->items = $n['out'] === [] ? [Lang::t('(none)')] : array_column($this->nodeLists['outEdges'], 'text'); $this->inEdges->items = $n['in'] === [] ? [Lang::t('(none)')] : array_column($this->nodeLists['inEdges'], 'text'); if ($this->pathRows->items === []) { $this->nodeLists['pathRows'] = []; } } public function onEdgeChange(ListBox $sender, int $index, string $item): void { $this->onNodeRowChange($sender, $index, $item); } public function onPathRowChange(ListBox $sender, int $index, string $item): void { $this->onNodeRowChange($sender, $index, $item); } public function onBackClick(Button $sender): void { $this->showView($this->previous === 'inspector' ? 'classes' : $this->previous); } /** "Path to a root": the shortest paths from a root (global, static, frame, orphan) to the node. */ public function onPathClick(Button $sender): void { if ($this->node === null) { return; } $rows = []; foreach ($this->studio->pathsToRoot($this->snapshots->selected, $this->node, 3) as $k => $path) { $rows[] = ['text' => Lang::t('Path {n}', ['n' => $k + 1]), 'node' => null]; foreach ($path as $i => $step) { $what = '#' . $step['node'] . ' ' . ($step['class'] ?? $step['type']); $rows[] = ['text' => $i === 0 ? sprintf(' %s %s %s', $step['kind'], $step['name'], $what) : sprintf(' → %s %s', $step['name'], $what), 'node' => (int)$step['node']]; } } if ($rows === []) { $rows[] = ['text' => Lang::t('No root reaches this node'), 'node' => null]; } $this->nodeLists['pathRows'] = $rows; $this->pathRows->props['selected'] = -1; $this->pathRows->items = array_column($rows, 'text'); } // query ------------------------------------------------------------------------------------------------------- public function onQuerySubmit(TextBox $sender): void { $this->runQuery(); } public function onQueryClick(Button $sender): void { $this->runQuery(); } private function runQuery(): void { $this->viewTitle->text = Lang::t('Query the nodes of the snapshot'); $rows = []; try { $rows = $this->studio->queryRows($this->snapshots->selected, trim($this->queryText->text)); $this->queryStatus->text = Lang::t('{n} nodes match (at most 200 shown): click one to inspect it', ['n' => count($rows)]); } catch (\ValueError $e) { $this->queryStatus->text = $e->getMessage(); } $this->nodeLists['queryRows'] = $rows; $this->queryRows->props['selected'] = -1; $this->queryRows->scrollY = 0; $this->queryRows->items = array_column($rows, 'text'); } // series ------------------------------------------------------------------------------------------------------ public function onOpenSeriesClick(Button $sender): void { FilePicker::open(['title' => 'Open .cryom', 'filters' => ['Cryo metric series' => ['cryom']]]) ->then(function (mixed $file) { if (is_string($file) && $file !== '') { $this->openSeries($file); } }); } public function onDemoSeriesClick(Button $sender): void { $this->openSeries($this->engine->config->path('assets/demo/' . Studio::DEMO_SERIES)); } public function openSeries(string $path): void { $this->seriesPath = $path; if ($this->view === 'series') { $this->showSeries(); } else { $this->showView('series'); } } private function showSeries(): void { $this->viewTitle->text = Lang::t('Memory over time (.cryom series) and its marks'); $this->seriesName->text = basename($this->seriesPath); try { $series = Studio::readSeries($this->seriesPath); } catch (\Throwable $e) { $this->chart->points = []; $this->chart->marks = []; $this->seriesInfo->text = basename($this->seriesPath) . ': ' . $e->getMessage(); return; } $samples = $series['samples']; $t0 = $samples === [] ? 0.0 : (float)$samples[0]['time']; $this->chart->points = array_map(fn (array $s) => [(float)$s['time'] - $t0, (float)$s['memory']], $samples); $this->chart->marks = array_map(fn (array $m) => [(float)$m['time'] - $t0, (string)$m['label']], $series['marks']); $sum = \App\Cryo\MetricSeries::summarize($series); $this->seriesInfo->text = $samples === [] ? Lang::t('No samples') : Lang::t('{samples} samples every {ms} ms over {duration} s · memory {min} → {max} (last {last}) · slope {slope} MB/h · {marks} marks', [ 'samples' => $sum['samples'], 'ms' => $series['interval_ms'], 'duration' => sprintf('%.1f', $sum['duration']), 'min' => Studio::bytes($sum['min']), 'max' => Studio::bytes($sum['max']), 'last' => Studio::bytes($sum['last']), 'slope' => $sum['slope_mb_per_hour'] ?? '?', 'marks' => count($series['marks']), ]); } // stack (freeze file) ------------------------------------------------------------------------------------------ public function onOpenFreezeClick(Button $sender): void { FilePicker::open(['title' => 'Open .cryf', 'filters' => ['Cryo freeze files' => ['cryf']]]) ->then(function (mixed $file) { if (is_string($file) && $file !== '') { $this->openFreeze($file); } }); } public function onDemoFreezeClick(Button $sender): void { $this->openFreeze($this->engine->config->path('assets/demo/' . Studio::DEMO_FREEZE)); } public function openFreeze(string $path): void { $this->freezePath = $path; $this->freeze = null; if ($this->view === 'stack') { $this->showStack(); } else { $this->showView('stack'); } } private function showStack(): void { $this->viewTitle->text = Lang::t('Call stack of a freeze file (.cryf)'); $this->freezeName->text = basename($this->freezePath); $this->frames->props['selected'] = -1; $this->frameVars->items = []; $this->frameSource->text = ''; try { $this->freeze ??= FreezeFile::open($this->freezePath); $info = Studio::freezeInfo($this->freezePath, $this->freeze); } catch (\Throwable $e) { $this->freeze = null; $this->freezeInfo->text = basename($this->freezePath) . ': ' . $e->getMessage(); $this->frames->items = []; return; } $flags = array_filter([$info['signed'] ? Lang::t('signed') : '', $info['compressed'] ? 'zlib' : '']); $this->freezeInfo->text = Lang::t('PHP {php} · frozen {date} on {host} · {flags} · {thaws} thaws · {frames} frames · resumes {resume}', [ 'php' => self::phpVersion((int)($info['php'] ?? 0)), 'date' => isset($info['time']) ? gmdate('Y-m-d H:i:s', (int)$info['time']) . ' UTC' : '?', 'host' => $info['host'] ?? '?', 'flags' => $flags === [] ? Lang::t('not signed') : implode(', ', $flags), 'thaws' => $info['thaw_count'] ?? 0, 'frames' => $info['frames'], 'resume' => $info['resume'] ?? '?', ]) . "\n" . Lang::t('Script: {script}', ['script' => $info['script'] ?? '?']); $this->frames->items = array_map(fn (array $f) => Studio::frameLine($f), $this->freeze->frames()); if ($this->freeze->frames() !== []) { $this->frames->select(0); } } public function onFrameChange(ListBox $sender, int $index, string $item): void { if ($this->freeze === null) { return; } $frame = $this->freeze->frames()[$index] ?? null; if ($frame === null) { return; } $vars = $this->freeze->variables($index); if (!isset($frame['func'])) { $vars += $this->freeze->globals(); // {main}: its variables are the globals } $this->varsTitle->text = Lang::t('Variables of {frame}', ['frame' => Studio::frameName($frame)]); $this->frameVars->items = $vars === [] ? [Lang::t('(none)')] : array_map(fn (string $name, array $v) => "$name = {$v[1]}", array_keys($vars), $vars); $this->frameSource->text = $this->studio->sourceExcerpt(($frame['file'] ?? '') . ':' . ($frame['line'] ?? 0) . ' ' . Studio::frameName($frame), 2); } // live (a running script) ------------------------------------------------------------------------------------ /** The link to the running script (tests give it a fake server with setTransport()). */ public function live(): LiveClient { \assert($this->live !== null); return $this->live; } public function onLiveConnectClick(Button $sender): void { $live = $this->live(); if ($live->isActive()) { $live->disconnect(); } elseif ($live->connect($this->liveUrl->text, $this->liveToken->text)) { $this->liveUrl->text = $live->base(); $this->engine->options->set('live_url', $live->base()); // the address only, never the token } $this->liveMessage = ''; $this->showLive(); } public function onLiveSubmit(TextBox $sender): void { $this->live()->disconnect(); $this->onLiveConnectClick($this->liveConnect); } /** Snapshot: the script writes a cryo_snapshot() at its next safe point; the file joins the snapshots. */ public function onLiveSnapshotClick(Button $sender): void { $this->liveMessage = Lang::t('Snapshot asked: the script takes it at its next safe point...'); $this->showLive(); $this->live()->snapshot( // the answer may come at once (fake server) or in a later frame fn (string $bytes, string $name) => $this->addLiveSnapshot($bytes, $name), function (string $message) { $this->liveMessage = $message; $this->showLive(); }, ); } /** Saves a snapshot received from the script (temporary folder) and adds it to the analysed ones. */ public function addLiveSnapshot(string $bytes, string $name): ?string { $dir = sys_get_temp_dir() . '/cryo-studio-live'; @mkdir($dir, 0700, true); $path = $dir . '/' . $name; for ($n = 2; file_exists($path); $n++) { $path = $dir . '/' . preg_replace('/(\.cryo)?$/', "-$n.cryo", $name, 1); } if (@file_put_contents($path, $bytes) === false) { $this->liveMessage = Lang::t('Cannot write {file}', ['file' => $path]); $this->showLive(); return null; } $this->leaveDemo(); try { $this->studio->add($path, Lang::t('Live {name}', ['name' => (string)preg_replace('/^cryo-live-/', '', basename($path, '.cryo'))])); } catch (\Throwable $e) { @unlink($path); $this->liveMessage = basename($path) . ': ' . $e->getMessage(); $this->showLive(); return null; } $this->node = null; $index = array_search($path, $this->studio->paths(), true); $this->liveMessage = Lang::t('{name} added to the snapshots ({n} in all): every screen can use it', ['name' => basename($path), 'n' => $this->studio->count()]); $this->refreshSnapshots($index === false ? $this->studio->count() - 1 : (int)$index); return $path; } protected function tick(float $dt): void { if ($this->live === null) { return; } $this->live->tick($dt); if ($this->view === 'live' && $this->live->version !== $this->liveShown) { $this->showLive(); } } private function showLive(): void { $live = $this->live(); $this->liveShown = $live->version; $this->viewTitle->text = Lang::t('Live: memory of a running script, snapshots on demand'); $this->liveConnect->text = $live->isActive() ? Lang::t('Disconnect') : Lang::t('Connect'); $this->liveSnapshot->enabled = $live->isConnected() && !$live->isSnapshotting(); $status = $live->status === '' ? Lang::t('Not connected') : $live->status; $this->liveStatus->text = $this->liveMessage === '' ? $status : $status . "\n" . $this->liveMessage; $this->liveStatus->color = $live->error ? (string)($this->theme->colors['danger'] ?? '#c62828') : ''; $this->liveChart->points = $live->chartPoints(); $this->liveChart->marks = $live->chartMarks(); $this->liveCounters->text = implode("\n", $live->counterLines()); $classes = $live->classLines(); $this->liveClasses->items = $classes !== [] ? $classes : ($live->isConnected() ? [Lang::t('(start the script with -d cryo.metrics=1 to count the objects per class)')] : []); } private static function phpVersion(int $id): string { return intdiv($id, 10000) . '.' . intdiv($id % 10000, 100) . '.' . $id % 100; }}