Compare commits

..
5 Commits
Author SHA1 Message Date
waozi 7c23f286b2 Add hosted Werkzeug frontend and taskmgr.v1 service export 2026-11-21 13:34:55 -03:00
waozi a1c137ed50 Show real Taiji task CPU and use verified retained rendering 2026-11-21 03:55:19 -03:00
waozi 065e4fe9b3 Bound task grouping and sorting work and reuse guest table text 2026-11-21 00:46:24 -03:00
waozi 12ea2043f5 Run the shared Task Manager on TaijiOS ZX 2026-11-20 23:43:03 -03:00
waoziandClaude Opus 5.5 9c26d44122 Expand applications to their processes and read AMD/Intel GPU use
Clicking a window in Applications lists the processes counted toward it,
each with state, CPU, memory and GPU. Model.ProcessOwner exposes the
ownership AppUsages already computes.

Per-process GPU shares no longer need NVIDIA: gpu_drm.zi reads the
kernel's standard DRM fdinfo counters (nanosecond engines with capacity,
or cycle pairs), counts each client once and reports its busiest engine.
The GPU column appears only when a source has data instead of showing
n/a. CPU and GPU shares below 10% show one decimal, so light use on a
many-core machine no longer reads 00. The NVML helper names itself
taskmgr-gpu instead of exe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 01:32:47 -03:00
33 changed files with 3647 additions and 403 deletions

No files matched your search

+26
View File
@@ -2,6 +2,32 @@
## [Unreleased]
### Added
- Display measured Taiji task CPU percentages from cumulative scheduler CPU and
captured monotonic time, with per-task validity and incarnation-safe deltas.
- Use Kryon's retained Taiji surface after matching table/dialog pixels and
validating refresh, selected-task control, resize and reopen at 32 MiB.
- Run the shared Task Manager interface on TaijiOS ZX with real guest tasks,
allocator memory, selected-task control and bounded platform sampling.
- Clicking an application expands it to the processes it owns, each with its
state, CPU, memory and GPU use.
- AMD, Intel and other GPUs with standard DRM fdinfo counters now report
per-application GPU use, not only NVIDIA.
### Changed
- Bound process grouping and stable sorting work at full task capacity, reuse
unchanged guest table text and reduce fixed text storage without changing
refresh rates, task limits or the shared interface.
- CPU and GPU shares show one decimal below 10% (`0.4`) instead of rounding
light use to `00`.
- The Applications GPU column appears only when a per-process GPU source has
data, instead of a column of `n/a`.
- The GPU helper process is named `taskmgr-gpu` instead of `exe`.
## [0.1.3] - 2026-11-13
### Added
+51 -2
View File
@@ -4,7 +4,7 @@ ZIRAN ?= ./scripts/ziran.sh
export LDLIBS += -lX11
SOURCES := $(wildcard src/*.zi) $(wildcard tests/*.zi) ziran.toml ziran.lock scripts/ziran.sh Makefile
.PHONY: all build run check test x11-test memory-test shot package clean
.PHONY: all build run check test x11-test memory-test shot package clean performance-test taiji-performance
all: build
@@ -21,8 +21,18 @@ build/model-test: $(SOURCES)
$(ZIRAN) build --project --target=c --exe --entry model_test:main -o build/model-test-c tests/model_test.zi
cp build/model-test-c/model_test build/model-test
test: build/model-test
build/ordering-test: $(SOURCES)
$(ZIRAN) build --project --target=c --exe --entry ordering_test:main -o build/ordering-test-c tests/ordering_test.zi
cp build/ordering-test-c/ordering_test build/ordering-test
build/guest-cpu-test: $(SOURCES)
$(ZIRAN) build --project --target=c --exe --entry guest_cpu_test:main -o build/guest-cpu-test-c tests/guest_cpu_test.zi
cp build/guest-cpu-test-c/guest_cpu_test build/guest-cpu-test
test: build/model-test build/ordering-test build/guest-cpu-test
./build/model-test
./build/ordering-test
./build/guest-cpu-test
build/windows-test: $(SOURCES)
$(ZIRAN) build --project --target=c --exe --entry windows_test:main -o build/windows-test-c tests/windows_test.zi
@@ -48,3 +58,42 @@ shot: build
clean:
rm -rf build
# The Taiji owner supplies the canonical typed host module directory.
.PHONY: taiji taiji-test
taiji:
./scripts/package-taiji.sh
taiji-test:
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --module-path "$(TAIJIOS_TASK_MODULES)" --entry taiji_model_test:main \
--bind taijios_tasks:Capture=taiji_model_test:Capture \
--bind taijios_tasks:SampleNanos=taiji_model_test:SampleNanos \
--bind taijios_tasks:TaskAt=taiji_model_test:TaskAt \
--bind taijios_tasks:PoolAt=taiji_model_test:PoolAt \
--bind taijios_tasks:Terminate=taiji_model_test:Terminate \
-o build/taiji-model-test.zx tests/taiji_model_test.zi
$(ZIRAN) run build/taiji-model-test.zx
# Deterministic full-capacity grouping/sort benchmark (three passes each).
build/performance-test: $(SOURCES)
$(ZIRAN) build --project --target=c --exe --entry performance_test:main -o build/performance-test-c tests/performance_test.zi
cp build/performance-test-c/performance_test build/performance-test
performance-test: build/performance-test
./build/performance-test
# Explicit guest test artifacts; neither target installs or modifies the menu.
taiji-performance:
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --module-path "$(TAIJIOS_TASK_MODULES)" --bind-host taijios_tasks --bind-host kryon/pixmap --entry performance_test:main -o build/performance-test.zx tests/performance_test.zi
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --module-path "$(TAIJIOS_TASK_MODULES)" --bind-host taijios_tasks --bind-host kryon/pixmap --entry guest_profile:main -o build/guest-profile.zx tests/guest_profile.zi
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --define TASKMGR_RETAINED --module-path "$(TAIJIOS_TASK_MODULES)" --bind-host taijios_tasks --bind-host kryon/pixmap --entry guest_profile:main -o build/guest-profile-retained.zx tests/guest_profile.zi
# Uninstrumented retained candidate for the guest owner's full lifecycle gate.
.PHONY: taiji-retained-test
taiji-retained-test:
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --module-path "$(TAIJIOS_TASK_MODULES)" --bind-host taijios_tasks --bind-host kryon/pixmap --entry taiji_host:main -o build/taskmgr-retained-test.zx src/taiji_host.zi
# Real CPU probe; run in a disposable 32 MiB guest beside an owned Sleep task.
.PHONY: taiji-cpu-live
taiji-cpu-live:
$(ZIRAN) bundle --project --define TASKMGR_TAIJI --module-path "$(TAIJIOS_TASK_MODULES)" --bind-host taijios_tasks --bind-host kryon/pixmap --entry taiji_cpu_live:main -o build/taiji-cpu-live.zx tests/taiji_cpu_live.zi
+101 -5
View File
@@ -15,11 +15,15 @@ three-pane status bar.
- **Applications** lists top-level EWMH windows and can switch to one, request
that it close, or open a new command. CPU, Memory and GPU columns total each
window's process tree: its `_NET_WM_PID` plus every descendant that no
nearer listed window owns. Windows without a PID show `-`. GPU shares come
from NVML on NVIDIA's driver, sampled by `taskmgr --gpu-helper`, a
display-free child of the same binary that runs only while this tab or
Performance is open,
so NVML's memory never enters the window process; other drivers show `n/a`.
nearer listed window owns. Clicking a window expands it to those processes.
Windows without a PID show `-`. Only top-level desktop windows appear, so
background services do not, and under Wayland only XWayland windows do.
Per-process GPU shares come from DRM fdinfo counters (AMD, Intel and other
drivers that publish them) and, on NVIDIA's driver, from NVML sampled by
`taskmgr --gpu-helper` (`taskmgr-gpu`), a display-free child of the same
binary that runs only while this tab or Performance is open, so NVML's
memory never enters the window process. The GPU column appears only once a
source has data. Shares below 10% show one decimal.
- **Processes** is a sortable DataViews table with image name, PID, CPU, CPU
time and resident memory. Rows are grouped by image name by default, with all
Codex-family processes combined under `codex`; Options → Group Processes
@@ -81,3 +85,95 @@ several process and retained-text refreshes, then enforces a 30 MiB RSS cap.
The desktop profile opens an SDL2 window through Kryon's `desktop` backend.
The `tui`, `web`, `portable`, and headless `shot` profiles use the same
application `Frame` declared in `ziran.toml`.
## TaijiOS ZX
The same `app:Frame`, process model, sorting and selection run on TaijiOS.
The small `taiji_host` entry uses canonical `kryon/host/surface`; it contains
no UI. `platform_taiji` reads only the typed `taijios_tasks` host service.
Linux keeps its existing `/proc`, EWMH, GPU helper and native host behavior.
```sh
TAIJIOS_TASK_MODULES=/path/to/taijios/appl/cmd make taiji-test taiji
```
This writes `build/taskmgr.zx`. The Taiji launcher owner installs that artifact
with its existing `TASKMGR_ZX` integration; this repository does not modify the
emulator, menu or launcher. The guest requires `/prog` plus `taijios_tasks`,
Kryon's software surface/pixmap and monotonic clock host capabilities.
Guest PID values identify Dis tasks. `Est. Memory` is the guest's Dis
stack/module estimate in KiB, converted to bytes for display; it is not RSS.
The status and Performance memory reading is the real main allocator pool in
bytes against its configured limit, not total system RAM. `CPU %` uses real
cumulative task CPU nanoseconds divided
by elapsed captured monotonic nanoseconds; 100% means one core. The first sample,
new/reused task identity, counter reset, unavailable counter or nonpositive elapsed
time displays `n/a` until a comparable next sample. Idle tasks then show real zero.
`Task CPU` is the sum of comparable live task deltas, not whole-machine CPU:
new/exited/unmeasured tasks and kernel/idle work are excluded. It can exceed 100%
when guest execution threads run concurrently. Performance shows the comparable
task count. CPU time, Linux windows, GPU and other unsupported counters remain
explicitly unavailable. The guest requires the additive `SampleNanos` capability
and seven-field `TaskAt` CPU/incarnation/timestamp-error extension from the matching
emulator. Timestamp uncertainty must be smaller than the interval. A task delta
above 100% is accepted as saturation only when its excess fits within the measured
capture uncertainty; larger inconsistencies display `n/a`.
The guest has no shell launch or group termination. End Process targets only
the selected captured guest PID through the native `/prog/PID/ctl` operation.
Refresh storage and task count are bounded; failed captures clear visible rows.
`make taiji-test` runs 1,000 service-fixture refreshes, unit conversion,
unavailable/stale handling and selected-PID control through a ZX bundle.
For the real guest CPU model test, build `make taiji-cpu-live` with the same
`TAIJIOS_TASK_MODULES`, then run `python3 scripts/guest-cpu-test.py /path/to/taijios`.
It starts a disposable 32 MiB guest, measures its busy ZX task beside an owned
sleeper, and checks real CPU sorting. No guest task is fabricated or controlled.
`python3 scripts/guest-lifecycle-test.py /path/to/taijios` mounts only the built
artifact in a disposable private-Xvfb guest and runs the canonical Taiji CPU and
GUI lifecycle suite. `--emu /path/to/emu` can select the runtime owner's verified
candidate. This does not install the app. Actual installation/menu integration
remains with the Taiji launcher owner. See the CPU follow-up in
[tests/PERFORMANCE.md](tests/PERFORMANCE.md) for local lifecycle and paired renderer
results at the default 32 MiB pool.
## Performance measurements
Grouping uses a bounded hash index; raw and group order use stable merge sort.
The native 2,048-task and guest 1,024-task limits are unchanged. Guest sampling
still runs at the selected refresh rate, but unchanged process rows reuse their
formatted order. Pool readings update independently. Text storage keeps both
retained generations and sizes native window titles separately from process names.
```sh
make performance-test
python3 scripts/native-performance.py build/taskmgr-desktop
TAIJIOS_TASK_MODULES=/path/to/taijios/appl/cmd make taiji-performance
python3 scripts/guest-performance.py /path/to/taijios build/guest-profile.zx --seconds 30
```
The model workload groups and sorts a deterministic full-capacity fixture three
times; fixture values never appear in the app. `TASKMGR_PERF_SMALL` builds the
same workload with 128 rows for comparison with the earlier quadratic algorithm.
Run `build/performance-test.zx` through the actual guest's `zxrun` with
`-p main=32M`. The guest profile is an explicit test entry calling the normal
`App.Frame` at the same surface size and idle interval. It reports declaration
time, real allocator bytes/high water, emulator CPU, and input-to-next-callback
time. That callback measurement does not include final pixel presentation.
The native profile measures process CPU and input-to-observed-tab-redraw time.
Both GUI scripts create a scrubbed private Xvfb and stop only their own processes.
`make taiji-performance` also builds `build/guest-profile-retained.zx`, selecting
Kryon's `RunRetained` with the same shared app and observations. Production Taiji
uses that retained surface; the normal profile remains a comparison test.
`make taiji-retained-test` builds an uninstrumented lifecycle test artifact at
`build/taskmgr-retained-test.zx`. These explicit test targets do not install
anything. Use `--cycles 6 --seconds 90 --require-cpu`
with the guest profiler for the paired table/dialog workload.
See [the measured baseline and limitations](tests/PERFORMANCE.md). Model work is
substantially faster. Retained guest rendering reduced idle CPU by 73% and the
table/dialog workload CPU by 67% in one paired local run; those measurements are
not a universal performance guarantee. The native 30 MiB RSS test remains an enforced regression
threshold; repeated measurements can exceed it as anonymous huge-page residency
and file-backed library pages vary. A raised measurement limit is not a cap pass.
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Run the real CPU model probe beside an owned sleeper in a disposable guest."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
from tempfile import TemporaryDirectory
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('taiji', type=Path)
parser.add_argument('--emu', type=Path)
args = parser.parse_args()
root = args.taiji.resolve()
emu = (args.emu or root / 'Linux/386/bin/emu').resolve()
env = os.environ.copy()
for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS',
'XDG_RUNTIME_DIR', 'XDG_SESSION_ID', 'SESSION_MANAGER', 'HARMONY_GUEST_DISPLAY'):
env.pop(key, None)
env['HARMONY_DESKTOP_RECOVERY'] = '0'
with TemporaryDirectory(dir=root / 'build/zx-smoke', prefix='taskmgr-cpu-') as directory:
image = Path(directory) / 'probe.zx'
shutil.copyfile(Path(__file__).resolve().parents[1] / 'build/taiji-cpu-live.zx', image)
command = f"bind '#p' /prog; sleep 10 &; sleep 1; zxrun /{image.relative_to(root)}"
result = subprocess.run([emu, '-p', 'main=32M', '-r', root, '/dis/sh.dis', '-c', command],
env=env, start_new_session=True, capture_output=True, timeout=30)
assert len(result.stdout) <= 128 * 1024, 'guest probe output exceeded bound'
assert result.returncode in (0, -9), (result.returncode, result.stderr[:4096])
assert not result.stderr, result.stderr[:4096]
assert b'TASK_CPU_LIVE_OK ' in result.stdout and result.stdout.endswith(b'\n0\n'), result.stdout
print(result.stdout.decode(), end='')
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Run the canonical guest's real lifecycle test against this project's artifact."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
from tempfile import TemporaryDirectory
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('taiji', type=Path)
parser.add_argument('--emu', type=Path)
args = parser.parse_args()
root = args.taiji.resolve()
emu = (args.emu or root / 'Linux/386/bin/emu').resolve()
env = os.environ.copy()
for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS',
'XDG_RUNTIME_DIR', 'XDG_SESSION_ID', 'SESSION_MANAGER', 'HARMONY_GUEST_DISPLAY'):
env.pop(key, None)
env['HARMONY_DESKTOP_RECOVERY'] = '0'
env['PYTHONDONTWRITEBYTECODE'] = '1'
env['PYTHONPATH'] = str(root / 'appl/cmd/tcltk')
with TemporaryDirectory(dir=root / 'build/zx-smoke', prefix='taskmgr-lifecycle-') as directory:
shutil.copyfile(Path(__file__).resolve().parents[1] / 'build/taskmgr.zx',
Path(directory) / 'taskmgr.zx')
subprocess.run(['python3', '-u', str(root / 'appl/wm/taskmgr_zx_test.py'), str(emu),
'--cpu', '--gui', '--guest-overlay', directory],
env=env, cwd=root, check=True)
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Measure an explicit Task Manager test host on a private default-32M guest."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import select
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import time
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('taiji', type=Path)
parser.add_argument('image', type=Path)
parser.add_argument('--seconds', type=int, default=12)
parser.add_argument('--emu', type=Path)
parser.add_argument('--require-cpu', action='store_true')
parser.add_argument('--cycles', type=int, default=0, help='bounded table/modal/cancel cycles')
parser.add_argument('--output', type=Path, help='save complete measurement JSON')
args = parser.parse_args()
if not 1 <= args.seconds <= 300 or not 0 <= args.cycles <= 32:
parser.error("--seconds must be 1..300 and --cycles 0..32")
root = args.taiji.resolve()
sys.path.insert(0, str(root / 'appl/cmd/tcltk'))
from test_logwindow import private_display
from test_tcltk import launch, stop, until
for key in ('DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS',
'XDG_RUNTIME_DIR', 'XDG_SESSION_ID', 'SESSION_MANAGER', 'HARMONY_GUEST_DISPLAY'):
os.environ.pop(key, None)
os.environ['HARMONY_DESKTOP_RECOVERY'] = '0'
def ticks(pid):
# Host emulator CPU is a benchmark measurement, never guest process data.
fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
return int(fields[11]) + int(fields[12])
with TemporaryDirectory(dir=root / 'build/zx-smoke', prefix='taskmgr-perf-') as scratch, private_display() as env:
image = Path(scratch) / 'profile.zx'
shutil.copyfile(args.image, image)
guest = launch(env, (args.emu or root / 'Linux/386/bin/emu').resolve(), '-p', 'main=32M', '-r', root,
'-g', '800x600', 'wm/wm', '/dis/sh.dis', '-c',
f'zxrun -w /{image.relative_to(root)}', stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = bytearray()
def drain():
for stream in select.select([guest.stdout], [], [], 0)[0]:
output.extend(os.read(stream.fileno(), 4096))
assert len(output) < 256 * 1024, 'profile output exceeded bound'
assert guest.poll() is None, output.decode(errors='replace')
return output
def command(*cmd):
return subprocess.run(cmd, env=env, capture_output=True, check=True, timeout=8).stdout
try:
window = until(lambda: subprocess.run(['xdotool', 'search', '--onlyvisible', '--name', '^inferno$'], env=env, capture_output=True).stdout.strip(), 'guest window missing').decode()
until(lambda: b'FRAME_PERF frame=2 ' in drain(), 'test app did not render', timeout=30)
# Allow startup buffers to settle; then measure an unchanged idle window.
time.sleep(2)
drain()
before = ticks(guest.pid)
start = time.monotonic()
end = start + args.seconds
while time.monotonic() < end:
select.select([guest.stdout], [], [], .1)
drain()
idle = {'wall_s': time.monotonic() - start, 'host_cpu_s': (ticks(guest.pid) - before) / os.sysconf('SC_CLK_TCK')}
# Force input delivery without changing task data or sampling frequency.
before = ticks(guest.pid)
start = time.monotonic()
latencies = []
for index in range(10):
frame_before = bytes(drain()).count(b"FRAME_PERF ")
event_start = time.monotonic()
command('xdotool', 'mousemove', '--window', window, str(90 + index % 2), '65')
until(lambda: bytes(drain()).count(b"FRAME_PERF ") > frame_before, "input frame missing", timeout=5)
latencies.append((time.monotonic() - event_start) * 1000)
input_metrics = {'events': 10, 'callback_latency_ms': latencies, 'wall_s': time.monotonic() - start,
'host_cpu_s': (ticks(guest.pid) - before) / os.sysconf('SC_CLK_TCK')}
if args.require_cpu:
# Exercise the shared table header, then read its first rendered CPU
# cell from this private guest. Cover the three-state sort cycle;
# the initial guest focus click may be consumed by its WM.
command('xdotool', 'mousemove', '--window', window, '100', '12', 'mousedown', '1', 'sleep', '.25', 'mouseup', '1')
time.sleep(.7)
sorted_busy = False
for attempt in range(3):
command('xdotool', 'mousemove', '--window', window, '218', '116', 'sleep', '.04', 'mousedown', '1', 'sleep', '.25', 'mouseup', '1')
time.sleep(1.5)
cell = command('import', '-window', window, '-crop', '40x26+200+130', '-resize', '400%', 'png:-')
text = subprocess.run(['tesseract', 'stdin', 'stdout', '--psm', '7'], input=cell,
env=env, capture_output=True, check=True, timeout=8).stdout.decode()
print(f'CPU_GUI_FIRST attempt={attempt} text={text.strip()!r}', flush=True)
reading = re.fullmatch(r'\s*(\d+(?:\.\d+)?)\s*', text)
if reading and 5 < float(reading[1]) <= 100:
sorted_busy = True
break
Path('build/taskmgr-performance.png').write_bytes(command('import', '-window', window, 'png:-'))
assert sorted_busy, f'CPU header did not put a busy task first: {text!r}'
print('TASK_CPU_GUI_SORT_OK: CPU header puts a real busy task first')
workload = {'cycles': 0}
if args.cycles:
def click(x, y):
command('xdotool', 'mousemove', '--window', window, str(x), str(y),
'sleep', '.04', 'mousedown', '1', 'sleep', '.25', 'mouseup', '1')
def word(label):
picture = command('import', '-window', window, '-resize', '200%', 'png:-')
tsv = subprocess.run(['tesseract', 'stdin', 'stdout', '--psm', '11', 'tsv'],
input=picture, env=env, capture_output=True, check=True, timeout=8).stdout
for line in tsv.decode().splitlines()[1:]:
cells = line.split('\t')
if len(cells) == 12 and cells[11].lower().strip('.,:') == label:
return ((int(cells[6]) + int(cells[8]) // 2) // 2,
(int(cells[7]) + int(cells[9]) // 2) // 2)
return None
# Use the actual table and confirmation modal without killing any
# task. Owned-process termination is covered by guest-lifecycle-test.
click(100, 12)
before = ticks(guest.pid)
start = time.monotonic()
modal_pixels = None
for cycle in range(args.cycles):
click(173, 116) # PID column: every cycle exercises a sort.
time.sleep(.8)
click(70, 146)
click(344, 444)
no = until(lambda: word('no'), 'confirmation modal did not open', timeout=12)
if modal_pixels is None:
modal_pixels = hashlib.sha256(command('import', '-window', window,
'-crop', '400x130+0+205', 'rgb:-')).hexdigest()
# Keep sampling while the confirmation modal is open.
time.sleep(1)
click(*no)
until(lambda: not word('no'), 'confirmation modal did not close', timeout=12)
drain()
print(f'TABLE_MODAL_CYCLE_OK cycle={cycle + 1}', flush=True)
workload = {'cycles': args.cycles, 'wall_s': time.monotonic() - start,
'host_cpu_s': (ticks(guest.pid) - before) / os.sysconf('SC_CLK_TCK'),
'modal_pixels_sha256': modal_pixels}
# Capture only this private display. Retain a digest for matched UI runs.
pixels = command('import', '-window', window, 'rgb:-')
Path('build/taskmgr-performance.png').write_bytes(command('import', '-window', window, 'png:-'))
cells = command('import', '-window', window, '-crop', '260x300+0+100', 'rgb:-')
frames = [tuple(map(int, row)) for row in re.findall(rb'FRAME_PERF frame=(\d+) declaration_ms=(\d+) pool=(\d+) high=(\d+) valid=(-?\d+)', bytes(drain()))]
assert len(frames) >= 12 and all(row[4] == 0 for row in frames), output.decode(errors='replace')
assert max(row[3] for row in frames) <= 32 * 1024 * 1024, 'guest pool exceeded default 32 MiB'
assert max(row[2] for row in frames[-6:]) - min(row[2] for row in frames[-6:]) <= 256 * 1024, 'guest pool did not settle'
if args.require_cpu:
cpu_rows = re.findall(rb'FRAME_CPU valid=(\d+) measured=(\d+) percent=([0-9.]+)', bytes(drain()))
assert cpu_rows and any(int(valid) and int(count) and float(value) > 0
for valid, count, value in cpu_rows), 'no live CPU reading'
print('TASK_CPU_GUI_MODEL_OK: live CPU samples while shared app renders')
result = {'idle': idle, 'input': input_metrics, 'workload': workload, 'frames': len(frames),
'declaration_ms': [row[1] for row in frames],
'pool_bytes': [row[2] for row in frames], 'highwater_bytes': max(row[3] for row in frames),
'pixels_sha256': hashlib.sha256(pixels).hexdigest(),
'static_header_sha256': hashlib.sha256(command('import', '-window', window, '-crop', '400x130+0+0', 'rgb:-')).hexdigest(),
'process_cells_sha256': hashlib.sha256(cells).hexdigest()}
if args.output:
args.output.write_text(json.dumps(result, sort_keys=True) + '\n')
print(json.dumps({key: result[key] for key in ('idle', 'workload', 'frames', 'highwater_bytes', 'pixels_sha256')}, sort_keys=True))
else:
print(json.dumps(result, sort_keys=True))
finally:
stop(guest)
diagnostic = guest.stderr.read(4096)
guest.stdout.close()
guest.stderr.close()
assert not diagnostic, diagnostic.decode(errors='replace')
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Measure one native Task Manager on a scrubbed private Xvfb display."""
import argparse
import json
import os
from pathlib import Path
import select
import subprocess
import tempfile
import time
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('binary', type=Path)
parser.add_argument('--seconds', type=int, default=12)
args = parser.parse_args()
if args.seconds < 1:
parser.error('--seconds must be positive')
binary = args.binary.resolve()
def ticks(pid):
fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
return int(fields[11]) + int(fields[12])
def until(check, timeout=8):
end = time.monotonic() + timeout
while time.monotonic() < end:
value = check()
if value:
return value
time.sleep(.01)
raise AssertionError('native window/redraw timed out')
with tempfile.TemporaryDirectory(dir='build', prefix='native-perf-') as scratch:
env = {'PATH': os.environ['PATH'], 'HOME': str(Path(scratch).resolve()),
'TMPDIR': str(Path(scratch).resolve()), 'HARMONY_DESKTOP_RECOVERY': '0'}
read_fd, write_fd = os.pipe()
display = subprocess.Popen(['Xvfb', '-displayfd', str(write_fd), '-screen', '0',
'800x600x24', '-nolisten', 'tcp'], env=env,
pass_fds=(write_fd,), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
os.close(write_fd)
app = None
try:
assert select.select([read_fd], [], [], 8)[0], 'private Xvfb did not start'
env['DISPLAY'] = ':' + os.read(read_fd, 32).decode().strip()
def command(*cmd):
return subprocess.run(cmd, env=env, capture_output=True, check=True, timeout=8).stdout
app = subprocess.Popen([str(binary)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def find():
assert app.poll() is None, 'native app exited'
return subprocess.run(['xdotool', 'search', '--onlyvisible', '--pid', str(app.pid)], env=env, capture_output=True).stdout.strip()
window = until(find).decode().splitlines()[0]
command('xdotool', 'windowfocus', window)
time.sleep(2)
start = time.monotonic(); before = ticks(app.pid)
time.sleep(args.seconds)
idle = {'wall_s': time.monotonic() - start, 'cpu_s': (ticks(app.pid) - before) / os.sysconf('SC_CLK_TCK')}
latencies = []
start = time.monotonic(); before = ticks(app.pid)
# Tab highlight gives an observable pixel change for each delivered input.
def tab_pixels():
return command('import', '-window', window, '-crop', '300x28+0+20', 'rgb:-')
for index in range(10):
pixels = tab_pixels()
event_start = time.monotonic()
command('xdotool', 'key', '--window', window, '--clearmodifiers', 'ctrl+' + ('1' if index % 2 == 0 else '2'))
until(lambda: tab_pixels() != pixels)
latencies.append((time.monotonic() - event_start) * 1000)
active = {'wall_s': time.monotonic() - start, 'cpu_s': (ticks(app.pid) - before) / os.sysconf('SC_CLK_TCK'),
'events': 10, 'observed_redraw_ms': latencies}
status = {}
for line in Path(f'/proc/{app.pid}/status').read_text().splitlines():
if line.split(':')[0] in ('VmRSS', 'RssAnon', 'RssFile', 'RssShmem', 'THP_enabled'):
key, value = line.split(':', 1); status[key] = value.strip()
huge = [line for line in Path(f'/proc/{app.pid}/smaps_rollup').read_text().splitlines() if line.startswith('AnonHugePages:')]
print(json.dumps({'idle': idle, 'input': active, 'memory': status, 'huge': huge}, sort_keys=True))
finally:
os.close(read_fd)
for process in (app, display):
if process is not None:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill(); process.wait()
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Uses the canonical package toolchain and the guest owner's typed host module.
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
: "${TAIJIOS_TASK_MODULES:?Set TAIJIOS_TASK_MODULES to TaijiOS appl/cmd}"
mkdir -p build
exec ./scripts/ziran.sh bundle --project --define TASKMGR_TAIJI \
--module-path "$TAIJIOS_TASK_MODULES" --bind-host taijios_tasks \
--bind-host kryon/pixmap \
--entry taiji_host:main -o build/taskmgr.zx src/taiji_host.zi
+430 -133
View File
@@ -1,14 +1,39 @@
using UI :: #import "Widgets";
Button :: #import "kryon/button";
Text :: #import "kryon/text";
Box :: #import "kryon/box";
Fieldset :: #import "kryon/fieldset";
Menu :: #import "kryon/menu";
Modal :: #import "kryon/modal";
TextField :: #import "kryon/text_field";
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/control_props"
#import "kryon/drawing_props"
#import "kryon/text_align"
#import "kryon/key_input"
#import "kryon/tree_input"
#import "kryon/tree"
#import "kryon/paint_queue"
#import "std/byte_text_linux"
using Model :: #import "model";
Apps :: #import "windows";
Gpu :: #import "gpu_processes";
#if !#defined(TASKMGR_TAIJI) {
GpuDrm :: #import "gpu_drm";
}
Tables :: #import "data_views/TableView";
Theme :: #import "kryon/Theme";
SystemTheme :: #import "kryon/SystemTheme";
SystemThemeHostLinux :: #import "kryon/SystemThemeHostLinux";
Window :: #import "kryon/Window";
Number :: #import "std/number_text";
Timer :: #import "std/timer_linux";
Platform :: #import "task_platform";
#if !#defined(TASKMGR_TAIJI) {
SystemThemeHostLinux :: #import "kryon/SystemThemeHostLinux";
Timer :: #import "std/timer_linux";
} else {
GuestClock :: #import "kryon/Clock";
}
Shortcuts :: #import "app_shortcuts";
#import "layout"
@@ -23,6 +48,7 @@ Shortcuts :: #import "app_shortcuts";
//
// TASKMGR_TAB=applications|processes|performance picks the starting tab.
#if !#defined(TASKMGR_TAIJI) {
libc :: #system_library "libc";
// SystemThemeHostLinux reads the supervising X11 container palette. Keep its
// native library on the final application link as well as inside the module.
@@ -30,6 +56,8 @@ theme_x11 :: #system_library "X11";
Environment :: (name: *u8) -> *u8 #foreign libc "getenv";
ThemeXInitThreads :: () -> s32 #foreign theme_x11 "XInitThreads";
}
TAB_APPLICATIONS :: 0;
TAB_PROCESSES :: 1;
TAB_PERFORMANCE :: 2;
@@ -72,11 +100,19 @@ APP_COLUMN_GPU :: 4;
// Ten-digit PIDs, percentages, elapsed times and adaptive byte values fit in
// 16 bytes; process/group names use the model's bounded 32-byte capacity.
CELL_WIDTH :: 16;
// Column bounds: signed 32-bit PID, normalized whole CPU %, adaptive u64 bytes.
PID_CELL_WIDTH :: 11;
CPU_CELL_WIDTH :: 4;
MEMORY_CELL_WIDTH :: 14;
NAME_WIDTH :: Model.NAME_CAPACITY;
STATUS_WIDTH :: 160;
// A flattened grouped table contains every raw process plus at most one header
// per two members: singleton groups use their raw row directly.
#if #defined(TASKMGR_TAIJI) {
MAX_DISPLAY_ROWS :: Model.MAX_PROCESSES;
} else {
MAX_DISPLAY_ROWS :: Model.MAX_PROCESSES + Model.MAX_PROCESSES / 2;
}
process_columns: [5]string = .{"Image Name", "PID", "CPU", "CPU Time", "Memory"};
process_fractions: [5]float32 = .{0.40, 0.12, 0.10, 0.16, 0.22};
@@ -85,6 +121,9 @@ app_columns: [5]string = .{"Task", "Status", "CPU", "Memory", "GPU"};
app_fractions: [5]float32 = .{0.40, 0.20, 0.11, 0.17, 0.12};
app_widths: [APP_COLUMNS]s32;
widths_for: float32;
widths_gpu: bool;
// Set when a window was expanded or collapsed; Frame rebuilds the rows.
apps_layout_changed: bool;
group_order: [Model.MAX_PROCESSES]s32;
raw_order: [Model.MAX_PROCESSES]s32;
@@ -112,37 +151,67 @@ expanded_count: s32;
CellText :: struct {
cell: [MAX_DISPLAY_ROWS * COLUMNS]string
name: [MAX_DISPLAY_ROWS * NAME_WIDTH]u8
pid: [MAX_DISPLAY_ROWS * CELL_WIDTH]u8
cpu: [MAX_DISPLAY_ROWS * CELL_WIDTH]u8
pid: [MAX_DISPLAY_ROWS * PID_CELL_WIDTH]u8
cpu: [MAX_DISPLAY_ROWS * CPU_CELL_WIDTH]u8
#if !#defined(TASKMGR_TAIJI) {
time: [MAX_DISPLAY_ROWS * CELL_WIDTH]u8
mem: [MAX_DISPLAY_ROWS * CELL_WIDTH]u8
}
mem: [MAX_DISPLAY_ROWS * MEMORY_CELL_WIDTH]u8
}
text_stores_a: CellText;
text_stores_b: CellText;
text_active: s32;
last_table_revision: u64;
// Window manager task lists, also in two generations. A window row totals its
// process tree (see Model.AppUsages); an expanded window lists those
// processes under it. process is -1 on a window row.
#if !#defined(TASKMGR_TAIJI) {
APP_ROWS :: Apps.MAX_WINDOWS + Model.MAX_PROCESSES;
TASK_WIDTH :: Apps.TITLE_CAPACITY + 8;
PROCESS_TASK_WIDTH :: NAME_WIDTH + 20;
AppRow :: struct {
window: s32
process: s32
}
// Window manager task lists, also in two generations. CPU, memory and GPU are
// the window's whole process tree (see Model.AppUsages).
AppText :: struct {
list: Apps.AppList
cell: [Apps.MAX_WINDOWS * APP_COLUMNS]string
cpu: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
mem: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
gpu: [Apps.MAX_WINDOWS * CELL_WIDTH]u8
rows: [APP_ROWS]AppRow
row_count: s32
cell: [APP_ROWS * APP_COLUMNS]string
task: [Apps.MAX_WINDOWS * TASK_WIDTH]u8
process_task: [Model.MAX_PROCESSES * PROCESS_TASK_WIDTH]u8
cpu: [APP_ROWS * CPU_CELL_WIDTH]u8
mem: [APP_ROWS * MEMORY_CELL_WIDTH]u8
gpu: [APP_ROWS * CPU_CELL_WIDTH]u8
}
app_pids: [Apps.MAX_WINDOWS]s32;
no_external_gpus: [1]Model.GpuExternal;
app_usage: [Apps.MAX_WINDOWS]Model.AppUsage;
tree_pids: [Model.MAX_PROCESSES]s32;
// NVML and DRM per-process GPU shares, merged for the current refresh.
gpu_pids: [2 * Gpu.MAX_GPU_PROCESSES]s32;
gpu_percent: [2 * Gpu.MAX_GPU_PROCESSES]float64;
gpu_count: s32;
// The GPU column appears only once a per-process source has data.
app_gpu_shown: bool;
expanded_windows: [Apps.MAX_WINDOWS]u64;
expanded_window_count: s32;
app_stores_a: AppText;
app_stores_b: AppText;
app_active: s32;
} else {
app_gpu_shown: bool;
}
no_external_gpus: [1]Model.GpuExternal;
current_tab: s32 = TAB_PROCESSES;
started: bool;
menu_state: MenuState;
menu_state: Menu.MenuState;
sort_column: s32 = Model.COLUMN_CPU;
sort_direction: s32 = -1;
@@ -156,7 +225,8 @@ scroll_offset: s32 = 0;
app_selected_row: s32 = -1;
app_selected_window: u64;
app_selected_column: s32 = -1;
// The process under the selected window, or -1 when the window row is.
app_selected_pid: s32 = -1;
app_scroll_offset: s32 = 0;
refresh_interval_ms: s64 = SPEED_NORMAL_MS;
@@ -193,10 +263,6 @@ palette_base: u32;
palette_text: u32;
palette_border: u32;
Color32 :: (packed: u32) -> Color {
return ColorFromPacked(packed)
}
PaletteLayer :: (opacity: u32) -> u32 {
return Theme.StateLayer(palette_background, palette_text, opacity)
}
@@ -221,7 +287,7 @@ Inset :: (bounds: Rectangle, amount: float32) -> Rectangle {
TaskButton :: (session: Session, id: s32, label: string, bounds: Rectangle,
accent: bool, disabled: bool) -> bool {
props: ButtonProps
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
@@ -233,21 +299,25 @@ TaskButton :: (session: Session, id: s32, label: string, bounds: Rectangle,
props.tone = ButtonTone.ButtonToneAccent
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
}
return Button(session, props) == 1
return Button.Draw(session, props) == 1
}
ValueLabel :: (session: Session, key: s32, text: string, bounds: Rectangle, font: s32) {
Text(session, TextProps.{.key = cast(u64)key, .bounds = bounds, .text = text, .font = font,
Text.Draw(session, Text.Props.{.key = cast(u64)key, .bounds = bounds, .text = text, .size = font,
.align = TextAlign.TextAlignEnd})
}
CenteredLabel :: (session: Session, key: s32, text: string, bounds: Rectangle, font: s32) {
Text(session, TextProps.{.key = cast(u64)key, .bounds = bounds, .text = text, .font = font,
Text.Draw(session, Text.Props.{.key = cast(u64)key, .bounds = bounds, .text = text, .size = font,
.align = TextAlign.TextAlignCenter})
}
// Picks the starting tab from TASKMGR_TAB, matching its first letter.
StartingTab :: () -> s32 {
#if #defined(TASKMGR_TAIJI) {
return TAB_PROCESSES
} else {
variable := "TASKMGR_TAB"
name: [16]u8
length: s32 = 0
@@ -263,6 +333,8 @@ StartingTab :: () -> s32 {
if first == 112 && value[1] == 101 { return TAB_PERFORMANCE }
if first == 80 && value[1] == 101 { return TAB_PERFORMANCE }
return TAB_PROCESSES
}
}
// Group names are retained as bytes, never as string views into refreshed
@@ -418,14 +490,26 @@ RebuildOrder :: (store: *CellText) {
store.cell[base + Model.COLUMN_PID] = "-"
} else {
store.cell[base + Model.COLUMN_PID] = Number.FormatInteger(cast(s64)entry.pid,
store.pid[cell:cell + CELL_WIDTH])
store.pid[index * PID_CELL_WIDTH:(index + 1) * PID_CELL_WIDTH])
}
#if #defined(TASKMGR_TAIJI) {
store.cell[base + Model.COLUMN_CPU] = "n/a"
if entry.cpu_available {
store.cell[base + Model.COLUMN_CPU] = Model.FormatCpu(entry.cpu_percent,
store.cpu[index * CPU_CELL_WIDTH:(index + 1) * CPU_CELL_WIDTH])
}
store.cell[base + Model.COLUMN_CPU_TIME] = "n/a"
} else {
store.cell[base + Model.COLUMN_CPU] = Model.FormatCpu(entry.cpu_percent,
store.cpu[cell:cell + CELL_WIDTH])
store.cpu[index * CPU_CELL_WIDTH:(index + 1) * CPU_CELL_WIDTH])
store.cell[base + Model.COLUMN_CPU_TIME] = Model.FormatCpuTime(entry.ticks,
store.time[cell:cell + CELL_WIDTH])
store.cell[base + Model.COLUMN_MEMORY] = Model.FormatBytes(entry.memory_bytes,
store.mem[cell:cell + CELL_WIDTH])
}
store.cell[base + Model.COLUMN_MEMORY] = "n/a"
if !Platform.IsGuest() || entry.memory_available {
store.cell[base + Model.COLUMN_MEMORY] = Model.FormatBytes(entry.memory_bytes,
store.mem[index * MEMORY_CELL_WIDTH:(index + 1) * MEMORY_CELL_WIDTH])
}
}
}
@@ -441,6 +525,7 @@ BuildOrder :: () {
// The Status column: a window whose process the kernel has stopped cannot
// answer, as a hung program could not on the classic task manager.
#if !#defined(TASKMGR_TAIJI) {
AppStatus :: (pid: s32) -> string {
if pid <= 0 { return "Running" }
snapshot := Model.Current()
@@ -451,58 +536,184 @@ AppStatus :: (pid: s32) -> string {
return "Running"
}
RebuildApps :: (store: *AppText) {
Apps.AppsRefresh(*store.list)
app_selected_row = -1
count := store.list.count
if count > 0 {
for index: 0..count - 1 { app_pids[index] = store.list.windows[index].pid }
shares := Gpu.GpuSharesCurrent()
Model.AppUsages(Model.Current(), app_pids[0:count], shares.pids[0:shares.count],
shares.percent[0:shares.count], Gpu.GpuSharesReady(), app_usage[0:count])
for index: 0..count - 1 {
entry := *store.list.windows[index]
usage := *app_usage[index]
base := index * APP_COLUMNS
text_base := index * CELL_WIDTH
if entry.id == app_selected_window { app_selected_row = index }
store.cell[base] = TextView(entry.title[0:entry.title_count])
store.cell[base + 1] = AppStatus(entry.pid)
if usage.found {
store.cell[base + APP_COLUMN_CPU] = Model.FormatCpu(usage.cpu_percent,
store.cpu[text_base:text_base + CELL_WIDTH])
store.cell[base + APP_COLUMN_MEMORY] = Model.FormatBytes(usage.memory_bytes,
store.mem[text_base:text_base + CELL_WIDTH])
} else {
store.cell[base + APP_COLUMN_CPU] = "-"
store.cell[base + APP_COLUMN_MEMORY] = "-"
}
if !usage.gpu_known {
store.cell[base + APP_COLUMN_GPU] = "n/a"
} else if usage.found {
store.cell[base + APP_COLUMN_GPU] = Model.FormatCpu(usage.gpu_percent,
store.gpu[text_base:text_base + CELL_WIDTH])
} else {
store.cell[base + APP_COLUMN_GPU] = "-"
WindowExpanded :: (id: u64) -> bool {
if expanded_window_count > 0 {
for index: 0..expanded_window_count - 1 {
if expanded_windows[index] == id { return true }
}
}
return false
}
ToggleWindow :: (id: u64) {
if expanded_window_count > 0 {
for index: 0..expanded_window_count - 1 {
if expanded_windows[index] == id {
expanded_window_count -= 1
expanded_windows[index] = expanded_windows[expanded_window_count]
return
}
}
}
if app_selected_row < 0 { app_selected_window = 0 }
if expanded_window_count >= Apps.MAX_WINDOWS { return }
expanded_windows[expanded_window_count] = id
expanded_window_count += 1
}
BuildApps :: () {
AddShares :: (shares: *Gpu.GpuShares) {
if shares.count <= 0 { return }
for index: 0..shares.count - 1 {
if gpu_count >= cast(s32)gpu_pids.count { return }
gpu_pids[gpu_count] = shares.pids[index]
gpu_percent[gpu_count] = shares.percent[index]
gpu_count += 1
}
}
GpuShareFor :: (pid: s32) -> float64 {
total: float64 = 0.0
if gpu_count > 0 {
for index: 0..gpu_count - 1 {
if gpu_pids[index] == pid { total += gpu_percent[index] }
}
}
return total
}
// Merges every per-process GPU source: NVML through its helper and DRM
// fdinfo of the processes the windows own. DRM is sampled only on a regular
// refresh while the tab is visible, so its rate is measured over a full
// interval. Needs owners from a preceding Model.AppUsages call.
CollectGpuShares :: (snapshot: *Model.Snapshot, sample: bool) {
if sample && current_tab == TAB_APPLICATIONS && snapshot.count > 0 {
owned: s32 = 0
for index: 0..snapshot.count - 1 {
if Model.ProcessOwner(snapshot, index) >= 0 {
tree_pids[owned] = snapshot.processes[index].pid
owned += 1
}
}
GpuDrm.DrmSample(tree_pids[0:owned])
}
gpu_count = 0
if Gpu.GpuSharesReady() { AddShares(Gpu.GpuSharesCurrent()) }
if GpuDrm.DrmAvailable() { AddShares(GpuDrm.DrmShares()) }
app_gpu_shown = Gpu.GpuSharesReady() || GpuDrm.DrmAvailable()
}
// Fills the CPU, Memory and GPU cells of ROW.
UsageCells :: (store: *AppText, row: s32, cpu: float64, memory: u64, gpu: float64) {
base := row * APP_COLUMNS
store.cell[base + APP_COLUMN_CPU] = Model.FormatCpu(cpu, store.cpu[row * CPU_CELL_WIDTH:(row + 1) * CPU_CELL_WIDTH])
store.cell[base + APP_COLUMN_MEMORY] = Model.FormatBytes(memory, store.mem[row * MEMORY_CELL_WIDTH:(row + 1) * MEMORY_CELL_WIDTH])
store.cell[base + APP_COLUMN_GPU] = Model.FormatCpu(gpu, store.gpu[row * CPU_CELL_WIDTH:(row + 1) * CPU_CELL_WIDTH])
}
AddWindowRow :: (store: *AppText, window: s32) {
row := store.row_count
if row >= APP_ROWS { return }
entry := *store.list.windows[window]
usage := *app_usage[window]
store.rows[row] = AppRow.{window = window, process = -1}
marker := " "
if usage.processes > 0 { marker = ifx WindowExpanded(entry.id) then "▾ " else "▸ " }
parts: [2]string = .{marker, TextView(entry.title[0:entry.title_count])}
base := row * APP_COLUMNS
store.cell[base] = JoinAll(parts[:], store.task[window * TASK_WIDTH:(window + 1) * TASK_WIDTH])
store.cell[base + 1] = AppStatus(entry.pid)
if usage.found {
UsageCells(store, row, usage.cpu_percent, usage.memory_bytes, usage.gpu_percent)
} else {
store.cell[base + APP_COLUMN_CPU] = "-"
store.cell[base + APP_COLUMN_MEMORY] = "-"
store.cell[base + APP_COLUMN_GPU] = "-"
}
if entry.id == app_selected_window && app_selected_pid < 0 { app_selected_row = row }
store.row_count += 1
}
AddProcessRow :: (store: *AppText, window: s32, process_index: s32) {
row := store.row_count
if row >= APP_ROWS { return }
process := *Model.Current().processes[process_index]
store.rows[row] = AppRow.{window = window, process = process_index}
digits: [16]u8
name: [Model.NAME_CAPACITY]u8
if process.name_count > 0 {
for index: 0..process.name_count - 1 { name[index] = process.name[index] }
}
parts: [5]string = .{" ", TextView(name[0:process.name_count]), " (",
Number.FormatInteger(cast(s64)process.pid, digits[:]), ")"}
base := row * APP_COLUMNS
store.cell[base] = JoinAll(parts[:], store.process_task[process_index * PROCESS_TASK_WIDTH:(process_index + 1) * PROCESS_TASK_WIDTH])
store.cell[base + 1] = Model.StateName(process.state)
UsageCells(store, row, process.cpu_percent, process.memory_bytes, GpuShareFor(process.pid))
if store.list.windows[window].id == app_selected_window && process.pid == app_selected_pid {
app_selected_row = row
}
store.row_count += 1
}
// The processes counted toward WINDOW, in PID order. Windows of one process
// share its owner slot, so each lists the same tree.
AddProcessRows :: (store: *AppText, window: s32) {
snapshot := Model.Current()
index := Model.FindProcess(snapshot, app_pids[window])
if index < 0 { return }
owner := Model.ProcessOwner(snapshot, index)
for process: 0..snapshot.count - 1 {
if Model.ProcessOwner(snapshot, process) == owner { AddProcessRow(store, window, process) }
}
}
// Rebuilds the window list and its rows. SAMPLE is false when only the
// expansion changed, so GPU rates are not measured over a split second.
RebuildApps :: (store: *AppText, sample: bool) {
Apps.AppsRefresh(*store.list)
snapshot := Model.Current()
count := store.list.count
store.row_count = 0
app_selected_row = -1
if count > 0 {
for index: 0..count - 1 { app_pids[index] = store.list.windows[index].pid }
Model.AppUsages(snapshot, app_pids[0:count], gpu_pids[0:0], gpu_percent[0:0], false,
app_usage[0:count])
CollectGpuShares(snapshot, sample)
Model.AppUsages(snapshot, app_pids[0:count], gpu_pids[0:gpu_count],
gpu_percent[0:gpu_count], app_gpu_shown, app_usage[0:count])
for window: 0..count - 1 {
AddWindowRow(store, window)
if WindowExpanded(store.list.windows[window].id) { AddProcessRows(store, window) }
}
}
if app_selected_row < 0 {
app_selected_window = 0
app_selected_pid = -1
}
}
BuildApps :: (sample: bool = true) {
if app_active == 0 {
RebuildApps(*app_stores_b)
RebuildApps(*app_stores_b, sample)
app_active = 1
} else {
RebuildApps(*app_stores_a)
RebuildApps(*app_stores_a, sample)
app_active = 0
}
}
ActiveApps :: () -> *Apps.AppList {
if app_active == 0 { return *app_stores_a.list }
return *app_stores_b.list
ActiveAppText :: () -> *AppText {
if app_active == 0 { return *app_stores_a }
return *app_stores_b
}
// Task, Status, CPU and Memory, plus GPU when a source has data.
AppColumnCount :: () -> s32 {
return ifx app_gpu_shown then APP_COLUMNS else APP_COLUMNS - 1
}
} else {
BuildApps :: (sample: bool = true) {}
}
// Copies the message parts into the raw status bytes for later frames.
@@ -524,8 +735,9 @@ SetStatusText :: (text: string) {
}
ColumnWidths :: (width: float32) {
if widths_for == width { return }
if widths_for == width && widths_gpu == app_gpu_shown { return }
widths_for = width
widths_gpu = app_gpu_shown
usable := width - 18.0
for column: 0..COLUMNS - 1 {
value := cast(s32)(usable * process_fractions[column])
@@ -533,57 +745,62 @@ ColumnWidths :: (width: float32) {
process_widths[column] = value
}
for column: 0..APP_COLUMNS - 1 {
value := cast(s32)(usable * app_fractions[column])
fraction := app_fractions[column]
// Without a GPU column its share goes to the Task names.
if column == 0 && !app_gpu_shown { fraction += app_fractions[APP_COLUMN_GPU] }
value := cast(s32)(usable * fraction)
if value < 40 { value = 40 }
app_widths[column] = value
}
}
MenuBar :: (session: Session, bounds: Rectangle) -> s32 {
if !menu_state.initialized { MenuStateInit(*menu_state) }
file_items: [3]MenuItem
if !menu_state.initialized { Menu.MenuStateInit(*menu_state) }
file_items: [3]Menu.MenuItem
file_items[0].id = MENU_NEW_TASK
file_items[0].label = "New Task (Run...)"
file_items[1].kind = MenuItemKind.MenuSeparator
file_items[0].disabled = Platform.IsGuest()
file_items[1].kind = Menu.MenuItemKind.MenuSeparator
file_items[2].id = MENU_EXIT
file_items[2].label = "Exit Task Manager"
option_items: [2]MenuItem
option_items[0].kind = MenuItemKind.MenuCheck
option_items: [2]Menu.MenuItem
option_items[0].kind = Menu.MenuItemKind.MenuCheck
option_items[0].id = MENU_CONFIRM_END
option_items[0].label = "Confirm Before Ending Processes"
option_items[0].checked = confirm_end
option_items[1].kind = MenuItemKind.MenuCheck
option_items[1].kind = Menu.MenuItemKind.MenuCheck
option_items[1].id = MENU_GROUP_PROCESSES
option_items[1].label = "Group Processes"
option_items[1].checked = group_processes
option_items[1].disabled = Platform.IsGuest()
speed_items: [4]MenuItem
speed_items: [4]Menu.MenuItem
speed_labels: [4]string = .{"High", "Normal", "Low", "Paused"}
speed_values: [4]s64 = .{SPEED_HIGH_MS, SPEED_NORMAL_MS, SPEED_LOW_MS, 0}
for index: 0..3 {
speed_items[index].kind = MenuItemKind.MenuRadio
speed_items[index].kind = Menu.MenuItemKind.MenuRadio
speed_items[index].id = MENU_SPEED_HIGH + cast(s32)index
speed_items[index].label = speed_labels[index]
speed_items[index].checked = refresh_interval_ms == speed_values[index]
}
view_items: [4]MenuItem
view_items: [4]Menu.MenuItem
view_items[0].id = MENU_REFRESH
view_items[0].label = "Refresh Now"
view_items[1].kind = MenuItemKind.MenuSubmenu
view_items[1].kind = Menu.MenuItemKind.MenuSubmenu
view_items[1].label = "Update Speed"
view_items[1].submenu = speed_items[:]
view_items[2].kind = MenuItemKind.MenuSeparator
view_items[3].kind = MenuItemKind.MenuCheck
view_items[2].kind = Menu.MenuItemKind.MenuSeparator
view_items[3].kind = Menu.MenuItemKind.MenuCheck
view_items[3].id = MENU_KERNEL_TIMES
view_items[3].label = "Show Kernel Times"
view_items[3].checked = show_kernel_times
help_items: [1]MenuItem
help_items: [1]Menu.MenuItem
help_items[0].id = MENU_ABOUT
help_items[0].label = "About Task Manager"
groups: [4]MenuGroup
groups: [4]Menu.MenuGroup
groups[0].label = "File"
groups[0].items = file_items[:]
groups[1].label = "Options"
@@ -592,14 +809,14 @@ MenuBar :: (session: Session, bounds: Rectangle) -> s32 {
groups[2].items = view_items[:]
groups[3].label = "Help"
groups[3].items = help_items[:]
return Menu(session, MenuProps.{.key = 20, .bounds = bounds}, groups[:], *menu_state).activated_id
return Menu.Draw(session, Menu.Props.{.key = 20, .bounds = bounds}, groups[:], *menu_state).activated_id
}
RunMenu :: (id: s32) {
if id == MENU_NEW_TASK { OpenRunDialog() }
if id == MENU_EXIT { Window.WindowQuit() }
if id == MENU_EXIT { Platform.CloseWindow() }
if id == MENU_CONFIRM_END { confirm_end = !confirm_end }
if id == MENU_GROUP_PROCESSES {
if id == MENU_GROUP_PROCESSES && !Platform.IsGuest() {
group_processes = !group_processes
selected_row = -1
selected_pid = -1
@@ -619,6 +836,7 @@ RunMenu :: (id: s32) {
}
OpenRunDialog :: () {
if Platform.IsGuest() { SetStatusText("Task launch unavailable on Taiji."); return }
dialog = DIALOG_RUN
command_pending = false
command_length = 0
@@ -629,7 +847,7 @@ OpenRunDialog :: () {
// Writes the field's text with one edit applied into command_next; the next
// frame's SettleCommand copies it back.
ApplyEdit :: (length: s32, edit: TextFieldEdit) -> s32 {
ApplyEdit :: (length: s32, edit: TextField.Edit) -> s32 {
if !edit.changed { return length }
if edit.start < 0 || edit.end < edit.start || edit.end > length { return length }
new_length := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
@@ -671,7 +889,7 @@ RunCommand :: () {
RunDialog :: (session: Session, font: s32) {
SettleCommand()
modal := ModalFrame(session, ModalFrameProps.{.key = 300, .title = "Create New Task",
modal := Modal.Draw(session, Modal.Props.{.key = 300, .title = "Create New Task",
.width = 460, .height = 210, .left_label = "Cancel", .right_label = "OK",
.has_left_action = true, .has_right_action = true})
commit := modal.right_clicked
@@ -682,7 +900,7 @@ RunDialog :: (session: Session, font: s32) {
key := KeyboardTake(session)
text := TypedTextTake(session, typed[:])
input := TextFieldInputFor(key, KeyboardModifiers(session), text)
result := TextField(session, TextFieldProps.{.key = 302, .id = 302,
result := TextField.Draw(session, TextField.Props.{.key = 302, .id = 302,
.bounds = .{area.x, area.y + 30.0, area.width, 36.0},
.value = TextView(command_bytes[0:command_length]), .label = "Open",
.placeholder = "for example: xterm", .max_bytes = Model.COMMAND_CAPACITY,
@@ -701,11 +919,11 @@ RunDialog :: (session: Session, font: s32) {
}
AboutDialog :: (session: Session) {
actions: [1]ActionModalAction
actions: [1]Modal.ActionModalAction
actions[0].label = "OK"
actions[0].tone = ButtonTone.ButtonToneAccent
actions[0].emphasis = ButtonEmphasis.ButtonEmphasisFilled
answer := ActionModal(session, ActionModalProps.{.key = 310, .title = "About Task Manager",
answer := Modal.ActionModal(session, Modal.ActionModalProps.{.key = 310, .title = "About Task Manager",
.message = "taskmgr shows the applications, processes and performance of this Linux computer. It reads /proc directly and lists windows from the X11 window manager.",
.max_width = 440}, actions[:])
if answer.action != 0 { dialog = DIALOG_NONE }
@@ -812,48 +1030,58 @@ EndProcessDialog :: (session: Session) {
Number.FormatInteger(cast(s64)end_pid, pid_line[:]), ")?"}
message = JoinAll(parts[:], process_message_line[:])
}
actions: [2]ActionModalAction
actions: [2]Modal.ActionModalAction
actions[0].label = "No"
actions[1].label = "Yes"
actions[1].tone = ButtonTone.ButtonToneDanger
actions[1].emphasis = ButtonEmphasis.ButtonEmphasisFilled
answer := ActionModal(session, ActionModalProps.{.key = 320, .title = "Task Manager Warning",
answer := Modal.ActionModal(session, Modal.ActionModalProps.{.key = 320, .title = "Task Manager Warning",
.message = message, .max_width = 460}, actions[:])
if answer.action == 2 { EndSelectedTarget() }
if answer.action != 0 { dialog = DIALOG_NONE }
}
ApplicationsTab :: (session: Session, area: Rectangle) {
list := ActiveApps()
#if #defined(TASKMGR_TAIJI) {
CenteredLabel(session, 205, "Window task lists are unavailable on TaijiOS.", area, 14)
} else {
store := ActiveAppText()
list := *store.list
table_bounds := Rectangle.{area.x, area.y, area.width, area.height - BUTTON_HEIGHT - PAD}
if table_bounds.height < 60.0 { table_bounds.height = 60.0 }
rows: [Apps.MAX_WINDOWS]Tables.TableRow
count := list.count
if app_active == 0 {
if count > 0 {
for index: 0..count - 1 {
rows[index].cells = app_stores_a.cell[index * APP_COLUMNS:(index + 1) * APP_COLUMNS]
}
}
} else {
if count > 0 {
for index: 0..count - 1 {
rows[index].cells = app_stores_b.cell[index * APP_COLUMNS:(index + 1) * APP_COLUMNS]
rows: [APP_ROWS]Tables.TableRow
count := store.row_count
shown := AppColumnCount()
if count > 0 {
for index: 0..count - 1 {
base := index * APP_COLUMNS
if app_active == 0 {
rows[index].cells = app_stores_a.cell[base:base + shown]
} else {
rows[index].cells = app_stores_b.cell[base:base + shown]
}
}
}
table := Tables.TableView(session, Tables.TableViewProps.{.key = 200,
.bounds = table_bounds, .columns = app_columns[:], .rows = rows[0:count],
.column_widths = app_widths[:], .selected_row = app_selected_row,
.selected_column = app_selected_column, .sort_column = -1,
.bounds = table_bounds, .columns = app_columns[0:shown], .rows = rows[0:count],
.column_widths = app_widths[0:shown], .selected_row = app_selected_row,
.selected_column = -1, .sort_column = -1,
.scroll_offset = app_scroll_offset, .row_height = 26, .header_height = 30,
.resizable = true})
app_selected_row = table.selected_row
app_selected_column = table.selected_column
app_scroll_offset = table.scroll_offset
app_selected_window = 0
app_selected_pid = -1
if app_selected_row >= 0 && app_selected_row < count {
app_selected_window = list.windows[app_selected_row].id
row := store.rows[app_selected_row]
app_selected_window = list.windows[row.window].id
if row.process >= 0 {
app_selected_pid = Model.Current().processes[row.process].pid
} else if table.clicked_row == app_selected_row && app_usage[row.window].processes > 0 {
// Clicking a window shows or hides the processes it owns.
ToggleWindow(app_selected_window)
apps_layout_changed = true
}
}
if !list.available {
CenteredLabel(session, 205, "No window manager task list is available on this display.",
@@ -881,9 +1109,14 @@ ApplicationsTab :: (session: Session, area: Rectangle) {
OpenRunDialog()
}
}
}
ProcessesTab :: (session: Session, area: Rectangle) {
raw := Model.Current()
if !raw.processes_available {
Label(session, 109, "Guest process service unavailable", area, 14)
return
}
grouped_snapshot := Model.GroupedCurrent()
table_bounds := Rectangle.{area.x, area.y, area.width, area.height - BUTTON_HEIGHT - PAD}
if table_bounds.height < 60.0 { table_bounds.height = 60.0 }
@@ -935,7 +1168,7 @@ ProcessesTab :: (session: Session, area: Rectangle) {
}
button_y := area.y + area.height - BUTTON_HEIGHT
none := selected_pid <= 0 && !selected_is_group
none := (Platform.IsGuest() && selected_is_group) || (selected_pid <= 0 && !selected_is_group)
button_label: string = "End Process"
if selected_is_group { button_label = "End Group" }
if TaskButton(session, 110, button_label, .{area.x + area.width - BUTTON_WIDTH, button_y,
@@ -980,7 +1213,7 @@ DrawHistorySeries :: (session: Session, inner: Rectangle, series: []float32, col
x1 := inner.x + inner.width * cast(float32)index / cast(float32)(count - 1)
y0 := inner.y + inner.height * (1.0 - series[index - 1] / 100.0)
y1 := inner.y + inner.height * (1.0 - series[index] / 100.0)
PaintLine(session, -1, .{x0, y0, x1 - x0, y1 - y0}, Color32(color))
PaintLine(session, -1, .{x0, y0, x1 - x0, y1 - y0}, ColorFromPacked(color))
}
}
}
@@ -1015,9 +1248,9 @@ GpuLegend :: (device: *Model.GpuDevice, kind: s32, output: []u8) -> string {
HistoryGraph :: (session: Session, key: s32, bounds: Rectangle, label: string, kind: s32,
font: s32, with_kernel: bool) {
border := GraphColor(kind, 0)
Box(session, BoxProps.{.key = cast(u64)key, .bounds = bounds,
.fill = Color32(cast(u32)0x000000ff),
.border = Color32(border), .radius = 0.0})
Box.Draw(session, Box.Props.{.key = cast(u64)key, .bounds = bounds,
.fill = ColorFromPacked(cast(u32)0x000000ff),
.border = ColorFromPacked(border), .radius = 0.0})
inner := Rectangle.{bounds.x + 2.0, bounds.y + 2.0,
bounds.width - 4.0, bounds.height - 4.0}
if kind == Model.HISTORY_GPU || kind == Model.HISTORY_VRAM {
@@ -1040,10 +1273,10 @@ HistoryGraph :: (session: Session, key: s32, bounds: Rectangle, label: string, k
inner.y + 2.0 + cast(float32)device_index * 16.0,
inner.width - 6.0, 15.0}
PaintLine(session, -1, .{row.x + 3.0, row.y + 7.0, 8.0, 0.0},
Color32(color))
ColorFromPacked(color))
PaintClippedLabel(session, -1, GpuLegend(device, kind, legend[:]),
cast(s32)(row.x + 15.0), cast(s32)row.y, font,
Color32(color), inner)
ColorFromPacked(color), inner)
}
}
} else {
@@ -1074,7 +1307,7 @@ GroupContent :: (bounds: Rectangle) -> Rectangle {
PerformanceGraph :: (session: Session, key: s32, bounds: Rectangle, title: string,
semantic_label: string, history_kind: s32, reading: string, font: s32,
with_kernel: bool) {
Fieldset(session, FieldsetProps.{.key = cast(u64)key, .bounds = bounds, .title = title})
Fieldset.Draw(session, Fieldset.Props.{.key = cast(u64)key, .bounds = bounds, .title = title})
content := GroupContent(bounds)
reading_height: float32 = 18.0
graph := Rectangle.{content.x, content.y, content.width, content.height - reading_height - 3.0}
@@ -1085,6 +1318,29 @@ PerformanceGraph :: (session: Session, key: s32, bounds: Rectangle, title: strin
}
PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
#if #defined(TASKMGR_TAIJI) {
bytes: [32]u8
Label(session, 449, "Guest main pool allocated", area, font)
reading := "n/a"
if Model.Current().memory_available { reading = Model.FormatBytes(Model.Current().memory_used, bytes[:]) }
Label(session, 450, reading,
.{area.x, area.y + 40.0, area.width, 30.0}, font)
measured_bytes: [16]u8
all_bytes: [16]u8
count_bytes: [80]u8
count_parts: [4]string = .{"Comparable tasks: ",
Number.FormatInteger(cast(s64)Model.Current().cpu_measured_tasks, measured_bytes[:]),
" / ", Number.FormatInteger(cast(s64)Model.Current().count, all_bytes[:])}
Label(session, 453, JoinAll(count_parts[:], count_bytes[:]),
.{area.x, area.y + 160.0, area.width, 30.0}, font)
cpu_bytes: [24]u8
cpu_reading := "n/a (sampling)"
if Model.Current().cpu_available { cpu_reading = Model.FormatAccountedCpu(Model.Current().cpu_percent, cpu_bytes[:]) }
Label(session, 451, "Measured task CPU % (one core = 100%)",
.{area.x, area.y + 90.0, area.width, 30.0}, font)
Label(session, 452, cpu_reading,
.{area.x, area.y + 125.0, area.width, 30.0}, font)
} else {
snapshot := Model.Current()
half := (area.width - PAD) / 2.0
info_height: float32 = 92.0
@@ -1137,14 +1393,14 @@ PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
b: [32]u8
c: [32]u8
totals := Rectangle.{area.x, info_y, half, info_height}
Fieldset(session, FieldsetProps.{.key = 440, .bounds = totals, .title = "Totals"})
Fieldset.Draw(session, Fieldset.Props.{.key = 440, .bounds = totals, .title = "Totals"})
totals_area := GroupContent(totals)
InfoRow(session, 441, totals_area, 0, "Handles", Model.FormatThousands(snapshot.handles, a[:]), font)
InfoRow(session, 443, totals_area, 1, "Threads", Model.FormatThousands(snapshot.threads, b[:]), font)
InfoRow(session, 445, totals_area, 2, "Processes", Model.FormatThousands(cast(s64)snapshot.count, c[:]), font)
physical := Rectangle.{right_x, info_y, half, info_height}
Fieldset(session, FieldsetProps.{.key = 450, .bounds = physical, .title = "Physical Memory"})
Fieldset.Draw(session, Fieldset.Props.{.key = 450, .bounds = physical, .title = "Physical Memory"})
physical_area := GroupContent(physical)
d: [32]u8
e: [32]u8
@@ -1155,7 +1411,7 @@ PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
second_info_y := info_y + info_height + PAD
commit := Rectangle.{area.x, second_info_y, half, info_height}
Fieldset(session, FieldsetProps.{.key = 460, .bounds = commit, .title = "Commit Charge"})
Fieldset.Draw(session, Fieldset.Props.{.key = 460, .bounds = commit, .title = "Commit Charge"})
commit_area := GroupContent(commit)
g: [32]u8
h: [32]u8
@@ -1165,7 +1421,7 @@ PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
InfoRow(session, 465, commit_area, 2, "Peak", Model.FormatKilobytesBytes(Model.CommitPeakKb(), i[:]), font)
kernel := Rectangle.{right_x, second_info_y, half, info_height}
Fieldset(session, FieldsetProps.{.key = 470, .bounds = kernel, .title = "Kernel Memory"})
Fieldset.Draw(session, Fieldset.Props.{.key = 470, .bounds = kernel, .title = "Kernel Memory"})
kernel_area := GroupContent(kernel)
j: [32]u8
k: [32]u8
@@ -1177,6 +1433,7 @@ PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
InfoRow(session, 471, kernel_area, 0, "Total", Model.FormatKilobytesBytes(kernel_total, j[:]), font)
InfoRow(session, 473, kernel_area, 1, "Paged", Model.FormatKilobytesBytes(details.kernel_paged_kb, k[:]), font)
InfoRow(session, 475, kernel_area, 2, "Nonpaged", Model.FormatKilobytesBytes(details.kernel_nonpaged_kb, l[:]), font)
}
}
// The status bar: process count, CPU usage and memory in use, each in its
@@ -1184,14 +1441,22 @@ PerformanceTab :: (session: Session, area: Rectangle, font: s32) {
StatusBar :: (session: Session, bounds: Rectangle, font: s32) {
theme := Theme.CurrentTheme()
snapshot := Model.Current()
Box(session, BoxProps.{.key = 500, .bounds = bounds, .fill = Color32(PaletteLayer(5)),
.border = Color32(palette_border)})
Box.Draw(session, Box.Props.{.key = 500, .bounds = bounds, .fill = ColorFromPacked(PaletteLayer(5)),
.border = ColorFromPacked(palette_border)})
count_line: [16]u8
processes_line: [48]u8
processes_parts: [2]string = .{"Processes: ", Number.FormatInteger(cast(s64)snapshot.count, count_line[:])}
cpu_line: [16]u8
cpu_text: [48]u8
cpu_parts: [3]string = .{"CPU Usage: ", Model.FormatCpu(snapshot.cpu_percent, cpu_line[:]), "%"}
cpu_value := ""
cpu_caption := "CPU Usage: "
#if #defined(TASKMGR_TAIJI) {
cpu_value = Model.FormatAccountedCpu(snapshot.cpu_percent, cpu_line[:])
cpu_caption = "Task CPU: "
} else {
cpu_value = Model.FormatCpu(snapshot.cpu_percent, cpu_line[:])
}
cpu_parts: [3]string = .{cpu_caption, cpu_value, "%"}
used_line: [32]u8
total_line: [32]u8
memory_text: [96]u8
@@ -1199,13 +1464,23 @@ StatusBar :: (session: Session, bounds: Rectangle, font: s32) {
" / ", Model.FormatBytes(snapshot.memory_total, total_line[:])}
texts: [3]string = .{JoinAll(processes_parts[:], processes_line[:]),
JoinAll(cpu_parts[:], cpu_text[:]), JoinAll(memory_parts[:], memory_text[:])}
if !snapshot.processes_available { texts[0] = "Processes: n/a" }
if !snapshot.cpu_available { texts[1] = "CPU: n/a" }
#if #defined(TASKMGR_TAIJI) {
if !snapshot.cpu_available { texts[1] = "Task CPU: n/a" }
}
if !snapshot.memory_available { texts[2] = "Memory: n/a" }
#if #defined(TASKMGR_TAIJI) {
widths: [3]float32 = .{0.24, 0.32, 0.44}
} else {
widths: [3]float32 = .{0.24, 0.24, 0.52}
}
x := bounds.x + 4.0
for index: 0..2 {
width := (bounds.width - 16.0) * widths[index]
pane := Rectangle.{x, bounds.y + 3.0, width, bounds.height - 6.0}
Box(session, BoxProps.{.key = cast(u64)(501 + cast(s32)index * 2), .bounds = pane,
.fill = Color32(palette_background), .border = Color32(palette_border),
Box.Draw(session, Box.Props.{.key = cast(u64)(501 + cast(s32)index * 2), .bounds = pane,
.fill = ColorFromPacked(palette_background), .border = ColorFromPacked(palette_border),
.radius = theme.metrics.radius_mark})
Label(session, 502 + cast(s32)index * 2, texts[index], .{pane.x + 6.0, pane.y + 2.0, pane.width - 12.0,
pane.height - 4.0}, font)
@@ -1229,6 +1504,7 @@ TaskTabs :: (session: Session, bounds: Rectangle) {
#program_export
Frame :: (session: Session, viewport: Rectangle) -> s32 {
if !started {
#if !#defined(TASKMGR_TAIJI) {
unused ThemeXInitThreads()
palette := SystemThemeHostLinux.SystemPaletteRead()
// Some GTK/host themes report the window background correctly but
@@ -1242,11 +1518,27 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
palette_text = palette.text
palette_border = palette.border
unused SystemTheme.SystemPaletteInstall(palette)
}
#if #defined(TASKMGR_TAIJI) {
theme := Theme.CurrentTheme()
palette_background = theme.colors.background
palette_text = theme.colors.foreground
palette_border = theme.colors.border
palette_base = palette_background
process_columns[2] = "CPU %"
process_columns[4] = "Est. Memory"
group_processes = false
}
current_tab = StartingTab()
started = true
}
frames_since_refresh += 1
now_ms := Timer.MonotonicMilliseconds()
now_ms: s64 = -1
#if !#defined(TASKMGR_TAIJI) {
now_ms = Timer.MonotonicMilliseconds()
} else {
now_ms = GuestClock.Milliseconds()
}
refreshed := last_refresh_ms < 0
if refresh_interval_ms > 0 {
if now_ms >= 0 && last_refresh_ms >= 0 &&
@@ -1274,17 +1566,22 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
if now_ms >= 0 { last_refresh_ms = now_ms } else { last_refresh_ms = 0 }
refresh_requested = false
}
if refreshed || pending_sort {
if pending_sort || (refreshed && Model.TableRevision() != last_table_revision) {
BuildOrder()
last_table_revision = Model.TableRevision()
pending_sort = false
}
if apps_layout_changed && !refreshed {
BuildApps(false)
}
apps_layout_changed = false
page := PageFor(viewport, 640.0)
font := FontSize(*page, 14)
small := FontSize(*page, 13)
theme := Theme.CurrentTheme()
Box(session, BoxProps.{.key = 1, .bounds = viewport, .fill = Color32(palette_background)})
Box.Draw(session, Box.Props.{.key = 1, .bounds = viewport, .fill = ColorFromPacked(palette_background)})
tabs_y := viewport.y + MENU_HEIGHT + 6.0
TaskTabs(session, .{viewport.x + 8.0, tabs_y, viewport.width - 16.0, TAB_HEIGHT})
@@ -1293,8 +1590,8 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
panel_y := tabs_y + TAB_HEIGHT
panel := Rectangle.{viewport.x + 8.0, panel_y, viewport.width - 16.0, status_y - panel_y - 6.0}
if panel.height < 80.0 { panel.height = 80.0 }
Box(session, BoxProps.{.key = 41, .bounds = panel, .fill = Color32(PaletteLayer(3)),
.border = Color32(palette_border), .radius = theme.metrics.radius_small})
Box.Draw(session, Box.Props.{.key = 41, .bounds = panel, .fill = ColorFromPacked(PaletteLayer(3)),
.border = ColorFromPacked(palette_border), .radius = theme.metrics.radius_small})
content := Inset(panel, PAD)
ColumnWidths(content.width)
if current_tab == TAB_APPLICATIONS {
+5 -9
View File
@@ -1,22 +1,18 @@
// Compact native host for the classic task-manager layout. Keeping the
// initial surface at its useful size avoids allocating 960x600 Cairo, SDL and
// X11 framebuffers merely to show a deliberately compact system utility.
#import "kryon/desktop_loop";
using Kryon :: #import "kryon/Kryon";
Desktop :: #import "kryon/desktop_loop";
#import "kryon/tree_frame"
App :: #import "app";
Gpu :: #import "gpu_processes";
// Custom hosts currently provide the bridge symbol consumed by desktop_loop.
#program_export
ProjectFrame :: (session: Session, viewport: Rectangle) -> s32 {
return App.Frame(session, viewport)
}
// `taskmgr --gpu-helper` is the display-free NVML sampler the Applications
// tab starts from this same binary (see gpu_processes.zi).
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
if Gpu.HelperRequested(argc, argv) { return Gpu.HelperMain() }
Gpu.GpuSharesEnable()
return RunDesktop(400, 480)
unused TreeFrameUse()
return Desktop.Run(App.Frame, 400, 480)
}
+344
View File
@@ -0,0 +1,344 @@
// Per-process GPU shares from DRM fdinfo, the kernel's standard per-client
// counters (amdgpu, i915, xe, msm, panfrost and others). Every open DRM file
// reports busy time per engine, either drm-engine-NAME in nanoseconds (shared
// by drm-engine-capacity-NAME instances) or drm-cycles-NAME against
// drm-total-cycles-NAME. A client's share is its busiest engine since the
// previous sample, and a client counts once even when several descriptors or
// processes hold it. NVIDIA's proprietary driver publishes no such counters;
// gpu_processes.zi covers it through NVML.
Files :: #import "std/file";
Number :: #import "std/number_text";
Timer :: #import "std/timer_linux";
Gpu :: #import "gpu_processes";
MAX_FDINFO_ENGINES :: 16;
FdinfoClient :: struct {
client: u64
device: u64
engines: [MAX_FDINFO_ENGINES]u64
busy: [MAX_FDINFO_ENGINES]u64
total: [MAX_FDINFO_ENGINES]u64
capacity: [MAX_FDINFO_ENGINES]u64
count: s32
has_client: bool
}
#scope_file
c :: #system_library "c";
ReadLinkRaw :: (path: *u8, output: *u8, size: usize) -> isize #foreign c "readlink";
MAX_COUNTERS :: 1024;
MAX_SEEN :: 512;
// One engine of one client as of the previous sample.
Counter :: struct {
client: u64
device: u64
engine: u64
busy: u64
total: u64
live: bool
}
counters: [MAX_COUNTERS]Counter;
counter_count: s32;
seen_clients: [MAX_SEEN]u64;
seen_devices: [MAX_SEEN]u64;
seen_count: s32;
previous_ms: s64 = -1;
found_any: bool;
shares: Gpu.GpuShares;
fdinfo_text: [4096]u8;
Hash :: (text: []u8) -> u64 {
value: u64 = 14695981039346656037
for byte: text {
value = (value ^ cast(u64)byte) * 1099511628211
}
return value
}
StartsWith :: (line: []u8, prefix: string) -> bool {
if line.count < prefix.count { return false }
for index: 0..cast(s32)prefix.count - 1 {
if line[index] != prefix[index] { return false }
}
return true
}
// The first decimal number after the colon, or -1.
LineNumber :: (line: []u8) -> s64 {
cursor: s32 = 0
total := cast(s32)line.count
while cursor < total && line[cursor] != 58 { cursor += 1 }
while cursor < total && (line[cursor] < 48 || line[cursor] > 57) { cursor += 1 }
if cursor >= total { return -1 }
value: s64 = 0
while cursor < total && line[cursor] >= 48 && line[cursor] <= 57 {
value = value * 10 + cast(s64)(line[cursor] - 48)
cursor += 1
}
return value
}
// The engine name between PREFIX and the colon.
EngineName :: (line: []u8, prefix: string) -> []u8 {
end := cast(s32)prefix.count
while end < cast(s32)line.count && line[end] != 58 { end += 1 }
return line[prefix.count:end]
}
EngineSlot :: (reading: *FdinfoClient, name: []u8) -> s32 {
key := Hash(name)
if reading.count > 0 {
for index: 0..reading.count - 1 {
if reading.engines[index] == key { return index }
}
}
if reading.count >= MAX_FDINFO_ENGINES { return -1 }
slot := reading.count
reading.engines[slot] = key
reading.busy[slot] = 0
reading.total[slot] = 0
reading.capacity[slot] = 1
reading.count += 1
return slot
}
ParseLine :: (line: []u8, reading: *FdinfoClient) {
if StartsWith(line, "drm-client-id:") {
value := LineNumber(line)
if value >= 0 {
reading.client = cast(u64)value
reading.has_client = true
}
return
}
if StartsWith(line, "drm-pdev:") {
reading.device = Hash(line)
return
}
prefixes: [4]string = .["drm-engine-capacity-", "drm-engine-", "drm-total-cycles-", "drm-cycles-"]
for kind: 0..3 {
prefix := prefixes[kind]
if !StartsWith(line, prefix) { continue }
value := LineNumber(line)
slot := EngineSlot(reading, EngineName(line, prefix))
if value < 0 || slot < 0 { return }
if kind == 0 { reading.capacity[slot] = cast(u64)value }
if kind == 1 || kind == 3 { reading.busy[slot] = cast(u64)value }
if kind == 2 { reading.total[slot] = cast(u64)value }
return
}
}
AppendText :: (output: []u8, at: s32, piece: string) -> s32 {
length := at
for byte: piece {
if length >= cast(s32)output.count - 1 { break }
output[length] = byte
length += 1
}
return length
}
// "/proc/PID/KIND/NAME" as a NUL-terminated path; the string excludes NUL.
ProcPath :: (pid: s32, kind: string, name: string, output: []u8) -> string {
digits: [16]u8
length := AppendText(output, 0, "/proc/")
length = AppendText(output, length, Number.FormatInteger(cast(s64)pid, digits[:]))
length = AppendText(output, length, kind)
if name.count > 0 {
length = AppendText(output, length, "/")
length = AppendText(output, length, name)
}
output[length] = 0
return TextView(output[0:length])
}
IsDrmDescriptor :: (path: *u8) -> bool {
target: [64]u8
length := ReadLinkRaw(path, *target[0], 63)
if length < 9 { return false }
return StartsWith(target[0:cast(s32)length], "/dev/dri/")
}
ReadFdinfo :: (path: string, reading: *FdinfoClient) -> bool {
file := Files.OpenRead(path)
if !file.valid { return false }
total: s32 = 0
while total < cast(s32)fdinfo_text.count {
count := Files.ReadAt(file, fdinfo_text[total:fdinfo_text.count], cast(s64)total)
if count <= 0 { break }
total += cast(s32)count
}
unused Files.CloseFile(file)
return ParseFdinfo(fdinfo_text[0:total], reading)
}
// Takes the client once per sample; false when another descriptor or
// process already counted it.
ClaimClient :: (reading: *FdinfoClient) -> bool {
if seen_count > 0 {
for index: 0..seen_count - 1 {
if seen_clients[index] == reading.client && seen_devices[index] == reading.device {
return false
}
}
}
if seen_count >= MAX_SEEN { return false }
seen_clients[seen_count] = reading.client
seen_devices[seen_count] = reading.device
seen_count += 1
return true
}
// Updates the stored counters and returns the client's busiest engine since
// the previous sample, or -1 when this is its first sample.
ClientPercent :: (reading: *FdinfoClient, elapsed_ms: s64) -> float64 {
best: float64 = -1.0
if reading.count <= 0 { return best }
for engine: 0..reading.count - 1 {
key := reading.engines[engine]
found: s32 = -1
if counter_count > 0 {
for index: 0..counter_count - 1 {
entry := *counters[index]
if entry.client == reading.client && entry.device == reading.device && entry.engine == key {
found = index
break
}
}
}
if found >= 0 {
entry := *counters[found]
percent := EnginePercent(entry.busy, reading.busy[engine], entry.total,
reading.total[engine], elapsed_ms, reading.capacity[engine])
if percent > best { best = percent }
} else if counter_count < MAX_COUNTERS {
found = counter_count
counter_count += 1
}
if found >= 0 {
entry := *counters[found]
entry.client = reading.client
entry.device = reading.device
entry.engine = key
entry.busy = reading.busy[engine]
entry.total = reading.total[engine]
entry.live = true
}
}
return best
}
AddShare :: (pid: s32, percent: float64) {
if shares.count >= Gpu.MAX_GPU_PROCESSES { return }
shares.pids[shares.count] = pid
shares.percent[shares.count] = percent
shares.count += 1
}
SampleProcess :: (pid: s32, elapsed_ms: s64) {
directory_path: [64]u8
directory := Files.OpenDirectory(ProcPath(pid, "/fd", "", directory_path[:]))
descriptor_path: [96]u8
info_path: [96]u8
while true {
entry := Files.NextDirectoryEntry(*directory)
if !entry.valid { break }
name := TextView(entry.name[0:entry.name_count])
if name == "." || name == ".." { continue }
unused ProcPath(pid, "/fd", name, descriptor_path[:])
if !IsDrmDescriptor(*descriptor_path[0]) { continue }
reading: FdinfoClient
if !ReadFdinfo(ProcPath(pid, "/fdinfo", name, info_path[:]), *reading) { continue }
found_any = true
if !ClaimClient(*reading) { continue }
percent := ClientPercent(*reading, elapsed_ms)
if percent >= 0.0 && elapsed_ms > 0 { AddShare(pid, percent) }
}
Files.CloseDirectory(*directory)
}
#scope_export
// Parses one DRM fdinfo file; false unless it names a client with engines.
#program_export
ParseFdinfo :: (text: []u8, reading: *FdinfoClient) -> bool {
start: s32 = 0
total := cast(s32)text.count
while start < total {
end := start
while end < total && text[end] != 10 { end += 1 }
ParseLine(text[start:end], reading)
start = end + 1
}
return reading.has_client && reading.count > 0
}
// Busy percent of one engine between two samples: cycle counters against
// their own total, nanosecond counters against wall time and capacity.
#program_export
EnginePercent :: (busy_before: u64, busy_now: u64, total_before: u64, total_now: u64,
elapsed_ms: s64, capacity: u64) -> float64 {
if busy_now < busy_before { return 0.0 }
busy := cast(float64)(busy_now - busy_before)
percent: float64 = 0.0
if total_now > 0 {
if total_now <= total_before { return 0.0 }
percent = 100.0 * busy / cast(float64)(total_now - total_before)
} else {
if elapsed_ms <= 0 { return 0.0 }
lanes := capacity
if lanes == 0 { lanes = 1 }
percent = 100.0 * busy / (cast(float64)elapsed_ms * 1000000.0 * cast(float64)lanes)
}
if percent > 100.0 { percent = 100.0 }
return percent
}
// Samples the DRM clients of PIDS; the first call only records counters.
#program_export
DrmSample :: (pids: []s32) {
now := Timer.MonotonicMilliseconds()
elapsed: s64 = 0
if previous_ms >= 0 && now > previous_ms { elapsed = now - previous_ms }
shares.count = 0
seen_count = 0
if counter_count > 0 {
for index: 0..counter_count - 1 { counters[index].live = false }
}
for pid: pids { SampleProcess(pid, elapsed) }
// Drop counters of clients that closed.
kept: s32 = 0
if counter_count > 0 {
for index: 0..counter_count - 1 {
if counters[index].live {
counters[kept] = counters[index]
kept += 1
}
}
}
counter_count = kept
previous_ms = now
}
// True once any DRM client with engine counters was seen in this run.
#program_export
DrmAvailable :: () -> bool { return found_any }
#program_export
DrmShares :: () -> *Gpu.GpuShares { return *shares }
// Forgets every counter, so the next sample starts fresh; for tests and for
// reopening the tab after a pause.
#program_export
DrmReset :: () {
counter_count = 0
seen_count = 0
previous_ms = -1
shares.count = 0
}
+18 -1
View File
@@ -19,7 +19,7 @@
// "E". "X" means NVML is unusable.
Model :: #import "model";
Channel :: #import "std/process_channel_linux";
Files :: #import "std/file";
Number :: #import "std/number_text";
@@ -39,6 +39,16 @@ GpuDeviceReadings :: struct {
count: s32
}
#if #defined(TASKMGR_TAIJI) {
#scope_export
shares: GpuShares;
devices: GpuDeviceReadings;
GpuSharesPoll :: (active: bool) {}
GpuSharesReady :: () -> bool { return false }
GpuSharesCurrent :: () -> *GpuShares { return *shares }
GpuDevicesCurrent :: () -> *GpuDeviceReadings { return *devices }
} else {
Channel :: #import "std/process_channel_linux";
#scope_file
c :: #system_library "c";
@@ -51,6 +61,8 @@ WriteRaw :: (fd: s32, bytes: *u8, count: usize) -> isize #foreign c "write";
SleepRaw :: (micros: u32) -> s32 #foreign c "usleep";
ParentRaw :: () -> s32 #foreign c "getppid";
TimeRaw :: (output: *s64) -> s64 #foreign c "time";
SetNameRaw :: (option: s32, name: *u8) -> s32 #foreign c "prctl";
PR_SET_NAME :: 15;
NVML_SUCCESS :: 0;
MAX_DEVICES :: GPU_DEVICE_LIMIT;
@@ -399,6 +411,9 @@ HelperRequested :: (argc: s32, argv: **u8) -> bool {
// stream one block per sample until the parent exits or stops reading.
#program_export
HelperMain :: () -> s32 {
// Started through /proc/self/exe, the helper would otherwise be "exe".
helper_name: [16]u8
if CopyCString("taskmgr-gpu", helper_name[:]) { unused SetNameRaw(PR_SET_NAME, *helper_name[0]) }
parent := ParentRaw()
if size_of(NvmlSample) != 32 || size_of(NvmlPci) != 68 || size_of(NvmlMemory) != 24 ||
!LoadNvml() {
@@ -539,3 +554,5 @@ GpuSharesReset :: () {
staging_devices.count = 0
current_devices.count = 0
}
}
+29
View File
@@ -0,0 +1,29 @@
// Delta arithmetic shared by the guest adapter and deterministic fixtures.
#scope_export
Reading :: struct {
counter: s64
clock: s64
identity: s64
error: s64
}
// CPU and monotonic wall counters must use the same unit. Identity identifies
// a task incarnation, not merely its reusable PID. Never invent a first delta.
Percent :: (before: Reading, after: Reading) -> (value: float64, valid: bool) {
if before.identity <= 0 || before.identity != after.identity ||
before.counter < 0 || after.counter < before.counter ||
before.clock < 0 || after.clock <= before.clock ||
before.error < 0 || after.error < 0 { return .{0, false} }
elapsed := after.clock - before.clock
used := after.counter - before.counter
// Each CPU read falls within its captured timestamp error. Require a
// useful interval and add bounds by subtraction to avoid signed overflow.
if before.error >= elapsed || after.error >= elapsed - before.error { return .{0, false} }
error := before.error + after.error
if used > elapsed {
if used - elapsed > error { return .{0, false} }
// One task has at most one executing interpreter thread. Saturation
// is valid only within the host's measured capture-skew interval.
return .{100, true}
}
return .{cast(float64)used * 100.0 / cast(float64)elapsed, true}
}
+784
View File
@@ -0,0 +1,784 @@
// Hosted portable Task Manager frontend for Werkzeug (KRYON_HOSTED_UI).
// Communicates with the host's `taskmgr.v1` service backed by taskmgr's Model.
Box :: #import "kryon/box";
Button :: #import "kryon/button";
Scroll :: #import "kryon/scroll";
Text :: #import "kryon/text";
TextField :: #import "kryon/text_field";
#import "kryon/app_context"
#import "kryon/app_protocol"
#import "kryon/control_props"
#import "kryon/drawing_props"
#import "kryon/geometry"
#import "kryon/session"
#import "kryon/text_align"
#import "kryon/tree"
#import "std/number_text"
#import "std/text_buffer"
#import "std/vec"
// Performance gauge vector shape (MingCute-style 24x24).
ICON_SHAPE :: "M12 4a9 9 0 0 0-9 9c0 2.75 1.24 5.21 3.18 6.86a1 1 0 0 0 1.3-.06l1.06-1.06a1 1 0 0 0-.06-1.47A6.98 6.98 0 0 1 5 13a7 7 0 1 1 14 0c0 1.66-.58 3.19-1.55 4.38a1 1 0 0 0-.06 1.36l1.06 1.06a1 1 0 0 0 1.38.07A8.96 8.96 0 0 0 21 13a9 9 0 0 0-9-9zm3.54 5.46a1 1 0 0 0-1.42 0l-2.83 2.83a1.5 1.5 0 1 0 1.42 1.42l2.83-2.83a1 1 0 0 0 0-1.42z";
TAB_PROCESSES :: 0;
TAB_PERFORMANCE :: 1;
COL_NAME :: 0;
COL_PID :: 1;
COL_CPU :: 2;
COL_TIME :: 3;
COL_MEMORY :: 4;
MAX_ROWS :: 160;
MAX_HISTORY :: 60;
Row :: struct {
pid: s32
group_count: s32
cpu_x10: s32
memory_bytes: u64
ticks: u64
threads: s32
state: [16]u8
name: [40]u8
}
FieldState :: struct {
cursor: s32
anchor: s32
scroll_x: s32
}
session: Session;
current_tab: s32 = TAB_PROCESSES;
sort_col: s32 = COL_CPU;
sort_desc: bool = true;
grouped: bool = true;
refresh_interval: float64 = 1.0;
last_refresh: float64 = -10.0;
force_refresh: bool = true;
need_query: bool = true;
scroll_y: s32;
unsupported: bool;
unsupported_reason: [160]u8;
processes_available: bool;
cpu_available: bool;
memory_available: bool;
total_processes: s32;
cpu_x10: s32;
kernel_x10: s32;
mem_used: u64;
mem_total: u64;
total_threads: s64;
total_handles: s64;
commit_kb: s64;
commit_limit_kb: s64;
commit_peak_kb: s64;
avail_kb: s64;
cache_kb: s64;
kpaged_kb: s64;
knonpaged_kb: s64;
swap_total_kb: s64;
swap_free_kb: s64;
self_pid: s32;
cpu_hist: [MAX_HISTORY]s32;
cpu_hist_count: s32;
kern_hist: [MAX_HISTORY]s32;
kern_hist_count: s32;
mem_hist: [MAX_HISTORY]s32;
mem_hist_count: s32;
rows: [MAX_ROWS]Row;
row_count: s32;
selected_pid: s32 = -1;
selected_name: [40]u8;
selected_group_count: s32;
confirm_end: bool;
run_dialog: bool;
status_msg: [128]u8;
filter_text: [96]u8;
filter_field: FieldState;
run_text: [256]u8;
run_field: FieldState;
focused_field: s32; // 0 none, 1 filter, 2 run
CopyText :: (dst: []u8, src: string) {
limit := src.count
if limit >= dst.count { limit = dst.count - 1 }
for index: 0..limit - 1 { dst[index] = src[index] }
dst[limit] = cast(u8)0
}
AppendStr :: (dst: []u8, used: s32, text: string) -> s32 {
pos := used
for index: 0..text.count - 1 {
if pos >= cast(s32)dst.count - 1 { break }
dst[pos] = text[index]
pos += 1
}
dst[pos] = cast(u8)0
return pos
}
AppendInt :: (dst: []u8, used: s32, value: s64) -> s32 {
num: [32]u8
return AppendStr(dst, used, FormatInteger(value, num[:]))
}
ParseS64 :: (text: string) -> s64 {
if text.count == 0 { return 0 }
neg := false
index: s64 = 0
if text[0] == cast(u8)45 { neg = true; index = 1 }
value: s64 = 0
while index < text.count {
ch := text[index]
if ch < cast(u8)48 || ch > cast(u8)57 { break }
value = value * 10 + cast(s64)(ch - cast(u8)48)
index += 1
}
return ifx neg then 0 - value else value
}
ParseU64 :: (text: string) -> u64 {
value: u64 = 0
for index: 0..text.count - 1 {
ch := text[index]
if ch < cast(u8)48 || ch > cast(u8)57 { break }
value = value * cast(u64)10 + cast(u64)(ch - cast(u8)48)
}
return value
}
NextToken :: (line: string, cursor: *s64) -> string {
start := cursor.*
if start >= line.count { return "" }
pos := start
while pos < line.count && line[pos] != cast(u8)9 { pos += 1 }
cursor.* = ifx pos < line.count then pos + 1 else pos
return line[start:pos]
}
WriteQuoted :: (bytes: *Vec(u8), text: string) {
BuilderPrint(bytes, "\"")
for byte: text {
if byte == cast(u8)34 || byte == cast(u8)92 { BuilderPrint(bytes, "\\") }
if byte >= cast(u8)32 { unused VecPush(bytes.*, byte) }
}
BuilderPrint(bytes, "\"")
}
FormatTenths :: (tenths: s32, out: []u8) -> string {
whole := tenths / 10
frac := tenths % 10
if frac < 0 { frac = 0 - frac }
used := AppendInt(out, 0, cast(s64)whole)
used = AppendStr(out, used, ".")
used = AppendInt(out, used, cast(s64)frac)
used = AppendStr(out, used, "%")
return TextView(out[:used])
}
FormatBytesShort :: (bytes: u64, out: []u8) -> string {
if bytes >= cast(u64)1073741824 {
tenths := (bytes * cast(u64)10) / cast(u64)1073741824
used := AppendInt(out, 0, cast(s64)(tenths / cast(u64)10))
used = AppendStr(out, used, ".")
used = AppendInt(out, used, cast(s64)(tenths % cast(u64)10))
used = AppendStr(out, used, " GiB")
return TextView(out[:used])
}
if bytes >= cast(u64)1048576 {
tenths := (bytes * cast(u64)10) / cast(u64)1048576
used := AppendInt(out, 0, cast(s64)(tenths / cast(u64)10))
used = AppendStr(out, used, ".")
used = AppendInt(out, used, cast(s64)(tenths % cast(u64)10))
used = AppendStr(out, used, " MiB")
return TextView(out[:used])
}
kb := bytes / cast(u64)1024
used := AppendInt(out, 0, cast(s64)kb)
used = AppendStr(out, used, " KiB")
return TextView(out[:used])
}
ParseHistoryLine :: (line: string, target: []s32) -> s32 {
cursor: s64 = 0
unused NextToken(line, *cursor)
count: s32 = 0
while cursor < line.count && count < cast(s32)target.count {
tok := NextToken(line, *cursor)
if tok.count == 0 { break }
target[count] = cast(s32)ParseS64(tok)
count += 1
}
return count
}
ParseSnapshot :: (reply: string) {
row_count = 0
unsupported = false
pos: s64 = 0
while pos < reply.count {
end := pos
while end < reply.count && reply[end] != cast(u8)10 { end += 1 }
line := reply[pos:end]
pos = ifx end < reply.count then end + 1 else end
if line.count == 0 { continue }
cursor: s64 = 0
tag := NextToken(line, *cursor)
if tag == "unsupported" {
unsupported = true
CopyText(unsupported_reason[:], NextToken(line, *cursor))
return
}
if tag == "ok" {
processes_available = ParseS64(NextToken(line, *cursor)) != 0
cpu_available = ParseS64(NextToken(line, *cursor)) != 0
memory_available = ParseS64(NextToken(line, *cursor)) != 0
total_processes = cast(s32)ParseS64(NextToken(line, *cursor))
cpu_x10 = cast(s32)ParseS64(NextToken(line, *cursor))
kernel_x10 = cast(s32)ParseS64(NextToken(line, *cursor))
mem_used = ParseU64(NextToken(line, *cursor))
mem_total = ParseU64(NextToken(line, *cursor))
total_threads = ParseS64(NextToken(line, *cursor))
total_handles = ParseS64(NextToken(line, *cursor))
commit_kb = ParseS64(NextToken(line, *cursor))
commit_limit_kb = ParseS64(NextToken(line, *cursor))
commit_peak_kb = ParseS64(NextToken(line, *cursor))
avail_kb = ParseS64(NextToken(line, *cursor))
cache_kb = ParseS64(NextToken(line, *cursor))
kpaged_kb = ParseS64(NextToken(line, *cursor))
knonpaged_kb = ParseS64(NextToken(line, *cursor))
swap_total_kb = ParseS64(NextToken(line, *cursor))
swap_free_kb = ParseS64(NextToken(line, *cursor))
self_pid = cast(s32)ParseS64(NextToken(line, *cursor))
continue
}
if tag == "cpu" { cpu_hist_count = ParseHistoryLine(line, cpu_hist[:]); continue }
if tag == "kern" { kern_hist_count = ParseHistoryLine(line, kern_hist[:]); continue }
if tag == "mem" { mem_hist_count = ParseHistoryLine(line, mem_hist[:]); continue }
if tag == "p" && row_count < MAX_ROWS {
item := *rows[row_count]
item.* = Row.{}
item.pid = cast(s32)ParseS64(NextToken(line, *cursor))
item.group_count = cast(s32)ParseS64(NextToken(line, *cursor))
item.cpu_x10 = cast(s32)ParseS64(NextToken(line, *cursor))
item.memory_bytes = ParseU64(NextToken(line, *cursor))
item.ticks = ParseU64(NextToken(line, *cursor))
item.threads = cast(s32)ParseS64(NextToken(line, *cursor))
CopyText(item.state[:], NextToken(line, *cursor))
CopyText(item.name[:], NextToken(line, *cursor))
row_count += 1
}
}
// Keep selection coherent with updated rows.
if selected_pid >= 0 {
found := false
for index: 0..row_count - 1 {
if rows[index].pid == selected_pid {
CopyText(selected_name[:], TextUntilNul(rows[index].name[:]))
selected_group_count = rows[index].group_count
found = true
break
}
}
if !found {
selected_pid = -1
selected_name[0] = cast(u8)0
selected_group_count = 0
confirm_end = false
}
}
}
QuerySnapshot :: (refresh: bool) {
bytes: Vec(u8)
BuilderPrint(*bytes, "{\"op\":\"snapshot\",\"sort\":%,\"desc\":%,\"grouped\":%,\"refresh\":%,\"filter\":",
sort_col, ifx sort_desc then 1 else 0, ifx grouped then 1 else 0, ifx refresh then 1 else 0)
WriteQuoted(*bytes, TextUntilNul(filter_text[:]))
BuilderPrint(*bytes, "}")
reply: string
{
request := TextView(VecSlice(bytes, 0, bytes.count))
reply = AppService("taskmgr.v1", request)
}
VecFree(bytes)
ParseSnapshot(reply)
}
SendEndSelected :: () {
if selected_pid < 0 { return }
bytes: Vec(u8)
if grouped && selected_group_count > 1 {
BuilderPrint(*bytes, "{\"op\":\"end_group\",\"name\":")
WriteQuoted(*bytes, TextUntilNul(selected_name[:]))
BuilderPrint(*bytes, "}")
} else {
BuilderPrint(*bytes, "{\"op\":\"end_pid\",\"pid\":%}", selected_pid)
}
reply: string
{
reply = AppService("taskmgr.v1", TextView(VecSlice(bytes, 0, bytes.count)))
}
VecFree(bytes)
cursor: s64 = 0
unused NextToken(reply, *cursor)
msg := NextToken(reply, *cursor)
// Trim trailing newline.
if msg.count > 0 && msg[msg.count - 1] == cast(u8)10 { msg = msg[:msg.count - 1] }
CopyText(status_msg[:], msg)
confirm_end = false
force_refresh = true
}
SendRunCommand :: () {
bytes: Vec(u8)
{
cmd := TextUntilNul(run_text[:])
if cmd.count == 0 {
CopyText(status_msg[:], "Enter a command to run")
return
}
BuilderPrint(*bytes, "{\"op\":\"run\",\"command\":")
WriteQuoted(*bytes, cmd)
BuilderPrint(*bytes, "}")
}
reply: string
{
reply = AppService("taskmgr.v1", TextView(VecSlice(bytes, 0, bytes.count)))
}
VecFree(bytes)
cursor: s64 = 0
unused NextToken(reply, *cursor)
msg := NextToken(reply, *cursor)
if msg.count > 0 && msg[msg.count - 1] == cast(u8)10 { msg = msg[:msg.count - 1] }
CopyText(status_msg[:], msg)
run_text[0] = cast(u8)0
run_field = FieldState.{}
run_dialog = false
focused_field = 0
force_refresh = true
}
ApplyEdit :: (buffer: []u8, edit: TextField.Edit) -> bool {
if !edit.changed { return false }
length := cast(s32)TextUntilNul(buffer).count
if edit.start < 0 || edit.end < edit.start || edit.end > length { return false }
used := length - (edit.end - edit.start) + cast(s32)edit.replacement.count
if used >= cast(s32)buffer.count || used >= 512 { return false }
next: [512]u8
pos: s32 = 0
for i: 0..edit.start - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)edit.replacement.count - 1 { next[pos] = edit.replacement[i]; pos += 1 }
for i: edit.end..length - 1 { next[pos] = buffer[i]; pos += 1 }
for i: 0..cast(s32)buffer.count - 1 {
buffer[i] = ifx i < used then next[i] else cast(u8)0
}
return true
}
DrawField :: (id: s32, label: string, buffer: []u8, state: *FieldState, bounds: Rectangle) -> bool {
snapshot: [512]u8
CopyText(snapshot[:], TextUntilNul(buffer))
props: TextField.Props
props.key = cast(u64)(600 + id)
props.focus_id = 600 + id
props.bounds = bounds
props.label = label
props.value = TextUntilNul(snapshot[:])
props.cursor = state.cursor
props.anchor = state.anchor
props.scroll_x = state.scroll_x
props.focused = focused_field == id
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
if props.focused { props.input = AppFieldInput() }
result := TextField.Draw(session, props)
state.cursor = result.cursor
state.anchor = result.anchor
state.scroll_x = result.scroll_x
changed := ApplyEdit(buffer, result.edit)
if result.focused { focused_field = id }
if result.escaped && focused_field == id { focused_field = 0 }
return changed
}
Action :: (id: s32, label: string, bounds: Rectangle, accent: bool, disabled: bool) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.disabled = disabled
props.size = ControlSize.ControlSizeSmall
props.tone = ifx accent then ButtonTone.ButtonToneAccent else ButtonTone.ButtonToneNeutral
props.emphasis = ifx accent then ButtonEmphasis.ButtonEmphasisFilled else ButtonEmphasis.ButtonEmphasisSoft
return Button.Draw(session, props) != 0
}
DangerAction :: (id: s32, label: string, bounds: Rectangle, disabled: bool) -> bool {
props: Button.Props
props.key = cast(u64)id
props.id = id
props.bounds = bounds
props.label = label
props.disabled = disabled
props.size = ControlSize.ControlSizeSmall
props.tone = ButtonTone.ButtonToneDanger
props.emphasis = ButtonEmphasis.ButtonEmphasisFilled
return Button.Draw(session, props) != 0
}
DrawText :: (key: u64, value: string, bounds: Rectangle, size: s32, align: TextAlign) {
Text.Draw(session, Text.Props.{.key = key, .bounds = bounds, .text = value, .size = size,
.align = align, .wrap = Text.Wrap.TextWrapEllipsis})
}
DrawGraph :: (base_key: u64, title: string, value_text: string, samples: []s32, count: s32,
bounds: Rectangle, bar_color: Color, secondary: []s32, secondary_count: s32) {
dark := AppDark()
bg := ifx dark then Color.{33, 36, 43, 255} else Color.{242, 245, 250, 255}
border := ifx dark then Color.{66, 71, 87, 255} else Color.{209, 217, 230, 255}
track := ifx dark then Color.{46, 51, 61, 255} else Color.{227, 232, 242, 255}
Box.Draw(session, Box.Props.{.key = base_key, .bounds = bounds, .fill = bg, .border = border, .radius = 8.0})
DrawText(base_key + 1, title, Rectangle.{bounds.x + 10.0, bounds.y + 6.0, bounds.width * 0.6, 20.0}, 14, TextAlign.TextAlignStart)
DrawText(base_key + 2, value_text, Rectangle.{bounds.x + bounds.width * 0.55, bounds.y + 6.0, bounds.width * 0.45 - 10.0, 20.0}, 14, TextAlign.TextAlignEnd)
plot := Rectangle.{bounds.x + 10.0, bounds.y + 30.0, bounds.width - 20.0, bounds.height - 40.0}
if plot.height < 24.0 || plot.width < 40.0 { return }
Box.Draw(session, Box.Props.{.key = base_key + 3, .bounds = plot, .fill = track, .radius = 4.0})
if count <= 0 { return }
slot_w := plot.width / cast(float32)MAX_HISTORY
offset := MAX_HISTORY - count
for i: 0..count - 1 {
pct := cast(float32)samples[i] / 1000.0
if pct < 0.0 { pct = 0.0 }
if pct > 1.0 { pct = 1.0 }
h := plot.height * pct
if h < 1.5 && samples[i] > 0 { h = 1.5 }
x := plot.x + cast(float32)(offset + i) * slot_w
w := ifx slot_w > 1.5 then slot_w - 0.5 else slot_w
if h > 0.0 {
Box.Draw(session, Box.Props.{.key = base_key + 10 + cast(u64)i,
.bounds = Rectangle.{x, plot.y + plot.height - h, w, h}, .fill = bar_color})
}
if i < secondary_count && secondary[i] > 0 {
spct := cast(float32)secondary[i] / 1000.0
if spct > 1.0 { spct = 1.0 }
sh := plot.height * spct
if sh > 0.0 {
Box.Draw(session, Box.Props.{.key = base_key + 90 + cast(u64)i,
.bounds = Rectangle.{x, plot.y + plot.height - sh, w, sh},
.fill = Color.{217, 77, 71, 216}})
}
}
}
}
ToggleSort :: (column: s32) {
if sort_col == column {
sort_desc = !sort_desc
} else {
sort_col = column
sort_desc = column != COL_NAME
}
need_query = true
}
DrawProcesses :: (area: Rectangle) {
// Filter + Controls row.
top_y := area.y
filter_w := area.width - 172.0
if filter_w < 100.0 { filter_w = area.width }
if DrawField(1, "Filter processes...", filter_text[:], *filter_field,
Rectangle.{area.x, top_y, filter_w, 36.0}) {
scroll_y = 0
need_query = true
}
if filter_w < area.width {
if Action(20, ifx grouped then "Grouped" else "All PIDs",
Rectangle.{area.x + filter_w + 6.0, top_y, 82.0, 36.0}, grouped, false) {
grouped = !grouped
scroll_y = 0
need_query = true
}
if Action(21, "Refresh",
Rectangle.{area.x + filter_w + 94.0, top_y, 78.0, 36.0}, false, false) {
force_refresh = true
}
}
// Sort header row.
header_y := top_y + 42.0
col_name_w := area.width * 0.44
col_pid_w := area.width * 0.16
col_cpu_w := area.width * 0.16
col_mem_w := area.width - col_name_w - col_pid_w - col_cpu_w - 12.0
if Action(30, ifx sort_col == COL_NAME then (ifx sort_desc then "Name v" else "Name ^") else "Name",
Rectangle.{area.x, header_y, col_name_w, 28.0}, sort_col == COL_NAME, false) {
ToggleSort(COL_NAME)
}
if Action(31, ifx sort_col == COL_PID then (ifx sort_desc then "PID v" else "PID ^") else "PID",
Rectangle.{area.x + col_name_w + 4.0, header_y, col_pid_w, 28.0}, sort_col == COL_PID, false) {
ToggleSort(COL_PID)
}
if Action(32, ifx sort_col == COL_CPU then (ifx sort_desc then "CPU v" else "CPU ^") else "CPU",
Rectangle.{area.x + col_name_w + col_pid_w + 8.0, header_y, col_cpu_w, 28.0}, sort_col == COL_CPU, false) {
ToggleSort(COL_CPU)
}
if Action(33, ifx sort_col == COL_MEMORY then (ifx sort_desc then "Mem v" else "Mem ^") else "Mem",
Rectangle.{area.x + col_name_w + col_pid_w + col_cpu_w + 12.0, header_y, col_mem_w, 28.0}, sort_col == COL_MEMORY, false) {
ToggleSort(COL_MEMORY)
}
// Bottom action bar height.
footer_h: float32 = ifx confirm_end || run_dialog then 86.0 else 44.0
list_y := header_y + 34.0
list_h := area.y + area.height - list_y - footer_h - 6.0
if list_h < 60.0 { list_h = 60.0 }
list_bounds := Rectangle.{area.x, list_y, area.width, list_h}
row_h: float32 = 34.0
content_h := cast(s32)(cast(float32)row_count * row_h) + 8
if content_h < cast(s32)list_h { content_h = cast(s32)list_h }
scroll := Scroll.Draw(session, Scroll.Props.{.key = 700, .bounds = list_bounds,
.scroll_offset = scroll_y, .content_height = content_h, .scale = 1.0})
scroll_y = scroll.scroll_offset
if scroll.opened {
dark := AppDark()
alt_bg := ifx dark then Color.{38, 41, 48, 255} else Color.{245, 247, 252, 255}
sel_bg := ifx dark then Color.{46, 77, 122, 255} else Color.{214, 230, 250, 255}
cw := scroll.content.width - 10.0
for i: 0..row_count - 1 {
y := scroll.content.y + cast(float32)i * row_h
item := rows[i]
is_sel := item.pid == selected_pid
if is_sel || (i % 2 == 1) {
Box.Draw(session, Box.Props.{.key = cast(u64)(2000 + i * 8),
.bounds = Rectangle.{scroll.content.x, y, cw, row_h - 2.0},
.fill = ifx is_sel then sel_bg else alt_bg, .radius = 4.0})
}
name_buf: [56]u8
used := AppendStr(name_buf[:], 0, TextUntilNul(item.name[:]))
if grouped && item.group_count > 1 {
used = AppendStr(name_buf[:], used, " (")
used = AppendInt(name_buf[:], used, cast(s64)item.group_count)
used = AppendStr(name_buf[:], used, ")")
}
if Action(3000 + cast(s32)i, TextView(name_buf[:used]),
Rectangle.{scroll.content.x + 2.0, y + 2.0, col_name_w - 4.0, row_h - 6.0}, is_sel, false) {
selected_pid = item.pid
CopyText(selected_name[:], TextUntilNul(item.name[:]))
selected_group_count = item.group_count
confirm_end = false
}
pid_buf: [16]u8
cpu_buf: [16]u8
mem_buf: [20]u8
DrawText(cast(u64)(2000 + i * 8 + 1), FormatInteger(cast(s64)item.pid, pid_buf[:]),
Rectangle.{scroll.content.x + col_name_w + 4.0, y + 7.0, col_pid_w, 20.0}, 13, TextAlign.TextAlignEnd)
DrawText(cast(u64)(2000 + i * 8 + 2), FormatTenths(item.cpu_x10, cpu_buf[:]),
Rectangle.{scroll.content.x + col_name_w + col_pid_w + 8.0, y + 7.0, col_cpu_w, 20.0}, 13, TextAlign.TextAlignEnd)
DrawText(cast(u64)(2000 + i * 8 + 3), FormatBytesShort(item.memory_bytes, mem_buf[:]),
Rectangle.{scroll.content.x + col_name_w + col_pid_w + col_cpu_w + 12.0, y + 7.0, col_mem_w - 14.0, 20.0}, 13, TextAlign.TextAlignEnd)
}
End(session)
}
// Footer actions / confirmation / run bar.
foot_y := list_y + list_h + 6.0
if confirm_end && selected_pid >= 0 {
prompt_buf: [96]u8
used := AppendStr(prompt_buf[:], 0, "End ")
used = AppendStr(prompt_buf[:], used, TextUntilNul(selected_name[:]))
if grouped && selected_group_count > 1 {
used = AppendStr(prompt_buf[:], used, " group?")
} else {
used = AppendStr(prompt_buf[:], used, " (PID ")
used = AppendInt(prompt_buf[:], used, cast(s64)selected_pid)
used = AppendStr(prompt_buf[:], used, ")?")
}
DrawText(810, TextView(prompt_buf[:used]), Rectangle.{area.x, foot_y, area.width, 24.0}, 14, TextAlign.TextAlignStart)
if DangerAction(42, "Confirm End", Rectangle.{area.x, foot_y + 30.0, 130.0, 36.0}, false) {
SendEndSelected()
}
if Action(43, "Cancel", Rectangle.{area.x + 138.0, foot_y + 30.0, 96.0, 36.0}, false, false) {
confirm_end = false
}
} else if run_dialog {
unused DrawField(2, "Command to run...", run_text[:], *run_field,
Rectangle.{area.x, foot_y, area.width, 36.0})
if Action(44, "Start", Rectangle.{area.x, foot_y + 42.0, 96.0, 34.0}, true, false) {
SendRunCommand()
}
if Action(45, "Cancel", Rectangle.{area.x + 104.0, foot_y + 42.0, 96.0, 34.0}, false, false) {
run_dialog = false
focused_field = 0
}
} else {
can_end := selected_pid > 0 && selected_pid != self_pid
if DangerAction(40, ifx grouped && selected_group_count > 1 then "End Group" else "End Task",
Rectangle.{area.x, foot_y, 118.0, 36.0}, !can_end) {
confirm_end = true
}
if Action(41, "New Task", Rectangle.{area.x + 126.0, foot_y, 102.0, 36.0}, false, false) {
run_dialog = true
focused_field = 2
}
msg := TextUntilNul(status_msg[:])
if msg.count > 0 {
DrawText(811, msg, Rectangle.{area.x + 236.0, foot_y + 8.0, area.width - 236.0, 22.0}, 12, TextAlign.TextAlignEnd)
}
}
}
DrawStatCard :: (base_key: u64, title: string, lines: []string, bounds: Rectangle) {
dark := AppDark()
bg := ifx dark then Color.{33, 36, 43, 255} else Color.{242, 245, 250, 255}
border := ifx dark then Color.{66, 71, 87, 255} else Color.{209, 217, 230, 255}
Box.Draw(session, Box.Props.{.key = base_key, .bounds = bounds, .fill = bg, .border = border, .radius = 8.0})
DrawText(base_key + 1, title, Rectangle.{bounds.x + 10.0, bounds.y + 8.0, bounds.width - 20.0, 20.0}, 14, TextAlign.TextAlignStart)
for i: 0..lines.count - 1 {
DrawText(base_key + 2 + cast(u64)i, lines[i],
Rectangle.{bounds.x + 10.0, bounds.y + 32.0 + cast(float32)i * 20.0, bounds.width - 20.0, 18.0}, 13, TextAlign.TextAlignStart)
}
}
DrawPerformance :: (area: Rectangle) {
// Update speed selector row.
speed_w := (area.width - 18.0) / 4.0
if Action(50, "High", Rectangle.{area.x, area.y, speed_w, 30.0}, refresh_interval == 0.5, false) { refresh_interval = 0.5 }
if Action(51, "Normal", Rectangle.{area.x + speed_w + 6.0, area.y, speed_w, 30.0}, refresh_interval == 1.0, false) { refresh_interval = 1.0 }
if Action(52, "Low", Rectangle.{area.x + (speed_w + 6.0) * 2.0, area.y, speed_w, 30.0}, refresh_interval == 4.0, false) { refresh_interval = 4.0 }
if Action(53, "Paused", Rectangle.{area.x + (speed_w + 6.0) * 3.0, area.y, speed_w, 30.0}, refresh_interval == 0.0, false) { refresh_interval = 0.0 }
graph_y := area.y + 38.0
graph_h: float32 = 126.0
cpu_val: [24]u8
mem_val: [48]u8
mem_u: [20]u8
mem_t: [20]u8
used_m := AppendStr(mem_val[:], 0, FormatBytesShort(mem_used, mem_u[:]))
used_m = AppendStr(mem_val[:], used_m, " / ")
used_m = AppendStr(mem_val[:], used_m, FormatBytesShort(mem_total, mem_t[:]))
DrawGraph(900, "CPU Usage", FormatTenths(cpu_x10, cpu_val[:]), cpu_hist[:], cpu_hist_count,
Rectangle.{area.x, graph_y, area.width, graph_h}, Color.{51, 148, 230, 230},
kern_hist[:], kern_hist_count)
DrawGraph(1100, "Memory Usage", TextView(mem_val[:used_m]), mem_hist[:], mem_hist_count,
Rectangle.{area.x, graph_y + graph_h + 10.0, area.width, graph_h}, Color.{56, 173, 115, 230},
mem_hist[:0], 0)
cards_y := graph_y + (graph_h + 10.0) * 2.0
card_w := (area.width - 10.0) * 0.5
card_h: float32 = 122.0
l1: [48]u8; l2: [48]u8; l3: [48]u8; l4: [48]u8
u1 := AppendStr(l1[:], 0, "Processes: "); u1 = AppendInt(l1[:], u1, cast(s64)total_processes)
u2 := AppendStr(l2[:], 0, "Threads: "); u2 = AppendInt(l2[:], u2, total_threads)
u3 := AppendStr(l3[:], 0, "Handles: ")
if total_handles >= 0 { u3 = AppendInt(l3[:], u3, total_handles) } else { u3 = AppendStr(l3[:], u3, "n/a") }
kbuf: [16]u8
u4 := AppendStr(l4[:], 0, "Kernel CPU: "); u4 = AppendStr(l4[:], u4, FormatTenths(kernel_x10, kbuf[:]))
sys_lines: [4]string = .[TextView(l1[:u1]), TextView(l2[:u2]), TextView(l3[:u3]), TextView(l4[:u4])]
DrawStatCard(1300, "System", sys_lines[:], Rectangle.{area.x, cards_y, card_w, card_h})
m1: [48]u8; m2: [48]u8; m3: [48]u8; m4: [48]u8
b1: [20]u8; b2: [20]u8; b3: [20]u8; b4: [20]u8
mu1 := AppendStr(m1[:], 0, "Available: "); mu1 = AppendStr(m1[:], mu1, FormatBytesShort(cast(u64)avail_kb * 1024, b1[:]))
mu2 := AppendStr(m2[:], 0, "Cached: "); mu2 = AppendStr(m2[:], mu2, FormatBytesShort(cast(u64)cache_kb * 1024, b2[:]))
mu3 := AppendStr(m3[:], 0, "Commit: "); mu3 = AppendStr(m3[:], mu3, FormatBytesShort(cast(u64)commit_kb * 1024, b3[:]))
swap_used := ifx swap_total_kb > swap_free_kb then swap_total_kb - swap_free_kb else 0
mu4 := AppendStr(m4[:], 0, "Swap: "); mu4 = AppendStr(m4[:], mu4, FormatBytesShort(cast(u64)swap_used * 1024, b4[:]))
mem_lines: [4]string = .[TextView(m1[:mu1]), TextView(m2[:mu2]), TextView(m3[:mu3]), TextView(m4[:mu4])]
DrawStatCard(1320, "Memory", mem_lines[:], Rectangle.{area.x + card_w + 10.0, cards_y, card_w, card_h})
}
DrawStatusBar :: (bounds: Rectangle) {
dark := AppDark()
bg := ifx dark then Color.{31, 33, 41, 255} else Color.{237, 240, 245, 255}
Box.Draw(session, Box.Props.{.key = 1400, .bounds = bounds, .fill = bg, .radius = 4.0})
buf: [128]u8
cpu_b: [16]u8
mu_b: [20]u8
mt_b: [20]u8
used := AppendStr(buf[:], 0, "Processes: ")
used = AppendInt(buf[:], used, cast(s64)total_processes)
used = AppendStr(buf[:], used, " | CPU: ")
used = AppendStr(buf[:], used, FormatTenths(cpu_x10, cpu_b[:]))
used = AppendStr(buf[:], used, " | Mem: ")
used = AppendStr(buf[:], used, FormatBytesShort(mem_used, mu_b[:]))
used = AppendStr(buf[:], used, " / ")
used = AppendStr(buf[:], used, FormatBytesShort(mem_total, mt_b[:]))
DrawText(1401, TextView(buf[:used]),
Rectangle.{bounds.x + 8.0, bounds.y + 4.0, bounds.width - 16.0, bounds.height - 6.0}, 12, TextAlign.TextAlignStart)
}
Draw :: () {
session = AppSession()
bounds := AppBounds()
if !AppSupports("taskmgr.v1") {
DrawText(1, "Update Werkzeug to open Task Manager.",
Rectangle.{bounds.x + 16.0, bounds.y + 24.0, bounds.width - 32.0, 28.0}, 16, TextAlign.TextAlignStart)
return
}
now := AppNow()
due := refresh_interval > 0.0 && (now - last_refresh >= refresh_interval || now < last_refresh)
if force_refresh || due {
QuerySnapshot(true)
last_refresh = now
force_refresh = false
need_query = false
} else if need_query {
QuerySnapshot(false)
need_query = false
}
if unsupported {
DrawText(2, TextUntilNul(unsupported_reason[:]),
Rectangle.{bounds.x + 16.0, bounds.y + 24.0, bounds.width - 32.0, 48.0}, 15, TextAlign.TextAlignStart)
return
}
pad: float32 = 12.0
area := Rectangle.{bounds.x + pad, bounds.y + 8.0, bounds.width - pad * 2.0, bounds.height - 16.0}
tab_w := (area.width - 8.0) * 0.5
if Action(10, "Processes", Rectangle.{area.x, area.y, tab_w, 34.0}, current_tab == TAB_PROCESSES, false) {
current_tab = TAB_PROCESSES
}
if Action(11, "Performance", Rectangle.{area.x + tab_w + 8.0, area.y, tab_w, 34.0}, current_tab == TAB_PERFORMANCE, false) {
current_tab = TAB_PERFORMANCE
}
status_h: float32 = 26.0
body := Rectangle.{area.x, area.y + 42.0, area.width, area.height - 42.0 - status_h - 6.0}
if current_tab == TAB_PROCESSES {
DrawProcesses(body)
} else {
DrawPerformance(body)
}
DrawStatusBar(Rectangle.{area.x, area.y + area.height - status_h, area.width, status_h})
AppKeyboard(focused_field != 0)
}
#scope_export
#program_export
Main :: () -> s32 {
mode := AppMode()
if mode == APP_IDENTIFY {
AppIdentity("taskmgr", 1)
AppDescribe("Task Manager", ICON_SHAPE)
return APP_PROTOCOL
}
if mode == APP_FRAME {
Draw()
}
return 0
}
+5 -2
View File
@@ -1,8 +1,11 @@
using UI :: #import "Widgets";
Text :: #import "kryon/text";
#import "kryon/geometry"
#import "kryon/session"
#import "std/byte_text_linux"
using SharedLayout :: #import "kryon/PageLayout";
Label :: (session: Session, key: s32, text: string, bounds: Rectangle, font: s32) {
Text(session, TextProps.{.key = cast(u64)key, .bounds = bounds, .text = text, .font = font})
Text.Draw(session, Text.Props.{.key = cast(u64)key, .bounds = bounds, .text = text, .size = font})
}
// Concatenates PARTS into OUTPUT, which the caller owns; the returned string
+159 -184
View File
@@ -6,143 +6,19 @@
using Files :: #import "std/file";
Number :: #import "std/number_text";
libc :: #system_library "libc";
SysConf :: (name: s32) -> s64 #foreign libc "sysconf";
SendSignal :: (pid: s32, signal: s32) -> s32 #foreign libc "kill";
ProcessId :: () -> s32 #foreign libc "getpid";
RunShell :: (command: *u8) -> s32 #foreign libc "system";
using Platform :: #import "task_platform";
CLOCK_TICKS_NAME :: 2; // _SC_CLK_TCK
PAGE_SIZE_NAME :: 30; // _SC_PAGESIZE
STOP_SIGNAL :: 15; // SIGTERM
// Keep the fixed snapshot bounded, but large enough for development hosts and
// servers with several thousand visible processes. A lower cap silently hid
// rows (including taskmgr's own test process) once /proc exceeded 1,024 PIDs.
// Two thousand entries retain that headroom on the development host (which
// runs roughly 1,400 processes) without keeping unused process and UI rows in
// every retained generation.
MAX_PROCESSES :: 2048;
// Linux TASK_COMM_LEN is 16 including the terminator. Keep extra room for
// synthetic group labels without doubling every process snapshot row.
NAME_CAPACITY :: 32;
COLUMNS :: 5;
COMMAND_CAPACITY :: 1024;
// Process table columns, in the classic task manager order.
COLUMN_NAME :: 0;
COLUMN_PID :: 1;
COLUMN_CPU :: 2;
COLUMN_CPU_TIME :: 3;
COLUMN_MEMORY :: 4;
// Samples kept for each Performance graph; one is taken per refresh.
HISTORY_LENGTH :: 60;
HISTORY_CPU :: 0;
HISTORY_KERNEL :: 1;
HISTORY_MEMORY :: 2;
HISTORY_GPU :: 3;
HISTORY_VRAM :: 4;
MAX_GPUS :: 16;
GPU_CARD_LIMIT :: 64;
STATE_RUNNING :: 82; // R
STATE_SLEEPING :: 83; // S
STATE_WAITING :: 68; // D
STATE_STOPPED :: 84; // T
STATE_ZOMBIE :: 90; // Z
STATE_IDLE :: 73; // I
Process :: struct {
pid: s32
name_count: s32
name: [NAME_CAPACITY]u8
state: u8
// Parent PID from /proc/<pid>/stat field 4; it sits in the padding before
// cpu_percent, so the snapshot row does not grow.
ppid: s32
cpu_percent: float64
memory_bytes: u64
ticks: u64
threads: s32
// One for a raw process; more than one for an aggregated process group.
group_count: s32
}
GroupEndResult :: struct {
requested: s32
sent: s32
failed: s32
}
// Memory figures from /proc/meminfo, in kilobytes as the kernel reports them.
// Commit charge is Committed_AS against CommitLimit; kernel memory is the slab
// allocator, split into reclaimable (paged) and unreclaimable (nonpaged).
MemoryDetails :: struct {
total_kb: s64
available_kb: s64
cache_kb: s64
commit_kb: s64
commit_limit_kb: s64
kernel_paged_kb: s64
kernel_nonpaged_kb: s64
swap_total_kb: s64
swap_free_kb: s64
}
// One stable DRM card. card_index comes from cardN, so labels and histories do
// not change when directory enumeration order does. Unsupported counters stay
// explicit instead of looking like 0% or 100% usage.
GpuDevice :: struct {
card_index: s32
busy_supported: bool
busy_percent: float64
vram_supported: bool
vram_used: u64
vram_total: u64
}
Snapshot :: struct {
processes: [MAX_PROCESSES]Process
count: s32
cpu_percent: float64
kernel_percent: float64
memory_used: u64
memory_total: u64
busy_ticks: u64
kernel_ticks: u64
total_ticks: u64
threads: s64
// Allocated file handles from /proc/sys/fs/file-nr, or -1.
handles: s64
memory: MemoryDetails
gpu_percent: float64
gpus: [MAX_GPUS]GpuDevice
gpu_count: s32
gpu_supported_count: s32
vram_used: u64
vram_total: u64
}
// Group rows retain only the representative raw-process index and the values
// that are actually aggregated for the process table. Keeping a third full
// Snapshot duplicated every process name, state and GPU/system field.
ProcessGroup :: struct {
process_index: s32
group_count: s32
cpu_percent: float64
memory_bytes: u64
ticks: u64
}
GroupedSnapshot :: struct {
groups: [MAX_PROCESSES]ProcessGroup
count: s32
using Types :: #import "model_types";
#if #defined(TASKMGR_TAIJI) {
Guest :: #import "platform_taiji";
}
state_names: [7]string = .{"Running", "Sleeping", "Waiting", "Stopped", "Zombie", "Idle", "Other"};
snapshot: Snapshot;
table_revision: u64;
#program_export
TableRevision :: () -> u64 { return table_revision }
// Only PID/ticks plus the three system counters are needed from the preceding
// sample to calculate CPU deltas. This replaces a second full raw snapshot.
previous_pids: [MAX_PROCESSES]s32;
@@ -168,6 +44,9 @@ clock_ticks: float64;
page_bytes: u64;
timing_ready: bool;
grouped_snapshot: GroupedSnapshot;
// Reused bounded workspace; grouping keeps first-seen order and verifies collisions.
group_slots: [MAX_PROCESSES * 2]s32;
sort_scratch: [MAX_PROCESSES]s32;
#program_export
Current :: () -> *Snapshot {
@@ -207,6 +86,10 @@ StateName :: (state: u8) -> string {
// Reads a small file, such as a /proc entry, fully into a caller-owned buffer.
// Returns the byte count, or -1 when the path cannot be opened.
ReadSmall :: (path: string, buffer: []u8) -> s32 {
#if #defined(TASKMGR_TAIJI) {
return -1
} else {
file := Files.OpenRead(path)
if !file.valid { return -1 }
total: s32 = 0
@@ -217,6 +100,8 @@ ReadSmall :: (path: string, buffer: []u8) -> s32 {
}
Files.CloseFile(file)
return total
}
}
StatPath :: (pid: s32, output: []u8) -> string {
@@ -569,6 +454,10 @@ GpuVramPercent :: (device: *GpuDevice) -> float64 {
// with none of those files (NVIDIA's driver) uses the external reading for
// its PCI address when one was set.
ReadGpuStats :: (snapshot: *Snapshot) {
#if #defined(TASKMGR_TAIJI) {
return
} else {
directory := Files.OpenDirectory("/sys/class/drm")
busy_buffer: [128]u8
used_buffer: [128]u8
@@ -608,6 +497,8 @@ ReadGpuStats :: (snapshot: *Snapshot) {
}
Files.CloseDirectory(*directory)
FinalizeGpuStats(snapshot)
}
}
LowerByte :: (byte: u8) -> u8 {
@@ -645,21 +536,30 @@ SameProcessGroup :: (left: *Process, right: *Process) -> bool {
BuildGroupedSnapshot :: (source: *Snapshot, target: *GroupedSnapshot) {
target.count = 0
if source.count <= 0 { return }
slots: s32 = 2
while slots < source.count * 2 { slots *= 2 }
for slot: 0..slots - 1 { group_slots[slot] = -1 }
for index: 0..source.count - 1 {
entry := *source.processes[index]
group: s32 = -1
if target.count > 0 {
for candidate: 0..target.count - 1 {
representative := target.groups[candidate].process_index
if representative >= 0 && representative < source.count &&
SameProcessGroup(*source.processes[representative], entry) {
group = candidate
break
}
hash: u64 = 14695981039346656037
if IsCodexProcessName(entry.name[0:entry.name_count]) {
hash = 0
} else if entry.name_count > 0 {
for byte: 0..entry.name_count - 1 {
hash = (hash ^ cast(u64)LowerByte(entry.name[byte])) * 1099511628211
}
}
slot := cast(s32)(hash & cast(u64)(slots - 1))
group := group_slots[slot]
while group >= 0 {
representative := target.groups[group].process_index
if SameProcessGroup(*source.processes[representative], entry) { break }
slot = (slot + 1) & (slots - 1)
group = group_slots[slot]
}
if group < 0 {
group = target.count
group_slots[slot] = group
target.groups[group].process_index = index
target.groups[group].group_count = 1
target.groups[group].cpu_percent = entry.cpu_percent
@@ -796,6 +696,15 @@ MAX_TREE_DEPTH :: 64;
// represents (-1 for none). Rebuilt by AppUsages; never retained across calls.
pid_order: [MAX_PROCESSES]s32;
owner_slot: [MAX_PROCESSES]s32;
// The window slot each snapshot process counts toward (-1 for none), as of
// the last AppUsages call.
process_owner: [MAX_PROCESSES]s32;
#program_export
ProcessOwner :: (snapshot: *Snapshot, index: s32) -> s32 {
if index < 0 || index >= snapshot.count { return -1 }
return process_owner[index]
}
// /proc lists PIDs in ascending order, so this insertion sort is linear in
// practice and still correct when the order differs.
@@ -868,6 +777,7 @@ AppUsages :: (snapshot: *Snapshot, window_pids: []s32, gpu_pids: []s32,
cursor = IndexOfPid(snapshot, parent)
depth += 1
}
process_owner[index] = slot
if slot < 0 { continue }
process := *snapshot.processes[index]
usage := *output[slot]
@@ -896,7 +806,17 @@ AppUsages :: (snapshot: *Snapshot, window_pids: []s32, gpu_pids: []s32,
// arrays and system counters retained from the previous sample.
#program_export
Refresh :: () {
#if #defined(TASKMGR_TAIJI) {
if Guest.Sample(*snapshot) { table_revision += 1 }
// Guest UI has no group operation; avoid building an unused second view.
grouped_snapshot.count = 0
} else {
table_revision += 1
EnsureTiming()
snapshot.processes_available = true
snapshot.cpu_available = false
snapshot.memory_available = false
previous_count = snapshot.count
if previous_count > 0 {
for index: 0..previous_count - 1 {
@@ -933,6 +853,7 @@ Refresh :: () {
if stat_length > 0 {
sample_busy, sample_total, ok := CpuTotals(stat_buffer[0:stat_length])
if ok {
target.cpu_available = true
busy = sample_busy
total_ticks = sample_total
kernel_ticks = CpuKernelTicks(stat_buffer[0:stat_length])
@@ -944,6 +865,7 @@ Refresh :: () {
total_kb := target.memory.total_kb
available_kb := target.memory.available_kb
if total_kb > 0 {
target.memory_available = true
target.memory_total = cast(u64)total_kb * 1024
if available_kb >= 0 && available_kb <= total_kb {
target.memory_used = (cast(u64)total_kb - cast(u64)available_kb) * 1024
@@ -1011,6 +933,8 @@ Refresh :: () {
PushHistoryExtended(target.cpu_percent, target.kernel_percent, memory_percent,
target.gpu_percent, vram_percent)
}
}
}
ClampPercent :: (value: float64) -> float32 {
@@ -1162,54 +1086,87 @@ CompareRows :: (snapshot: *Snapshot, left: s32, right: s32, column: s32) -> s32
return CompareProcesses(*snapshot.processes[left], *snapshot.processes[right], column)
}
// Fills ORDER with a stable sort of the snapshot rows for COLUMN. Direction 1
// sorts ascending, -1 descending, and 0 leaves the natural /proc order.
// Compare aggregates directly; avoid copying two complete Process records for
// every group comparison. Codex aliases use the same name as GroupProcess.
CompareGroups :: (source: *Snapshot, grouped: *GroupedSnapshot, left: s32, right: s32,
column: s32) -> s32 {
a := *grouped.groups[left]
b := *grouped.groups[right]
if column == COLUMN_NAME {
first := *source.processes[a.process_index]
second := *source.processes[b.process_index]
canonical: [5]u8 = .{99, 111, 100, 101, 120}
left_name := first.name[0:first.name_count]
right_name := second.name[0:second.name_count]
if IsCodexProcessName(left_name) { left_name = canonical[:] }
if IsCodexProcessName(right_name) { right_name = canonical[:] }
return CompareName(left_name, right_name)
}
if column == COLUMN_PID {
return CompareProcesses(*source.processes[a.process_index], *source.processes[b.process_index], column)
}
if column == COLUMN_CPU {
if a.cpu_percent < b.cpu_percent { return -1 }
if a.cpu_percent > b.cpu_percent { return 1 }
} else if column == COLUMN_CPU_TIME {
if a.ticks < b.ticks { return -1 }
if a.ticks > b.ticks { return 1 }
} else if column == COLUMN_MEMORY {
if a.memory_bytes < b.memory_bytes { return -1 }
if a.memory_bytes > b.memory_bytes { return 1 }
}
return 0
}
// Bottom-up stable merge sort has bounded O(n log n) comparisons, including
// reverse PID/memory order. Scratch is shared by these sequential UI operations.
SortIndices :: (source: *Snapshot, grouped: *GroupedSnapshot, order: []s32,
count: s32, column: s32, direction: s32, groups: bool) {
if count > 0 { for index: 0..count - 1 { order[index] = index } }
if column < 0 || column >= COLUMNS || direction == 0 || count < 2 { return }
width: s32 = 1
while width < count {
start: s32 = 0
while start < count {
middle := start + width
if middle > count { middle = count }
end := middle + width
if end > count { end = count }
left := start
right := middle
for output: start..end - 1 {
take_left := right >= end
if left < middle && right < end {
comparison: s32
if groups { comparison = CompareGroups(source, grouped, order[left], order[right], column) }
else { comparison = CompareRows(source, order[left], order[right], column) }
if direction < 0 { comparison = -comparison }
take_left = comparison <= 0
}
if take_left && left < middle { sort_scratch[output] = order[left]; left += 1 }
else { sort_scratch[output] = order[right]; right += 1 }
}
start = end
}
for index: 0..count - 1 { order[index] = sort_scratch[index] }
width *= 2
}
}
// Direction 1 sorts ascending, -1 descending; 0 preserves snapshot order.
#program_export
SortOrder :: (snapshot: *Snapshot, order: []s32, column: s32, direction: s32) {
count := snapshot.count
if count > cast(s32)order.count { count = cast(s32)order.count }
if count > 0 {
for index: 0..count - 1 { order[index] = index }
}
if column < 0 || column >= COLUMNS || direction == 0 || count < 2 { return }
for slot: 1..count - 1 {
key := order[slot]
position := slot - 1
while position >= 0 {
comparison := CompareRows(snapshot, order[position], key, column)
if direction < 0 { comparison = -comparison }
if comparison <= 0 { break }
order[position + 1] = order[position]
position -= 1
}
order[position + 1] = key
}
SortIndices(snapshot, *grouped_snapshot, order, count, column, direction, false)
}
// Stable ordering for compact aggregate groups.
#program_export
SortGroupOrder :: (source: *Snapshot, grouped: *GroupedSnapshot, order: []s32,
column: s32, direction: s32) {
count := grouped.count
if count > cast(s32)order.count { count = cast(s32)order.count }
if count > 0 {
for index: 0..count - 1 { order[index] = index }
}
if column < 0 || column >= COLUMNS || direction == 0 || count < 2 { return }
for slot: 1..count - 1 {
key := order[slot]
key_process := GroupProcess(source, *grouped.groups[key])
position := slot - 1
while position >= 0 {
other := GroupProcess(source, *grouped.groups[order[position]])
comparison := CompareProcesses(*other, *key_process, column)
if direction < 0 { comparison = -comparison }
if comparison <= 0 { break }
order[position + 1] = order[position]
position -= 1
}
order[position + 1] = key
}
SortIndices(source, grouped, order, count, column, direction, true)
}
#program_export
@@ -1307,16 +1264,21 @@ FormatCpuTime :: (ticks: u64, output: []u8) -> string {
return TextView(output[0:length])
}
// A CPU share as a whole percentage with at least two digits, as "07".
// A share of the whole machine: one decimal below 10% ("0.4", "7.2") so light
// use on a many-core CPU does not read as zero, whole percent above ("43").
#program_export
FormatCpu :: (percent: float64, output: []u8) -> string {
value := cast(s64)(percent + 0.5)
if value < 0 { value = 0 }
if value > 100 { value = 100 }
tenths := cast(s64)(percent * 10.0 + 0.5)
if tenths < 0 { tenths = 0 }
if tenths > 1000 { tenths = 1000 }
digits: [8]u8
length: s32 = 0
if value < 10 { length = Append(output, length, "0") }
length = Append(output, length, Number.FormatInteger(value, digits[:]))
if tenths >= 100 {
whole := Append(output, 0, Number.FormatInteger((tenths + 5) / 10, digits[:]))
return TextView(output[0:whole])
}
length := Append(output, 0, Number.FormatInteger(tenths / 10, digits[:]))
length = Append(output, length, ".")
length = Append(output, length, Number.FormatInteger(tenths % 10, digits[:]))
return TextView(output[0:length])
}
@@ -1362,3 +1324,16 @@ EndProcessGroup :: (source: *Snapshot, group: *Process) -> GroupEndResult {
}
return result
}
// Sum of comparable guest task deltas; multiple guest execution threads may
// exceed one core. This is deliberately distinct from native machine CPU.
#program_export
FormatAccountedCpu :: (percent: float64, output: []u8) -> string {
tenths := cast(s64)(percent * 10.0 + 0.5)
if tenths < 0 { return "n/a" }
digits: [24]u8
length := Append(output, 0, Number.FormatInteger(tenths / 10, digits[:]))
length = Append(output, length, ".")
length = Append(output, length, Number.FormatInteger(tenths % 10, digits[:]))
return TextView(output[0:length])
}
+143
View File
@@ -0,0 +1,143 @@
// Shared process model and bounded snapshot storage.
CLOCK_TICKS_NAME :: 2; // _SC_CLK_TCK
PAGE_SIZE_NAME :: 30; // _SC_PAGESIZE
STOP_SIGNAL :: 15; // SIGTERM
// Keep the fixed snapshot bounded, but large enough for development hosts and
// servers with several thousand visible processes. A lower cap silently hid
// rows (including taskmgr's own test process) once /proc exceeded 1,024 PIDs.
// Two thousand entries retain that headroom on the development host (which
// runs roughly 1,400 processes) without keeping unused process and UI rows in
// every retained generation.
// The guest service captures at most 1024 tasks. Linux retains its capacity.
#if #defined(TASKMGR_TAIJI) {
#scope_export
MAX_PROCESSES :: 1024;
} else {
#scope_export
MAX_PROCESSES :: 2048;
}
// Linux TASK_COMM_LEN is 16 including the terminator. Keep extra room for
// synthetic group labels without doubling every process snapshot row.
NAME_CAPACITY :: 32;
COLUMNS :: 5;
COMMAND_CAPACITY :: 1024;
// Process table columns, in the classic task manager order.
COLUMN_NAME :: 0;
COLUMN_PID :: 1;
COLUMN_CPU :: 2;
COLUMN_CPU_TIME :: 3;
COLUMN_MEMORY :: 4;
// Samples kept for each Performance graph; one is taken per refresh.
HISTORY_LENGTH :: 60;
HISTORY_CPU :: 0;
HISTORY_KERNEL :: 1;
HISTORY_MEMORY :: 2;
HISTORY_GPU :: 3;
HISTORY_VRAM :: 4;
MAX_GPUS :: 16;
GPU_CARD_LIMIT :: 64;
STATE_RUNNING :: 82; // R
STATE_SLEEPING :: 83; // S
STATE_WAITING :: 68; // D
STATE_STOPPED :: 84; // T
STATE_ZOMBIE :: 90; // Z
STATE_IDLE :: 73; // I
Process :: struct {
pid: s32
name_count: s32
name: [NAME_CAPACITY]u8
state: u8
memory_available: bool
cpu_available: bool
// Parent PID from /proc/<pid>/stat field 4; it sits in the padding before
// cpu_percent, so the snapshot row does not grow.
ppid: s32
cpu_percent: float64
memory_bytes: u64
ticks: u64
threads: s32
// One for a raw process; more than one for an aggregated process group.
group_count: s32
}
GroupEndResult :: struct {
requested: s32
sent: s32
failed: s32
}
// Memory figures from /proc/meminfo, in kilobytes as the kernel reports them.
// Commit charge is Committed_AS against CommitLimit; kernel memory is the slab
// allocator, split into reclaimable (paged) and unreclaimable (nonpaged).
MemoryDetails :: struct {
total_kb: s64
available_kb: s64
cache_kb: s64
commit_kb: s64
commit_limit_kb: s64
kernel_paged_kb: s64
kernel_nonpaged_kb: s64
swap_total_kb: s64
swap_free_kb: s64
}
// One stable DRM card. card_index comes from cardN, so labels and histories do
// not change when directory enumeration order does. Unsupported counters stay
// explicit instead of looking like 0% or 100% usage.
GpuDevice :: struct {
card_index: s32
busy_supported: bool
busy_percent: float64
vram_supported: bool
vram_used: u64
vram_total: u64
}
Snapshot :: struct {
#if #defined(TASKMGR_TAIJI) {
cpu_measured_tasks: s32
}
processes_available: bool
cpu_available: bool
memory_available: bool
processes: [MAX_PROCESSES]Process
count: s32
cpu_percent: float64
kernel_percent: float64
memory_used: u64
memory_total: u64
busy_ticks: u64
kernel_ticks: u64
total_ticks: u64
threads: s64
// Allocated file handles from /proc/sys/fs/file-nr, or -1.
handles: s64
memory: MemoryDetails
gpu_percent: float64
gpus: [MAX_GPUS]GpuDevice
gpu_count: s32
gpu_supported_count: s32
vram_used: u64
vram_total: u64
}
// Group rows retain only the representative raw-process index and the values
// that are actually aggregated for the process table. Keeping a third full
// Snapshot duplicated every process name, state and GPU/system field.
ProcessGroup :: struct {
process_index: s32
group_count: s32
cpu_percent: float64
memory_bytes: u64
ticks: u64
}
GroupedSnapshot :: struct {
groups: [MAX_PROCESSES]ProcessGroup
count: s32
}
+12
View File
@@ -0,0 +1,12 @@
#scope_export
// Native Linux bindings; never imported by a Taiji bundle.
libc :: #system_library "libc";
SysConfRaw :: (name: s32) -> s64 #foreign libc "sysconf";
SendSignalRaw :: (pid: s32, signal: s32) -> s32 #foreign libc "kill";
ProcessIdRaw :: () -> s32 #foreign libc "getpid";
RunShellRaw :: (command: *u8) -> s32 #foreign libc "system";
SysConf :: (name: s32) -> s64 { return SysConfRaw(name) }
SendSignal :: (pid: s32, signal: s32) -> s32 { return SendSignalRaw(pid, signal) }
ProcessId :: () -> s32 { return ProcessIdRaw() }
RunShell :: (command: *u8) -> s32 { return RunShellRaw(command) }
+107
View File
@@ -0,0 +1,107 @@
// Only typed guest capabilities: no host filesystem or Linux process calls.
using Types :: #import "model_types";
Tasks :: #import "taijios_tasks";
Cpu :: #import "guest_cpu";
CpuRow :: struct {
pid: s32
reading: Cpu.Reading
}
// Two bounded generations; TaskAt is in guest PID order. Binary lookup avoids
// cross-row aliasing when tasks appear/disappear between captures.
previous: [MAX_PROCESSES]CpuRow;
next: [MAX_PROCESSES]CpuRow;
previous_count: s32;
Previous :: (pid: s32) -> Cpu.Reading {
low: s32 = 0
high := previous_count
while low < high {
middle := low + (high - low) / 2
if previous[middle].pid < pid { low = middle + 1 } else { high = middle }
}
if low < previous_count && previous[low].pid == pid { return previous[low].reading }
return .{}
}
VisibleRowEqual :: (left: *Process, right: *Process) -> bool {
if left.pid != right.pid || left.state != right.state || left.name_count != right.name_count ||
left.memory_available != right.memory_available || left.memory_bytes != right.memory_bytes ||
left.cpu_available != right.cpu_available || left.cpu_percent != right.cpu_percent { return false }
if left.name_count > 0 {
for index: 0..left.name_count - 1 { if left.name[index] != right.name[index] { return false } }
}
return true
}
#program_export
Sample :: (target: *Snapshot) -> bool {
old_count := target.count
changed := !target.processes_available
target.count = 0
target.processes_available = false
target.cpu_available = false
target.cpu_percent = 0
target.cpu_measured_tasks = 0
target.memory_available = false
target.memory_used = 0
target.memory_total = 0
target.handles = -1
target.threads = -1
count := Tasks.Capture()
if count < 0 || count > MAX_PROCESSES {
previous_count = 0
return old_count != 0 || !changed
}
target.processes_available = true
stamp := Tasks.SampleNanos()
fields: [7]s64
name: [64]u8
user: [64]u8
for index: 0..count - 1 {
if Tasks.TaskAt(index, fields[:], name[:], user[:]) != 0 {
target.count = 0
target.processes_available = false
previous_count = 0
target.cpu_available = false
target.cpu_percent = 0
target.cpu_measured_tasks = 0
return old_count != 0 || !changed
}
entry: Process
if fields[0] <= 0 || fields[0] > 2147483647 { continue }
entry.pid = cast(s32)fields[0]
reading: Cpu.Reading = .{fields[4], stamp, fields[5], fields[6]}
percent, valid := Cpu.Percent(Previous(entry.pid), reading)
entry.cpu_available = valid
entry.cpu_percent = percent
if valid {
target.cpu_percent += percent
target.cpu_measured_tasks += 1
}
next[target.count] = .{entry.pid, reading}
entry.group_count = 1
entry.state = STATE_SLEEPING
if fields[2] == 4 { entry.state = STATE_RUNNING }
if fields[2] == 7 { entry.state = STATE_STOPPED }
for byte: name {
if byte == 0 || entry.name_count >= NAME_CAPACITY { break }
entry.name[entry.name_count] = byte
entry.name_count += 1
}
entry.memory_available = fields[3] >= 0 && fields[3] <= 18014398509481983
if entry.memory_available { entry.memory_bytes = cast(u64)fields[3] * 1024 }
if target.count >= old_count || !VisibleRowEqual(*target.processes[target.count], *entry) { changed = true }
target.processes[target.count] = entry
target.count += 1
}
previous_count = target.count
if previous_count > 0 {
for index: 0..previous_count - 1 { previous[index] = next[index] }
}
target.cpu_available = target.cpu_measured_tasks > 0
if old_count != target.count { changed = true }
if Tasks.PoolAt(0, fields[:]) == 0 && fields[0] >= 0 && fields[1] >= 0 {
target.memory_available = true
target.memory_used = cast(u64)fields[0]
target.memory_total = cast(u64)fields[1]
}
return changed
}
+241
View File
@@ -0,0 +1,241 @@
// Host service for portable Task Manager frontends (e.g., Werkzeug).
// Runs in the native host process and exposes bounded /proc snapshots and
// process control over the `taskmgr.v1` service protocol.
Json :: #import "std/json_scan";
#import "std/vec"
#import "std/text_buffer"
#import "std/byte_text_linux"
#import "std/c_string"
#import "kryon/app_files"
#if !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
Model :: #import "model";
using Types :: #import "model_types";
}
MAX_ROWS :: 160;
Context :: struct {
initialized: bool
}
reply_buf: [131072]u8;
Number :: (request: string, name: string) -> s32 {
at := Json.FieldAt(request, 0, name)
if at < 0 { return 0 }
value := Json.ReadNumber(request, at)
if !value.valid || value.value < -2147483647.0 || value.value > 2147483647.0 { return 0 }
return cast(s32)value.value
}
Text :: (request: string, name: string, out: []u8) -> string {
count := Json.ReadStringText(request, Json.FieldAt(request, 0, name), out)
return ifx count >= 0 && count < out.count then TextView(out[:count]) else ""
}
Finish :: (context: *Context, bytes: Vec(u8)) -> string {
unused context
count := cast(s64)bytes.count
if count >= reply_buf.count { count = reply_buf.count - 1 }
{
slice := VecSlice(bytes, 0, cast(usize)count)
for index: 0..count - 1 { reply_buf[index] = slice[index] }
}
reply_buf[count] = cast(u8)0
VecFree(bytes)
return TextView(reply_buf[:count])
}
ReplyLine :: (context: *Context, prefix: string, message: string) -> string {
bytes: Vec(u8)
BuilderPrint(*bytes, "%\t%\n", prefix, message)
return Finish(context, bytes)
}
#if !#defined(PLATFORM_WEB) && !#defined(ANDROID_BUILD) {
order_scratch: [MAX_PROCESSES]s32;
AsciiLower :: (byte: u8) -> u8 {
if byte >= cast(u8)65 && byte <= cast(u8)90 { return byte + cast(u8)32 }
return byte
}
ContainsFold :: (haystack: string, needle: string) -> bool {
if needle.count == 0 { return true }
if needle.count > haystack.count { return false }
limit := haystack.count - needle.count
for start: 0..limit {
matched := true
for offset: 0..needle.count - 1 {
if AsciiLower(haystack[start + offset]) != AsciiLower(needle[offset]) {
matched = false
break
}
}
if matched { return true }
}
return false
}
SanitizeName :: (bytes: *Vec(u8), name: string) {
for byte: name {
if byte == cast(u8)9 || byte == cast(u8)10 || byte == cast(u8)13 {
unused VecPush(bytes.*, cast(u8)32)
} else {
unused VecPush(bytes.*, byte)
}
}
}
AppendHistory :: (bytes: *Vec(u8), tag: string, kind: s32) {
samples: [HISTORY_LENGTH]float32
values := Model.History(kind, samples[:])
BuilderPrint(bytes, "%", tag)
for index: 0..values.count - 1 {
tenths := cast(s64)(values[index] * 10.0 + 0.5)
if tenths < 0 { tenths = 0 }
if tenths > 1000 { tenths = 1000 }
BuilderPrint(bytes, "\t%", tenths)
}
BuilderPrint(bytes, "\n")
}
SnapshotReply :: (context: *Context, request: string) -> string {
sort_column := Number(request, "sort")
if sort_column < 0 || sort_column >= COLUMNS { sort_column = COLUMN_CPU }
desc := Number(request, "desc") != 0
grouped := Number(request, "grouped") != 0
refresh := Number(request, "refresh") != 0
filter_bytes: [128]u8
filter := Text(request, "filter", filter_bytes[:])
if !context.initialized || refresh {
Model.Refresh()
context.initialized = true
}
snapshot := Model.Current()
bytes: Vec(u8)
cpu_x10 := cast(s64)(snapshot.cpu_percent * 10.0 + 0.5)
kern_x10 := cast(s64)(snapshot.kernel_percent * 10.0 + 0.5)
BuilderPrint(*bytes, "ok\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\t%\n",
ifx snapshot.processes_available then 1 else 0,
ifx snapshot.cpu_available then 1 else 0,
ifx snapshot.memory_available then 1 else 0,
snapshot.count,
cpu_x10,
kern_x10,
snapshot.memory_used,
snapshot.memory_total,
snapshot.threads,
snapshot.handles,
snapshot.memory.commit_kb,
snapshot.memory.commit_limit_kb,
Model.CommitPeakKb(),
snapshot.memory.available_kb,
snapshot.memory.cache_kb,
snapshot.memory.kernel_paged_kb,
snapshot.memory.kernel_nonpaged_kb,
snapshot.memory.swap_total_kb,
snapshot.memory.swap_free_kb,
Model.CurrentProcessId())
AppendHistory(*bytes, "cpu", HISTORY_CPU)
AppendHistory(*bytes, "kern", HISTORY_KERNEL)
AppendHistory(*bytes, "mem", HISTORY_MEMORY)
direction: s32 = ifx desc then -1 else 1
emitted: s32 = 0
if grouped {
groups := Model.GroupedCurrent()
if groups.count > 0 {
Model.SortGroupOrder(snapshot, groups, order_scratch[0:groups.count], sort_column, direction)
for index: 0..groups.count - 1 {
if emitted >= MAX_ROWS { break }
row := Model.GroupProcess(snapshot, *groups.groups[order_scratch[index]])
name := TextView(row.name[0:row.name_count])
if filter.count > 0 && !ContainsFold(name, filter) { continue }
row_cpu := cast(s64)(row.cpu_percent * 10.0 + 0.5)
BuilderPrint(*bytes, "p\t%\t%\t%\t%\t%\t%\t%\t",
row.pid, row.group_count, row_cpu, row.memory_bytes,
row.ticks, row.threads, Model.StateName(row.state))
SanitizeName(*bytes, name)
BuilderPrint(*bytes, "\n")
emitted += 1
}
}
} else if snapshot.count > 0 {
Model.SortOrder(snapshot, order_scratch[0:snapshot.count], sort_column, direction)
for index: 0..snapshot.count - 1 {
if emitted >= MAX_ROWS { break }
row := snapshot.processes[order_scratch[index]]
name := TextView(row.name[0:row.name_count])
if filter.count > 0 && !ContainsFold(name, filter) { continue }
row_cpu := cast(s64)(row.cpu_percent * 10.0 + 0.5)
BuilderPrint(*bytes, "p\t%\t%\t%\t%\t%\t%\t%\t",
row.pid, row.group_count, row_cpu, row.memory_bytes,
row.ticks, row.threads, Model.StateName(row.state))
SanitizeName(*bytes, name)
BuilderPrint(*bytes, "\n")
emitted += 1
}
}
return Finish(context, bytes)
}
EndGroupByName :: (context: *Context, name: string) -> string {
if name.count == 0 { return ReplyLine(context, "err", "No process group selected") }
snapshot := Model.Current()
target: Process
limit := name.count
if limit > NAME_CAPACITY { limit = NAME_CAPACITY }
for index: 0..limit - 1 { target.name[index] = name[index] }
target.name_count = cast(s32)limit
result := Model.EndProcessGroup(snapshot, *target)
bytes: Vec(u8)
if result.sent > 0 {
BuilderPrint(*bytes, "ok\tEnded % process(es)", result.sent)
if result.failed > 0 { BuilderPrint(*bytes, " (% failed)", result.failed) }
BuilderPrint(*bytes, "\n")
} else {
BuilderPrint(*bytes, "err\tCould not end process group\n")
}
return Finish(context, bytes)
}
}
#scope_export
Call :: (context: *Context, request: string) -> string {
#if #defined(PLATFORM_WEB) || #defined(ANDROID_BUILD) {
unused request
return ReplyLine(context, "unsupported", "System process monitoring is available on desktop Linux.")
} else {
op_bytes: [32]u8
op := Text(request, "op", op_bytes[:])
if op == "snapshot" {
return SnapshotReply(context, request)
}
if op == "end_pid" {
pid := Number(request, "pid")
if pid <= 0 || pid == Model.CurrentProcessId() {
return ReplyLine(context, "err", "Cannot end this process")
}
if Model.EndTask(pid) {
return ReplyLine(context, "ok", "Termination signal sent")
}
return ReplyLine(context, "err", "Could not end process (permission denied or exited)")
}
if op == "end_group" {
name_bytes: [64]u8
return EndGroupByName(context, Text(request, "name", name_bytes[:]))
}
if op == "run" {
cmd_bytes: [512]u8
command := Text(request, "command", cmd_bytes[:])
if command.count == 0 { return ReplyLine(context, "err", "Enter a command to run") }
if Model.StartTask(command) {
return ReplyLine(context, "ok", "Command started")
}
return ReplyLine(context, "err", "Could not start command")
}
return ReplyLine(context, "err", "Unknown operation")
}
}
+15
View File
@@ -0,0 +1,15 @@
// Taiji provides the same Kryon software surface used by its other ZX apps.
Surface :: #import "kryon/host/surface";
App :: #import "app";
#import "kryon/session"
#import "kryon/tree"
Draw :: (frame: Surface.Frame) {
session: Session = .{frame.slot, frame.epoch}
unused App.Frame(session, TreeRootBounds(session))
}
#program_export
main :: () -> s32 {
return Surface.RunRetained(.{.title = "Task Manager", .width = 400, .height = 480}, Draw, 250)
}
+52
View File
@@ -0,0 +1,52 @@
#scope_export
// Platform policy selected at build time, never from host environment.
#if #defined(TASKMGR_TAIJI) {
Tasks :: #import "taijios_tasks";
Surface :: #import "kryon/host/surface";
} else {
Native :: #import "platform_linux";
Window :: #import "kryon/Window";
}
IsGuest :: () -> bool {
#if #defined(TASKMGR_TAIJI) {
return true
} else {
return false
}
}
ProcessId :: () -> s32 {
#if #defined(TASKMGR_TAIJI) {
return -1
} else {
return Native.ProcessId()
}
}
SysConf :: (name: s32) -> s64 {
#if #defined(TASKMGR_TAIJI) {
return -1
} else {
return Native.SysConf(name)
}
}
SendSignal :: (pid: s32, signal: s32) -> s32 {
#if #defined(TASKMGR_TAIJI) {
return Tasks.Terminate(pid)
} else {
return Native.SendSignal(pid, signal)
}
}
RunShell :: (command: *u8) -> s32 {
#if #defined(TASKMGR_TAIJI) {
return -1
} else {
return Native.RunShell(command)
}
}
CloseWindow :: () {
#if #defined(TASKMGR_TAIJI) {
Surface.Close()
} else {
Window.WindowQuit()
}
}
+8
View File
@@ -21,6 +21,12 @@ AppList :: struct {
available: bool
}
#if #defined(TASKMGR_TAIJI) {
#scope_export
AppsRefresh :: (list: *AppList) { list.count = 0; list.available = false }
AppsSwitchTo :: (window: u64) -> bool { return false }
AppsCloseWindow :: (window: u64) -> bool { return false }
} else {
#scope_file
c :: #system_library "c";
@@ -314,3 +320,5 @@ AppsSwitchTo :: (window: u64) -> bool {
AppsCloseWindow :: (window: u64) -> bool {
return SendClientMessage(window, close_atom, 0, SOURCE_PAGER)
}
}
+276
View File
@@ -0,0 +1,276 @@
# Task Manager performance measurements
Measured locally on Omega, 2026-11-21, from the canonical checkout with its
existing ignored local Ziran/Kryon overrides. Baseline: the previous Task Manager
milestone, before the grouping/sorting/text changes. Native GUI baseline used the
previous installed executable. Guest comparison used the same explicit profile
host, 400 × 480 surface, 250 ms surface idle interval, one-second process sampling,
private Xvfb and default 32 MiB main pool. These are local measurements, not CI. A build using only published locked
dependencies was not repeated; the package tool notes additional dependency
metadata in the local Kryon override.
## Deterministic model workload
Each row contains three grouping passes, three reverse-memory raw sorts and
three group sorts. Capacity, stable ordering and returned checksum are checked.
Times below are single matched observations, not statistical guarantees.
| Workload | Baseline grouping/raw/group sort | After grouping/raw/group sort |
| --- | --- | --- |
| Native 2,048 rows (µs) | 24,635 / 8,190 / 29,168 | 86 / 94 / 79 |
| Guest 128 rows (ms) | 140 / 39 / 106 | 3 / 4 / 3 |
| Guest 1,024 rows (ms) | default instruction budget exceeded | 21 / 43 / 37 |
The full native workload totals 61,993 → 259 µs; the comparable guest workload
285 → 10 ms. Full guest capacity now completes within the original instruction
budget. This synthetic model workload does not measure UI rendering or fabricate
process metrics. Native ordering tests compare every column and direction with
an independent stable-sort oracle; grouping checks case folding/Codex aliases.
## Actual guest UI
Matched 12-second idle windows followed by ten pointer events, each waiting for
the next app callback. The service supplies real guest tasks and pool readings.
| Measurement | Baseline | After |
| --- | --- | --- |
| Idle emulator CPU / wall (s) | 6.96 / 12.049 | 6.81 / 12.050 |
| Input emulator CPU / wall (s) | 3.36 / 5.846 | 3.29 / 5.785 |
| Steady main pool (bytes) | 24,747,104 | 24,513,408 |
| Main pool high water (bytes) | 25,693,376 | 25,634,144 |
| App declaration after startup (ms) | usually 11–14 | usually 11–14 |
| Input-to-next-callback (ms) | 542–662 | 422–663 |
Process-cell pixel digests matched exactly; status memory values legitimately
changed. The 233,696-byte steady-pool saving is real, but these runs do not show
a material overall GUI CPU/latency improvement. Canonical Kryon's surface loop
still performs full raster/presentation on idle and pointer movement; that
upstream hot path was reported to the owning coordinator. Callback times are
polling upper bounds and exclude completed pixel presentation.
## Native GUI and RSS
Matched 12-second idle and ten alternating Applications/Processes shortcuts:
baseline CPU 0.14 s idle / 0.04 s input; after 0.12 s / 0.04 s. Observed tab redraw
was approximately 29–31 ms in both runs, including input-tool and capture cost.
These small differences are not evidence of a material native GUI speedup.
Three 30-second RSS runs of the baseline installed executable peaked at 32,792,
32,564 and 30,716 KiB. Three after runs peaked at 30,960, 32,972 and 29,328 KiB.
Those characterization runs explicitly used `TASKMGR_RSS_LIMIT_KB=100000`; that
is measurement headroom, not a pass against the normal 30,720 KiB threshold.
Default-cap testing also reproduced a failure. The cap has not been raised.
The CPU comparison exposed 2,048 KiB of anonymous huge pages in one baseline
run and 4,096 KiB in an after run, tracking much of the RSS variance. File-backed
library residency is about 22 MiB. A tested process-local huge-page opt-out did
not remove pages already resident at startup or reliably meet the cap; it was
removed. Reducing fixed backing storage preserves capacity, but does not imply
that every reserved byte was resident before this change. The final installed executable also peaked at 30,760 KiB in the default-cap
30-second test, which failed by 40 KiB. Native memory remains
a limitation requiring upstream/runtime or allocation work; do not claim a stable
30 MiB cap from these results.
## Reproduction
From Task Manager:
```sh
make check test performance-test x11-test
TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji-test taiji taiji-performance
python3 scripts/native-performance.py build/taskmgr-desktop
python3 scripts/guest-performance.py /mnt/storage/Projects/taijiosnet/taijios build/guest-profile.zx --seconds 30
./scripts/memory-test.sh
```
Run guest model artifact `/build/zx-smoke/taskmgr-performance.zx` using the
canonical emulator with `-p main=32M -r "$PWD" /dis/sh.dis -c 'zxrun /build/zx-smoke/taskmgr-performance.zx'`.
Copy only the built test artifact to that disposable test path first; no source
copy or installation is needed. The shell may end by killing its emulator after
printing the successful `MODEL_PERF ... checksum=1024` and exit status `0`.
The bridge/GUI lifecycle test remains the Taiji installer's existing command:
```sh
PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$PWD/appl/cmd/tcltk" python3 -u appl/wm/taskmgr_zx_test.py Linux/386/bin/emu --gui
```
That command is run from TaijiOS after its owner installs the stable Task Manager
artifact. It uses a disposable guest and only its owned sleeper for termination.
## Installation verification
The optimized native executable was installed with `./scripts/ziran.sh install`
and passed `TASKMGR_BINARY=/home/wao/.local/bin/taskmgr ./scripts/x11-test.sh`.
The installed native memory run failed the unchanged 30 MiB cap as described above.
The Taiji owner installed the stable `build/taskmgr.zx` artifact with its matching
emulator, launcher and panel. The installed SHA-256 is
`17e529fc13c7199f3e7f1efd73262a17bf20f3328c765f01f0bffe2844d3b55d`.
Its existing private-Xvfb lifecycle command exited zero with `TASK_BRIDGE_OK`,
`TASK_NAMESPACE_OK` and `TASK_GUI_OK`: real tasks, PID sorting, selection,
confirmed termination of an owned sleeper, live refresh and close at 32 MiB.
Earlier attempts using a new launcher overlay with the old installed emulator
failed ABI loading before the app ran; the matching installation resolved it.
An independent rerun of the installed lifecycle command also passed. Repeating
the 30-second profile against the matching newly installed stack produced 69
frames: steady pool 24,557,024 bytes, high water 25,187,680 bytes, idle emulator
CPU 16.83 / 30.031 seconds. The settled pool changed only 64 bytes. This last
run verifies the new runtime installation; it is not a matched baseline
comparison with the older runtime. Existing owner desktop instances were preserved.
Both installed artifacts include the checkout's pre-existing memory-first startup
preference. That owner hunk remains outside the app performance commit.
## Guest CPU follow-up
The CPU-capable Taiji emulator and this checkout were tested locally with the
same ignored canonical dependency overrides and explicit full-raster surface
path (the then-current `retain_paint=false` API, now normal `Run`). This does not validate a published-dependencies-only
build. Task CPU uses cumulative guest execution nanoseconds, task incarnation,
captured monotonic time and the measured capture timestamp error. New/reset or
invalid readings remain unavailable; no host process statistics supply app data.
The real 32 MiB model probe measured its busy ZX task at 99.979236% and its owned
Sleep task at 0%, and verified CPU sorting. Pure arithmetic tests cover the first
sample, idle/busy deltas, resets/reuse, nonpositive elapsed time, exact/excessive
capture-skew bounds and signed-limit arithmetic. Typed model tests cover CPU
availability, aggregation, sorting, capture failure and bounded refresh storage.
The shared GUI profile then completed 60 frames over a 30-second idle window and
ten input events with real CPU readings. Main pool settled at 25,579,200 bytes;
high water was 26,252,928 bytes, within 33,554,432 bytes. The last six readings
were stable; total settled growth was 32 bytes. Private-display OCR showed numeric
per-task CPU and a `Task CPU` total. CPU time remains explicitly unavailable.
This run is a CPU correctness/memory gate, not a matched performance comparison.
```sh
make check test x11-test
TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji-test taiji taiji-performance taiji-cpu-live
python3 scripts/guest-cpu-test.py /mnt/storage/Projects/taijiosnet/taijios --emu /mnt/storage/Projects/taijiosnet/taijios/emu/Linux/o.emu
python3 scripts/guest-performance.py /mnt/storage/Projects/taijiosnet/taijios build/guest-profile.zx --seconds 30 --emu /mnt/storage/Projects/taijiosnet/taijios/emu/Linux/o.emu --require-cpu
```
A separate 39-frame private GUI run exercised CPU header sorting through its
sort cycle and OCR-verified the real busy task first (`99`), with the high water
unchanged. The first focus/header attempt did not change sort; two later clicks
selected ascending then descending order. The test allows this bounded cycle.
The production GUI lifecycle subsequently reproduced a 32 MiB failure after the
owned sleeper was confirmed killed, before View/Refresh/Exit. Both observed
allocator PCs map to `compiler_exec_ExecResizeAddresses` in the guest interpreter;
requests were about 2.6 MiB with about 29.6 MiB already allocated. Two runs failed
at different address-producing instructions (PixmapBlendMask and QueuePaint).
The runtime owner has this evidence; this app does not change its interpreter.
The core address-slot fix resolved this failure on the same previous artifact;
the current normal/retained comparison below uses that fixed runtime.
```sh
python3 scripts/guest-lifecycle-test.py /mnt/storage/Projects/taijiosnet/taijios --emu /mnt/storage/Projects/taijiosnet/taijios/emu/Linux/o.emu
```
The guest owner subsequently installed normal production bundle
`1750e67b7246c9b3d5db8a0694a903c755b252a11b7c29ebbfbeb78ab9d3f069`
with the fixed matching emulator. Its private-Xvfb 32 MiB test passed owned-sleeper
termination, live refresh, PID sorting, resize, bottom-control reflow twice,
close and reopen (installation receipt `7621fa0cfbd827f29d6d3895638a5447b777`).
The earlier installation report above applies to the preceding performance
milestone. Native RSS limitations remain unchanged.
## Fixed-runtime paired table/dialog run
The normal comparison used `Surface.Run(window, Draw, 250)`. The explicit
profile test builds the same `App.Frame` and observations twice, selecting
`Run` or experimental `RunRetained` with `TASKMGR_RETAINED`. Neither changes task
capacity, the one-second process sampler or the 250 ms callback interval.
After the full lifecycle gate below passed, the production entry was promoted
to `Surface.RunRetained(window, Draw, 250)`.
Both runs used the same fixed Linux/386 emulator (Build ID
`22e6b24cff005f119b9261619e38b4ab94598f60`), main pool 32 MiB, private Xvfb and
scrubbed display/session environment. The workload is 90 seconds idle, ten
pointer events, actual CPU-header sorting verified from private pixels, then six
PID sort/select/End Process confirmation/No cycles while sampling continues.
No task is killed by this profiling workload; the separate canonical guest
lifecycle suite tests killing its owned disposable sleeper, refresh and close.
| Local measurement | Normal | Retained |
| --- | --- | --- |
| Idle emulator CPU / elapsed (s) | 54.10 / 90.029 | 14.53 / 90.037 |
| Six table/dialog cycles CPU / elapsed (s) | 75.94 / 82.050 | 24.71 / 38.551 |
| App callbacks | 341 | 523 |
| Final main pool (bytes) | 24,145,888 | 23,302,080 |
| Main pool high water (bytes) | 24,480,576 | 24,119,616 |
| Last six pool samples' range (bytes) | 0 | 0 |
Both completed all cycles and numeric CPU assertions. Static table-header pixels
matched exactly, as did the confirmation-dialog crop. Full-image hashes differ
because live CPU/memory values differ; they are not a pixel-equality verdict.
The retained run used about 73% less idle CPU and 67% less workload CPU in this
single pair. These observations are not a statistical guarantee or a pure render
microbenchmark; other managed tasks shared the machine. OCR and waits are part
of the elapsed workload. The larger retained callback count reflects its faster
loop, rather than a changed sampling or callback interval.
Only the real main allocator pool/high water is exposed to the profile. Direct
interpreter address-slot high water and presentation counts are unavailable in
the typed app API, so these results do not invent either measurement. The guest
runtime owner separately instruments address lifetime and installed lifecycle.
```sh
TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji taiji-performance
python3 scripts/guest-performance.py /mnt/storage/Projects/taijiosnet/taijios build/guest-profile.zx --seconds 90 --cycles 6 --emu /mnt/storage/Projects/taijiosnet/taijios/emu/Linux/o.emu --require-cpu --output build/guest-normal-long.json
python3 scripts/guest-performance.py /mnt/storage/Projects/taijiosnet/taijios build/guest-profile-retained.zx --seconds 90 --cycles 6 --emu /mnt/storage/Projects/taijiosnet/taijios/emu/Linux/o.emu --require-cpu --output build/guest-retained-long.json
```
Bundle SHA-256 identities: normal production `1750e67b7246c9b3d5db8a0694a903c755b252a11b7c29ebbfbeb78ab9d3f069`,
normal profile `77d4a7ed07cb5eed83260ab845d49e3903f94d349ff8c4620dd77179f0bc3e6e`,
retained profile `4c67f924659b8e882bb8cc2773a39912ad5bb12ec570580074ee6a151cfec2e4`.
Static header digest: `d372ed887957bd0dfd72ec3ac8454d9485db4caa74392fa9f0391b5144091084`;
modal digest: `15775f17018dbbe29622d038bae779356ec04a1c68c836efd10cea05d922e5ed`.
The uninstrumented retained lifecycle candidate used the same production host
with compile-time `TASKMGR_RETAINED`; no UI or profile logger was copied. It was built
with `TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji-retained-test`.
Its explicit test artifact is `build/taskmgr-retained-test.zx`, SHA-256
`9f82ce6c01013022ff41739baa45949badf89151e4d40f189c0a7a06658cb03b`.
The guest owner passed the identical 32 MiB owned-sleeper termination, View
refresh, grow/shrink with bottom-control reflow, close/reopen/repeat and
panel/chrome suite on these bytes (receipt `7a766798fc947f3150f4c75327ae7a426cd4`).
It atomically installed the tested artifact at `dis/wm/taskmgr.zx`, verified byte
equality and passed the installed production-path recheck with
`--cpu --gui --require-window-resize` (receipt `1ea00a52cae5c616dcb9bdfd850cd90d464a`).
Existing desktop instances were preserved.
The guest owner also measured successful interpreter address-table allocation
capacity under hardware GDB breakpoints during the full lifecycle: normal
1,448,408 bytes, retained 697,756 bytes (receipt
`76fe2d465a5a84afd72775cdf219e4accd12`). Both instrumented lifecycle runs passed.
These are address-table capacity peaks, not total guest memory or live slot
counts. They complement the actual allocator high-water readings above.
The earlier first-four-frame measurement was 731,044 / 417,392 bytes; it is
superseded for lifecycle coverage by this complete run.
## Final production source and package pin
The production host now calls `RunRetained` directly. Rebuilding it through
`TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji`
writes stable `build/taskmgr.zx`, SHA-256
`109c2314690c0ecd19624119aa9a3229a91245b3ec91e883e6f4997b2a6be200`.
Removing the test-only define/branch changed the bundle identity, so the app
lane repeated `python3 scripts/guest-lifecycle-test.py /mnt/storage/Projects/taijiosnet/taijios --emu /mnt/storage/Projects/taijiosnet/taijios/Linux/386/bin/emu`.
It passed the namespace/CPU and real private-Xvfb selected-task kill, live refresh
and close tests at 32 MiB (receipt `4d35328ed6eba7016ad97942038b22089e86`).
This artifact was handed to the same sole guest installer for its final
production-path copy and resize recheck.
The manifest pins canonical Gitea Kryon revision
`b764139c3c03b3ee183e2e712f9f045b4575fc92`, independently verified against
remote master and its exported `RunRetained` source. The normal lock was generated
with the documented `ZIRAN_LOCK_GIT_OBJECTS` / `ziran lock` command, using only
existing canonical repositories. After that pin, `make check test` and
`TAIJIOS_TASK_MODULES=/mnt/storage/Projects/taijiosnet/taijios/appl/cmd make taiji-test taiji`
passed again and produced the same production digest (receipt
`03f1f459b05a15a4c6e5b9d0fe001fd05656`). These remain current-tree local tests with
ignored dependency overrides; no locked-only build is claimed. Kryon's working
manifest still declares dependency metadata beyond that pinned commit, which
the package tool resolves in memory for local builds.
+42
View File
@@ -0,0 +1,42 @@
Cpu :: #import "guest_cpu";
#program_export
main :: () -> s32 {
initial: Cpu.Reading = .{100, 1000, 7, 0}
value, valid := Cpu.Percent(.{}, initial)
if valid { return 1 }
value, valid = Cpu.Percent(initial, .{350, 2000, 7, 0})
if !valid || value != 25.0 { return 2 }
value, valid = Cpu.Percent(initial, .{100, 2000, 7, 0})
if !valid || value != 0 { return 3 }
value, valid = Cpu.Percent(initial, .{1100, 2000, 7, 0})
if !valid || value != 100 { return 4 }
value, valid = Cpu.Percent(initial, .{50, 2000, 7, 0})
if valid { return 5 }
value, valid = Cpu.Percent(initial, .{350, 2000, 8, 0})
if valid { return 6 }
value, valid = Cpu.Percent(initial, .{350, 1000, 7, 0})
if valid { return 7 }
value, valid = Cpu.Percent(initial, .{350, 999, 7, 0})
if valid { return 8 }
value, valid = Cpu.Percent(initial, .{-1, 2000, 7, 0})
if valid { return 9 }
value, valid = Cpu.Percent(initial, .{1101, 2000, 7, 0})
if valid { return 10 }
value, valid = Cpu.Percent(.{9223372036854775700, 9223372036854775700, 1, 0},
.{9223372036854775750, 9223372036854775800, 1, 0})
if !valid || value != 50 { return 11 }
// Exact measured skew bounds admit saturation, never a larger excess.
value, valid = Cpu.Percent(.{100, 1000, 7, 2}, .{1105, 2000, 7, 3})
if !valid || value != 100 { return 12 }
value, valid = Cpu.Percent(.{100, 1000, 7, 2}, .{1106, 2000, 7, 3})
if valid { return 13 }
value, valid = Cpu.Percent(.{100, 1000, 7, -1}, .{350, 2000, 7, 0})
if valid { return 14 }
value, valid = Cpu.Percent(.{100, 1000, 7, 500}, .{350, 2000, 7, 500})
if valid { return 15 }
value, valid = Cpu.Percent(.{100, 1000, 7, 9223372036854775807},
.{350, 2000, 7, 9223372036854775807})
if valid { return 16 }
print("taskmgr guest CPU arithmetic tests passed\n")
return 0
}
+29
View File
@@ -0,0 +1,29 @@
// Explicit test host: unchanged app UI with timing/pool observations.
Surface :: #import "kryon/host/surface";
Clock :: #import "kryon/Clock";
Tasks :: #import "taijios_tasks";
App :: #import "app";
Model :: #import "model";
#import "kryon/session"
#import "kryon/tree"
frames: s32;
Draw :: (frame: Surface.Frame) {
session: Session = .{frame.slot, frame.epoch}
start := Clock.Milliseconds()
unused App.Frame(session, TreeRootBounds(session))
elapsed := Clock.Milliseconds() - start
snapshot := Model.Current()
print("FRAME_CPU valid=% measured=% percent=%\n", cast(s32)snapshot.cpu_available, snapshot.cpu_measured_tasks, snapshot.cpu_percent)
pool: [4]s64
code := Tasks.PoolAt(0, pool[:])
frames += 1
print("FRAME_PERF frame=% declaration_ms=% pool=% high=% valid=%\n", frames, elapsed, pool[0], pool[2], code)
}
#program_export
main :: () -> s32 {
#if #defined(TASKMGR_RETAINED) {
return Surface.RunRetained(.{.title = "Task Manager", .width = 400, .height = 480}, Draw, 250)
} else {
return Surface.Run(.{.title = "Task Manager", .width = 400, .height = 480}, Draw, 250)
}
}
+51 -8
View File
@@ -1,5 +1,6 @@
using Model :: #import "model";
Gpu :: #import "gpu_processes";
GpuDrm :: #import "gpu_drm";
Shortcuts :: #import "app_shortcuts";
Files :: #import "std/file";
@@ -386,8 +387,10 @@ FormatTest :: () -> bool {
print("format: adaptive meminfo units wrong\n")
return false
}
if Model.FormatCpu(7.4, buffer[:]) != "07" || Model.FormatCpu(42.6, buffer[:]) != "43" ||
Model.FormatCpu(0.0, buffer[:]) != "00" || Model.FormatCpu(100.0, buffer[:]) != "100" {
if Model.FormatCpu(7.4, buffer[:]) != "7.4" || Model.FormatCpu(42.6, buffer[:]) != "43" ||
Model.FormatCpu(0.0, buffer[:]) != "0.0" || Model.FormatCpu(0.04, buffer[:]) != "0.0" ||
Model.FormatCpu(0.36, buffer[:]) != "0.4" || Model.FormatCpu(9.96, buffer[:]) != "10" ||
Model.FormatCpu(100.0, buffer[:]) != "100" {
print("format: cpu column wrong\n")
return false
}
@@ -405,30 +408,34 @@ HistoryTest :: () -> bool {
Model.PushHistory(150.0, -5.0, 41.5)
Model.PushHistory(30.0, 3.0, 42.0)
values: [Model.HISTORY_LENGTH]float32
cpu := Model.History(Model.HISTORY_CPU, values[:])
last := Model.HISTORY_LENGTH - 1
cpu := Model.History(Model.HISTORY_CPU, values[:])
if cast(s32)cpu.count != Model.HISTORY_LENGTH || cpu[last] != 30.0 ||
cpu[last - 1] != 100.0 || cpu[last - 2] != 10.0 {
print("history: cpu samples wrong or unclamped\n")
return false
}
kernel := Model.History(Model.HISTORY_KERNEL, values[:])
kernel_values: [Model.HISTORY_LENGTH]float32
kernel := Model.History(Model.HISTORY_KERNEL, kernel_values[:])
if kernel[last] != 3.0 || kernel[last - 1] != 0.0 {
print("history: kernel samples wrong\n")
return false
}
memory := Model.History(Model.HISTORY_MEMORY, values[:])
memory_values: [Model.HISTORY_LENGTH]float32
memory := Model.History(Model.HISTORY_MEMORY, memory_values[:])
if memory[last] != 42.0 || memory[last - 1] != 41.5 {
print("history: memory samples wrong\n")
return false
}
Model.PushHistoryExtended(11.0, 4.0, 43.0, 67.0, 81.0)
gpu := Model.History(Model.HISTORY_GPU, values[:])
gpu_values: [Model.HISTORY_LENGTH]float32
gpu := Model.History(Model.HISTORY_GPU, gpu_values[:])
if gpu[last] != 67.0 {
print("history: GPU sample wrong\n")
return false
}
vram := Model.History(Model.HISTORY_VRAM, values[:])
vram_values: [Model.HISTORY_LENGTH]float32
vram := Model.History(Model.HISTORY_VRAM, vram_values[:])
if vram[last] != 81.0 {
print("history: VRAM sample wrong\n")
return false
@@ -437,7 +444,8 @@ HistoryTest :: () -> bool {
for step: 0..Model.HISTORY_LENGTH + 4 {
Model.PushHistory(cast(float64)(step % 100), 0.0, 0.0)
}
wrapped := Model.History(Model.HISTORY_CPU, values[:])
wrapped_values: [Model.HISTORY_LENGTH]float32
wrapped := Model.History(Model.HISTORY_CPU, wrapped_values[:])
newest := cast(float32)((Model.HISTORY_LENGTH + 4) % 100)
if wrapped[last] != newest || wrapped[0] != newest - cast(float32)(Model.HISTORY_LENGTH - 1) {
print("history: wrapped samples out of order\n")
@@ -672,6 +680,40 @@ ExternalGpuTest :: () -> bool {
return true
}
// AMD/Intel per-process GPU use comes from DRM fdinfo counters.
DrmFdinfoTest :: () -> bool {
amd := "pos:\t0\nflags:\t02100002\ndrm-driver:\tamdgpu\ndrm-pdev:\t0000:03:00.0\ndrm-client-id:\t42\ndrm-memory-vram:\t1024 KiB\ndrm-engine-gfx:\t1500000 ns\ndrm-engine-compute:\t0 ns\n"
bytes: [256]u8
reading: GpuDrm.FdinfoClient
if !GpuDrm.ParseFdinfo(BytesOf(amd, bytes[:]), *reading) || reading.client != 42 ||
reading.count != 2 || reading.busy[0] != 1500000 || reading.capacity[0] != 1 {
print("drm: amdgpu fdinfo parsed wrong\n")
return false
}
intel := "drm-driver:\ti915\ndrm-client-id:\t7\ndrm-engine-capacity-video:\t2\ndrm-engine-video:\t900 ns\n"
video: GpuDrm.FdinfoClient
if !GpuDrm.ParseFdinfo(BytesOf(intel, bytes[:]), *video) || video.count != 1 ||
video.capacity[0] != 2 || video.busy[0] != 900 {
print("drm: engine capacity parsed wrong\n")
return false
}
none := "pos:\t0\nflags:\t02\n"
empty: GpuDrm.FdinfoClient
if GpuDrm.ParseFdinfo(BytesOf(none, bytes[:]), *empty) {
print("drm: non-DRM fdinfo accepted\n")
return false
}
// 250 ms busy in 1000 ms, then shared by two engine instances.
if GpuDrm.EnginePercent(0, 250000000, 0, 0, 1000, 1) != 25.0 ||
GpuDrm.EnginePercent(0, 250000000, 0, 0, 1000, 2) != 12.5 ||
GpuDrm.EnginePercent(100, 50, 0, 0, 1000, 1) != 0.0 ||
GpuDrm.EnginePercent(0, 30, 100, 200, 1000, 1) != 30.0 {
print("drm: engine percent wrong\n")
return false
}
return true
}
GpuSharesTest :: () -> bool {
Gpu.GpuSharesReset()
if Gpu.GpuSharesReady() {
@@ -731,6 +773,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
if !AppUsageTest() { print("application usage test failed\n"); return 76 }
if !GpuSharesTest() { print("GPU shares test failed\n"); return 77 }
if !ExternalGpuTest() { print("external GPU test failed\n"); return 78 }
if !DrmFdinfoTest() { print("DRM fdinfo test failed\n"); return 79 }
if !SortTest() { print("sort test failed\n"); return 67 }
if !FormatTest() { print("format test failed\n"); return 68 }
if !SignalTest() { print("signal binding test failed\n"); return 69 }
+108
View File
@@ -0,0 +1,108 @@
// Independent bounded oracle for stable row/group ordering and hash grouping.
Model :: #import "model";
source: Model.Snapshot;
groups: Model.GroupedSnapshot;
expected_groups: Model.GroupedSnapshot;
actual: [64]s32;
expected: [64]s32;
Compare :: (a: *Model.Process, b: *Model.Process, column: s32) -> s32 {
if column == Model.COLUMN_NAME {
for index: cast(s32)0..31 {
if index >= a.name_count || index >= b.name_count { break }
x := a.name[index]; y := b.name[index]
if x < y { return -1 }; if x > y { return 1 }
}
if a.name_count < b.name_count { return -1 }
if a.name_count > b.name_count { return 1 }
return 0
}
if column == Model.COLUMN_CPU {
if a.cpu_percent < b.cpu_percent { return -1 }; if a.cpu_percent > b.cpu_percent { return 1 }
return 0
}
x: u64; y: u64
if column == Model.COLUMN_PID { x = cast(u64)a.pid; y = cast(u64)b.pid }
if column == Model.COLUMN_CPU_TIME { x = a.ticks; y = b.ticks }
if column == Model.COLUMN_MEMORY { x = a.memory_bytes; y = b.memory_bytes }
if x < y { return -1 }; if x > y { return 1 }; return 0
}
#program_export
main :: () -> s32 {
source.count = 64
for index: cast(s32)0..63 {
entry := *source.processes[index]
entry.pid = index + 1
entry.name_count = 2
entry.name[0] = cast(u8)(65 + index % 3)
if index % 2 == 0 { entry.name[0] += cast(u8)32 }
entry.name[1] = cast(u8)(48 + index % 5)
entry.cpu_percent = cast(float64)(index % 4)
entry.memory_bytes = cast(u64)((index * 17) % 11)
entry.ticks = cast(u64)((index * 7) % 9)
}
// Different Codex aliases must occupy the same first-seen group.
for index: cast(s32)0..1 {
entry := *source.processes[index]
entry.name_count = 6
entry.name[0] = 67; entry.name[1] = 111; entry.name[2] = 100
entry.name[3] = 101; entry.name[4] = 120; entry.name[5] = cast(u8)(65 + index)
}
Model.BuildGroupedSnapshot(*source, *groups)
for index: cast(s32)0..63 {
entry := *source.processes[index]
group: s32 = -1
for candidate: 0..expected_groups.count - 1 {
if Model.SameProcessGroup(*source.processes[expected_groups.groups[candidate].process_index], entry) {
group = candidate; break
}
}
if group < 0 { group = expected_groups.count; expected_groups.count += 1; expected_groups.groups[group].process_index = index }
expected_groups.groups[group].group_count += 1
expected_groups.groups[group].cpu_percent += entry.cpu_percent
expected_groups.groups[group].memory_bytes += entry.memory_bytes
expected_groups.groups[group].ticks += entry.ticks
}
if groups.count != expected_groups.count { return 1 }
for index: cast(s32)0..groups.count - 1 {
a := groups.groups[index]; b := expected_groups.groups[index]
if a.process_index != b.process_index || a.group_count != b.group_count ||
a.cpu_percent != b.cpu_percent || a.memory_bytes != b.memory_bytes || a.ticks != b.ticks { return 2 }
}
for mode: cast(s32)0..1 {
count := ifx mode == 0 then source.count else groups.count
for column: cast(s32)0..Model.COLUMNS - 1 {
for direction: cast(s32)-1..1 {
for index: cast(s32)0..count - 1 { expected[index] = index }
if direction != 0 {
for slot: 1..count - 1 {
key := expected[slot]
key_row := source.processes[key]
if mode == 1 { key_row = Model.GroupProcess(*source, *groups.groups[key]) }
at := slot - 1
while at >= 0 {
row := source.processes[expected[at]]
if mode == 1 { row = Model.GroupProcess(*source, *groups.groups[expected[at]]) }
if Compare(*row, *key_row, column) * direction <= 0 { break }
expected[at + 1] = expected[at]; at -= 1
}
expected[at + 1] = key
}
}
if mode == 0 { Model.SortOrder(*source, actual[0:count], column, direction) }
else { Model.SortGroupOrder(*source, *groups, actual[0:count], column, direction) }
for index: cast(s32)0..count - 1 { if actual[index] != expected[index] {
print("ordering mismatch: groups=% column=% direction=% at=% actual=% expected=%\n", mode, column, direction, index, actual[index], expected[index])
return 3
} }
}
}
}
// Odd sizes and truncated output must retain stability too.
source.count = 31
Model.SortOrder(*source, actual[0:17], Model.COLUMN_PID, -1)
for index: cast(s32)0..16 { if actual[index] != 16 - index { return 4 } }
print("taskmgr ordering oracle passed\n")
return 0
}
+55
View File
@@ -0,0 +1,55 @@
// Deterministic full-capacity model workload; never displayed as guest data.
Model :: #import "model";
Number :: #import "std/number_text";
#if #defined(TASKMGR_TAIJI) {
Clock :: #import "kryon/Clock";
} else {
Clock :: #import "std/timer_linux";
}
source: Model.Snapshot;
groups: Model.GroupedSnapshot;
order: [Model.MAX_PROCESSES]s32;
Now :: () -> s64 {
#if #defined(TASKMGR_TAIJI) {
return Clock.Milliseconds()
} else {
return Clock.MonotonicNanoseconds() / 1000
}
}
#program_export
main :: () -> s32 {
source.count = Model.MAX_PROCESSES
#if #defined(TASKMGR_PERF_SMALL) {
source.count = 128
}
for index: 0..source.count - 1 {
entry := *source.processes[index]
entry.pid = index + 1
entry.memory_bytes = cast(u64)(source.count - index) * 1024
entry.cpu_percent = cast(float64)(index % 100)
entry.group_count = 1
entry.name_count = 8
for byte: 0..3 { entry.name[byte] = 97 }
value := index
for digit: 0..3 { entry.name[7 - digit] = cast(u8)(48 + value % 10); value /= 10 }
}
start := Now()
for pass: 0..2 { Model.BuildGroupedSnapshot(*source, *groups) }
grouped_ms := Now() - start
start = Now()
for pass: 0..2 { Model.SortOrder(*source, order[:], Model.COLUMN_MEMORY, 1) }
raw_ms := Now() - start
if order[0] != source.count - 1 || order[source.count - 1] != 0 { return 1 }
start = Now()
for pass: 0..2 { Model.SortGroupOrder(*source, *groups, order[:], Model.COLUMN_MEMORY, 1) }
sort_ms := Now() - start
if order[0] != source.count - 1 || groups.count != source.count { return 2 }
#if #defined(TASKMGR_TAIJI) {
units := "ms"
} else {
units := "us"
}
print("MODEL_PERF rows=% passes=3 units=% group=% raw_sort=% group_sort=% checksum=%\n",
source.count, units, grouped_ms, raw_ms, sort_ms, source.processes[order[0]].pid)
return 0
}
+37
View File
@@ -0,0 +1,37 @@
// Real default-pool guest probe: our ZX task burns CPU beside an owned sleeper.
// No process is fabricated or controlled here; the disposable runner owns both.
Model :: #import "model";
Clock :: #import "kryon/Clock";
#import "std/byte_text_linux"
#program_export
main :: () -> s32 {
Model.Refresh()
initial := Model.Current()
if initial.cpu_available || !initial.memory_available || initial.memory_total != 33554432 { return 3 }
deadline := Clock.Milliseconds() + 300
work: u64 = 1
while Clock.Milliseconds() < deadline {
for index: 0..255 { work = work * 1664525 + 1013904223 }
}
Model.Refresh()
snapshot := Model.Current()
busy: s32 = 0
asleep: s32 = 0
order: [Model.MAX_PROCESSES]s32
for index: 0..snapshot.count - 1 {
row := *snapshot.processes[index]
if row.cpu_available {
print("TASK_CPU_ROW pid=% name=% percent=%\n", row.pid,
TextView(row.name[0:row.name_count]), row.cpu_percent)
if row.cpu_percent > 5 { busy += 1 }
if row.name_count == 5 && row.name[0] == 83 && row.name[1] == 108 &&
row.name[2] == 101 && row.name[3] == 101 && row.name[4] == 112 &&
row.cpu_percent == 0 { asleep += 1 }
}
}
if !snapshot.cpu_available || busy < 1 || asleep < 1 { return 1 }
Model.SortOrder(snapshot, order[:], Model.COLUMN_CPU, -1)
if snapshot.processes[order[0]].cpu_percent <= 5 { return 2 }
print("TASK_CPU_LIVE_OK measured=% sum=% checksum=%\n", snapshot.cpu_measured_tasks, snapshot.cpu_percent, work)
return 0
}
+134
View File
@@ -0,0 +1,134 @@
// Typed service fixtures test units, stale clearing, bounded refresh and target IDs.
Model :: #import "model";
mode: s32;
terminated: s32;
stamp: s64 = 1000000000;
counter: s64 = 100000000;
identity: s64 = 1;
#program_export
SampleNanos :: () -> s64 { return stamp }
#program_export
Capture :: () -> s32 {
if mode == 1 { return -1 }
if mode == 6 { return 0 }
if mode == 7 { return Model.MAX_PROCESSES }
return 2
}
#program_export
TaskAt :: (index: s32, fields: []s64, name: []u8, user: []u8) -> s32 {
if mode == 2 && index == 1 { return -1 }
fields[0] = 100 + index
fields[1] = 7
fields[2] = 4
fields[3] = ifx index == 0 then 12 else -1
fields[4] = ifx index == 0 then counter else 0
fields[5] = identity + cast(s64)index
fields[6] = 0
if mode == 8 { fields[4] = -1 }
if mode == 9 { fields[0] = 200 + index }
name[0] = cast(u8)(65 + index % 26)
if mode == 5 { name[0] = 90 }
name[1] = 0
user[0] = 0
return 0
}
#program_export
PoolAt :: (index: s32, fields: []s64) -> s32 {
if mode == 3 { return -1 }
fields[0] = ifx mode == 4 then 8192 else 4096
fields[1] = 33554432
fields[2] = 8192
return 0
}
#program_export
Terminate :: (pid: s32) -> s32 { terminated = pid; return 0 }
#program_export
main :: () -> s32 {
max_bytes: [14]u8
full_bytes: [32]u8
maximum := cast(u64)18446744073709551615
if Model.FormatBytes(maximum, max_bytes[:]) != Model.FormatBytes(maximum, full_bytes[:]) { return 12 }
Model.Refresh()
initial_revision := Model.TableRevision()
for sample: 0..999 {
Model.Refresh()
snapshot := Model.Current()
if !snapshot.processes_available || snapshot.count != 2 { return 1 }
if snapshot.cpu_available || !snapshot.memory_available { return 2 }
if snapshot.memory_used != 4096 || snapshot.memory_total != 33554432 { return 3 }
if snapshot.processes[0].pid != 100 || snapshot.processes[0].memory_bytes != 12288 { return 4 }
if snapshot.processes[1].memory_available { return 5 }
}
if Model.TableRevision() != initial_revision { return 13 }
mode = 4
Model.Refresh()
if Model.TableRevision() != initial_revision || Model.Current().memory_used != 8192 { return 14 }
mode = 5
Model.Refresh()
if Model.TableRevision() == initial_revision { return 15 }
mode = 0
Model.Refresh()
if !Model.EndTask(101) || terminated != 101 { return 6 }
if Model.EndTask(0) || terminated != 101 { return 7 }
if Model.StartTask("host command must not execute") { return 8 }
mode = 1
Model.Refresh()
if Model.Current().processes_available || Model.Current().count != 0 { return 9 }
mode = 2
Model.Refresh()
if Model.Current().processes_available || Model.Current().count != 0 { return 10 }
mode = 3
Model.Refresh()
if Model.Current().memory_available || Model.Current().memory_used != 0 { return 11 }
mode = 6
Model.Refresh()
if !Model.Current().processes_available || Model.Current().count != 0 { return 16 }
mode = 7
Model.Refresh()
if Model.Current().count != 1024 || Model.Current().processes[1023].pid != 1123 { return 17 }
// Start a new task pair; first reading is unavailable, then a real delta.
mode = 9
stamp = 2000000000
Model.Refresh()
if Model.Current().processes[0].cpu_available { return 18 }
stamp += 1000000000
counter += 250000000
Model.Refresh()
snapshot := Model.Current()
if !snapshot.cpu_available || snapshot.cpu_measured_tasks != 2 ||
!snapshot.processes[0].cpu_available || snapshot.processes[0].cpu_percent != 25.0 ||
snapshot.processes[1].cpu_percent != 0 || snapshot.cpu_percent != 25.0 { return 19 }
order: [2]s32
Model.SortOrder(snapshot, order[:], Model.COLUMN_CPU, -1)
if order[0] != 0 { return 20 }
// Same clock, changed identity and counter rollback never carry a delta.
Model.Refresh()
if Model.Current().cpu_available { return 21 }
stamp += 1000000000
identity = 20
Model.Refresh()
if Model.Current().cpu_available { return 22 }
stamp += 1000000000
counter = 0
Model.Refresh()
if Model.Current().processes[0].cpu_available { return 23 }
stamp += 1000000000
Model.Refresh()
if !Model.Current().processes[0].cpu_available || Model.Current().processes[0].cpu_percent != 0 { return 24 }
mode = 8
stamp += 1000000000
Model.Refresh()
if Model.Current().cpu_available { return 25 }
mode = 1
Model.Refresh()
if Model.Current().cpu_available { return 26 }
mode = 9
stamp += 1000000000
Model.Refresh()
if Model.Current().cpu_available { return 27 }
// More than one core of measured task CPU must not be clamped in totals.
total_text: [24]u8
if Model.FormatAccountedCpu(125.5, total_text[:]) != "125.5" { return 28 }
print("taskmgr Taiji adapter tests passed\n")
return 0
}
+53 -53
View File
@@ -19,6 +19,15 @@
"source": true,
"url": "https://github.com/libsdl-org/SDL.git"
},
{
"commit": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "p2af20e0c835b1c63",
"name": "webp",
"ref": "ec6ed304767e10c125ab2820f3b01d6fd773e147",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "1844042d1ca751e62e61df7617dba19c98588339",
"dependencies": {},
@@ -28,6 +37,15 @@
"source": true,
"url": "https://github.com/webmproject/libwebp.git"
},
{
"commit": "f5f186bb13569ef13338f81366ff63fb9b9282f6",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p3ed49c5d0912e411",
"name": "avif",
"ref": "f5f186bb13569ef13338f81366ff63fb9b9282f6",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
"dependencies": {},
@@ -37,6 +55,15 @@
"source": true,
"url": "https://github.com/AOMediaCodec/libavif.git"
},
{
"commit": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"dependencies": {"libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
"id": "p59deb49c7f103127",
"name": "audio",
"ref": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2",
"url": "https://github.com/ziranlang/audio.git"
},
{
"commit": "bd278217e2bac754d868b3d6502eac4257658d4b",
"dependencies": {"dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa"},
@@ -63,24 +90,6 @@
"source": true,
"url": "https://aomedia.googlesource.com/aom"
},
{
"commit": "f84c162594e518cb306bfd0ce41783ad55b6c730",
"dependencies": {"av1": "p5d7d12505a42f7b3", "dav1d": "pb24767b9eb34d961", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db"},
"dependency_refs": {"av1": "bd278217e2bac754d868b3d6502eac4257658d4b", "dav1d": "54706fc6bc0cdecab7e9593974a4039cc038fca7", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199"},
"id": "p872d871f84f2284f",
"name": "avif",
"ref": "f84c162594e518cb306bfd0ce41783ad55b6c730",
"url": "https://github.com/ziranlang/avif.git"
},
{
"commit": "02145a00a1f0df2a111da04a75f3fef260883897",
"dependencies": {"image_codec": "p69c0e968ae5735d9", "libwebp": "p3b3c785a0e17e605"},
"dependency_refs": {"image_codec": "360553150917f352e49e1beb78917370792ccaef", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339"},
"id": "pa068bd09450b2a80",
"name": "webp",
"ref": "02145a00a1f0df2a111da04a75f3fef260883897",
"url": "https://github.com/ziranlang/webp.git"
},
{
"commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7",
"dependencies": {},
@@ -91,31 +100,22 @@
"url": "https://github.com/videolan/dav1d.git"
},
{
"commit": "942fea7809063407e2b4fa9611a2247ab6b3b894",
"dependencies": {"kryon": "pee06f03a46364dfb"},
"dependency_refs": {"kryon": "master"},
"id": "pc4c837bf2ac33dfb",
"name": "DataViews",
"ref": "master",
"url": "https://github.com/kryonlabs/data-views.git"
"commit": "43e6ea3d76ded207e2be93ff82b2a609c3cfeb91",
"dependencies": {"audio": "p59deb49c7f103127", "avif": "p3ed49c5d0912e411", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "f5f186bb13569ef13338f81366ff63fb9b9282f6", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
"id": "pbc3b5919c300641a",
"name": "kryon",
"ref": "43e6ea3d76ded207e2be93ff82b2a609c3cfeb91",
"url": "https://git.waozi.xyz/kryonlabs/kryon.git"
},
{
"commit": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"dependencies": {},
"id": "pcc7aa76725f2fb2f",
"name": "raylib",
"ref": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e",
"source": true,
"url": "https://github.com/raysan5/raylib.git"
},
{
"commit": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b",
"dependencies": {"libopus": "pe1fe9bbe80bf1d6d", "libsamplerate": "p0dd67588478f9a3e"},
"dependency_refs": {"libopus": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6", "libsamplerate": "c96f5e3de9c4488f4e6c97f59f5245f22fda22f7"},
"id": "pd258d453b63edc1f",
"name": "audio",
"ref": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b",
"url": "https://github.com/ziranlang/audio.git"
"commit": "b764139c3c03b3ee183e2e712f9f045b4575fc92",
"dependencies": {"audio": "p59deb49c7f103127", "avif": "p3ed49c5d0912e411", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "f5f186bb13569ef13338f81366ff63fb9b9282f6", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
"id": "pbece9ca38cacd9ea",
"name": "kryon",
"ref": "b764139c3c03b3ee183e2e712f9f045b4575fc92",
"url": "https://git.waozi.xyz/kryonlabs/kryon.git"
},
{
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
@@ -127,23 +127,23 @@
"url": "https://github.com/xiph/opus.git"
},
{
"commit": "b154a5faec4e52e9982d75956d9c71d5309ba9a7",
"dependencies": {"audio": "pd258d453b63edc1f", "avif": "p872d871f84f2284f", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "raylib": "pcc7aa76725f2fb2f", "sdl3": "p16cd0434af3dff7b", "webp": "pa068bd09450b2a80"},
"dependency_refs": {"audio": "f5eed1e6c817997d51508f9c3c7b948a0bb4ad0b", "avif": "f84c162594e518cb306bfd0ce41783ad55b6c730", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "raylib": "fafa2cea97d0cb379d832086ba45a989fa6f9c8e", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "02145a00a1f0df2a111da04a75f3fef260883897"},
"id": "pee06f03a46364dfb",
"name": "kryon",
"ref": "master",
"url": "https://github.com/kryonlabs/kryon.git"
"commit": "e8abb23a4bbae6d92b62d477f816d0fa5ded5e1a",
"dependencies": {"kryon": "pbc3b5919c300641a"},
"dependency_refs": {"kryon": "43e6ea3d76ded207e2be93ff82b2a609c3cfeb91"},
"id": "pe83f832fd9ca0b92",
"name": "DataViews",
"ref": "e8abb23a4bbae6d92b62d477f816d0fa5ded5e1a",
"url": "https://git.waozi.xyz/kryonlabs/data-views.git"
}
],
"root": {
"dependencies": {"data_views": "pc4c837bf2ac33dfb", "kryon": "pee06f03a46364dfb"},
"dependency_refs": {"data_views": "master", "kryon": "master"},
"dependencies": {"data_views": "pe83f832fd9ca0b92", "kryon": "pbece9ca38cacd9ea"},
"dependency_refs": {"data_views": "e8abb23a4bbae6d92b62d477f816d0fa5ded5e1a", "kryon": "b764139c3c03b3ee183e2e712f9f045b4575fc92"},
"name": "taskmgr"
},
"toolchain": {
"commit": "d2db9d35feaf2a3278dc7bed571022b0e0323247",
"ref": "master",
"url": "https://github.com/ziranlang/ziran.git"
"commit": "5462fe2ebf2c3c42663249e47ef99d61f45ff39f",
"ref": "5462fe2ebf2c3c42663249e47ef99d61f45ff39f",
"url": "https://git.waozi.xyz/ziranlang/ziran.git"
}
}
+7 -6
View File
@@ -6,19 +6,20 @@ bridge_modules = ["app"]
tool = "kryon"
[toolchain]
git = "https://github.com/ziranlang/ziran.git"
ref = "master"
git = "https://git.waozi.xyz/ziranlang/ziran.git"
ref = "5462fe2ebf2c3c42663249e47ef99d61f45ff39f"
[dependencies.kryon]
git = "https://github.com/kryonlabs/kryon.git"
ref = "master"
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
ref = "b764139c3c03b3ee183e2e712f9f045b4575fc92"
[dependencies.data_views]
git = "https://github.com/kryonlabs/data-views.git"
ref = "master"
git = "https://git.waozi.xyz/kryonlabs/data-views.git"
ref = "e8abb23a4bbae6d92b62d477f816d0fa5ded5e1a"
[exports]
model = "src/model.zi"
service = "src/service.zi"
[install]
bin = "taskmgr"