diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 09c4651..b16f866 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -19,7 +19,10 @@ jobs:
- name: Install Qt Quick build dependencies
run: |
sudo apt-get update
- sudo apt-get install -y qt6-base-dev qt6-declarative-dev qmake6 zlib1g-dev
+ sudo apt-get install -y qt6-base-dev qt6-declarative-dev qmake6 libglib2.0-dev libegl-dev \
+ qml6-module-qtquick-controls qml6-module-qtquick-layouts \
+ qml6-module-qtquick-templates qml6-module-qttest qml6-module-qtquick-window \
+ qml6-module-qtqml-workerscript qml6-module-qtquick-dialogs
- name: gofmt
run: |
@@ -42,8 +45,16 @@ jobs:
- name: go test
run: go test ./...
- - name: Viewer protocol tests
- run: make test-viewer
+ # Skipped without KVM (and the rendering test without Wayland):
+ # hosted runners exercise only the build of these tests.
+ - name: Display protocol tests
+ run: make test-display
- name: Terminal emulator tests
run: make test-terminal
+
+ - name: GUI backend tests
+ run: make test-backend
+
+ - name: QML UI tests
+ run: make test-qml
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..98be577
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,38 @@
+name: Release
+
+# Attaches the portable tarball OmaStore installs (omastore.toml) to the
+# GitHub release of every version tag, creating the release if needed.
+on:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: write
+
+jobs:
+ tarball:
+ runs-on: ubuntu-latest
+ # Built on Arch: omavm-gui links the system's Qt 6, and Omarchy follows
+ # Arch's. Ubuntu's older Qt would work too, but only by accident.
+ container: archlinux:latest
+ steps:
+ - name: Install build dependencies
+ run: pacman -Syu --noconfirm --needed base-devel git go qt6-base qt6-declarative glib2 libglvnd github-cli
+
+ - uses: actions/checkout@v7
+
+ - name: Build
+ run: |
+ git config --global --add safe.directory "$GITHUB_WORKSPACE"
+ go test ./...
+ make dist VERSION="${GITHUB_REF_NAME#v}"
+
+ - name: Upload to the release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 ||
+ gh release create "$GITHUB_REF_NAME" --verify-tag --generate-notes
+ gh release upload "$GITHUB_REF_NAME" --clobber \
+ build/dist/omavm-*-x86_64-linux.tar.gz \
+ build/dist/omavm-*-x86_64-linux.tar.gz.sha256
diff --git a/CLAUDE.md b/CLAUDE.md
index c1d9fb6..3c8a3ec 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8,7 +8,7 @@ Este arquivo é a constituição técnica e de produto do OmaVM. Qualquer agente
O repositório contém Core e CLI em Go, GUI Qt Quick/QML, backends Distrobox e QEMU/KVM, testes e CI. **A Fase 1 (vertical slice mínimo de Box e Machine) está concluída** (ver Current Priorities); a partir de 2026-09-26 o projeto está na Fase 2, com escopo liberado para os itens listados em Current Priorities → Fase 2. Recursos ainda marcados como futuros fora dessa lista continuam sendo objetivos, não capacidades entregues, e continuam gated por necessidade real (ver Coding Principles, Scope/Non-Goals). O requisito de Go é definido em `go.mod`.
-Desligamento normal nunca deve virar Force Stop automaticamente. Restart usa desligamento normal seguido de Start; falhas preservam a Machine. O disco tem prioridade de boot sobre a ISO, que pode ser desconectada no próximo Start por Settings (`--disconnect-iso`). Alterações do registro são protegidas por um lock entre processos durante leitura, operação e gravação.
+Desligamento normal nunca deve virar Force Stop automaticamente. Restart usa desligamento normal seguido de Start; falhas preservam a Machine. O disco tem prioridade de boot sobre a ISO, que pode ser desconectada no próximo Start por Settings (`--disconnect-iso`). Concorrência entre processos (desde 2026-09-29): o lock do **registro** (`environments.json.lock`) só cobre ler-alterar-gravar e nunca é mantido durante uma chamada ao backend; operações que mudam **um** ambiente (start, stop, restart, pause, snapshots, remoção) seguram o lock **desse ambiente** (`locks/.lock`) durante a chamada ao backend, sempre pegando-o antes do lock do registro. Criar e remover são em duas fases: o ambiente fica no registro com `operation: "creating"`/`"removing"` (status `creating`/`removing`) enquanto o backend trabalha — um pull de imagem de minutos não trava mais os outros ambientes. Um `flock` morre com o processo, então uma marca com o lock livre é uma operação interrompida: vira status `error` e o ambiente só aceita ser removido. `Open` e `Exec` não pegam lock (o `Open` de uma Box é o shell interativo). O registro é gravado como a lista simples que versões antigas leem; `Load` também lê o envelope `{"version": N, "environments": [...]}` e recusa versões mais novas — só passe a gravá-lo quando houver uma mudança incompatível de fato.
**Linguagem: Go**, confirmado. Além disso, siga apenas as convenções idiomáticas padrão do Go (formatação via `gofmt`, nomes de pacote, etc.) — o layout de diretórios em si é uma decisão aberta (ver Open Technical Decisions).
@@ -160,17 +160,29 @@ omavm status radic --json
OmaVM é **Omarchy-first**. Integração com o host é feature central, não avançada. Tratar como capacidades de primeira classe (quando aplicável ao backend): clipboard, compartilhamento de diretórios, project folders, Wayland, áudio, microfone, notificações, resolução dinâmica, SSH, execução de comandos, transferência de arquivos, GPU acceleration. A UI expõe capacidades/intenções, não os mecanismos internos usados para implementá-las.
-Implementado até agora: frontend Qt Quick/QML com toast in-app; entrada `.desktop` + ícone (`data/`) para o `omavm-gui` aparecer no launcher/taskbar com app-id próprio; sincronização direta com o tema Omarchy ativo (dark/light, background, foreground, accent e selection), acompanhando trocas em runtime. A aplicação apenas consome `colors.toml`; não mantém tema próprio. Como OMAcut/OMAwrite, a janela principal é tiled por padrão; não adicione regra Hyprland para fazê-la flutuar. OMAcalc é uma exceção compacta explicitamente marcada como floating, não um precedente para a OmaVM.
+Implementado até agora: frontend Qt Quick/QML com toast in-app; entrada `.desktop` + ícone (`data/`) para o `omavm-gui` aparecer no launcher/taskbar com app-id próprio; sincronização direta com o tema Omarchy ativo (dark/light, background, foreground, accent e selection), acompanhando trocas em runtime. A aplicação apenas consome `colors.toml`; não mantém tema próprio. Consumir não significa repassar cegamente: texto precisa de 7:1 (WCAG 2.2 AAA 1.4.6) sobre as duas superfícies, então `Backend::loadTheme` ajusta `foreground`/`muted` (`readableTextColor`) e as cores de estado usadas como texto — verde, vermelho e `themeAccentText` — com `accessibleColor`, que mantém o tom e só clareia ou escurece o necessário; o accent cru fica para os controles do Material. `everyThemeTextMeetsAAA` confere isso em todos os temas instalados. A acessibilidade é auditada pela árvore que o Qt entrega ao AT-SPI (`tst_accessibility.qml`): controle visível sem nome ou inalcançável por teclado falha o teste. Com a acessibilidade ativa, o Qt ignora `Accessible.checked` escrito à mão e anuncia o estado do próprio controle — seleção tem que ser um controle `checkable` de verdade, e uma escolha exclusiva (as cores) leva `Accessible.role: Accessible.RadioButton`, sem o qual o Qt 6.4 não a declara marcável. Os testes consultam a `QAccessibleInterface` (`accessibilityProblems`, `accessibleState`), nunca a propriedade anexada do QML, que diverge entre versões; o CI roda o Qt 6.4 do Ubuntu 24.04 e o desenvolvimento o Qt do Arch, e os dois precisam passar.
+
+A GUI roda ações de ambientes diferentes ao mesmo tempo (`Backend::busyEnvironments`, desde 2026-09-29): o Core já serializa cada ambiente pelo lock dele, então a GUI só recusa uma segunda ação no **mesmo** ambiente. Como OMAcut/OMAwrite, a janela principal é tiled por padrão; não adicione regra Hyprland para fazê-la flutuar. OMAcalc é uma exceção compacta explicitamente marcada como floating, não um precedente para a OmaVM.
**Quickshell (`omarchy-shell`)**: `contrib/dev.omavm.bar` é um plugin `bar-widget` real para o shell Quickshell plugin-based do Omarchy (`/usr/share/omarchy/shell`), não especulativo — mostra a contagem de Environments (via `omavm list --json`) e abre o `omavm-gui` ao clicar. `make install` já copia o plugin para `~/.config/omarchy/plugins/` (via `install-quickshell-plugin`, chamado automaticamente como dependência), mas **nunca habilitado automaticamente**: plugins de terceiros rodam sem sandbox dentro do shell já ativo do usuário, então habilitar é sempre um passo manual e explícito do usuário (`omarchy plugin enable`), nunca algo que um agente/instalador faz sozinho. Copiar o arquivo é inofensivo (só existe no disco até alguém rodar `omarchy plugin enable`); é esse comando — nunca disparado por `make install` nem por qualquer target — que carrega QML de terceiros no shell já ativo. Isso desbloqueou `omavm list`/`status --json` na CLI (já citado como aspiração no CLI/GUI Contract) — mantenha esse contrato JSON estável, é consumido por automação externa agora, não só hipoteticamente.
-**Color tags + Travel Mode — implementado (2026-09-27)**, a partir da pesquisa sobre Parallels Desktop (2026-09-26): `EnvironmentSettings.Color` vem de uma paleta fixa (`core.EnvironmentColors`: red/orange/yellow/green/blue/purple/gray — não hex livre, pra não competir com o tema Omarchy) e é o único mecanismo garantido; a sincronização com o gerenciador de arquivos do host é best-effort em cima disso, nunca uma promessa (Security Model). Só a Machine (QEMU) implementa a capability opcional `core.HostLinker`: `Configure` chama `Link` quando o `--color` muda, criando/atualizando `~/OmaVM/` como symlink pro qcow2 da Machine (dá a ela uma presença real e navegável no filesystem, papel equivalente ao bundle `.pvm` do Parallels) e tentando `setfattr -n user.xdg.tags` nesse link — se `setfattr` não existir ou falhar, a cor interna continua válida mesmo assim, só a integração visual no file manager que não acontece (o Omarchy pode ou não honrar essa xattr, fora do controle da OmaVM). `Remove` chama `Unlink`. Box ainda não implementa `HostLinker` (não tem um único arquivo pra vincular) — a cor fica só interna nesse caso, sem erro.
+**Color tags + Travel Mode — implementado (2026-09-27)**, a partir da pesquisa sobre Parallels Desktop (2026-09-26): `EnvironmentSettings.Color` vem de uma paleta fixa (`core.EnvironmentColors`: red/orange/yellow/green/blue/purple/gray — não hex livre, pra não competir com o tema Omarchy) e é o único mecanismo garantido; a sincronização com o gerenciador de arquivos do host é best-effort em cima disso, nunca uma promessa (Security Model). Só a Machine (QEMU) implementa a capability opcional `core.HostLinker`: `Configure` chama `Link` quando o `--color` muda, criando/atualizando `~/OmaVM/` como symlink pro qcow2 da Machine (dá a ela uma presença real e navegável no filesystem, papel equivalente ao bundle `.pvm` do Parallels) e tentando `setfattr -n user.xdg.tags` nesse link — se `setfattr` não existir ou falhar, a cor interna continua válida mesmo assim, só a integração visual no file manager que não acontece (o Omarchy pode ou não honrar essa xattr, fora do controle da OmaVM). `Remove` chama `Unlink`. Box ainda não implementa `HostLinker` (não tem um único arquivo pra vincular) — a cor fica só interna nesse caso, sem erro. Desde 2026-09-28 o `Link` também grava `metadata::custom-icon` (GVFS, via `gio set --nofollow-symlinks`) no próprio link, apontando para o ícone da cor (`data/icons/colors/.svg`, instalado em `/omavm/icons/`, achado por `desktop.ColorIcon`): é o que o **Nautilus** do Omarchy lê — ele ignora `user.xdg.tags`, que continua gravado para Dolphin/Baloo. Mesmo best-effort.
Travel Mode: `internal/backend/qemu/power.go` lê `/sys/class/power_supply` diretamente (sem depender do `upower`) só no momento do `Start`, não como daemon (`omavmd` continua fora de escopo). Se o host está na bateria, o usuário não fixou `--cpus` explicitamente e `EnvironmentSettings.TravelModeDisabled` está falso (default), o `Start` daquela sessão usa metade dos CPUs padrão (nunca sobrescrevendo o valor persistido) e loga via `slog`. Não reage a uma Machine já rodando quando a energia muda em tempo real — isso exigiria um watcher em background, que é exatamente o primeiro caso de uso concreto que justificaria um `omavmd` de verdade no futuro, mas essa decisão foi propositalmente adiada.
+**Integrações são opt-out (decisão do usuário, 2026-09-28)**: toda integração nova com o host/desktop vem ligada e é desligável por ambiente em Settings — nunca um opt-in que o usuário precisa descobrir. Exceções que continuam manuais: habilitar o plugin Quickshell e a regra Hyprland pessoal (config de terceiros/pessoal que a OmaVM não escreve). Integração com custo de segurança também vem ligada quando o usuário decide assim — como o SSH via vsock —, mas o custo é **dito na tela** (Settings, `--help`, `omavm host`), nunca escondido (Security Model).
+
+**Travel Mode para Boxes — implementado (2026-09-28)**: `internal/backend/distrobox/travel.go`, no Start/Open da Box, usa ` update --cpus` (Podman, ou Docker se for ele que tem o container) por baixo do Distrobox: na bateria, metade dos CPUs; na tomada, todos de volta. Testado contra Podman 6.1 + Distrobox 1.8: o limite vale com o container parado ou rodando e sobrevive a `distrobox enter` e stop/start; `--cpus 0` e `--cpu-quota -1/0` **não** removem um limite, por isso "sem limite" é `--cpus `. Box nunca limitada e na tomada não recebe `update` nenhum. Mesma opção opt-out `TravelModeDisabled` da Machine, agora para os dois Kinds. A leitura de energia saiu de `qemu/power.go` para `internal/power` (dois usos). Limites fixos de CPU/memória por Box continuam não implementados.
+
+**SSH em Machines via vsock — implementado (2026-09-28), ligado por padrão por decisão do usuário**: `internal/backend/qemu/vsock.go` adiciona `-device vhost-vsock-pci,guest-cid=N` quando `/dev/vhost-vsock` é acessível e `EnvironmentSettings.SSHDisabled` é falso. O CID é aleatório acima de 65535 (longe dos sequenciais do libvirt), guardado em `/machines//vsock-cid` para a chave do host não mudar; se o QEMU recusar (`unable to set guest cid: Address already in use`, outro VM tem o CID), sorteia outro e tenta uma vez mais. O CID em uso é lido do `/proc//cmdline` do QEMU. `omavm ssh NOME [--user U] [-- CMD]` (capability `core.RemoteShell`) e `omavm exec` numa Machine (antes `ErrUnsupported`; agora `BatchMode=yes`, argumentos citados para o shell remoto) rodam `ssh vsock/` com `systemd-ssh-proxy`; as opções na linha de comando vencem o `ssh_config.d` do systemd, que loga como root e desliga a checagem de chave: aqui o login é o usuário do host e a chave fica em `known_hosts` sob `HostKeyAlias=omavm-` (`accept-new`). O guest precisa de systemd ≥ 256 com sshd; sem isso, erro claro. **Custo de segurança dito na tela**: o CID é global no host, então qualquer processo, Boxes incluídas, alcança o sshd do guest e só o login dele protege — Settings mostra isso em texto (não só tooltip), assim como `--help` e `omavm host`. Validado com QEMU real: sobe sem root, `savevm`/`loadvm` funcionam com o dispositivo, e `omavm ssh` chega ao CID pelo proxy (sem sshd no guest de teste, cai na mensagem de ajuda); login num guest real **não** foi verificado.
+
+**Entrada no launcher por ambiente — implementado (2026-09-28), opt-out**: `internal/desktop` escreve `$XDG_DATA_HOME/applications/dev.omavm.env..desktop` para cada ambiente (nome pelo ID, que nunca muda). `Exec` de Machine é `omavm open NOME` (inicia se preciso e abre o viewer); de Box é `omavm-gui --terminal NOME` (ou `omavm open` com `Terminal=true` sem a GUI). Ícone pela cor do ambiente. A Core só conhece a interface `core.Launcher` (`Service.SetLauncher`, injetada pelo `cmd/omavm`): publica no Create/Configure e também no Start/Open (o que cobre ambientes criados antes), retira no Remove e quando `EnvironmentSettings.LauncherDisabled` (`--launcher=false`, Settings → Automation). Falha de escrita nunca falha a operação. `make uninstall` apaga as entradas (apontariam para binários que sumiram); `omavm` as recria no próximo start.
+
**Ajuste de UX (2026-09-27)**: Travel Mode e o clipboard-share (abaixo) são **opt-out, não opt-in** — ligados por padrão, persistidos por Machine (`omavm settings NOME --travel-mode=false`/`--share-clipboard=false`, ou Settings → Automation na GUI), nunca um checkbox de sessão que o usuário precisa lembrar de reativar toda vez que abre o viewer. `EnvironmentSettings.ClipboardDisabled`/`TravelModeDisabled` guardam o estado invertido de propósito: o zero-value do Go (`false`) já significa "habilitado", então um `environments.json` antigo sem esses campos continua com tudo ligado.
-**Logs**: ambos os binários usam `log/slog` (JSON). `/var/log` é root-owned por padrão; a OmaVM nunca eleva privilégio silenciosamente para escrever lá (ver Security Model). O destino é `/var/log/omavm/.log` apenas se esse diretório já existir e for gravável; caso contrário cai para `$XDG_STATE_HOME/omavm/logs/`. Ver README seção "Logs" para o passo opcional (`sudo install -d ...`) que provisiona `/var/log/omavm`.
+**Logs**: ambos os binários usam `log/slog` (JSON). `/var/log` é root-owned por padrão; a OmaVM nunca eleva privilégio silenciosamente para escrever lá (ver Security Model). O destino é `/var/log/omavm/.log` apenas se esse diretório já existir e for gravável; caso contrário cai para `$XDG_STATE_HOME/omavm/logs/`. Ver README seção "Logs" para o passo opcional (`sudo install -d ...`) que provisiona `/var/log/omavm`. Desde 2026-09-28: rotação por tamanho (acima de 5 MiB o log vira `.log.1`), "log opened" só na primeira linha de cada arquivo, e comandos somente leitura (`list`, `status`, …, que a GUI e a barra rodam a cada poucos segundos) em nível Debug, que não é gravado — o log de 1,5 MB em dois dias era quase todo poll.
+
+**OmaStore (2026-09-29)**: `omastore.toml` na raiz lista a OmaVM na loja; valide com `omastore lint-manifest .` (estrito). O manifesto declara o que as heurísticas errariam: o executável é `bin/omavm-gui` (pelo nome do repositório a loja escolheria a CLI) e o ícone `data/icons/dev.omavm.app.svg`. O asset é o tarball plano de `make dist` (`bin/omavm`, `bin/omavm-gui`, `data/`), publicado por `.github/workflows/release.yml` a cada tag `v*`, compilado em `archlinux:latest` porque a GUI linka o Qt 6 do sistema. Instalado fora do `/usr`, cada binário acha o outro por ser vizinho em `bin/`, e `internal/desktop` usa os ícones de `data/` ao lado (`ColorIcon`, `appIcon`) em vez de nomes de tema que ninguém instalou.
## Coding Principles
@@ -197,6 +209,7 @@ Evitar:
- Testes de adapter (container engine, QEMU/KVM) validam a integração real e podem depender do ambiente/host; devem ficar claramente separados dos testes de domínio. A forma exata dessa separação é uma decisão aberta (ver Open Technical Decisions) e não deve ser fixada incidentalmente.
- CLI deve ser testável invocando o Core diretamente, sem precisar de GUI.
- Baseline padrão de Go a manter assim que houver `go.mod`: `go build ./...`, `go test ./...` (com `-run ` para um teste único), `go vet ./...`, `gofmt -l .`. Comandos mais específicos (lint adicional, tags de build para testes de integração, etc.) devem ser adicionados a este arquivo assim que existirem de fato no repositório — não documentar ferramentas ainda não escolhidas.
+- O JSON da CLI (`list`, `list --status`, `status`, `settings`, `snapshot list`) é contrato com GUI, barra e agentes: `TestJSONContract` compara com `cmd/omavm/testdata/*.golden.json`. Uma mudança intencional é regravada com `go test ./cmd/omavm -run TestJSONContract -update` e revisada no diff.
- `Makefile` disponível como atalho para esses mesmos comandos (`make build`, `make test`, `make vet`, `make fmt-check`, `make check`); ele não substitui os comandos Go diretos, apenas os agrupa.
- CI (`.github/workflows/ci.yml`, GitHub Actions) roda `gofmt -l .`, `go vet ./...`, `go build ./...`, `go test ./...` e compila a GUI com qmake6 em toda push/PR para `master`. Ele instala Qt 6 Base/Declarative para o frontend.
@@ -256,19 +269,23 @@ Nunca começar pela GUI chamando comandos de infraestrutura diretamente.
**Machine (via QEMU/KVM):** Create, Start, Stop, Status, Open, Remove.
-**Implementado (2026-09-26)**: `Open` numa Machine abre de fato um userspace gráfico via **VNC**, headless — QEMU expõe `virtio-vga-gl` sobre `-display egl-headless` (GPU acelerada mesmo sem display local) e escuta num socket unix (`-vnc unix:/vnc.sock`, mesmo modelo de confiança local-only que o antigo socket SPICE). `Open` não chama mais um visualizador externo: lança o próprio `omavm-gui` em modo `--viewer --title `, que carrega `gui/Viewer.qml` num `Window` fullscreen falhando de forma explícita — nunca em silêncio — se `omavm-gui` não estiver instalado. O protocolo RFB é implementado do zero em `gui/vncclient.h/.cpp` (handshake 3.8, segurança "None", só encoding Raw) em vez de linkar `libvncserver`/`libvncclient`: essa lib é GPL-2.0 e o projeto é MIT, e para um socket local sem autenticação nem compressão o protocolo necessário é pequeno o suficiente pra não justificar a dependência. `gui/vncview.h/.cpp` (`QQuickPaintedItem`) desenha o framebuffer e encaminha mouse/teclado de volta (PointerEvent/KeyEvent) — é um viewer interativo, não só uma prévia.
+**Implementado (2026-09-26, display migrado para D-Bus em 2026-09-28)**: `Open` numa Machine abre de fato o userspace gráfico dentro do próprio `omavm-gui`. A Machine roda headless com o **D-Bus display do QEMU em modo peer-to-peer** (`-display dbus,p2p=yes,gl=on` + `virtio-vga-gl`; sem render node utilizável no host, `virtio-vga` + `dbus,p2p=yes`). Ninguém escuta até o `Open`: `qemu.Backend.attachDisplay` cria um socketpair, entrega uma ponta ao QEMU via QMP (`getfd` com SCM_RIGHTS + `add_client protocol=@dbus-display`) e a outra ao viewer como fd herdado (`omavm-gui --display-fd 3 --title --share-clipboard=...`). Detalhes de QMP ficam no adapter; o viewer só fala o protocolo de display. Machines iniciadas antes dessa migração (ainda com VNC) recebem "restart it" em vez de um erro de QMP (resposta real do QEMU 11.1: `DeviceNotActive: D-Bus display is not in use`).
+
+Substituiu o cliente RFB próprio (removido): com `gl=on` os quadros chegam como **dma-bufs** (`ScanoutDMABUF`/`UpdateDMABUF`) e são importados como textura GL via EGL (`EGL_EXT_image_dma_buf_import`, com modifier — a Intel manda tiling X) sem cópia pela CPU; o QEMU segura a GPU do guest até cada `UpdateDMABUF` ser respondido, e `DisplayClient` responde depois do `frameSwapped` (ou em 50 ms, para janela oculta nunca travar o guest). Sem GPU, `ScanoutMap`/`UpdateMap` compartilham a superfície por memfd. `gui/displayclient.h/.cpp` (protocolo, sem GUI) usa **GDBus (gio, LGPL, link dinâmico)** e não QtDBus: toda conexão aqui é um socket já conectado entregue por outro processo, e o QtDBus não adota fd. O QEMU é servidor de autenticação nas duas conexões (principal e listener). `gui/displayview.h/.cpp` (`QQuickItem`) desenha e encaminha entrada; o viewer força o RHI OpenGL (`QQuickWindow::setGraphicsApi`). Orientação: o `y0_top` do QEMU é relativo ao framebuffer GL de baixo para cima (a UI GTK dele inverte quando é falso); o scene graph amostra de cima para baixo, então o viewer inverte quando `y0_top` é **verdadeiro** — validado por teste.
-O viewer negocia DesktopSize/ExtendedDesktopSize e envia SetDesktopSize após o redimensionamento da janela (debounce de 250 ms). O guest precisa responder às notificações de resolução da GPU virtio; enquanto isso a imagem mantém a proporção e o mouse acompanha a área desenhada. Uma resposta QEMU “Request forwarded” não é tratada como mudança já aplicada. `make test-viewer` valida o protocolo e, quando QEMU está disponível, a negociação sem discos de guest.
+Entrada: teclado por scancode físico (`gui/keymap.h`, evdev → qnum do QEMU), então o layout do guest manda (dead keys, AltGr); auto-repeat encaminha só os press; teclas pressionadas são soltas ao perder o foco. Ponteiro absoluto via `usb-tablet` (`qemu-xhci`); sem `IsAbsolute`, cai para movimento relativo. O cursor do guest (`CursorDefine`/`MouseSet`) vira o cursor do host — até o guest definir um, o host esconde o seu (o guest pode desenhar o próprio). Redimensionar a janela envia `SetUIInfo` (debounce de 250 ms, tamanho físico em mm para o DPI); só a virtio-gpu honra, a VGA padrão responde "unsupported".
-Clipboard de texto UTF-8 usa a extensão ExtendedClipboard do VNC, zlib com descompressão limitada e o canal `qemu-vdagent`/`com.redhat.spice.0`; não compartilha imagens ou arquivos. **Desde 2026-09-27**, se está ativo é uma configuração da Machine (`EnvironmentSettings.ClipboardDisabled`, opt-out, ligado por padrão — ver Current Priorities → Fase 2), não mais um checkbox na janela do viewer: `qemu.Backend.Open` lê o setting e passa `omavm-gui --viewer --share-clipboard=true|false`; `gui/Viewer.qml` só consome esse valor via `vncShareClipboard`, sem UI própria pra alternar. O guest precisa de `spice-vdagent` funcional na sessão gráfica. QGA conectado não comprova essa integração. Testes cobrem mensagens fragmentadas, limites e troca bidirecional entre dois clientes via QEMU real, sem afirmar compatibilidade de um desktop guest específico. Áudio (`virtio-sound-pci`/pipewire), virtiofs (shared folders) e QGA são independentes do protocolo de display.
+Clipboard de texto UTF-8 (até ~1 MiB) usa a interface `org.qemu.Display1.Clipboard` nos dois lados, com o guest ligado pelo canal `qemu-vdagent`/`com.redhat.spice.0`; não compartilha imagens ou arquivos. O QEMU chama o `Request` do viewer de forma **síncrona** (trava o loop dele), então a resposta é imediata; só um peer de clipboard por Machine (um segundo viewer segue sem). Se está ativo é uma configuração da Machine (`EnvironmentSettings.ClipboardDisabled`, opt-out, ligado por padrão), repassada como `--share-clipboard`; só vale com a janela ativa. O guest precisa de `spice-vdagent` funcional na sessão gráfica; QGA conectado não comprova essa integração. Testes: `make test-display` sobe um QEMU real sem disco — `displayclient_test` cobre memória compartilhada, dma-buf e o pacing; `displayview_test` renderiza fora da tela (`QQuickRenderControl`, nenhuma janela aparece) e confere a orientação nos dois caminhos; pula sem KVM/Wayland. Áudio (`virtio-sound-pci`/pipewire), virtiofs e QGA são independentes do display.
-O posicionamento da janela do viewer (fullscreen, workspace dedicado) é feito por uma regra Hyprland opt-in (`contrib/hypr/omavm-viewer.lua`, `o.window("dev.omavm.viewer", { workspace = "name:omavm", fullscreen = true })`) — nunca por `hyprctl dispatch` em runtime: a build de Hyprland em uso configura via Lua (`hl.window_rule`/`hl.dispatch`) e dispatches brutos com seletores tipo `class:...` quebram nesse parser. Como o plugin Quickshell, essa regra não é injetada automaticamente no config do usuário — é adicionada manualmente ao `windows.lua` pessoal (documentado no README), no mesmo padrão de regras pessoais já usado lá (`o.window(...)` direto, sem módulo separado).
+O posicionamento **estático** da janela do viewer (fullscreen, workspace dedicado) é feito por uma regra Hyprland opt-in (`contrib/hypr/omavm-viewer.lua`, `o.window("dev.omavm.viewer", { workspace = "name:omavm", fullscreen = true })`), avaliada em tempo de config, não em runtime. Como o plugin Quickshell, essa regra não é injetada automaticamente no config do usuário — é adicionada manualmente ao `windows.lua` pessoal (documentado no README), no mesmo padrão de regras pessoais já usado lá (`o.window(...)` direto, sem módulo separado).
-Duas pegadinhas resolvidas nessa regra (2026-09-26): (1) workspace **especial** (`special:...`) nunca fica visível automaticamente — é um overlay estilo scratchpad que só aparece com `togglespecialworkspace` explícito; por isso a regra usa uma workspace **nomeada** normal (`name:omavm`), que troca a view do monitor sozinha quando a janela abre. (2) `gui/Viewer.qml` não pede fullscreen pelo próprio QML (`visibility: Window.FullScreen`) — pedir dos dois lados (client Wayland e regra do compositor) vira um toggle e cancela um ao outro, deixando a janela destilada em vez de fullscreen. O fullscreen é responsabilidade exclusiva da regra Hyprland; sem ela, o viewer só abre como janela comum (comportamento documentado no README).
+**Runtime dispatch validado (2026-09-27)**: esta build de Hyprland do Omarchy é um fork com config em Lua, e `hyprctl dispatch ` nela avalia `` como código Lua (`hl.dispatch()`, literal, não tokenizado por shell) — por isso um dispatch clássico do Hyprland puro com seletor via string (`hyprctl dispatch focuswindow "class:^(...)$"`) falha aqui ("')' expected"): esses tokens brutos não formam Lua válido. A forma correta, confirmada contra uma sessão real e igual ao padrão que o próprio Quickshell do Omarchy usa (`/usr/share/omarchy/shell/plugins/bar/widgets/Workspaces.qml`), é um único argumento com uma expressão Lua válida usando a API estruturada `hl` (documentada em `/usr/share/hypr/stubs/hl.meta.lua`, leitura sempre segura): `hyprctl dispatch 'hl.dsp.focus({ workspace = "3" })'`. Consultas (sem side effect) usam `hyprctl repl ''`, que imprime o valor de retorno — ex.: `hl.get_workspaces()` traz `HL.Workspace[]` com `.id`/`.name`/`.is_empty`/`.special`/`.monitor`/`.visible` já prontos (sem precisar inferir "vazio" por parsing), e `hl.get_windows({ class = ..., title = ... })` filtra por igualdade exata, sem regex. `$HYPRLAND_INSTANCE_SIGNATURE` (env var, sem spawn de processo) é o jeito barato de checar se há sessão Hyprland antes de chamar `hyprctl`. Ficou confirmado que `hl.dsp.focus({ window = })` (focar uma janela específica não-ativa, em vez do workspace inteiro) não muda o foco de forma confiável nesta sessão de teste (focus-follows-mouse provavelmente reafirma o foco); só `hl.dsp.focus({ workspace = ... })` foi validado como confiável — ver `gui/backend.cpp`'s `placeInEmptyWorkspace` para o uso real. Essa descoberta habilitou a preferência opt-in "Open in an empty workspace" (`EnvironmentSettings.OpenInEmptyWorkspace`, ver Current Priorities → Fase 2), mas continua não substituindo a regra estática acima para fullscreen/workspace dedicado — as duas soluções coexistem para necessidades diferentes, ver nota de conflito logo abaixo.
-**Implementado (2026-09-27)**: o "Open" de uma Development Box também abre dentro do `omavm-gui`, em vez de um terminal externo (`xdg-terminal-exec`, removido). `gui/backend.cpp` relança o próprio binário em modo `--terminal --title ` (mesmo padrão do `--viewer` de Machine), que carrega `gui/TerminalViewer.qml` reaproveitando de propósito o mesmo app id `dev.omavm.viewer` — a regra Hyprland opt-in acima cobre os dois sem configuração adicional. `internal/backend/distrobox`'s `Open()` (anexação interativa via `distrobox enter`, stdio herdado) não muda: o modo `--terminal` só cria um PTY próprio (`forkpty`, glibc) e executa `omavm open ` dentro dele — o mesmo comando que já funcionava num terminal real — então `omavm open` continua funcionando normalmente para humanos, scripts e agentes fora da GUI.
+Duas pegadinhas resolvidas nessa regra (2026-09-26): (1) workspace **especial** (`special:...`) nunca fica visível automaticamente — é um overlay estilo scratchpad que só aparece com `togglespecialworkspace` explícito; por isso a regra usa uma workspace **nomeada** normal (`name:omavm`), que troca a view do monitor sozinha quando a janela abre. (2) `gui/Viewer.qml` não pede fullscreen pelo próprio QML (`visibility: Window.FullScreen`) — pedir dos dois lados (client Wayland e regra do compositor) vira um toggle e cancela um ao outro, deixando a janela destilada em vez de fullscreen. Desde 2026-09-29 (pedido do usuário) o viewer de Machine abre em tela cheia **por padrão** (`EnvironmentSettings.FullscreenDisabled`, opt-out, só Machine; `--fullscreen=false`, Settings → Automation): `gui/main.cpp` só pede tela cheia (`showFullScreen()` no `Viewer.qml`) quando `hasPersonalViewerRule` não acha regra pessoal — com a regra, ela manda e o pedido duplo continua evitado. O terminal de Box não vai para tela cheia: sozinho num workspace vazio ele já ocupa a tela.
-O emulador (`gui/terminal.h/.cpp`, `gui/terminalview.h/.cpp`) é implementado do zero — mesma razão de licença do cliente RFB (Backend Rules/Coding Principles: projeto MIT, viewers de terminal maduros como QTermWidget são GPL). Parser Ground/Escape/CSI/OSC cobre: movimento e endereçamento de cursor, SGR (16 cores, 256 cores, truecolor `38/48;2`), scrolling region, alternate screen buffer (`?1049`/`?47` — obrigatório pra vim/htop/less/tmux não corromperem a tela primária), scrollback limitado, e título via OSC 0/2. Fora de escopo por enquanto (falha graciosamente, não quebra): mouse reporting, integração de clipboard, hyperlinks OSC 8, sixel. A paleta ANSI vem de `colors.toml` (via `gui/colorstoml.h`, extraído de `Backend::loadTheme()` — mesmo parser, dois usos reais agora) em vez de cores fixas, mesmo raciocínio de sync com o tema Omarchy do resto da GUI. Testes em `gui/tests/terminal_test.cpp` (`make test-terminal`) cobrem o parser via `feed()` direto (sem PTY) e dois testes de PTY real (`forkpty`+`execvp`+leitura+escrita via `/bin/sh`/`/bin/cat`).
+**Implementado (2026-09-27)**: o "Open" de uma Development Box também abre dentro do `omavm-gui`, em vez de um terminal externo (`xdg-terminal-exec`, removido). `gui/backend.cpp` relança o próprio binário em modo `--terminal --title ` (mesmo padrão do `--display-fd` de Machine), que carrega `gui/TerminalViewer.qml` reaproveitando de propósito o mesmo app id `dev.omavm.viewer` — a regra Hyprland opt-in acima cobre os dois sem configuração adicional. `internal/backend/distrobox`'s `Open()` (anexação interativa via `distrobox enter`, stdio herdado) não muda: o modo `--terminal` só cria um PTY próprio (`forkpty`, glibc) e executa `omavm open ` dentro dele — o mesmo comando que já funcionava num terminal real — então `omavm open` continua funcionando normalmente para humanos, scripts e agentes fora da GUI.
+
+O emulador (`gui/terminal.h/.cpp`, `gui/terminalview.h/.cpp`) é implementado do zero — mesma razão de licença do antigo cliente RFB (Backend Rules/Coding Principles: projeto MIT, viewers de terminal maduros como QTermWidget são GPL). Parser Ground/Escape/CSI/OSC cobre: movimento e endereçamento de cursor, SGR (16 cores, 256 cores, truecolor `38/48;2`), scrolling region, alternate screen buffer (`?1049`/`?47` — obrigatório pra vim/htop/less/tmux não corromperem a tela primária), scrollback limitado, título via OSC 0/2, e largura de caractere (desde 2026-09-28): CJK e emoji ocupam 2 colunas (célula-cabeça + célula de continuação com `ch` vazio), acentos combinantes se juntam à célula anterior, e escrever sobre metade de um caractere largo apaga a outra metade. Teclado (`TerminalSession::keySequence`, testável sem janela): segue o que `TERM=xterm-256color` promete — modo de aplicação das setas (DECCKM `?1h`, que o ncurses liga via `smkx` e depois só reconhece `\EOA`), modificadores no formato do xterm (`\E[1;5D` para Ctrl+←), `\E[Z` para Shift+Tab e os controles Ctrl+Espaço/`[`/`\`/`]`/`^`/`_`. A largura vem das tabelas Unicode do Qt, não do `wcwidth()` da glibc, que depende do locale (devolve -1 para tudo fora do ASCII com `LANG=C`, como no CI). Copiar (desde 2026-09-28): arrastar seleciona (vira seleção primária; clique do meio cola), clique duplo seleciona palavra/caminho, Ctrl+Shift+C e Ctrl+Insert (o Super+C do Omarchy) copiam — nunca chegam ao programa como Ctrl+C; a seleção não corta caractere largo e sobrevive ao descarte do scrollback (`droppedLines`). OSC 52 só de **escrita** (Neovim/tmux copiam para o host); pedido de leitura (`?`) é ignorado, porque deixaria qualquer coisa na Box ler o clipboard do host. É a mesma configuração opt-out `ClipboardDisabled` da Machine, que agora vale para os dois Kinds (repassada como `--share-clipboard`). O buffer de OSC é limitado (`kMaxOscLength`): um OSC sem terminador antes crescia sem limite. Parâmetros CSI são limitados a 65535, como no xterm (2026-09-29): achado por fuzz com ASan/UBSan, `ESC[2147483647C` com o cursor fora da coluna 0 estourava o int, levava o cursor a uma coluna negativa e o próximo erase escrevia fora da linha — segfault disparável por qualquer programa na Box ou por um `cat` de arquivo. `randomInputKeepsTheScreenConsistent` é um fuzz curto de semente fixa na suíte normal. Fora de escopo por enquanto (falha graciosamente, não quebra): mouse reporting, hyperlinks OSC 8, sixel. A paleta ANSI vem de `colors.toml` (via `gui/colorstoml.h`, extraído de `Backend::loadTheme()` — mesmo parser, dois usos reais agora) em vez de cores fixas, mesmo raciocínio de sync com o tema Omarchy do resto da GUI. Testes em `gui/tests/terminal_test.cpp` (`make test-terminal`) cobrem o parser via `feed()` direto (sem PTY) e dois testes de PTY real (`forkpty`+`execvp`+leitura+escrita via `/bin/sh`/`/bin/cat`).
Existe também `Previewer` (`internal/core/backend.go`), uma capability **opcional** do `Backend` (não faz parte da interface mínima acima): a Machine implementa via QMP `screendump` (independente do protocolo de display); Box não implementa — não tem display, e isso não deve ser escondido atrás de um placeholder que finja equivalência (Security Model). A GUI é o frontend Qt Quick/QML em `gui/` (`gui/EnvironmentCard.qml` mostra a miniatura por card só quando o Backend a oferece) — o antigo binding Go em `internal/gui/` foi removido.
@@ -278,7 +295,11 @@ Com a Fase 1 pronta, os três itens abaixo (pesquisa Parallels de 2026-09-26, ve
**Snapshot Manager — implementado (2026-09-27)**: `core.Snapshot{ID, Label, CreatedAt}` vive em `Environment.Snapshots`, persistido no mesmo `environments.json` (sem storage novo). `ID` é o tag técnico que o Core gera (`label` sanitizado + sufixo aleatório curto); `Label` é o único texto que CLI/GUI mostram (UX Principle #9). `EnvironmentSettings.SnapshotLimit` (default 10) descarta o mais antigo automaticamente a cada `CreateSnapshot` acima do limite — tanto no histórico do Core quanto no backend (`Service.CreateSnapshot` chama `RemoveSnapshot` do mais antigo antes de persistir).
-Só a Machine (QEMU) implementa a capability opcional `core.SnapshotManager`; Box retorna `ErrUnsupported` (mecanismo nativo do Distrobox/Podman para isso ainda não decidido — não implementado especulativamente). O adapter QEMU usa snapshots internos do qcow2: parada, `qemu-img snapshot -c/-a/-d` direto no arquivo; rodando, `human-monitor-command` via QMP (`savevm`/`loadvm`/`delvm` — as APIs QMP mais novas de snapshot exigem block nodes nomeados que este projeto não configura). `GoToSnapshot` numa Machine rodando pausa (`QMP stop`) em torno do `loadvm` e retoma (`cont`) depois — `loadvm` substitui todo o estado da máquina (RAM incluída), incompatível com um vCPU ainda executando.
+Disco da Machine (desde 2026-09-29, pedido do usuário): qcow2 esparso de **1 TiB** virtual (`qemu.diskSize`), que começa com ~200 KiB e só cresce conforme o guest escreve. `Start` amplia para 1 TiB (`growDisk`, `qemu-img resize`, nunca encolhe, best-effort) discos menores — Machines antigas de 20 GiB e qualquer uma que voltou a uma snapshot anterior, porque a snapshot do qcow2 guarda o próprio tamanho (verificado no QEMU 11.1). Se o disco do host enche, o QEMU pausa a Machine (`io-error`), que aparece como `paused` com o motivo e sai com Resume.
+
+O estado de cada Machine fica em `/machines//` (desde 2026-09-29; antes era ``): o nome nunca vira componente de caminho e não pesa no limite de 108 bytes dos sockets. `qemu.Backend.key` move o diretório antigo para o ID na primeira vez que vê a Machine parada (um QEMU rodando só é reconhecido pelo caminho do pidfile que recebeu) e refaz o link `~/OmaVM/`.
+
+Só a Machine (QEMU) implementa a capability opcional `core.SnapshotManager`; Box retorna `ErrUnsupported` (mecanismo nativo do Distrobox/Podman para isso ainda não decidido — não implementado especulativamente). O adapter QEMU usa snapshots internos do qcow2, **só de disco**: parada, `qemu-img snapshot -c/-a/-d` direto no arquivo; rodando, `blockdev-snapshot-internal-sync`/`blockdev-snapshot-delete-internal-sync` via QMP no disco `virtio0`. Com o QGA respondendo (desde 2026-09-29), o snapshot é cercado por `guest-fsfreeze-freeze`/`guest-fsfreeze-thaw` (o thaw sempre roda, com uma nova tentativa em outra conexão); sem QGA, ou se o guest recusar o freeze, o snapshot segue como se a energia tivesse sido cortada naquele instante, e fica marcado `crash_consistent` — o SnapshotsDialog diz isso ao lado da data. Testado só contra um agente falso (`TestSnapshotOfRunningMachineFreezesTheGuest`, `TestGuestSyncSkipsStaleReplies`); o freeze num guest Linux real com `qemu-guest-agent` **não** foi verificado. Até 2026-09-29 a Machine rodando usava `savevm`/`loadvm` (HMP), que **nunca funcionou na configuração real**: testado no QEMU 11.1, todo Machine tem `virtio-sound` ("State blocked by non-migratable device") e, com 3D, `virtio-vga-gl` ("virgl is not yet migratable"). `GoToSnapshot` exige a Machine parada — o QEMU só reverte snapshot de disco offline ("Revert to it offline using qemu-img") —, e o SnapshotsDialog desabilita "Go To" e explica isso enquanto ela roda. Regressões: `TestSnapshotOfRunningMachineIsDiskOnly`, `TestGoToSnapshotNeedsAStoppedMachine`, `tst_snapshotsdialog.qml`.
CLI: `omavm snapshot create --label "texto"` (flag pode vir antes ou depois do nome, como os demais comandos — `extractValueFlag` resolve isso do mesmo jeito que `extractBoolFlag` já fazia pro `--json`), `snapshot list [--json]`, `snapshot go-to `, `snapshot remove `; `settings --snapshot-limit N` ajusta o limite. GUI: `gui/SnapshotsDialog.qml` (aberto via "Snapshots…" no menu do card, só para Machines) lê `environment.snapshots` direto do JSON que `list --json` já traz — sem chamada extra de enriquecimento — e expõe criar/"Go To"/apagar.
@@ -288,6 +309,14 @@ CLI: `omavm snapshot create --label "texto"` (flag pode vir antes ou depo
CLI: `omavm apps [--json]`, `omavm apps --export `, `omavm apps --unexport `. GUI: `gui/AppsDialog.qml` (menu "Applications…" no card, só para Boxes) chama `backend.refreshApps` ao abrir e `exportApp`/`unexportApp` por item — diferente de Snapshots, a lista de apps não vem embutida no `list --json` do Environment (mudaria a cada chamada e não é um dado que precisa persistir no domínio), então tem sua própria chamada `apps --json` sob demanda.
+**"Open in an empty workspace" — implementado (2026-09-27), item de P2 (`docs/TODO.md`), não um dos três originais da Fase 2**: adicionado ao escopo por pedido direto do usuário (necessidade real documentada, não decisão especulativa do agente — Rules for AI Agents #7), depois de validar a API `hl` acima. **Ligado por padrão desde 2026-09-28** (decisão do usuário, ver "Integrações são opt-out"): `EnvironmentSettings.EmptyWorkspaceDisabled` guarda o opt-out; a chave antiga `open_in_empty_workspace` (opt-in) é simplesmente ignorada, porque quem a ligou queria o que agora é o padrão. Aplica-se aos dois Kinds. Desde 2026-09-29 quem posiciona é o **próprio viewer**, na inicialização dos modos `--display-fd`/`--terminal` em `gui/main.cpp` (`placeViewer`, flag `--empty-workspace`), antes de a janela existir: antes vivia no `Backend::open()` da GUI, e por isso uma Machine aberta pela entrada do launcher ou por `omavm open` (que lança o viewer direto de `qemu.Backend.Open`) nunca ia para um workspace vazio. O Core/Go só repassa a configuração (`qemu.viewerArgs`, entrada do launcher da Box); a política continua na integração com o desktop. Fluxo: se a preferência está ligada, `placeInEmptyWorkspace(title)` primeiro procura uma janela já aberta para esse ambiente (`hl.get_windows({class="dev.omavm.viewer", title=" — OmaVM"})`, mesmo título que `qemu.Backend.Open`/`gui/backend.cpp`'s modo `--terminal` já usam) e, se achar, só troca pro workspace dela (não abre outra cópia); senão escolhe o primeiro workspace elegível no monitor ativo (vazio via `HL.Workspace.is_empty`, não especial, não pertencente a outro monitor, incluindo um número ainda não materializado) e troca a view pra lá antes de criar a janela — ela abre onde o Hyprland já está focado. Se já havia uma janela desse ambiente, o novo viewer foca o workspace dela e sai sem abrir outra.
+
+Lacunas conhecidas, deixadas como fallback honesto em vez de resolvidas por adivinhação: (1) focar a janela específica (não só o workspace dela) não ficou confiável nos testes (ver nota de `hl.dsp.focus({window=...})` acima) — só o workspace é focado; (2) não há API pra distinguir um workspace "reservado por regra pessoal" de um workspace comum não-vazio, então regras pessoais não são detectadas, só workspaces vazios são pulados por estarem ocupados; (3) a busca é limitada a uma faixa fixa (1–30), não a uma "faixa configurada pelo usuário" que não existe como conceito consultável no Hyprland. Nenhuma dessas lacunas finge suporte que não existe — `WorkspacePlacement::Unavailable` cai no comportamento anterior (abrir no workspace atual) com uma mensagem. Sem sessão Hyprland (`NotApplicable`) a queda é silenciosa: com o padrão ligado, avisar a cada Open seria ruído.
+
+**Conflito conhecido com a regra estática do viewer**: se o usuário já carregou `contrib/hypr/omavm-viewer.lua` (a regra opt-in acima, que fixa `dev.omavm.viewer` sempre no workspace nomeado `name:omavm` em fullscreen), essa regra de janela tem precedência sobre "qual workspace estava focado quando a janela abriu". Desde 2026-09-28 (padrão ligado), `hasPersonalViewerRule()` em `gui/backend.cpp` procura `dev.omavm.viewer` fora de comentários em `~/.config/hypr/**/*.lua|*.conf`; se achar, a OmaVM não troca de workspace (a regra pessoal manda) — senão o usuário ficaria olhando um workspace vazio enquanto a regra move a janela. A config pessoal nunca é reescrita.
+
+**Diagnóstico do host e Vulkan — implementado (2026-09-28), por pedido direto do usuário**: `omavm host [--json]` (capability opcional `core.HostInspector`, só a Machine implementa, em `internal/backend/qemu/hostcaps.go`) informa KVM, OpenGL (render node + `virtio-vga-gl`), Vulkan e se dá para dedicar uma GPU a uma Machine. Só lê o host (sysfs, `/dev`, ICDs do Vulkan): nunca carrega módulo, liga driver ou muda permissão. O item de passthrough é **diagnóstico apenas** — GPU passthrough/VFIO e Looking Glass continuam fora do escopo abaixo (exigem configuração privilegiada do host, inviável com uma GPU só, e o Looking Glass mira guests Windows). Vulkan no guest (Venus: `virtio-vga-gl,blob=on,hostmem=4G,venus=on` + memória memfd) é **ligado por padrão quando a detecção passa** — só Mesa Intel/AMD, ICD instalado com biblioteca presente, `virgl_render_server`, `/dev/udmabuf` gravável — com opt-out por Machine (`EnvironmentSettings.VulkanDisabled`, `--vulkan=false`, Settings → Graphics). A falha do Venus não é detectável no Start (o virglrenderer só inicializa quando o driver do guest fala com a GPU), por isso a detecção é estática. Validado no host (QEMU sobe, Haiku renderiza com blob ligado); a aceleração dentro de um guest Linux **não** foi verificada — o usuário preferiu não baixar uma ISO de teste.
+
Continua fora do escopo até necessidade real: guest agent completo, GPU passthrough, orchestration distribuída, cloud/remote hosts, marketplace, dezenas de distros, networking editor avançado, plugin system, e o Blend Mode completo (além da base acima).
## Ephemeral Environments & Agentic Workflows
diff --git a/Makefile b/Makefile
index d2c992b..b9bc40d 100644
--- a/Makefile
+++ b/Makefile
@@ -2,7 +2,7 @@ PREFIX ?= $(HOME)/.local
QS_PLUGIN_DIR ?= $(HOME)/.config/omarchy/plugins/dev.omavm.bar
-.PHONY: build build-cli build-gui test vet fmt fmt-check check run run-gui clean install uninstall install-quickshell-plugin uninstall-quickshell-plugin test-viewer test-terminal
+.PHONY: dist build build-cli build-gui test vet fmt fmt-check check run run-gui clean install uninstall uninstall-environments install-quickshell-plugin uninstall-quickshell-plugin test-display test-terminal test-backend test-qml
build: build-cli build-gui
@@ -16,19 +16,31 @@ build-gui:
cp build/gui/omavm-gui bin/omavm-gui.new
mv bin/omavm-gui.new bin/omavm-gui
-test: test-viewer test-terminal
+test: test-display test-terminal test-backend test-qml
go test ./...
-test-viewer:
- mkdir -p build/viewer-tests
- cd build/viewer-tests && qmake6 ../../gui/tests/vncclient_test.pro && $(MAKE)
- ./build/viewer-tests/vncclient_test
+test-display:
+ mkdir -p build/display-tests
+ cd build/display-tests && qmake6 ../../gui/tests/displayclient_test.pro && $(MAKE)
+ ./build/display-tests/displayclient_test
+ cd build/display-tests && qmake6 ../../gui/tests/displayview_test.pro -o Makefile.view && $(MAKE) -f Makefile.view
+ ./build/display-tests/displayview_test
test-terminal:
mkdir -p build/terminal-tests
cd build/terminal-tests && qmake6 ../../gui/tests/terminal_test.pro && $(MAKE)
./build/terminal-tests/terminal_test
+test-backend:
+ mkdir -p build/backend-tests
+ cd build/backend-tests && qmake6 ../../gui/tests/backend_refresh_test.pro && $(MAKE)
+ ./build/backend-tests/backend_refresh_test
+
+test-qml:
+ mkdir -p build/qml-tests
+ cd build/qml-tests && qmake6 ../../gui/tests/qml_test.pro && $(MAKE)
+ QT_QPA_PLATFORM=offscreen ./build/qml-tests/qml_test
+
vet:
go vet ./...
@@ -53,6 +65,30 @@ run-gui: build-cli build-gui
clean:
rm -rf bin build
+# Portable release tarball, the asset OmaStore installs (omastore.toml,
+# .github/workflows/release.yml): bin/ holds both binaries side by side,
+# which is how each finds the other, and data/ sits next to it, where
+# internal/desktop looks for the color icons of a run outside /usr. The
+# CLI is static; the GUI uses the system's Qt 6.
+VERSION ?= $(shell git describe --tags --abbrev=0 2>/dev/null | sed 's/^v//')
+DIST_NAME = omavm-$(VERSION)-x86_64-linux
+
+dist: build-gui
+ @test -n "$(VERSION)" || { echo "set VERSION=x.y.z"; exit 1; }
+ CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/omavm ./cmd/omavm
+ rm -rf build/dist && mkdir -p build/dist/$(DIST_NAME)
+ install -Dm755 bin/omavm build/dist/$(DIST_NAME)/bin/omavm
+ install -Dm755 bin/omavm-gui build/dist/$(DIST_NAME)/bin/omavm-gui
+ install -Dm644 -t build/dist/$(DIST_NAME)/data/icons/colors data/icons/colors/*.svg
+ install -Dm644 data/icons/dev.omavm.app.svg build/dist/$(DIST_NAME)/data/icons/dev.omavm.app.svg
+ install -Dm644 data/dev.omavm.app.desktop build/dist/$(DIST_NAME)/data/dev.omavm.app.desktop
+ install -Dm644 -t build/dist/$(DIST_NAME) LICENSE README.md
+ @# Flat: bin/omavm-gui is the path omastore.toml names, with no
+ @# versioned top directory in front of it.
+ tar -C build/dist/$(DIST_NAME) -czf build/dist/$(DIST_NAME).tar.gz bin data LICENSE README.md
+ cd build/dist && sha256sum $(DIST_NAME).tar.gz > $(DIST_NAME).tar.gz.sha256
+ @echo "build/dist/$(DIST_NAME).tar.gz"
+
# User-level install (no root): binaries on PATH, a .desktop entry so
# omavm-gui shows up in the app launcher/taskbar with its own icon, icon
# caches refreshed best-effort, and the Quickshell bar-widget plugin
@@ -65,15 +101,72 @@ install: build install-quickshell-plugin
install -Dm755 bin/omavm-gui $(PREFIX)/bin/omavm-gui
install -Dm644 data/dev.omavm.app.desktop $(PREFIX)/share/applications/dev.omavm.app.desktop
install -Dm644 data/icons/dev.omavm.app.svg $(PREFIX)/share/icons/hicolor/scalable/apps/dev.omavm.app.svg
+ @# One icon per environment color, for launcher entries and the file
+ @# manager (internal/desktop's ColorIcon).
+ install -Dm644 -t $(PREFIX)/share/omavm/icons data/icons/colors/*.svg
-update-desktop-database $(PREFIX)/share/applications 2>/dev/null
- -gtk-update-icon-cache $(PREFIX)/share/icons/hicolor 2>/dev/null
+ @# ~/.local/share/icons/hicolor usually has no index.theme; the cache is
+ @# optional there (icon lookup works without it), so only refresh it
+ @# when the theme index exists instead of printing a spurious error.
+ @if [ -f $(PREFIX)/share/icons/hicolor/index.theme ]; then \
+ gtk-update-icon-cache -q $(PREFIX)/share/icons/hicolor || true; \
+ fi
+# Removes only the app itself (binaries, launcher entries, icons).
+# Environments OmaVM created (Distrobox containers, Machine disks) are
+# never touched here — uninstalling the manager must never silently
+# destroy a user's containers or virtual disks. If any are still
+# registered, this only warns and points at `uninstall-environments`.
uninstall:
+ @if [ -x "$(PREFIX)/bin/omavm" ]; then \
+ count=$$("$(PREFIX)/bin/omavm" list --json 2>/dev/null | grep -o '"name"' | wc -l); \
+ if [ "$$count" -gt 0 ] 2>/dev/null; then \
+ echo "Note: $$count OmaVM environment(s) still exist and were left untouched."; \
+ echo "Run 'make uninstall-environments' to remove them too (asks for confirmation)."; \
+ fi; \
+ fi
rm -f $(PREFIX)/bin/omavm $(PREFIX)/bin/omavm-gui
rm -f $(PREFIX)/share/applications/dev.omavm.app.desktop
rm -f $(PREFIX)/share/icons/hicolor/scalable/apps/dev.omavm.app.svg
+ rm -rf $(PREFIX)/share/omavm/icons
+ @# Per-environment launcher entries would run binaries that are gone;
+ @# omavm writes them again on the next start after a reinstall.
+ rm -f $(PREFIX)/share/applications/dev.omavm.env.*.desktop
-update-desktop-database $(PREFIX)/share/applications 2>/dev/null
+# Removes every Environment OmaVM still knows about (Boxes and
+# Machines) through `omavm remove` — never raw podman/qemu commands
+# here, so it gets the exact same Core validation and cleanup a human
+# already gets from the CLI (Stop before disk removal for Machines,
+# `distrobox rm --force` for Boxes — a Box's container is removed but
+# files in the shared home directory are never touched). Deliberately
+# separate from `install`/`uninstall`, never chained into either: opt-in
+# only. CONFIRM=1 skips the interactive prompt for scripted/CI use.
+uninstall-environments: build-cli
+ @json=$$(./bin/omavm list --json 2>/dev/null); \
+ if [ -z "$$json" ] || [ "$$json" = "[]" ]; then \
+ echo "No OmaVM environments found."; \
+ exit 0; \
+ fi; \
+ echo "This will permanently remove:"; \
+ echo " - Development Boxes: their containers (home directory files are not touched)"; \
+ echo " - Machines: their virtual disks and every snapshot"; \
+ echo "Affected environments:"; \
+ ./bin/omavm list | sed 's/^/ /'; \
+ if [ "$$CONFIRM" != "1" ]; then \
+ printf "Type 'yes' to remove all of them: "; \
+ read reply; \
+ if [ "$$reply" != "yes" ]; then \
+ echo "Aborted, nothing removed."; \
+ exit 1; \
+ fi; \
+ fi; \
+ printf '%s' "$$json" | grep -o '"name":"[^"]*"' | sed -E 's/"name":"(.*)"/\1/' | while IFS= read -r name; do \
+ [ -z "$$name" ] && continue; \
+ echo "Removing $$name..."; \
+ ./bin/omavm remove "$$name" || exit 1; \
+ done
+
# Copies the Omarchy Quickshell bar-widget plugin into place — nothing
# more, and also run as part of `install` above. It deliberately does NOT
# run `omarchy-shell shell rescanPlugins` or `omarchy plugin enable`,
@@ -82,7 +175,15 @@ uninstall:
# unsandboxed inside the already-live desktop shell, and this target
# respects that — copying the file is harmless, enabling it is not, so
# only the enable step stays manual.
+#
+# Removes the destination first so this is always an exact mirror of
+# contrib/dev.omavm.bar/, never an old install's leftover files sitting
+# alongside new ones: a plain `cp -r` only adds/overwrites, so a file
+# renamed or removed from the plugin since a previous install would
+# otherwise linger in $(QS_PLUGIN_DIR) forever and could still be picked
+# up by the shell.
install-quickshell-plugin:
+ rm -rf $(QS_PLUGIN_DIR)
mkdir -p $(QS_PLUGIN_DIR)
cp -r contrib/dev.omavm.bar/. $(QS_PLUGIN_DIR)/
@echo "Copied to $(QS_PLUGIN_DIR). Review the QML, then:"
diff --git a/README.md b/README.md
index a68fad1..05bae4a 100644
--- a/README.md
+++ b/README.md
@@ -22,9 +22,11 @@
Project status
-OmaVM is a desktop app for creating and managing environments on
-[Omarchy](https://omarchy.org). Work with another Linux distribution's tools
-in a **Box**, or install and boot a complete operating system in a **Machine**.
+OmaVM brings other Linux distributions and complete operating systems into
+your [Omarchy](https://omarchy.org) workflow. It is a desktop app for creating,
+using, and managing these environments: work with another Linux distribution's
+tools and applications in a **Box**, or install and boot a complete operating
+system in a **Machine**.
Start, open, and stop both from the same window, with a built-in terminal for
Boxes and a graphical viewer for Machines.
@@ -86,6 +88,31 @@ another system approachable, with advanced settings available when needed.
An optional [Quickshell bar widget](contrib/dev.omavm.bar) gives you a shortcut
to the app and an environment count in its tooltip.
+## Host ↔ guest integration
+
+The product direction is to let you copy text, move files, and open links and
+applications in either direction between Omarchy and an environment. These
+integrations are intended to be **on by default, with controls to turn each
+one off per environment** wherever supported.
+
+Today, Boxes share your home directory through Distrobox and can export
+applications to your Omarchy launcher. Machines offer configurable shared
+folders and bidirectional text clipboard sharing; clipboard sharing is on by
+default and can be disabled per Machine, but requires guest support.
+
+Every environment also appears in your app launcher, with an icon in its
+color tag, so it opens like any installed app (Settings → "Show in the app
+launcher" turns that off). In a Box's terminal, select text with the mouse
+and copy with Ctrl+Shift+C or Super+C; programs like Neovim and tmux can copy
+to your clipboard too, but can never read it (Settings turns that off). A
+Machine's color also shows on its `~/OmaVM/` link in Files.
+
+The full set of per-environment controls, file transfer, and bidirectional
+link/application opening is **planned**. A shared folder is not a file-transfer
+channel, and Box integration does not yet have independent off switches for
+every capability. See the [development roadmap](docs/TODO.md) for the remaining
+work and validation criteria.
+
## Status
OmaVM is actively developed and **not yet 1.0**. Both Boxes and Machines support
@@ -176,18 +203,45 @@ bin/omavm restart kernels
bin/omavm integration kernels
bin/omavm settings kernels --description "Kernel lab" --cpus 4 --memory-mib 4096
bin/omavm settings kernels --shared-path "$HOME/Projects" --shared-read-only
+bin/omavm ssh kernels # a shell in the guest
+bin/omavm exec kernels -- uname -r # one command, no prompts
```
+`ssh` and `exec` reach a Machine over a local host↔guest channel (vsock),
+with no guest networking. The guest needs systemd 256 or newer with sshd
+installed; you log in with your own user name (`--user` to change it) and
+the guest's key is remembered on first use. The channel is on by default,
+and **any program on this computer can reach it, Boxes included**: only the
+guest's login protects it. Turn it off per Machine with
+`omavm settings NAME --ssh=false` (or in Settings), then restart the Machine.
+
Machines expose the folder to the guest as the virtiofs tag `omavm-share`;
inside a Linux guest, mount it with `mount -t virtiofs omavm-share /mnt/omavm-share`.
`list` and `status` accept `--json` (in any position, e.g. both
`omavm list --json` and `omavm status radic --json` work) for
structured output aimed at agents, scripts, and the Quickshell bar
-widget below.
+widget below. `omavm list --status --json` adds every environment's
+current state (and, for Machines, whether guest tools answer) in one
+call, asking the container engine once for all Boxes; the GUI refreshes
+with it. The JSON shapes are covered by golden files in
+`cmd/omavm/testdata`: changing them is a deliberate, visible diff.
## Machines
+Every Machine has a 1 TiB virtual disk. It is a sparse qcow2 file: it
+starts at a few hundred KiB and takes space on your computer only as the
+guest writes to it, up to 1 TiB, so installers never run short. Machines
+created with a smaller disk grow to 1 TiB the next time they start (so
+does one sent back to a snapshot taken before that); inside an installed
+guest, the new space shows up as unpartitioned until you extend its
+partition. The guest can believe in more space than your computer
+has; if your disk fills up, the Machine is paused (its card says why) and
+**Resume** continues it once you free some space.
+
+An installed Machine whose ISO was deleted or moved still starts, from its
+disk.
+
Machines try the installed disk before the ISO, falling back to installation
media while the disk is not bootable. After installation, enable **Installation
finished — disconnect ISO on next start** in Settings. Shut down and start the
@@ -204,39 +258,50 @@ work. Deleting a running Machine also requires shutdown to succeed.
Registry changes are serialized across CLI and GUI processes so concurrent
creation, deletion and settings updates do not overwrite each other's records.
-Opening a Machine's graphical display launches `omavm-gui` in its built-in
-VNC viewer mode (`omavm-gui --viewer --title `) — no
-external VNC/SPICE client to install. Machines run fully headless
-(`-display egl-headless`, GPU-accelerated `virtio-vga-gl`) and expose the
-display over a local-only VNC Unix socket, plus PipeWire audio and virtiofs
-shared folders. Text clipboard sharing is a Machine setting (**Settings →
-Automation → Share text clipboard**, or `omavm settings NAME --share-clipboard`),
-on by default and applied automatically whenever you open the viewer — it is
-not a per-window checkbox you need to re-enable each time. Turn it off per
+Opening a Machine's graphical display shows it inside `omavm-gui` — no
+external VNC/SPICE client to install. Machines run headless with QEMU's
+D-Bus display; `omavm open` connects the viewer to it directly. With a
+usable host GPU (`omavm host` tells you), frames reach the viewer as GPU
+buffers without being copied through the CPU; otherwise they are shared
+through memory. Keyboard input follows the guest's own layout, the pointer
+is absolute, and the guest's cursor shape is used on the host. PipeWire
+audio and virtiofs shared folders work the same either way.
+
+Text clipboard sharing is a Machine setting (**Settings → Automation →
+Share text clipboard**, or `omavm settings NAME --share-clipboard`), on by
+default and applied automatically whenever you open the viewer — it is not
+a per-window checkbox you need to re-enable each time. Turn it off per
Machine if you don't want it. Only UTF-8 text is exchanged, limited to
approximately 1 MiB; images and files are not transferred. The guest desktop
must have a running `spice-vdagent` compatible with its graphical session. The
QEMU guest agent shown in the environment card is a different component and
-does not prove clipboard readiness. Restart an existing Machine to attach the
-clipboard channel. This uses QEMU's `qemu-vdagent` bridge with VNC; it does not
-require a SPICE display or a new OmaVM guest daemon. Travel Mode (also in
-Settings → Automation, on by default) halves the Machine's default CPU
-allocation for that session while the host is running on battery, unless
-you've pinned a custom CPU count.
+does not prove clipboard readiness. Travel Mode (also in Settings →
+Automation, on by default) halves the Machine's default CPU allocation for
+that session while the host is running on battery, unless you've pinned a
+custom CPU count. Boxes get it too: each time a Box starts or opens on
+battery, its container is limited to half of this computer's CPUs, and gets
+all of them back once you're plugged in.
+
+Vulkan acceleration (**Settings → Graphics**, or `omavm settings NAME
+--vulkan`) is on by default and used only when the host supports it; the
+guest needs a recent Mesa with the Venus driver.
+
+Machines started by an OmaVM version from before the D-Bus display need a
+restart before they can be opened; `omavm open` says so.
By default the viewer opens as an ordinary window wherever Hyprland
would place it. Resizing that window requests a matching guest resolution
-through VNC after a short delay. This requires a guest display driver and
-desktop that honor virtio GPU resize requests. During boot, or when the guest
-does not resize, the viewer preserves the image proportions with black margins
-and maps pointer input to the displayed image.
-
-The protocol tests (`make test-viewer`, also part of `make test` and CI) cover
-fragmented resize/clipboard messages, bounded clipboard decompression,
-framebuffer bounds and rejected/forwarded resize requests.
-When QEMU is installed they also check negotiation against a temporary QEMU
-process without guest disks, including bidirectional Unicode clipboard between
-two clients; this is not a guest desktop compatibility test.
+after a short delay. This requires a guest display driver and desktop that
+honor virtio GPU resize requests. During boot, or when the guest does not
+resize, the viewer preserves the image proportions with black margins and
+maps pointer input to the displayed image.
+
+The display tests (`make test-display`, also part of `make test` and CI)
+start a temporary QEMU without guest disks and check both frame paths (GPU
+buffers and shared memory), frame pacing and that frames render upright. The
+rendering test draws offscreen — no window appears — and needs a Wayland
+session; both skip without KVM. This is not a guest desktop compatibility
+test.
The Box terminal's parser has its own suite (`make test-terminal`, also part
of `make test` and CI): cursor addressing, SGR colors (16/256/truecolor),
@@ -261,6 +326,24 @@ optional and never enabled automatically — see
rule applies to a Box's terminal viewer too, since it shares the same
`dev.omavm.viewer` app id — no separate rule needed for Boxes.
+Without such a rule, a Machine's display opens fullscreen by default
+(**Settings → Automation → Open the display fullscreen**, or `omavm
+settings NAME --fullscreen=false` to open it as a window).
+
+Separately, **Settings → Automation → Open in an empty workspace** (on by
+default for both Machines and Boxes; `omavm settings NAME
+--open-in-empty-workspace=false` turns it off) switches to a fresh, empty workspace
+on the active monitor right before opening that environment — however it
+is opened: the Experience Center, its launcher entry or `omavm open` — and — if a
+viewer/terminal for it is already open somewhere — switches to its
+workspace instead of opening a second one. This needs Omarchy's
+Lua-configured Hyprland specifically (it queries `hl.get_workspaces()`/
+`hl.get_windows()` over `hyprctl`); anywhere else, or if nothing eligible
+is found, it falls back to opening on the current workspace. If your
+Hyprland config has a rule for `dev.omavm.viewer` (such as the fullscreen
+rule above), that rule places the window and this setting stays out of its
+way.
+
## GUI (Experience Center)
```bash
@@ -281,7 +364,7 @@ terminal emulator implemented from scratch (PTY + a Ground/Escape/CSI/OSC
parser covering cursor addressing, SGR colors including 256-color and
truecolor, the alternate screen buffer used by vim/htop/less/tmux, and
scrollback), not an external terminal emulator. It shares the same
-`dev.omavm.viewer` app id as the Machine VNC viewer below, so the same
+`dev.omavm.viewer` app id as the Machine display viewer below, so the same
optional Hyprland window rule covers both.
A running Machine's card shows a live screenshot of its display
@@ -307,6 +390,32 @@ This puts `omavm`/`omavm-gui` on `PATH` and registers a `.desktop` entry
Omarchy app. Set `PREFIX=/usr/local` (with `sudo`) for a system-wide
install instead.
+`make uninstall` only removes the app itself. Environments it created
+(Distrobox containers, Machine virtual disks) are never touched — if
+any still exist, it prints a note instead of silently leaving them
+behind unmentioned. To remove those too, run `make uninstall-environments`
+separately; it lists everything that will be deleted and asks for
+confirmation (`CONFIRM=1` skips the prompt for scripted use).
+
+### From OmaStore
+
+OmaVM is listed in OmaStore through [`omastore.toml`](omastore.toml):
+
+```bash
+omastore install KitsuneSemCalda/OmaVM
+```
+
+The store installs the release tarball under your home directory and puts
+`omavm-gui` (the Experience Center) on `PATH`. The `omavm` CLI ships next to
+it in the same `bin/` directory, where the Experience Center, launcher
+entries and viewers find it; to use it from a shell, add that directory to
+`PATH` or use `make install` instead. It uses your system's Qt 6, which
+Omarchy already has.
+
+Releases get their tarball from `.github/workflows/release.yml` on every
+`v*` tag; `make dist VERSION=x.y.z` builds the same one locally
+(`build/dist/omavm-x.y.z-x86_64-linux.tar.gz`, with a `.sha256`).
+
## Logs
Both binaries log structured (JSON) events. `/var/log` is root-owned by
@@ -315,9 +424,16 @@ default, and OmaVM never escalates privileges silently to write there
`/var/log/omavm/.log` only if that directory already exists
and is writable; otherwise it falls back to
`$XDG_STATE_HOME/omavm/logs/.log` (usually
-`~/.local/state/omavm/logs/`). The very first log line always records
+`~/.local/state/omavm/logs/`). The first line of each log file records
which path is in effect.
+The log keeps commands that change something (create, start, settings,
+snapshots, …) and every failure; routine reads such as `list` and
+`status`, which the Experience Center and the Omarchy bar run every few
+seconds, are not recorded. Past 5 MiB a log moves to `.log.1`
+(replacing the previous one) and starts over, so each component keeps at
+most about 10 MiB.
+
To opt into the system location instead, provision it once yourself:
```bash
diff --git a/cmd/omavm/main.go b/cmd/omavm/main.go
index 8f27afd..90c2c77 100644
--- a/cmd/omavm/main.go
+++ b/cmd/omavm/main.go
@@ -11,6 +11,7 @@ import (
"fmt"
"log/slog"
"os"
+ "os/exec"
"strings"
"github.com/KitsuneSemCalda/OmaVM/internal/applog"
@@ -19,6 +20,7 @@ import (
"github.com/KitsuneSemCalda/OmaVM/internal/backend/distrobox"
"github.com/KitsuneSemCalda/OmaVM/internal/backend/qemu"
"github.com/KitsuneSemCalda/OmaVM/internal/core"
+ "github.com/KitsuneSemCalda/OmaVM/internal/desktop"
)
func main() {
@@ -34,10 +36,24 @@ func main() {
if err := run(os.Args[1:]); err != nil {
slog.Error("command failed", "error", err)
fmt.Fprintln(os.Stderr, "omavm:", err)
+ if os.Getenv("OMAVM_NOTIFY_ERRORS") == "1" {
+ notifyError(err)
+ }
os.Exit(1)
}
}
+// notifyError shows a failure as a desktop notification, for runs nobody
+// sees the terminal of: a launcher entry opening a Machine would otherwise
+// fail without a word. Best-effort; without notify-send, only the log has it.
+func notifyError(err error) {
+ path, lookErr := exec.LookPath("notify-send")
+ if lookErr != nil {
+ return
+ }
+ _ = exec.Command(path, "--app-name=OmaVM", "--icon=dev.omavm.app", "OmaVM", err.Error()).Run()
+}
+
func run(args []string) error {
if len(args) == 0 {
printUsage()
@@ -52,12 +68,31 @@ func run(args []string) error {
if err != nil {
return err
}
+ // Only for a person at a terminal: the GUI and agents read stderr as
+ // the error text of a failed command, and this line would pollute it.
+ if info, err := os.Stderr.Stat(); err == nil && info.Mode()&os.ModeCharDevice != 0 {
+ store.OnWait = func() {
+ fmt.Fprintln(os.Stderr, "omavm: waiting for another OmaVM operation to finish…")
+ }
+ }
boxBackend := box.New(distrobox.New(), container.New())
svc := core.NewService(store, boxBackend, qemuBackend)
+ if launcher, err := desktop.NewLauncher(); err == nil {
+ svc.SetLauncher(launcher)
+ } else {
+ slog.Warn("launcher entries disabled", "error", err)
+ }
ctx := context.Background()
cmd, rest := args[0], args[1:]
- slog.Info("command", "cmd", cmd, "args", rest)
+ // Reads (the GUI and the Omarchy bar poll list/status every few
+ // seconds) are debug-level so the log keeps the actions that changed
+ // something.
+ level := slog.LevelInfo
+ if readOnly(cmd, rest) {
+ level = slog.LevelDebug
+ }
+ slog.Log(ctx, level, "command", "cmd", cmd, "args", rest)
switch cmd {
case "create":
@@ -78,6 +113,8 @@ func run(args []string) error {
return cmdSimple(ctx, rest, "force-stop", svc.ForceStop)
case "status":
return cmdStatus(ctx, svc, rest)
+ case "host":
+ return cmdHost(ctx, svc, rest)
case "integration":
return cmdIntegration(ctx, svc, rest)
case "settings", "configure":
@@ -90,6 +127,8 @@ func run(args []string) error {
return cmdApps(ctx, svc, rest)
case "exec":
return cmdExec(ctx, svc, rest)
+ case "ssh":
+ return cmdSSH(ctx, svc, rest)
case "rm", "remove":
return cmdSimple(ctx, rest, "remove", svc.Remove)
case "list", "ls":
@@ -108,6 +147,8 @@ func cmdCreate(ctx context.Context, svc *core.Service, args []string) error {
name := fs.String("name", "", "environment name (required)")
kindStr := fs.String("kind", "box", `environment kind: "box" or "machine"`)
image := fs.String("image", "", "distro image (Box) or boot ISO path (Machine)")
+ cpus := fs.Int("cpus", 0, "virtual CPUs (Machines only, defaults to 2)")
+ memory := fs.Int("memory-mib", 0, "memory in MiB (Machines only, defaults to 2048)")
if err := fs.Parse(args); err != nil {
return err
}
@@ -119,7 +160,15 @@ func cmdCreate(ctx context.Context, svc *core.Service, args []string) error {
return err
}
- env, err := svc.Create(ctx, core.Environment{Name: *name, Image: *image, Kind: kind})
+ env, err := svc.Create(ctx, core.Environment{
+ Name: *name,
+ Image: *image,
+ Kind: kind,
+ Settings: core.EnvironmentSettings{
+ CPUs: *cpus,
+ MemoryMiB: *memory,
+ },
+ })
if err != nil {
return err
}
@@ -301,6 +350,31 @@ func cmdIntegration(ctx context.Context, svc *core.Service, args []string) error
return nil
}
+func cmdHost(ctx context.Context, svc *core.Service, args []string) error {
+ args, jsonOut := extractBoolFlag(args, "json")
+ if len(args) != 0 {
+ return errors.New("host: takes no arguments")
+ }
+ caps, err := svc.InspectHost(ctx)
+ if err != nil {
+ return err
+ }
+ if jsonOut {
+ return json.NewEncoder(os.Stdout).Encode(caps)
+ }
+ for _, c := range caps {
+ mark := "no "
+ if c.Available {
+ mark = "yes"
+ }
+ fmt.Printf("%s %s: %s\n", mark, c.Label, c.Detail)
+ if c.Hint != "" {
+ fmt.Printf(" %s\n", c.Hint)
+ }
+ }
+ return nil
+}
+
func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
if len(args) == 0 {
return errors.New("settings: expected an environment name")
@@ -316,8 +390,13 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
disconnectISO := fs.Bool("disconnect-iso", false, "disconnect installation media on next start (Machines only)")
snapshotLimit := fs.Int("snapshot-limit", 0, "max snapshots to keep, oldest discarded first (1-100)")
color := fs.String("color", "", "tag color: "+strings.Join(core.EnvironmentColors, ", "))
- shareClipboard := fs.Bool("share-clipboard", false, "share the text clipboard with the guest while the viewer is open (Machines only, on by default)")
- travelMode := fs.Bool("travel-mode", false, "reduce CPU allocation automatically while the host is on battery (Machines only, on by default)")
+ shareClipboard := fs.Bool("share-clipboard", false, "share the text clipboard with a Machine's guest, or let programs in a Box's terminal copy to it (on by default)")
+ travelMode := fs.Bool("travel-mode", false, "use half the CPUs automatically while the host is on battery (on by default)")
+ vulkan := fs.Bool("vulkan", false, "Vulkan acceleration when the host supports it (Machines only, on by default)")
+ ssh := fs.Bool("ssh", false, "reach the Machine with omavm ssh/exec over a local channel any program on this computer can use, Boxes included (Machines only, on by default)")
+ launcher := fs.Bool("launcher", false, "list this environment in the application launcher (on by default)")
+ openInEmptyWorkspace := fs.Bool("open-in-empty-workspace", false, "open this environment in an empty Hyprland workspace instead of the current one (on by default; requires Omarchy's Lua-based Hyprland)")
+ fullscreen := fs.Bool("fullscreen", false, "open the Machine's display fullscreen (Machines only, on by default)")
jsonOut := fs.Bool("json", false, "print JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
@@ -327,6 +406,7 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
}
patch := core.SettingsPatch{}
changed := false
+ modeFlags := 0
fs.Visit(func(f *flag.Flag) {
switch f.Name {
case "disconnect-iso":
@@ -350,24 +430,39 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
case "share-clipboard":
patch.ShareClipboard = shareClipboard
changed = true
+ case "vulkan":
+ patch.Vulkan = vulkan
+ changed = true
case "travel-mode":
patch.TravelMode = travelMode
changed = true
+ case "ssh":
+ patch.SSH = ssh
+ changed = true
+ case "launcher":
+ patch.Launcher = launcher
+ changed = true
+ case "open-in-empty-workspace":
+ patch.OpenInEmptyWorkspace = openInEmptyWorkspace
+ changed = true
+ case "fullscreen":
+ patch.Fullscreen = fullscreen
+ changed = true
case "shared-path":
patch.SharedPath = sharedPath
changed = true
case "shared-read-only":
- if *sharedWritable {
- return
- }
patch.SharedReadOnly = sharedReadOnly
+ modeFlags++
changed = true
case "shared-writable":
- patch.SharedReadOnly = new(bool)
+ readOnly := !*sharedWritable
+ patch.SharedReadOnly = &readOnly
+ modeFlags++
changed = true
}
})
- if *sharedReadOnly && *sharedWritable {
+ if modeFlags > 1 {
return errors.New("settings: choose only one of --shared-read-only or --shared-writable")
}
var settings core.EnvironmentSettings
@@ -389,9 +484,13 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
if settings.CPUs != 0 {
fmt.Printf("hardware: %d CPUs, %d MiB memory\n", settings.CPUs, settings.MemoryMiB)
fmt.Printf("installation media disconnected on next start: %t\n", settings.DisconnectISO)
- fmt.Printf("share clipboard: %t\n", !settings.ClipboardDisabled)
- fmt.Printf("travel mode (reduce CPUs on battery): %t\n", !settings.TravelModeDisabled)
+ fmt.Printf("vulkan acceleration (when the host supports it): %t\n", !settings.VulkanDisabled)
+ fmt.Printf("open the display fullscreen: %t\n", !settings.FullscreenDisabled)
+ fmt.Printf("ssh (reachable by any program on this computer, Boxes included): %t\n", !settings.SSHDisabled)
}
+ fmt.Printf("share clipboard: %t\n", !settings.ClipboardDisabled)
+ fmt.Printf("travel mode (reduce CPUs on battery): %t\n", !settings.TravelModeDisabled)
+ fmt.Printf("show in the app launcher: %t\n", !settings.LauncherDisabled)
if settings.SharedPath != "" {
mode := "writable"
if settings.SharedReadOnly {
@@ -402,6 +501,7 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error {
if settings.Color != "" {
fmt.Println("color:", settings.Color)
}
+ fmt.Printf("open in an empty workspace: %t\n", !settings.EmptyWorkspaceDisabled)
return nil
}
@@ -420,8 +520,60 @@ func cmdExec(ctx context.Context, svc *core.Service, args []string) error {
return svc.Exec(ctx, name, rest)
}
+// cmdSSH: omavm ssh NAME [--user LOGIN] [-- COMMAND...]
+func cmdSSH(ctx context.Context, svc *core.Service, args []string) error {
+ var command []string
+ for i, a := range args {
+ if a == "--" {
+ command = args[i+1:]
+ args = args[:i]
+ break
+ }
+ }
+ fs := flag.NewFlagSet("ssh", flag.ContinueOnError)
+ login := fs.String("user", "", "user to log in as in the guest (default: your user name)")
+ var name string
+ if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
+ name, args = args[0], args[1:]
+ }
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ if name == "" && fs.NArg() == 1 {
+ name = fs.Arg(0)
+ } else if fs.NArg() != 0 {
+ return errors.New("ssh: usage: omavm ssh [--user LOGIN] [-- command...]")
+ }
+ if name == "" {
+ return errors.New("ssh: expected a Machine name")
+ }
+ return svc.SSH(ctx, name, *login, command)
+}
+
func cmdList(ctx context.Context, svc *core.Service, args []string) error {
- _, jsonOut := extractBoolFlag(args, "json")
+ args, jsonOut := extractBoolFlag(args, "json")
+ _, withStatus := extractBoolFlag(args, "status")
+
+ if withStatus {
+ states, err := svc.ListWithStatus(ctx)
+ if err != nil {
+ return err
+ }
+ if jsonOut {
+ if states == nil {
+ states = []core.EnvironmentState{}
+ }
+ return json.NewEncoder(os.Stdout).Encode(states)
+ }
+ if len(states) == 0 {
+ fmt.Println("no environments yet — try: omavm create --name --kind box --image ")
+ return nil
+ }
+ for _, s := range states {
+ fmt.Printf("%s\t%s\t%s\t%s\n", s.Name, s.Kind, s.Status.State, s.Image)
+ }
+ return nil
+ }
envs, err := svc.List(ctx)
if err != nil {
@@ -489,11 +641,33 @@ func extractValueFlag(args []string, name string) ([]string, string, error) {
return out, value, nil
}
+// readOnly reports whether a command only reads state.
+func readOnly(cmd string, args []string) bool {
+ switch cmd {
+ case "list", "ls", "status", "integration", "preview", "host", "help", "-h", "--help":
+ return true
+ case "snapshot":
+ return len(args) > 0 && args[0] == "list"
+ case "apps":
+ for _, a := range args {
+ if strings.HasPrefix(a, "--export") || strings.HasPrefix(a, "--unexport") {
+ return false
+ }
+ }
+ return true
+ case "settings", "configure":
+ // Just a name shows the settings; any flag changes them.
+ return len(args) == 1
+ }
+ return false
+}
+
func printUsage() {
fmt.Fprintln(os.Stderr, `usage: omavm [arguments]
commands:
- create --name NAME --kind box|machine [--image IMAGE] create an environment
+ create --name NAME --kind box|machine --image IMAGE create an environment (a Box needs a
+ container image, a Machine an ISO)
start NAME start an environment
open NAME start (if needed) and attach
stop NAME stop an environment
@@ -503,8 +677,12 @@ commands:
force-stop NAME immediately stop a Machine
status NAME [--json] show environment status
integration NAME [--json] check Machine guest tools
+ host [--json] show what this computer offers Machines
settings NAME [--description TEXT] [--cpus N] [--color C] view or change settings
- [--share-clipboard=BOOL] [--travel-mode=BOOL] (Machines only, both on by default)
+ [--share-clipboard=BOOL] [--travel-mode=BOOL] (on by default)
+ [--vulkan=BOOL] [--ssh=BOOL] [--fullscreen=BOOL] (Machines only, on by default)
+ [--launcher=BOOL] list in the app launcher (on by default)
+ [--open-in-empty-workspace=BOOL] open in an empty workspace (on by default)
preview NAME capture a Machine screenshot
snapshot create NAME --label TEXT capture the environment's current state
snapshot list NAME [--json] list snapshots
@@ -513,7 +691,9 @@ commands:
apps NAME [--json] list exportable applications (Boxes only)
apps NAME --export APP_ID export an app as a host launcher
apps NAME --unexport APP_ID remove a previously exported launcher
- exec NAME -- CMD [ARGS...] run a command inside a Box
+ exec NAME -- CMD [ARGS...] run a command inside a Box, or a Machine over SSH
+ ssh NAME [--user LOGIN] [-- CMD...] open a shell in a Machine (guest needs systemd 256+
+ and sshd; any program here can reach it, Boxes too)
rm NAME remove an environment
- list [--json] list known environments`)
+ list [--status] [--json] list known environments, with their state`)
}
diff --git a/cmd/omavm/main_test.go b/cmd/omavm/main_test.go
new file mode 100644
index 0000000..5d6dce3
--- /dev/null
+++ b/cmd/omavm/main_test.go
@@ -0,0 +1,168 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "flag"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestReadOnlyCommands(t *testing.T) {
+ tests := []struct {
+ cmd string
+ args []string
+ want bool
+ }{
+ {"list", []string{"--json"}, true},
+ {"status", []string{"vm", "--json"}, true},
+ {"integration", []string{"vm"}, true},
+ {"snapshot", []string{"list", "vm"}, true},
+ {"snapshot", []string{"create", "vm", "--label", "x"}, false},
+ {"apps", []string{"box", "--json"}, true},
+ {"apps", []string{"box", "--export", "/usr/share/applications/a.desktop"}, false},
+ {"apps", []string{"box", "--unexport=/x.desktop"}, false},
+ {"settings", []string{"vm"}, true},
+ {"settings", []string{"vm", "--cpus", "4"}, false},
+ {"start", []string{"vm"}, false},
+ {"rm", []string{"vm"}, false},
+ }
+ for _, tt := range tests {
+ if got := readOnly(tt.cmd, tt.args); got != tt.want {
+ t.Errorf("readOnly(%q, %q) = %t, want %t", tt.cmd, tt.args, got, tt.want)
+ }
+ }
+}
+
+// Regression: a Machine opened from the app launcher failed silently.
+func TestNotifyErrorSendsDesktopNotification(t *testing.T) {
+ bin := t.TempDir()
+ log := filepath.Join(t.TempDir(), "args")
+ script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > " + log + "\n"
+ if err := os.WriteFile(filepath.Join(bin, "notify-send"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", bin)
+ notifyError(errors.New("start kernels: installation media missing"))
+ got, err := os.ReadFile(log)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(got), "start kernels: installation media missing") {
+ t.Fatalf("notification did not carry the error: %s", got)
+ }
+}
+
+func TestNotifyErrorWithoutNotifySendIsSilent(t *testing.T) {
+ t.Setenv("PATH", t.TempDir())
+ notifyError(errors.New("x"))
+}
+
+var update = flag.Bool("update", false, "rewrite the golden files in testdata")
+
+// The JSON the CLI prints is a contract: the GUI, the Omarchy bar plugin
+// and agents parse it. A change to it must be a decision, visible as a
+// golden file diff, never a side effect of renaming a Go field.
+func TestJSONContract(t *testing.T) {
+ withTestRegistry(t)
+
+ for golden, args := range map[string][]string{
+ "list.golden.json": {"list", "--json"},
+ "list-status.golden.json": {"list", "--status", "--json"},
+ "status.golden.json": {"status", "Desktop Fedora", "--json"},
+ "snapshot-list.golden.json": {"snapshot", "list", "Desktop Fedora", "--json"},
+ "settings.golden.json": {"settings", "dev", "--json"},
+ } {
+ t.Run(golden, func(t *testing.T) {
+ got := captureStdout(t, func() error { return run(args) })
+ path := filepath.Join("testdata", golden)
+ if *update {
+ if err := os.WriteFile(path, got, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("%v (run go test ./cmd/omavm -update to create it)", err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("omavm %s changed its JSON:\n got: %s\nwant: %s", strings.Join(args, " "), got, want)
+ }
+ })
+ }
+}
+
+// withTestRegistry points OmaVM at a copy of testdata/environments.json,
+// with no container engine and no QEMU: every status is decided without
+// touching the host.
+func withTestRegistry(t *testing.T) {
+ t.Helper()
+ registry, err := os.ReadFile(filepath.Join("testdata", "environments.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ state := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(state, "omavm"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(state, "omavm", "environments.json"), registry, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("XDG_STATE_HOME", state)
+ t.Setenv("XDG_DATA_HOME", t.TempDir())
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("PATH", t.TempDir())
+ t.Setenv("DBX_CONTAINER_MANAGER", "")
+}
+
+// Regression: --shared-writable=false made the shared folder writable,
+// the opposite of what it says.
+func TestSharedFolderModeFlags(t *testing.T) {
+ withTestRegistry(t)
+ for _, tc := range []struct {
+ flag string
+ readOnly bool
+ }{
+ {"--shared-read-only", true},
+ {"--shared-writable", false},
+ {"--shared-writable=false", true},
+ {"--shared-read-only=false", false},
+ {"--shared-writable=true", false},
+ } {
+ out := captureStdout(t, func() error { return run([]string{"settings", "Desktop Fedora", tc.flag, "--json"}) })
+ var settings struct {
+ ReadOnly bool `json:"shared_read_only"`
+ }
+ if err := json.Unmarshal(out, &settings); err != nil {
+ t.Fatal(err)
+ }
+ if settings.ReadOnly != tc.readOnly {
+ t.Errorf("%s: read-only = %t, want %t", tc.flag, settings.ReadOnly, tc.readOnly)
+ }
+ }
+}
+
+func captureStdout(t *testing.T, fn func() error) []byte {
+ t.Helper()
+ r, w, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ stdout := os.Stdout
+ os.Stdout = w
+ runErr := fn()
+ os.Stdout = stdout
+ w.Close()
+ out, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if runErr != nil {
+ t.Fatal(runErr)
+ }
+ return out
+}
diff --git a/cmd/omavm/testdata/environments.json b/cmd/omavm/testdata/environments.json
new file mode 100644
index 0000000..759c6d0
--- /dev/null
+++ b/cmd/omavm/testdata/environments.json
@@ -0,0 +1,21 @@
+[
+ {
+ "id": "0123456789abcdef",
+ "name": "dev",
+ "image": "fedora:latest",
+ "backend": "distrobox",
+ "kind": "box",
+ "settings": {"color": "green", "travel_mode_disabled": true}
+ },
+ {
+ "id": "fedcba9876543210",
+ "name": "Desktop Fedora",
+ "image": "/isos/fedora.iso",
+ "backend": "qemu",
+ "kind": "machine",
+ "settings": {"cpus": 4, "memory_mib": 4096, "description": "work"},
+ "snapshots": [
+ {"id": "clean-install-1a2b3c4d", "label": "Clean installation", "created_at": "2026-09-27T12:00:00Z"}
+ ]
+ }
+]
diff --git a/cmd/omavm/testdata/list-status.golden.json b/cmd/omavm/testdata/list-status.golden.json
new file mode 100644
index 0000000..ef46656
--- /dev/null
+++ b/cmd/omavm/testdata/list-status.golden.json
@@ -0,0 +1 @@
+[{"id":"0123456789abcdef","name":"dev","image":"fedora:latest","backend":"distrobox","kind":"box","settings":{"color":"green","travel_mode_disabled":true},"status":{"state":"unknown","detail":"Development Boxes need Podman or Docker (install one with: sudo pacman -S podman)"}},{"id":"fedcba9876543210","name":"Desktop Fedora","image":"/isos/fedora.iso","backend":"qemu","kind":"machine","settings":{"description":"work","cpus":4,"memory_mib":4096},"snapshots":[{"id":"clean-install-1a2b3c4d","label":"Clean installation","created_at":"2026-09-27T12:00:00Z"}],"status":{"state":"stopped"},"integration":{"guest_agent":"stopped","hint":"Start the Machine to check guest tools"}}]
diff --git a/cmd/omavm/testdata/list.golden.json b/cmd/omavm/testdata/list.golden.json
new file mode 100644
index 0000000..388b468
--- /dev/null
+++ b/cmd/omavm/testdata/list.golden.json
@@ -0,0 +1 @@
+[{"id":"0123456789abcdef","name":"dev","image":"fedora:latest","backend":"distrobox","kind":"box","settings":{"color":"green","travel_mode_disabled":true}},{"id":"fedcba9876543210","name":"Desktop Fedora","image":"/isos/fedora.iso","backend":"qemu","kind":"machine","settings":{"description":"work","cpus":4,"memory_mib":4096},"snapshots":[{"id":"clean-install-1a2b3c4d","label":"Clean installation","created_at":"2026-09-27T12:00:00Z"}]}]
diff --git a/cmd/omavm/testdata/settings.golden.json b/cmd/omavm/testdata/settings.golden.json
new file mode 100644
index 0000000..661c1c0
--- /dev/null
+++ b/cmd/omavm/testdata/settings.golden.json
@@ -0,0 +1 @@
+{"snapshot_limit":10,"color":"green","travel_mode_disabled":true}
diff --git a/cmd/omavm/testdata/snapshot-list.golden.json b/cmd/omavm/testdata/snapshot-list.golden.json
new file mode 100644
index 0000000..9709cd7
--- /dev/null
+++ b/cmd/omavm/testdata/snapshot-list.golden.json
@@ -0,0 +1 @@
+[{"id":"clean-install-1a2b3c4d","label":"Clean installation","created_at":"2026-09-27T12:00:00Z"}]
diff --git a/cmd/omavm/testdata/status.golden.json b/cmd/omavm/testdata/status.golden.json
new file mode 100644
index 0000000..ca14ac5
--- /dev/null
+++ b/cmd/omavm/testdata/status.golden.json
@@ -0,0 +1 @@
+{"state":"stopped"}
diff --git a/contrib/dev.omavm.bar/OmaVM.qml b/contrib/dev.omavm.bar/OmaVM.qml
index 7f73eaf..96dee4d 100644
--- a/contrib/dev.omavm.bar/OmaVM.qml
+++ b/contrib/dev.omavm.bar/OmaVM.qml
@@ -1,4 +1,5 @@
import QtQuick
+import QtQuick.Effects
import Quickshell
import Quickshell.Io
import qs.Commons
@@ -76,16 +77,40 @@ BarWidget {
onTriggered: root.refresh()
}
- // A plain glyph, not "VM N" text: with the widget now living in the
- // tray cluster, the count belongs in the tooltip like every other tray
- // icon (network/bluetooth/volume), not spelled out inline.
+ // The OmaVM window glyph (data/icons/dev.omavm.app.svg, flattened to a
+ // single-color line icon as icon.svg here) instead of the bare ▣ font
+ // glyph, so this reads as the app's own identity rather than a random
+ // Unicode box — matches docs/TODO.md P2 "Unificar a identidade do
+ // widget com o aplicativo". Recolored via BarIconButton's own
+ // iconComponent slot (see /usr/share/omarchy/shell/Ui/BarIconButton.qml)
+ // rather than a fixed color, so it follows the bar's foreground/active
+ // colors like every built-in icon does.
BarIconButton {
id: button
anchors.fill: parent
bar: root.bar
- text: "▣"
slotSize: Style.bar.statusSlot
tooltipText: "OmaVM — " + root.envCount + " environment" + (root.envCount === 1 ? "" : "s") + ", click to open"
+ iconComponent: Component {
+ Item {
+ Image {
+ id: glyphImage
+ anchors.fill: parent
+ source: Qt.resolvedUrl("icon.svg")
+ sourceSize.width: width * 2
+ sourceSize.height: height * 2
+ fillMode: Image.PreserveAspectFit
+ visible: false
+ asynchronous: true
+ }
+ MultiEffect {
+ anchors.fill: parent
+ source: glyphImage
+ colorization: 1
+ colorizationColor: button.active && button.useActiveColor ? button.activeColor : button.foreground
+ }
+ }
+ }
onPressed: function(b) {
if (b === Qt.RightButton) root.refresh()
else root.openExperienceCenter()
diff --git a/contrib/dev.omavm.bar/icon.svg b/contrib/dev.omavm.bar/icon.svg
new file mode 100644
index 0000000..357d7d5
--- /dev/null
+++ b/contrib/dev.omavm.bar/icon.svg
@@ -0,0 +1,6 @@
+
diff --git a/contrib/hypr/omavm-viewer.lua b/contrib/hypr/omavm-viewer.lua
index 2352505..4f9120a 100644
--- a/contrib/hypr/omavm-viewer.lua
+++ b/contrib/hypr/omavm-viewer.lua
@@ -1,5 +1,5 @@
-- Opt-in Hyprland window rule for OmaVM's Machine display viewer
--- (omavm-gui --viewer, launched by `omavm open`/`Open` on a Machine).
+-- (omavm-gui --display-fd, launched by `omavm open`/`Open` on a Machine).
--
-- Not loaded automatically: like OmaVM's Quickshell plugin
-- (contrib/dev.omavm.bar), this only takes effect once you explicitly
@@ -20,4 +20,12 @@
-- window rule alone never makes them visible. A plain named workspace
-- switches the monitor to it automatically when the window opens, same
-- as any other window-rule-targeted workspace.
+--
+-- Conflicts with OmaVM's own "Open in an empty workspace" Settings
+-- preference (also opt-in, per-environment): that preference switches to
+-- a fresh empty workspace right before launching, but this window rule
+-- still wins and sends the new window to the fixed "name:omavm"
+-- workspace anyway. The two solve different needs (one dedicated,
+-- fullscreen spot vs. a fresh workspace per environment) and aren't
+-- meant to compose — use one or the other, not both.
o.window("dev.omavm.viewer", { workspace = "name:omavm", fullscreen = true })
diff --git a/data/icons/colors/blue.svg b/data/icons/colors/blue.svg
new file mode 100644
index 0000000..b526852
--- /dev/null
+++ b/data/icons/colors/blue.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/gray.svg b/data/icons/colors/gray.svg
new file mode 100644
index 0000000..695303e
--- /dev/null
+++ b/data/icons/colors/gray.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/green.svg b/data/icons/colors/green.svg
new file mode 100644
index 0000000..5cd342f
--- /dev/null
+++ b/data/icons/colors/green.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/orange.svg b/data/icons/colors/orange.svg
new file mode 100644
index 0000000..8de50d9
--- /dev/null
+++ b/data/icons/colors/orange.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/purple.svg b/data/icons/colors/purple.svg
new file mode 100644
index 0000000..6daa838
--- /dev/null
+++ b/data/icons/colors/purple.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/red.svg b/data/icons/colors/red.svg
new file mode 100644
index 0000000..dbd8a7f
--- /dev/null
+++ b/data/icons/colors/red.svg
@@ -0,0 +1,9 @@
+
diff --git a/data/icons/colors/yellow.svg b/data/icons/colors/yellow.svg
new file mode 100644
index 0000000..88aed8f
--- /dev/null
+++ b/data/icons/colors/yellow.svg
@@ -0,0 +1,9 @@
+
diff --git a/docs/TODO.md b/docs/TODO.md
new file mode 100644
index 0000000..8af5c61
--- /dev/null
+++ b/docs/TODO.md
@@ -0,0 +1,291 @@
+# TODO — UI/UX e integração do OmaVM
+
+Plano criado em 2026-09-27, a partir da revisão dos componentes QML, do backend da GUI e da captura do Experience Center. Os achados de código ainda precisam de validação interativa; este documento não representa testes com usuários nem recursos já entregues.
+
+## Objetivo
+
+Alcançar uma experiência de uso com o nível de simplicidade, integração e acabamento esperado do Parallels Desktop, preservando a identidade nativa do Omarchy. Uma pessoa deve conseguir criar, abrir, utilizar e recuperar um ambiente sem precisar conhecer a infraestrutura de virtualização.
+
+A referência é a experiência do produto, não uma cópia visual ou uma promessa de paridade entre plataformas. O Parallels apresenta integração de aplicações pelo Coherence e uso em tela cheia; no OmaVM, essas ideias orientam a continuidade entre ambiente e host, respeitando as capacidades de Boxes e Machines. Referências: [produto oficial](https://www.parallels.com/products/desktop/) e [documentação oficial](https://docs.parallels.com/landing).
+
+Comparação de jornadas (2026-09-29): o [GNOME Boxes](https://help.gnome.org/gnome-boxes/create.html) reduz passos até a primeira VM utilizável com escolha de sistema, mídia detectada e instalação expressa quando suportada; o [Parallels](https://kb.parallels.com/en/125374) oferece download/instalação assistida em cenários suportados e investe na continuidade entre host e guest. Para o OmaVM, usar essas referências para avaliar tempo até o primeiro ambiente utilizável, clareza da próxima ação e recuperação de falhas. Preservar a escolha própria entre Development Box e Desktop; não inferir paridade de recursos nem priorizar um catálogo de imagens sem validar demanda.
+
+## Como usar este plano
+
+- **P0:** reproduzir riscos de concorrência e resolver falhas confirmadas de confiabilidade.
+- **P1:** concluir fluxos básicos, layout e acessibilidade.
+- **P2:** validar integração com Omarchy e guests.
+- **P3:** avaliar as [propostas de expansão](discovery.md) antes de implementar.
+
+Uma caixa aberta pode representar implementação pendente ou validação ainda necessária; as notas distinguem esses casos. Consulte o [histórico](review-history.md) para evidências anteriores. Revalidar os achados contra o código atual; build limpo não comprova usabilidade nem compatibilidade com guests.
+
+## Regras do plano
+
+- Manter Qt Quick Controls/Material, tema e escala de texto do Omarchy; reutilizar componentes existentes antes de criar abstrações.
+- Preservar o modelo Environment, a diferença de isolamento Box/Machine e o contrato GUI → CLI → Core → backend.
+- Priorizar fluxos completos e recuperação de falhas antes de acrescentar opções.
+- Consumir os mecanismos nativos do Omarchy; manter regras de workspace e atalhos como escolhas do usuário. Instalar o widget não deve habilitá-lo automaticamente.
+- Reutilizar o ícone oficial e as capturas existentes quando adequados; atualizar capturas após validar a interface entregue.
+- Manter desligamento normal e forçado separados; nunca transformar falha de desligamento em perda de dados automática.
+- Implementar capacidades de gerenciamento pelo Core/CLI antes de expô-las na GUI.
+- Decisão do usuário: clipboard, transferência de arquivos e abertura de links/aplicações devem funcionar nos dois sentidos entre host e guest, habilitados por padrão e desativáveis por ambiente. A preferência não equivale a suporte confirmado; preservar escolhas explícitas ao atualizar registros existentes.
+- P0 e P1 tratam da experiência existente. P2 melhora integração. P3 exige descoberta e decisão de escopo antes da implementação. A frente QEMU é transversal: seus achados entram nessas prioridades conforme impacto e evidência.
+- As diretrizes de [CLAUDE.md](../CLAUDE.md) continuam sendo a referência de produto. Propostas divergentes estão identificadas abaixo para decisão explícita.
+
+## Visão de produto para avaliar as ideias
+
+Síntese da leitura de [docs/ideias](ideias/README.md) em 2026-09-28. A direção mais forte é fazer cada ambiente parecer nativo no Omarchy, confiável no uso diário e previsível para automação. Três jornadas orientam a seleção de trabalho:
+
+1. **Ambiente como parte do desktop:** criar e abrir uma Box ou Machine, identificá-la no launcher e nas janelas, usar teclado, clipboard e aplicações, e voltar ao gerenciador sem pensar no backend.
+2. **Ambiente que se explica e se recupera:** acompanhar operações demoradas, entender pré-requisitos e limites reais, e receber um caminho de recuperação quando algo falhar, especialmente por falta de espaço no host.
+3. **Ambiente reproduzível para pessoas e agentes:** executar ações pela CLI com resultados interpretáveis, experimentar sem preservar alterações quando solicitado e, depois de validar a jornada, transportar um ambiente de forma independente.
+
+Critério de escolha: primeiro concluir e validar os fluxos atuais de P0–P2; depois selecionar a menor proposta que resolva uma fricção demonstrada nessas jornadas. A tabela em P3 registra o destino de **todas** as ideias sem convertê-las automaticamente em compromissos de implementação.
+
+## P0 — Confiabilidade: pendências de verificação
+
+Os sete ajustes de GUI foram registrados como implementados: bloqueio durante operações, preservação de formulários, erros persistentes, confirmações de snapshots, atualização da lista de snapshots, aviso de retenção e distinção entre vazio e falha. Evidências e limites estão no [histórico da revisão](review-history.md). A validação das jornadas permanece na seção de conclusão abaixo.
+
+- [x] **Reproduzir operações concorrentes na mesma Machine.** Conferir start/start e restauração/criação/exclusão de snapshots por CLI e GUI. A leitura de código identificou ausência de serialização nesses caminhos; escrita concorrente e perda de dados não foram demonstradas. Verificar também a proteção de locking do QEMU.
+ - Aceite: registrar reprodução em ambiente descartável, resultado de cada operação, estado final e impacto. Corrigir lacunas confirmadas; não agir sobre processos alheios nem perder histórico válido. Detalhes na frente QEMU e no histórico.
+ - Start/start: reproduzido e corrigido em 2026-09-27 (ver [histórico](review-history.md)). O locking do próprio `-pidfile` do QEMU já impedia dois processos reais no mesmo disco; o gap confirmado era só um erro cru vazando pra quem perdesse a corrida, corrigido tratando isso como sucesso idempotente.
+ - Snapshots (create/go-to) com Machine parada: reproduzido e corrigido em 2026-09-27 (ver histórico). `qemu-img` também tem locking de imagem próprio — sem corrupção, mas o mesmo tipo de erro cru vazando. Corrigido fazendo `GoToSnapshot` segurar o mesmo lock do registro que `CreateSnapshot`/`RemoveSnapshot` já seguravam, serializando no Core em vez de deixar a corrida chegar ao `qemu-img`. Reproduzido de novo após a correção: ambas terminam limpas.
+ - Snapshots com Machine **rodando** (savevm/loadvm/delvm via QMP): também reproduzido e verificado em 2026-09-27 com a mesma correção — Machine real ligada (sem ISO/guest), `create`+`go-to` concorrentes terminam com exit 0 nos dois, registro com os dois snapshots corretos e a Machine de volta a "running" depois do go-to. Item de P0 considerado fechado; `go test ./...` (suite inteira) passa.
+
+- [x] **Ações de ambientes diferentes não bloqueiam umas às outras.** (2026-09-29, pedido do usuário de operações assíncronas; substitui a decisão anterior de manter uma única ação em voo.) O Core serializa as operações de **um** ambiente com um lock por ambiente e segura o lock do registro só para ler e gravar (criação e remoção em duas fases, estados `creating`/`removing`), então um pull de imagem de minutos não trava mais os outros. A GUI acompanha: `busy` virou um mapa por ambiente (`busyEnvironments`), cada card, o diálogo de snapshots e o de aplicações olham só o próprio ambiente, a segunda ação no mesmo ambiente é recusada dizendo o que está rodando, e sair espera todas. Regressões: `TestSlowCreateDoesNotHoldOtherEnvironments`, `TestInterruptedCreationCanBeRemoved`, `TestOperationsOnOneEnvironmentWaitForEachOther` (Go, com `-race`) e `actionsOnDifferentEnvironmentsRunTogether` (Qt).
+
+- [x] **Super+C no terminal de uma Box interrompe o programa.** Corrigido em 2026-09-28: a janela do terminal da Box se marca com a tag dinâmica `terminal` ao ficar ativa (`terminalTagScript`, seletor por pid; testado com `hyprctl repl` numa sessão real), então o Omarchy manda Ctrl+Insert/Shift+Insert, que o terminal copia/cola; o viewer de Machine continua recebendo Ctrl+C. Regressão: `boxTerminalIsTaggedAsTerminal`. Registro original: O Omarchy decide o atalho universal pela tag `terminal` da janela ativa (`/usr/share/omarchy/default/hypr/bindings/clipboard.lua`): em terminais manda Ctrl+Insert/Shift+Insert; nas outras janelas, Ctrl+C/Ctrl+V. A tag vem de uma regra por classe em `apps/terminals.lua` (`Alacritty|kitty|…|org\.omarchy\..*|TUI\..*`). O terminal da Box abre como `dev.omavm.viewer`, sem a tag, então **Super+C chega como Ctrl+C = SIGINT** para o programa na Box, e Super+V chega como Ctrl+V. Encontrado lendo a config instalada em 2026-09-28; não reproduzido numa sessão real.
+ - Já feito, independente da decisão: o terminal cola com Shift+Insert e Ctrl+Shift+V, com bracketed paste (`?2004h`), testado em `make test-terminal`. Com a tag, Super+V passa a funcionar sozinho.
+ - Opções: (a) app id próprio para o terminal (ex.: `dev.omavm.terminal`) com uma regra opt-in em `contrib/hypr/` dando `+terminal` — limpo, mas só resolve para quem copiar a regra, e a regra de fullscreen compartilhada precisa cobrir as duas classes; (b) um app id no padrão `TUI.*` que o Omarchy já marca — resolve por padrão, mas apoia a OmaVM numa convenção interna do Omarchy; (c) marcar a própria janela em runtime com `hl.dsp.window.tag` (API sem documentação de argumentos; precisa de teste numa sessão real).
+ - Aceite: com a regra/solução escolhida, Super+C num terminal de Box não interrompe o programa e Super+V cola; o viewer de Machine continua recebendo o que recebe hoje.
+ - Relacionado: o terminal ainda não seleciona nem copia texto (Ctrl+Insert não tem o que copiar).
+
+## P1 — Fluxos básicos completos e interface adaptável
+
+- [ ] **Tornar configurações roláveis.** Limitar a altura ao espaço disponível, manter ações acessíveis e separar Geral, Hardware, Integração e Mídia de instalação.
+ - Aceite: todos os campos e Salvar/Cancelar são alcançáveis na menor janela suportada; desconectar ISO deixa de estar sob pasta compartilhada.
+ - Implementado parcialmente: altura limitada, conteúdo rolável e mídia de instalação em grupo próprio. Falta validar dimensões e escalas abaixo.
+- [ ] **Reorganizar cards em janelas estreitas.** Manter Start/Open/Resume visível, com nome e estado legíveis; reduzir primeiro informações secundárias.
+ - Aceite: abrir um ambiente continua sendo uma ação direta em 320 px de largura de janela.
+ - Implementado parcialmente: ação principal permanece visível como ícone abaixo de 500 px. Falta validar em 320 px.
+- [ ] **Revisar todos os diálogos em resize contínuo.** Ajustar títulos, textos, botões, estado vazio e mensagens; usar quebra de linha e rolagem quando necessário.
+ - Aceite: em 320×420, 640×480 e 960×640 não há campos ou ações essenciais inacessíveis; repetir com escala de 150% e 200%.
+ - Achado corrigido (2026-09-27): os botões de escolha do passo 0 do `CreateDialog.qml` (texto multi-linha com `\n`, altura fixa de 128px) vazavam texto pela borda direita na largura real do diálogo — `Button` do Qt Quick Controls não quebra linha automaticamente. Confirmado com `qml6`/`grim` num harness isolado reproduzindo a largura exata (~632px) antes e depois. Corrigido com `contentItem` próprio usando `Label { wrapMode: Text.Wrap }` e altura guiada pelo conteúdo. Os demais diálogos ainda não foram revisados sistematicamente nas três dimensões/escalas do aceite.
+ - Achados corrigidos (2026-09-27, mesma sessão): `CreateDialog.qml` passo "Ready to create" — nome sem `elide`/`fillWidth` no resumo podia alargar o `GridLayout` além do diálogo para nomes longos (Core não limita comprimento). `Main.qml` — estado vazio ("No environments yet") não tinha `wrapMode`/limite de largura no subtítulo, ao contrário do estado de erro logo abaixo que já tinha; corrigido replicando o mesmo tratamento. Ambos confirmados via harness `qml6`/`grim` isolado.
+- [ ] **Melhorar a escolha Box/Desktop por intenção.** Explicar com exemplos o que cada opção permite e o compartilhamento com o host; evitar sugerir que Box é uma máquina isolada ou incapaz de abrir aplicações gráficas.
+ - Aceite: uma pessoa consegue escolher entre terminal de desenvolvimento e instalação de um sistema com kernel próprio sem conhecer os backends.
+ - Implementado parcialmente (2026-09-27): `CreateDialog.qml` passo 0/1 ganhou exemplos concretos ("Desktop: instalar Windows, FreeBSD, Arch com kernel custom"; "Development Box: terminal Fedora/Ubuntu para um projeto — também abre e exporta apps gráficos") e o aviso de passo 1 deixou de sugerir que Box não abre app gráfico. `qmllint` sem erro estrutural. Falta validação visual/interativa (build da GUI pendente nesta sessão, ver histórico).
+- [ ] **Validar a criação antes de executar.** Mostrar erros junto aos campos, preservar foco e validar nome e mídia usando as regras do Core. Tratar corretamente caminhos com espaços e caracteres acentuados.
+ - Aceite: Enter e clique seguem a mesma validação; voltar uma etapa preserva os valores.
+ - Implementado parcialmente (2026-09-27): `CreateDialog.qml` ganhou `validateName()`, espelhando `validateEnvironmentName` do Core (`internal/core/service.go`) — mesmas regras (vazio, `.`/`..`, `/`, `\`, caracteres de controle), erro exibido junto ao campo e foco devolvido a ele; Enter (`onAccepted`) e o botão "Continue" passam pelo mesmo `createButton.clicked()`, então seguem a mesma checagem. Campos nunca são limpos ao voltar um passo (só `resetForm()` ao abrir o diálogo). Espaços e acentos não são restringidos (regra do Core já é permissiva) e todos os argumentos já seguem separados para o `QProcess` (nunca shell). Falta exercitar interativamente em janela real.
+- [ ] **Apresentar um resumo de criação.** Mostrar tipo, imagem/ISO e recursos efetivamente usados; oferecer ajuste de recursos da Machine sem exigir visita posterior às configurações.
+ - Aceite: os valores mostrados correspondem ao que será criado; defaults permitem concluir sem ajustes.
+ - Implementado (2026-09-27): novo passo "Ready to create" em `CreateDialog.qml` mostra tipo, imagem/ISO e nome; para Machine, `SpinBox` de CPUs (1–64) e memória (256–262144 MiB, padrão 2/2048, mesmos limites de `SettingsDialog.qml`) alimentam diretamente `backend.createEnvironment(...)`. Core (`internal/core/service.go`'s `Create`) e CLI (`cmd/omavm/main.go`'s `create --cpus/--memory-mib`) ganharam suporte a isso, com a mesma validação de faixa que `Configure` já aplica e um novo erro `ErrUnsupported` se usado com Box. Verificado: `go test ./...` (suite inteira) passa, incluindo teste novo `TestCreateHardwareSettingsRequireMachine`; testado manualmente via CLI (`omavm create --kind machine --cpus 4 --memory-mib 4096` seguido de `omavm settings --json` confirmando persistência, e rejeição limpa para `--kind box --cpus 4`). GUI (`qmllint` sem erro) ainda não validada em janela real.
+ - **Bug real encontrado e corrigido (2026-09-27), mesma família do achado em "Explicar ajustes automáticos e pendentes" (P2), mas em Create em vez de Configure.** `CreateDialog.qml` sempre enviava `--cpus 2 --memory-mib 2048` (os valores padrão mostrados no passo de resumo) pra `backend.createEnvironment(...)`, mesmo quando o usuário nunca tocava nos `SpinBox` — então **toda Machine criada pela GUI nascia com CPU/memória fixados desde o início**, desligando o Travel Mode permanentemente desde a criação (não só depois de um Save em Settings). Corrigido com o mesmo padrão de "touched" via `SpinBox.onValueModified` já usado em `SettingsDialog.qml`: `CreateDialog.qml` ganhou `cpusTouched`/`memoryTouched`, e `Backend::createEnvironment` (`gui/backend.cpp`/`.h`) só inclui `--cpus`/`--memory-mib` quando de fato tocados. Confirmado via CLI real: `create --kind machine` sem essas flags agora deixa `settings: {}` no `environments.json` bruto (antes desse fix já ficava correto no CLI puro, já que o bug morava só na GUI sempre mandando as flags) — `settings --json` continua mostrando os valores efetivos (2/2048) pra exibição.
+- [ ] **Levar a criação até o primeiro uso.** Depois de criar, oferecer uma ação direta para abrir o terminal da Development Box ou iniciar e abrir o instalador da Machine. Manter o ambiente criado visível caso a abertura falhe, com erro e nova tentativa no card; evitar criar uma segunda cópia ao repetir a ação.
+ - Aceite: uma pessoa conclui criação → primeiro terminal/instalador sem procurar uma ação no gerenciador; cancelar ou fechar a sugestão deixa o ambiente criado e utilizável depois. Medir os passos e o tempo até o primeiro uso nas duas jornadas, inclusive durante o pull de uma imagem de Box; aproveitar a proposta de [progresso ao criar Box](ideias/progresso-ao-criar-box.md) sem porcentagem fictícia.
+- [ ] **Fazer o verbo da ação principal corresponder ao resultado.** Hoje o card parado mostra "Start", mas chama `Backend::open`, que inicia e abre o ambiente. Escolher um rótulo que comunique o resultado para cada estado e tipo, mantendo "iniciar sem abrir" como ação separada somente se houver caso de uso visível.
+ - Aceite: a pessoa prevê se verá terminal/instalador/viewer após o clique; rótulo, nome acessível, tooltip e menu concordam entre si em estados parado, rodando e pausado. Validar também abertura pelo launcher e cliques repetidos.
+- [ ] **Tornar pré-requisitos e recursos compreensíveis.** Verificar disponibilidade necessária ao fluxo, memória e espaço; oferecer instrução contextual quando algo impedir a criação.
+ - Aceite: falhas previsíveis são explicadas antes da operação longa; não apresentar porcentagens ou estimativas fictícias.
+ - Implementado parcialmente (2026-09-27): binário ausente de `qemu-img`/`qemu-system-x86_64` agora falha com a mesma dica acionável que `virtiofsd` já tinha ("install it with: sudo pacman -S qemu-desktop"), em vez do erro cru do Go (achado já registrado na auditoria QEMU, ver abaixo). `distrobox` ausente já tinha diagnóstico equivalente antes desta sessão. Faixa de CPU/memória inválida também falha antes de qualquer chamada ao backend (ver item de resumo acima). Ainda faltam: checagem de espaço em disco/memória do host e de acesso a `/dev/kvm` antes da operação (o próprio QEMU recusa e o stderr chega ao usuário, mas não é antecipado). Teste de regressão: `TestMissingBinaryDiagnostic` em `internal/backend/qemu/lifecycle_test.go`.
+- [ ] **Fechar o ciclo da instalação.** Explicar quando abrir o instalador, como voltar ao gerenciador e como desconectar a ISO após instalar. Após o desligamento da Machine, apresentar a próxima ação no contexto da mídia de instalação; não presumir que o guest terminou a instalação só porque desligou.
+ - Aceite: criar → instalar → desligar → desconectar ISO → iniciar pelo disco é possível pela GUI, sem a pessoa precisar lembrar uma instrução lida antes da criação. A escolha de manter ou desconectar a ISO é explícita e reversível; testar instalação concluída, instalador interrompido e falha de boot pelo disco.
+ - Implementado parcialmente (2026-09-27): o passo de resumo do `CreateDialog.qml` agora explica o ciclo completo ("iniciar abre o instalador a partir da ISO; depois de instalar, desligue e desconecte a mídia em Settings antes de iniciar pelo disco") antes mesmo da criação — o mecanismo (`--disconnect-iso` em Settings) já existia e não mudou. Falta validar a jornada completa criada→instalada→desconectada→iniciada pelo disco numa sessão real.
+- [ ] **Padronizar linguagem e consequências.** Usar Desktop/Development Box consistentemente na interface, verbos específicos nas confirmações e “Remover do menu” para desfazer exportação de aplicações.
+ - Aceite: remover um atalho não parece desinstalar a aplicação; excluir ambiente explica o que será apagado.
+ - Implementado parcialmente: “Remove from menu” e exclusão com consequências específicas por tipo. Falta revisar os demais rótulos e confirmações.
+ - Achado corrigido (2026-09-27): auditado "Desktop"/"Development Box" em todos os `.qml` — já consistente, nenhum "Machine"/"Box"/"VM" solto vazando pra UI. As quatro confirmações que usavam `Dialog.Cancel | Dialog.Yes` (botão genérico "Yes" gerado pelo Qt) ganharam verbo específico via `standardButton(Dialog.Yes).text = ...` no `Component.onCompleted`: "Force Stop" (`confirmForceStop`, `Main.qml`), "Delete" (`confirmDelete` de Environment e `confirmDeleteSnapshot`), "Go To" (`confirmGoTo`, `SnapshotsDialog.qml`) — título e botão agora dizem a mesma coisa, em vez de um título específico com um "Yes" genérico embaixo. `qmllint` sem erro estrutural, `make build-gui` limpo; `standardButton()` é API padrão do Qt Quick Controls, verificado sem erro de runtime num harness isolado (sem captura visual desta vez — ver observação de privacidade no histórico). Falta revisar rótulos fora de diálogos de confirmação (ex.: textos de tooltip, menu) se alguma inconsistência aparecer numa passada futura.
+- [x] **Atualizar estados sem depender do botão Refresh.** Definir atualização limitada ao necessário, incluindo mudanças externas e conclusão de transições; impedir resultados atrasados de atualizar o ambiente errado.
+ - Aceite: iniciar/parar pelo CLI converge para o estado correto na GUI em até 5 segundos com a janela ativa, no host de teste documentado; não criar daemon apenas para isso.
+ - Implementado e verificado em 2026-09-27 (ver [histórico](review-history.md)): `Timer` em `Main.qml` (3s, só enquanto `win.active`) atualiza os estados; corrigida de junto uma falha latente de atribuição por índice obsoleto em `enrichEnvironment` (`gui/backend.h,cpp`, novo `m_environmentsGeneration`) que o polling tornaria fácil de disparar. Verificado automatizado, sem GUI/humano: Machine criada e iniciada só pelo CLI, GUI nunca tocada, card foi de "Stopped"/"Start" para "Running"/"Open" com preview real em ~4s. Host de teste: Omarchy, Hyprland, `XDG_STATE_HOME` isolado, sem guest OS instalado.
+ - Correção de flickering (2026-09-27): o polling agora usa `backend.poll()` sem alternar o estado visual de operação; o backend preserva status/integração/preview conhecidos e só notifica o modelo quando o valor muda. O preview permanece como miniatura da primeira captura enquanto a Machine está ligada, em vez de recarregar a cada 3s. Teste Qt focado confirma duas consultas idênticas sem `busyChanged` nem atualização redundante de ambientes; build da GUI e execução offscreen passaram. Falta confirmar visualmente na sessão real que a piscada relatada desapareceu.
+ - Continuação (2026-09-27): o usuário relatou que o viewer da Machine pisca só com o Experience Center aberto. Um cliente RFB em modo shared, conectado aos sockets VNC de duas Machines rodando (Haiku, Hello System), não registrou nenhuma atualização de framebuffer causada por `status`/`integration`/`preview`; o poll não mexe no display do guest. Custo real encontrado: `container.New()` rodava `podman info` em toda invocação do `omavm`, inclusive `list`/`status` de Machines (~330 ms de CPU por chamada, ~19 s de CPU em 25 s de poll com duas Machines). A detecção agora é preguiçosa (`internal/backend/container`), e `omavm list` caiu para ~3 ms. Além disso, um preview que falha (Haiku: `screendump: no surface`) era refeito em todo poll; agora espera 60 s antes de tentar de novo (`m_previewRetryAt`, teste `failedPreviewIsNotRetriedEveryPoll`). Hipótese ainda não confirmada visualmente: os picos de CPU a cada 3 s causavam o travamento percebido no viewer.
+ - Segunda causa, no próprio Experience Center (2026-09-28): a lista usava `backend.environments` (array JS) como model, e o `ListView` recria todos os delegates quando o array muda — confirmado com `qmltestrunner` (o card não é o mesmo objeto depois de uma mudança de status). Cada mudança de status, preview ou guest tools destruía e recriava todos os cards, rodando de novo o fade-in de 220 ms (piscar) e fechando qualquer menu "⋯" aberto. Corrigido com `gui/EnvironmentListModel.qml`, um `ListModel` sincronizado no lugar por nome; teste `tst_environmentlistmodel.qml` (mesmo card após mudança de status; inserir/remover/ordem). Falta confirmar na sessão real que a piscada sumiu.
+- [ ] **Concluir navegação por teclado e acessibilidade.** Dar nomes acessíveis a ícones e campos, foco visível, ordem de Tab coerente, retorno de foco ao fechar diálogos e indicação de seleção além da cor.
+ - Aceite: criar, abrir, configurar e cancelar uma ação destrutiva são possíveis sem mouse; conferir nomes com leitor de tela.
+ - Testes acrescentados em 2026-09-28: o card verifica nomes acessíveis nas duas ações, status expresso em texto, foco por Tab e abertura do menu com Espaço; a seleção das tags de cor já tinha teste de estado anunciado. Ainda faltam testes das demais jornadas e validação com Orca/AT-SPI; foco recebido não comprova, por si só, a aparência do indicador nem que ele não esteja encoberto.
+ - Auditoria pela árvore de acessibilidade (2026-09-29): `tst_accessibility.qml` percorre a `QAccessibleInterface` que o Qt entrega ao AT-SPI (a mesma que o Orca lê), com a acessibilidade ativa, nos cards (parado, rodando, pausado, com erro, estreito) e seus menus, na criação (cada passo), nas configurações (Machine e Box), nos snapshots e nas aplicações. Todo botão, campo, checkbox, spinbox, combo e item de menu visível precisa de nome, e os ativos precisam poder receber foco. Encontrou e corrigiu: os dois cartões Desktop/Development Box sem nome; descrição, CPUs, memória, pasta compartilhada, ISO, imagem, nome do ambiente e rótulo do snapshot sem nome (o placeholder não é anunciado); o campo interno dos spinboxes, onde vai o foco ao digitar. **Bug real:** com a acessibilidade ativa, o Qt substitui `Accessible.checked` pelo estado do próprio botão, então a cor selecionada nunca era anunciada — o teste anterior só passava porque rodava com a acessibilidade desligada; os círculos agora são botões marcáveis. Ainda fora: aparência e visibilidade do foco (2.4.7/2.4.13), ordem de Tab, retorno de foco ao fechar diálogos, a janela principal, viewer e terminal, e a validação com o Orca de verdade.
+- [ ] **Validar legibilidade nos temas.** Medir contraste dos textos, estados, foco e controles em temas claros/escuros; aumentar áreas de interação das tags de cor e conferir ícones em diferentes fontes.
+ - Aceite: documentar temas e resultados; usar como meta de produto [WCAG 2.2 1.4.6](https://www.w3.org/WAI/WCAG22/Understanding/contrast-enhanced) (AAA: 7:1 para texto normal, 4,5:1 para texto grande), [2.5.5](https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced) (AAA: alvo de 44×44) e os demais critérios aplicáveis de componentes e foco. Testes automatizados cobrem pares definidos de cores e controles identificados; não certificam a interface inteira nem temas arbitrários do usuário.
+ - Achado crítico corrigido (2026-09-27): todos os ícones renderizados via `Icon.qml` (usado em ~20 pontos — cards, diálogos, banner de erro, estado vazio) apareciam **pretos sem recoloração nenhuma** no app real, em qualquer tema — essencialmente invisíveis sobre fundo escuro. Não era um problema de contraste/escolha de cor, era o mecanismo de tingimento (`MultiEffect` do `QtQuick.Effects`, testadas duas variações: `colorization` e `maskEnabled`/`maskSource`) simplesmente não aplicando a cor no binário compilado, apesar de looks corretos em teste isolado. Corrigido trocando para `IconImage` (`QtQuick.Controls.impl`), o mesmo tipo que o Qt Quick Controls já usa para `icon.color` nativo em `Button`/`ToolButton` — mecanismo já comprovadamente funcional no app real (ícones do cabeçalho). Não confirmado visualmente por captura de tela nesta sessão (ver [histórico](review-history.md) para os incidentes de privacidade que impediram a verificação por `grim`, e a tentativa frustrada com `grabToImage`); `qmllint`/`make build-gui`/binário rodando sem erro de QML são a evidência disponível. **Pendente: confirmação visual humana** de que os ícones aparecem coloridos corretamente antes de considerar este achado fechado.
+ - Contraste medido (2026-09-27) contra o tema real e ativo do host de desenvolvimento (`~/.local/state/omarchy/current/theme/colors.toml`, `mode = "dark"`; cálculo de luminância relativa/WCAG, não captura de tela): todos os pares texto/fundo usados pelo app (`foreground`/`muted`/`accent`/`green`/`red` sobre `background`/`lighter_background`) passam 4,5:1, com uma exceção: **`muted` (#717a86) sobre `lighter_background`/`themeSurface` (#16181b) = 4,09:1** — passa o limiar de texto grande/UI (3:1) mas fica abaixo do limiar de texto normal (4,5:1). Combinação usada em `EnvironmentCard.qml` (descrição, rótulo de kind), `SnapshotsDialog.qml`/`AppsDialog.qml` (timestamp, texto secundário das linhas de lista) — todos em `Pane { Material.background: backend.themeSurface }` com texto em tamanho padrão, não "grande". Não corrigido: `themeMuted` vem direto do `colors.toml` do usuário (`muted` no tema Omarchy) — a OmaVM não deve substituir a cor escolhida pelo tema (CLAUDE.md: "não crie um sistema de temas próprio"); um ajuste de tamanho/peso de fonte para esse texto secundário cruzar para o limiar de "texto grande" seria uma decisão de produto separada, não feita aqui. Tema claro do Omarchy não medido (o host de desenvolvimento está em `mode = "dark"`); os valores de fallback hardcoded em `Backend::loadTheme` (usados antes do `colors.toml` carregar) também foram medidos à parte e têm o mesmo tipo de gap (`muted` 4,25:1/3,64:1) — mesma conclusão, não é bug de um valor específico, é margem apertada do conceito "cor muted sobre superfície elevada" em geral.
+ - Atualização de 2026-09-28: `Backend::loadTheme` agora preserva `foreground`/`muted` quando atingem 7:1 nas superfícies principal e elevada; caso contrário escolhe preto ou branco com o melhor contraste. Um teste C++ verifica o limite de 7:1 em exemplos claro/escuro e a preservação da cor original quando ela já atende. Isso supera o achado histórico de `muted` acima para esses textos, mas **não** cobre ainda texto em `accent`/`red`/`green`, foco, ícones ou qualquer combinação arbitrária de superfícies.
+ - Atualização de 2026-09-29: medido nos 22 temas instalados em `/usr/share/omarchy/themes`, o texto em cor de estado ficava abaixo de 7:1 em quase todos (vermelho em 20, accent em 17, verde em 13; 4 temas abaixo até de 3:1 no vermelho). `accessibleColor` (`gui/colorstoml.cpp`) agora leva verde, vermelho e o accent usado como texto (`themeAccentText`) a 7:1 **mantendo o tom** — mistura com branco ou preto só o necessário, por bisseção — em vez de trocar por preto/branco; o accent cru continua nos controles do Material, que desenham o próprio texto sobre ele. `everyThemeTextMeetsAAA` percorre todos os temas instalados (e três embutidos para o CI) e exige 7:1 de foreground, muted, accent, verde e vermelho sobre as duas superfícies; confirmado que falha sem a correção (verde do catppuccin-latte a 2,53:1). Ainda fora: foco, bordas e texto sobre controles do Material com fundo accent.
+ - Achado corrigido (2026-09-27): as tags de cor em `SettingsDialog.qml` (`ToolButton` de 22×22px) tinham a área clicável do tamanho exato do círculo visível — abaixo do mínimo de 24×24 do WCAG 2.5.8 (Target Size Minimum) e bem abaixo dos ~40-44px recomendados por guias de plataforma (Material/HIG). Corrigido separando tamanho visual de área de toque: `ToolButton` cresceu para 40×40, o círculo colorido (`contentItem`) manteve 22×22 centralizado dentro — mesma densidade visual, alvo de clique maior. `qmllint`/`make build-gui` limpos.
+ - Atualização de 2026-09-28: o teste QML para WCAG 2.2 2.5.5 (AAA) encontrou as tags em 40×40; as áreas clicáveis agora medem 44×44, com a bolinha visual de 22×22 preservada. O mesmo teste confere os alvos das ações principais dos cards. Os demais controles ainda precisam de auditoria de tamanho e das exceções previstas no critério.
+ - "Conferir ícones em diferentes fontes": já resolvido por construção antes desta sessão — nenhum glifo de fonte Unicode é usado como ícone em nenhum lugar do app (auditoria: `grep` por glifos como `▣`/`▶`/`⋮`/`⚠`/`✕` em todo `gui/*.qml` não encontra nada), todos os ícones já são SVG (ver histórico, sessão de troca de glifos por SVGs). O sub-item fica sem objeto — não há dependência de fonte do sistema para verificar.
+
+## P2 — Continuidade entre ambiente e Omarchy
+
+- [ ] **Validar instalação e entrada pelo desktop.** Conferir `make install`, entrada `.desktop`, resolução do ícone e abertura do app pelo launcher em uma sessão Omarchy com o PATH de usuário documentado.
+ - Aceite: OmaVM aparece com nome e ícone corretos no launcher e nas superfícies do shell que exibem ícones; abre sem terminal no host e identifica corretamente sua janela. Registrar separadamente o comportamento ao executar da árvore de fontes sem instalação.
+ - Base: `Makefile`, `data/dev.omavm.app.desktop`, `data/icons/dev.omavm.app.svg`, `gui/main.cpp`.
+- [ ] **Unificar a identidade do widget com o aplicativo.** Substituir o glifo `▣` pelo ícone oficial ou uma variante monocromática derivada dele, conforme os recursos e convenções do componente da barra. Preservar tamanho, contraste e nome acessível.
+ - Aceite: ícone legível em temas claro/escuro e escalas de P1, sem dependência de glifo de fonte; clique abre o Experience Center, tooltip informa a contagem e atualização acompanha criação/remoção no intervalo configurado. Validar zero ambientes e falha da CLI, sem apresentar falha como contagem confiável.
+ - Base: `contrib/dev.omavm.bar/`; manter habilitação manual e explicar como carregar alterações segundo o ciclo de vida do shell.
+ - Implementado parcialmente: widget e GUI usam SVGs com cores do tema. Falta validar o widget no Quickshell, temas, escalas e estados de erro; manter habilitação manual.
+- [ ] **Validar troca de tema com o aplicativo aberto.** Conferir gerenciador, diálogos, viewer e terminal, incluindo cores de seleção e foco. Integrar com a escala de texto do Omarchy sem criar preferências de tema paralelas.
+ - Aceite: troca claro/escuro atualiza as superfícies controladas pelo OmaVM sem reinício nem perda de formulário; o conteúdo gráfico do guest mantém o tema escolhido dentro dele. Registrar os resultados de contraste junto à tarefa de P1.
+ - Triagem de 2026-09-28: o Experience Center já observa `colors.toml` e usa a paleta em Material; viewer e terminal iniciavam com fundo/preenchimentos de erro fixos, e o terminal não atualizava as 16 cores após a troca. As duas janelas agora recebem a mesma paleta observada pelo `Backend`; o terminal redesenha as células existentes ao mudar o tema, e mensagens de erro usam superfície e texto do tema. `make build-gui` e os testes QML passaram; viewer e terminal carregaram sem erro de QML em modo offscreen. Falta validar a troca claro/escuro em uma sessão real, com as janelas abertas, e a escala de texto. A adaptação de `muted` para texto foi acrescentada na revisão de P1; cores semânticas ainda exigem avaliação.
+- [ ] **Completar a experiência do viewer.** Exibir conexão, desconexão, tentativa novamente e retorno ao gerenciador; tornar descobríveis a saída, atalhos e o efeito de fechar a janela.
+ - Aceite: falha de conexão oferece recuperação; fechar o viewer comunica que isso não equivale a desligar a Machine.
+- [ ] **Abrir ambientes em workspaces vazios do Hyprland.** Oferecer uma preferência de abertura entre workspace atual e workspace vazio, lembrando a escolha. Ao abrir um Desktop no modo workspace vazio, selecionar um workspace normal elegível no monitor de origem, abrir o viewer nele e levá-lo ao foco. Manter o Experience Center no workspace de origem. Aplicar a mesma opção ao terminal de Box, sem mover aplicações exportadas automaticamente.
+ - Política: definir vazio como ausência de janelas; considerar também os workspaces ainda não materializados dentro da faixa permitida pela configuração do usuário. Excluir workspaces especiais, reservados por regras pessoais e os visíveis em outro monitor. A seleção deve ser determinística e validada contra a versão instalada do Hyprland.
+ - Reabertura: se já existir um viewer do ambiente, focar sua janela e seu workspace atual, inclusive se o usuário a tiver movido; não abrir outra cópia nem consumir um novo workspace a cada clique. Identificar o ambiente de forma estável, pois o app id compartilhado `dev.omavm.viewer` sozinho não distingue duas Machines ou Boxes.
+ - Aceite: abrir dois ambientes ocupa dois workspaces elegíveis distintos sem deslocar janelas existentes; abrir novamente o primeiro retorna a ele. Validar workspace vazio existente, número disponível ainda não criado, aberturas próximas, movimento manual do viewer e múltiplos monitores. Revalidar o destino antes de posicionar a janela para evitar usar um workspace que acabou de ser ocupado.
+ - Recuperação: se não houver destino elegível ou a integração não estiver disponível, abrir no workspace atual com explicação. Não roubar foco se o usuário tiver mudado de contexto durante uma abertura demorada. Fechar o viewer não desliga o ambiente nem remove/move outras janelas; oferecer retorno ao gerenciador sem impor troca de workspace.
+ - Decisão de produto: validar se workspace vazio deve ser o padrão para Desktop; o terminal de Box pode continuar tiled no workspace atual. Tela cheia é uma preferência separada de posicionamento, sob responsabilidade do compositor.
+ - Decisão técnica — resolvida (2026-09-27): a API real (`hl` do Hyprland Lua do Omarchy, `/usr/share/hypr/stubs/hl.meta.lua`) foi validada contra uma sessão real antes de implementar, conforme exigia este item; ver `CLAUDE.md` → Omarchy Integration → "Runtime dispatch validado" para a política completa. `hyprctl dispatch` bruto com seletores tipo `class:...` continua quebrado nesse fork (confirmado), mas existe uma forma correta (`hyprctl dispatch 'hl.dsp.focus({...})'`, uma única expressão Lua) que já é o padrão usado pelo próprio Quickshell do Omarchy.
+ - Implementado parcialmente (2026-09-27), como preferência opt-in por ambiente: `EnvironmentSettings.OpenInEmptyWorkspace` (Core: `internal/core/environment.go`/`service.go`, aplica aos dois Kinds; CLI: `settings NAME --open-in-empty-workspace=true|false`; GUI: `SettingsDialog.qml`'s checkbox "Open in an empty workspace", visível para Box e Machine). Toda a lógica de Hyprland vive em `gui/backend.cpp`'s `placeInEmptyWorkspace()` (anonymous namespace), chamada de dentro de `Backend::open()` antes de lançar o viewer/terminal — nunca no Core/Go, preservando a regra de que essa política pertence à integração com o desktop. Reabertura: consulta `hl.get_windows({class="dev.omavm.viewer", title=" — OmaVM"})` (mesmo título que `qemu.Backend.Open`/`gui/backend.cpp`'s `--terminal` já usam) antes de escolher um workspace vazio, então identifica o ambiente de forma estável sem depender só do app id compartilhado. Vazio = `HL.Workspace.is_empty`, excluindo especiais e workspaces de outro monitor (via `hl.get_active_monitor()`), incluindo IDs ainda não materializados (busca 1–30). Indisponibilidade (sem Hyprland, sessão diferente, ou nenhum destino elegível) cai no comportamento atual (workspace corrente) com uma mensagem explicando — nunca falha silenciosa nem promessa de suporte que não existe.
+ - Lacunas conhecidas, deixadas como fallback honesto em vez de resolvidas por adivinhação (detalhado em `CLAUDE.md`): focar a janela específica (não só o workspace) não se mostrou confiável nos testes, então só o workspace é focado; workspaces "reservados por regras pessoais" não são detectáveis via a API disponível, então só são pulados se já estiverem ocupados; a "faixa configurada pelo usuário" não existe como conceito consultável no Hyprland, então a busca usa um limite fixo (30). Conflita com a regra Hyprland estática de fullscreen já documentada (`contrib/hypr/omavm-viewer.lua`) — as duas não foram desenhadas para compor, documentado no README/no próprio arquivo `.lua`.
+ - Evidência: mecanismo validado com chamadas reais e seguras (`hyprctl repl`/`hyprctl dispatch`) contra a sessão Hyprland real do host de desenvolvimento — criação/foco de workspace vazio confirmados (`hyprctl activeworkspace` mudou de fato), busca por janela existente confirmada com janelas reais (`foot`). `go build/vet/test` (suite inteira, incluindo `TestOpenInEmptyWorkspaceAppliesToBothKinds`) e `qmllint` limpos; `make build-gui` compila. Não testado através da GUI real clicando em Start/Open (evitado deliberadamente nesta sessão após dois incidentes anteriores de automação de input ao vivo — ver histórico) — a lógica foi validada isolando exatamente o script Lua que o C++ constrói, não através de um clique real na janela do app.
+ - Base: `contrib/hypr/omavm-viewer.lua`, `gui/backend.cpp` (`placeInEmptyWorkspace`, `Backend::open`), `gui/SettingsDialog.qml`, `internal/core/environment.go`, `internal/core/service.go`, `cmd/omavm/main.go`. A política pertence à integração com o desktop, sem acoplar o Core ao Hyprland.
+ - Atualização de 2026-09-29 (bug relatado pelo usuário: "o viewer não começa em tela cheia nem num workspace não usado"): o posicionamento só existia em `Backend::open()`, então uma Machine aberta pela entrada do launcher ou por `omavm open` nunca ia para um workspace vazio. Agora o **próprio viewer** posiciona a janela ao iniciar (`gui/main.cpp`, `placeViewer`, flag `--empty-workspace`), qualquer que seja o caminho; o Core só repassa a configuração (`qemu.viewerArgs`, entrada do launcher da Box). A Machine abre em tela cheia por padrão (`EnvironmentSettings.FullscreenDisabled`, opt-out), sem pedir quando há regra pessoal para o viewer. Regressões: `TestViewerIsToldWhereAndHowToOpen`, `TestBoxEntryCarriesTheWorkspaceSetting`, `TestFullscreenIsOnByDefaultAndMachineOnly`. **Não validado na sessão real** (trocaria o workspace e abriria uma janela em tela cheia na frente do usuário); a leitura dos workspaces pela API `hl` foi conferida ao vivo.
+- [ ] **Validar tela cheia, redimensionamento e escala.** Respeitar a política existente de janelas/workspaces do Hyprland, evitando comandos concorrentes de tela cheia. Distinguir ajuste visual da imagem e mudança real de resolução do guest.
+ - Aceite: foco e entrada permanecem corretos após redimensionar, alternar workspace e voltar ao gerenciador; testar janela tiled e regra opcional de tela cheia, incluindo terminal de Box. Nenhuma regra pessoal é aplicada automaticamente; recurso indisponível tem explicação, sem promessa de resolução dinâmica onde não há suporte.
+- [ ] **Tornar integração com o guest acionável.** Mostrar clipboard e pasta compartilhada com estado, pré-requisitos e instruções específicas para sistemas suportados; diferenciar não detectado de indisponível.
+ - Aceite: o usuário entende o que funciona e como habilitar o restante sem depender apenas de tooltip; encontra instruções de montagem da pasta e valida copiar/colar texto nos dois sentidos em um guest documentado. Mostrar por capacidade, quando verificável, "pronto", "precisa de componente no guest", "precisa reiniciar" ou "não verificado", com próximo passo concreto. Diferenciar preferência habilitada de funcionamento confirmado e agente QEMU de suporte a clipboard; preferir agentes/protocolos existentes e não apresentar status positivo sem uma verificação real da capacidade.
+- [ ] **Persistir preferências de integração bidirecional, opt-out.** Disponibilizar controles por ambiente para clipboard, transferência de arquivos e abertura de links/aplicações. O padrão permite host → guest e guest → host; permitir desativar cada capacidade e restringir uma direção quando o mecanismo suportar essa separação.
+ - Aceite: GUI e CLI consultam e alteram a mesma preferência persistida; reabrir viewer, reiniciar ambiente ou atualizar o registro não reativa uma capacidade explicitamente desabilitada. Ausência de preferência usa o padrão habilitado; mostrar separadamente configurado, disponível e efetivamente ativo.
+ - Aplicação: desligar impede novas trocas ou solicitações na capacidade/direção correspondente; documentar operações em andamento e eventual necessidade de reconexão/reinício. Não apresentar um controle direcional como efetivo quando o backend não consegue aplicá-lo; nesse caso oferecer desativação completa e explicar a limitação.
+ - Escopo: clipboard de texto já tem preferência por Machine; auditar e preservar seu comportamento. Transferência de arquivos e abertura de links/apps são evolução descrita em P3, com esta política de defaults definida. Em Boxes, inventariar os caminhos de integração do Distrobox antes de prometer bloqueio, pois compartilhar a home não equivale a um canal de transferência controlado pelo OmaVM.
+- [ ] **Aprimorar uso diário do terminal de Boxes.** Avaliar seleção, cópia/colagem, scrollback, escala de fonte e mensagens ao encerrar; implementar as lacunas prioritárias mantendo atalhos de aplicações de terminal.
+ - Aceite: validar shell, editor, pager e sessão encerrada com erro; permitir leitura do erro antes de fechar a janela.
+- [ ] **Completar exportação de aplicações de Boxes.** Mostrar carregamento, exportação em andamento, resultado e desfazer exportação; testar o lançamento pelo menu do Omarchy.
+ - Aceite: ícone e nome identificam a aplicação; exportar faz o atalho aparecer no launcher e abrir a aplicação da Box correta. Remover do menu retira o atalho e preserva a instalação no ambiente; falha permite nova tentativa sem perder a seleção.
+ - Jornada adicional: com a Box parada, clicar no aplicativo exportado deve iniciar o ambiente e abrir a aplicação sem terminal no host. Validar arquivo como argumento, caminhos com espaços/acentos, reabertura e erro de inicialização; identificar a Box quando duas exportam a mesma aplicação. Reutilizar a integração do Distrobox.
+- [ ] **Explicar ajustes automáticos e pendentes.** Mostrar quando mudanças exigem reinício e quando Travel Mode reduz recursos; diferenciar preferência configurada de valor efetivo.
+ - Aceite: salvar uma descrição não altera inadvertidamente a intenção de configuração de CPU; estados e defaults permanecem coerentes entre GUI e CLI.
+ - **"Diferenciar preferência configurada de valor efetivo" implementado (2026-09-27).** Descoberta útil ao investigar o bug abaixo: `backend.environments` (que alimenta `SettingsDialog.qml`) vem de `omavm list --json`, e `Service.List` retorna os ambientes **brutos** (`internal/core/service.go`, nunca resolvidos por `EffectiveSettings()`, ao contrário do retorno de `Settings()`/`Configure()`) — então `settings.cpus` no JSON de list já vem ausente (`omitempty`) quando CPUs nunca foi fixado, sem precisar de nenhuma mudança de API. `SettingsDialog.qml` ganhou `cpusPinned`/`memoryPinned` (checando isso) e uma legenda por campo: "Not pinned yet: adapts automatically, and Travel Mode may reduce it while on battery" vs "Pinned — won't change on its own" vs "Will be pinned to this value on save" (quando `cpusTouched`/`memoryTouched` nesta sessão do diálogo). `qmllint`/`make build-gui` limpos.
+ - **Bug real encontrado e corrigido (2026-09-27), exatamente o cenário do aceite.** `Service.Configure` (`internal/core/service.go`) montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10 só para exibição) e depois persistia essa cópia inteira incondicionalmente — então **qualquer** `Configure`, mesmo alterando só a descrição, gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido explicitamente fixados. Consequência real: `internal/backend/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0`; salvar qualquer coisa em Settings desligava essa redução automática permanentemente, na primeira vez, sem o usuário nunca ter tocado em CPU. A correção original nesta sessão (rastrear "touched" nos `SpinBox` da GUI para só enviar `--cpus`/`--memory-mib` quando o usuário realmente mexeu) foi necessária mas **não suficiente** — o bug real estava no Core, não na GUI, e afetava qualquer chamador (CLI direto incluído). Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto); o valor de retorno de `Configure` continua resolvido (`env.EffectiveSettings()` no fim, depois de persistir), então CLI/GUI continuam mostrando "2 CPUs" mesmo quando nada foi fixado.
+ - Evidência: reproduzido e corrigido com testes reais via CLI (`omavm create --kind machine` seguido de `omavm settings NOME --description "x"`, inspecionando o `environments.json` bruto diretamente — antes da correção: `cpus`/`memory_mib`/`snapshot_limit` apareciam gravados; depois: `settings` ficava só com `{"description":"x"}`, sem nenhum campo de hardware). Teste de regressão novo no Core, `TestConfigureUnrelatedFieldDoesNotPinHardwareDefaults` (`internal/core/service_test.go`) — confirmado que falha sem a correção (revertido manualmente pra provar) e passa com ela; também confirma que um pin explícito (`--cpus 4`) sobrevive a uma edição não relacionada posterior. `go test ./...` (suite inteira) e `make test` (inclui `make test-backend`, ver item de flickering acima) passam. Fix na GUI (rastreamento de "touched" em `SettingsDialog.qml`/`gui/backend.cpp,h`) mantido como complemento — evita reenviar `--cpus`/`--memory-mib` desnecessariamente mesmo com o Core já protegido, e documenta a intenção do usuário de forma mais explícita na camada de UI.
+- [ ] **Ajustar o Experience Center ao uso real.** Validar identificação da distribuição, previews, nomes longos e listas com 1, 10 e 30 ambientes. Adicionar busca simples se os testes mostrarem dificuldade de localização.
+ - Aceite: o usuário localiza o ambiente por nome sem depender de miniaturas; foco e posição da lista não se perdem ao atualizar.
+
+## Qualidade da integração com QEMU — frente transversal
+
+A confiabilidade do backend sustenta a experiência da Machine. Os itens abaixo são eixos de investigação, não defeitos confirmados nem autorização para ampliar o escopo funcional. Primeiro auditar a implementação e os testes existentes; para cada lacuna, registrar caminho de código, reprodução, impacto e prioridade. Encerrar como verificado o que já estiver coberto, sem reimplementar capacidades maduras do QEMU.
+
+Base da revisão: `internal/backend/qemu/`, contratos em `internal/core/`, CLI em `cmd/omavm/` e integração com o viewer em `gui/`. Manter controle de infraestrutura no backend e operações de gerenciamento acessíveis pelo Core/CLI. Relacionar os achados às tarefas de P0–P2, evitando abrir tarefas duplicadas para o mesmo problema.
+
+- [ ] **Auditar ciclo de vida e reconciliação de estado.** Conferir consistência entre processo QEMU, registro persistido e estado informado ao CLI/GUI durante start, pause, resume, shutdown, restart e encerramento inesperado. Revisar identificação do processo, arquivos de estado obsoletos e operações concorrentes. Achado e corrigido em 2026-09-29: um `qemu.pid`/`virtiofs.pid` deixado por crash ou reboot, com o pid já reaproveitado por outro processo, fazia a Machine parecer rodando (Start virava no-op) e o Force Stop mandava SIGTERM a esse processo; agora o pid só vale se a linha de comando dele tiver o pidfile/socket da Machine (`processHasArg`, teste `TestStalePidfileOfAnotherProcessIsNotRunning`). Também em 2026-09-28: Force Stop passou a esperar o QEMU sair, porque Delete logo depois falhava.
+ - Aceite: reproduzir falha de inicialização, saída inesperada, reabertura do gerenciador e ações concorrentes por CLI/GUI; não sinalizar sucesso antes da condição esperada nem agir sobre processo alheio. Falha de desligamento preserva a Machine e nunca vira Force Stop automaticamente. Relacionar à atualização de estados de P1.
+- [ ] **Auditar comunicação QMP.** Verificar negociação, associação entre pedidos e respostas, eventos intercalados, erros, desconexão, cancelamento e limites de espera. Avaliar onde eventos ajudam a acompanhar transições dentro do ciclo de vida atual, sem presumir conexão permanente ou criar daemon só para isso.
+ - Aceite: testes focados cobrem resposta de erro, ausência de resposta, conexão interrompida e evento intercalado; chamadas terminam com resultado ou erro identificável. Não repetir automaticamente uma operação mutável cujo resultado ficou desconhecido: reconciliar o estado antes de tentar novamente.
+- [ ] **Antecipar falhas de inicialização.** Revisar verificações de acesso ao KVM, executáveis e capacidades necessárias, mídia, permissões, memória/espaço e conflitos de discos ou sockets. Distinguir verificações possíveis antes de iniciar de falhas que só o QEMU pode confirmar.
+ - Aceite: dependência ausente, ISO inválida/inacessível e recurso ocupado produzem diagnóstico contextual, sem deixar o ambiente falsamente ativo. Limpar apenas recursos criados pela tentativa malsucedida e preservar dados anteriores. Alimentar a tarefa de pré-requisitos de P1 com as mesmas regras do backend.
+ - Duas lacunas pontuais da auditoria anterior corrigidas em 2026-09-27: (1) `qemu-img`/`qemu-system-x86_64` ausentes agora produzem o mesmo tipo de dica acionável que `virtiofsd` já tinha (`qemuBinaryPath`/`runQEMU`/`qemuErr` em `internal/backend/qemu/qemu.go`), em vez do erro cru do Go; (2) `Start()` agora remove também `qmp.sock` obsoleto junto com VNC/QGA, fechando a assimetria de limpeza de sockets identificada. Teste de regressão: `TestMissingBinaryDiagnostic`. Ainda faltam: checagem antecipada de `/dev/kvm`, memória/espaço em disco e conflito de sockets em uso por outro processo (o QEMU já recusa esses casos com stderr repassado, mas sem antecipação).
+- [ ] **Revisar discos, snapshots e falhas parciais.** Mapear a ordem das alterações no disco, no histórico e no registro, incluindo retenção, restauração e exclusão. Verificar restrições de uso de imagens em execução e espaço disponível, sem tratar uma checagem inicial como garantia contra esgotamento posterior.
+ - Aceite: em ambientes de teste descartáveis, exercitar falha de comando, interrupção entre etapas e espaço insuficiente; registrar estado final, pontos de recuperação preservados e caminho de recuperação. Nenhum sucesso aparente ou descarte silencioso de histórico válido após falha. Vincular as confirmações e avisos às tarefas de snapshots de P0.
+ - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código: `savevm`/`loadvm`/`delvm` (Machine rodando, via `human-monitor-command`) podiam reportar sucesso mesmo quando a operação HMP subjacente falhava.** `qmp.go`'s `human-monitor-command` é um passthrough para comandos legados do monitor humano do QEMU; QEMU reporta falhas desses comandos específicos (tag desconhecida, snapshot corrompido etc.) como texto simples dentro do campo `"return"` da resposta QMP, não como um erro de protocolo QMP (`"error"`). `internal/backend/qemu/qemu.go` só checava o erro de protocolo e descartava o texto de retorno (`_, err := qmpHumanMonitorCommand(...)`) nos três call sites — exatamente o cenário do aceite acima ("nenhum sucesso aparente... após falha"). Pior em `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; se o `loadvm` falhasse silenciosamente dessa forma, o código seguia direto para `cont`, retomando a Machine no estado anterior ao restore (nada foi restaurado) enquanto CLI/GUI reportavam "Go To" como bem-sucedido.
+ - Corrigido checando o texto de retorno (`strings.TrimSpace`) além do erro de protocolo nos três casos; texto não-vazio agora vira erro explícito. Em `GoToSnapshot` especificamente, o `cont` de resume agora é sempre tentado mesmo quando o `loadvm` falhou (a Machine já estava pausada por causa do `stop` anterior; deixá-la travada em pausa por causa de uma falha de restore seria um bug de lifecycle novo e distinto, não uma correção).
+ - Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/qemu/lifecycle_test.go`), com um servidor QMP fake retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` — confirmado que **falha** sem a correção (`GoToSnapshot` retornava `nil`) e passa com ela, incluindo a checagem de que `cont` ainda é enviado. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos.
+ - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código, exatamente o cenário do aceite ("descarte silencioso de histórico válido após falha").** `Service.CreateSnapshot` (`internal/core/service.go`) criava o novo snapshot no backend, tentava descartar os mais antigos por causa do limite de retenção, e só persistia tudo — o novo snapshot incluído — num único `store.Save` no final. Se o backend já tivesse criado o novo snapshot com sucesso mas uma remoção de um antigo falhasse no meio (disco cheio, QMP caindo, etc.), a função retornava erro **sem nunca salvar** — perdendo o rastro do snapshot novo (que já existe de verdade no backend, mas o Core não sabe mais dele — um "snapshot fantasma", invisível em `snapshot list`, sem caminho de volta a não ser editando o arquivo de estado à mão). Pior: se ALGUM descarte antigo já tivesse sido bem-sucedido antes da falha, o registro persistido ficava referenciando um snapshot que o backend já apagou.
+ - Corrigido persistindo incrementalmente: salva o novo snapshot imediatamente após o backend confirmar a criação, antes de mexer em retenção; salva de novo após cada descarte bem-sucedido dentro do loop de retenção. Uma falha no meio agora só afeta o passo que realmente falhou — nunca desfaz o que já era real. Em caso de falha na retenção, a função agora retorna o snapshot recém-criado (não mais um valor zerado) junto com o erro, já que ele genuinamente foi criado.
+ - Evidência: teste de regressão novo `TestSnapshotCreatedButRetentionDiscardFailsStillPersistsNewSnapshot` (`internal/core/service_test.go`), usando o `removeErr` já existente em `fakeSnapshotBackend` pra simular a falha — verificado que **falha** sem a correção (revertida manualmente, restaurada depois) e passa com ela. `go build/vet/test` (suite inteira), `make build-gui`, `make test-backend` limpos.
+ - **Achado relacionado, mesma auditoria (2026-09-27): `Service.Create` também podia deixar um recurso órfão.** Se `backend.Create` tem sucesso (container/disco de VM criados de verdade) mas o `store.Save` seguinte falha (disco cheio, permissão, etc.), o recurso ficava criado no backend sem nenhum registro apontando pra ele — invisível pro CLI/GUI, sem `remove` possível a não ser manualmente. Corrigido com rollback best-effort: se o `Save` falha depois do `backend.Create` ter sido bem-sucedido, `Create` agora chama `backend.Remove` antes de retornar o erro, deixando o estado como se a criação nunca tivesse acontecido (a menos que o próprio rollback também falhe, caso em que o erro menciona isso explicitamente). Teste de regressão: `TestCreateRollsBackBackendWhenRegistrySaveFails` (novo campo `saveErr` em `memStore`, o fake `Store` dos testes) — confirmado que falha sem a correção e passa com ela.
+ - Atualização de 2026-09-29: o disco de toda Machine é um qcow2 esparso de 1 TiB, ampliado no Start quando menor (inclusive depois de voltar a uma snapshot antiga, que devolve o tamanho de quando foi tirada — verificado no QEMU 11.1); espaço esgotado no host aparece como `paused` com o motivo e sai com Resume, em vez de "Needs attention". Snapshots com a Machine ligada congelam o filesystem do guest pelo QGA quando ele responde e ficam marcadas `crash_consistent` quando não (só com agente falso: `TestSnapshotOfRunningMachineFreezesTheGuest`, `TestGuestSyncSkipsStaleReplies`). Uma ISO removida não impede mais o boot pelo disco (`TestStartWithoutTheInstallationMediaBootsTheDisk`). Ainda falta exercitar espaço insuficiente de verdade.
+- [ ] **Verificar capacidades reais do guest.** Separar dispositivo configurado, canal disponível, agente conectado e função validada para clipboard, pasta compartilhada, áudio e informações do guest. Reutilizar agentes e protocolos existentes.
+ - Aceite: registrar matriz por guest, drivers e agentes testados; ausência de agente e função não verificada não aparecem como suporte confirmado. QGA conectado não comprova clipboard. Usar os resultados nas instruções e estados de integração de P2.
+- [ ] **Validar display e entrada durante transições.** Exercitar boot, mudança de resolução, resize contínuo, escala, teclado, mouse, desconexão e reabertura do viewer. Distinguir solicitação de resolução enviada da resolução efetivamente aplicada.
+ - Aceite: ponteiro corresponde à imagem exibida, entrada permanece utilizável e falha de conexão oferece recuperação; validar textos acentuados e combinações de teclas do host/guest. Separar testes de protocolo dos testes com desktop guest real e relacionar os resultados às tarefas do viewer de P2.
+- [ ] **Medir recursos e desempenho antes de ajustar defaults.** Registrar tempo até QMP disponível, abertura do viewer e guest utilizável separadamente; medir CPU/memória em repouso e sob uma carga reproduzível, além de I/O quando houver gargalo demonstrado. Conferir valores configurados e efetivos, incluindo Travel Mode.
+ - Aceite: baseline identifica hardware, versões, guest, carga e repetições; qualquer ajuste de CPU, memória, aceleração ou disco apresenta comparação antes/depois e impacto em compatibilidade e integridade dos dados. Não reduzir garantias de escrita para melhorar números nem introduzir tuning sem ganho medido.
+- [ ] **Melhorar diagnóstico de falhas do QEMU.** Conferir captura de erros de inicialização e execução, contexto da operação, ambiente e horário nos logs. Expor resumo compreensível e detalhes copiáveis sem depender de o usuário localizar processos ou sockets manualmente.
+ - Aceite: uma falha reproduzida pode ser relacionada ao ambiente e à operação tanto pelo CLI quanto pela GUI, com causa técnica disponível e próximo passo quando conhecido. Não registrar conteúdo de clipboard nem arquivos compartilhados; erros permanecem consultáveis conforme P0.
+
+Priorizar achados de perda de dados ou lifecycle incorreto em P0; inicialização e recuperação necessárias ao uso básico em P1; integração com guest e melhorias de desempenho comprovadas em P2. Recursos novos continuam sujeitos à descoberta e ao escopo de P3. Definir limiares de desempenho após medir a baseline, sem metas arbitrárias.
+
+### Achados anteriores
+
+A [auditoria de código de 2026-09-27](review-history.md#achados-da-auditoria-2026-09-27-leitura-de-código--não-reproduzido-em-host-real) registrou hipóteses de concorrência, tratamento de sockets e diagnóstico de dependências, além de lacunas de testes QMP. Nenhuma reprodução em guest real foi registrada nessa auditoria. Usar esses achados como ponto de partida, revalidando o código antes de corrigir.
+
+## P3 — Descoberta antes de ampliar o escopo
+
+O [catálogo de propostas](discovery.md) reúne instalação assistida, Blend Mode, arquivos e links bidirecionais, storage, networking, hardware, lifecycle, desempenho e recuperação. Cada proposta mantém seus critérios de aceite e depende de caso de uso, suporte do backend/guest e decisão de escopo antes da implementação.
+
+### Triagem das ideias de 2026-09-28
+
+Esta triagem liga as propostas de [docs/ideias](ideias/README.md) às jornadas acima. **Próxima** significa candidata a planejamento após revalidar a lacuna e a jornada correspondente, na prioridade indicada; **condicional** exige primeiro o caso de uso e a decisão de escopo de P3; **adiar** não justifica trabalho agora. Os arquivos vinculados guardam o esboço e os riscos; esta tabela não duplica suas especificações.
+
+| Ideia | Encaminhamento | Evidência ou decisão necessária |
+|---|---|---|
+| [Copiar do terminal da Box](ideias/terminal-copiar.md) | **Próxima — P0/P2** | Reproduzir o efeito de Super+C e concluir seleção/cópia, inclusive no scrollback; avaliar OSC 52 de escrita separadamente. |
+| [Progresso ao criar Box](ideias/progresso-ao-criar-box.md) | **Próxima — P1** | Medir espera real e duração do lock; separar preparação/download de registro sem permitir criação duplicada ou progresso fictício. |
+| [Espaço em disco do host](ideias/disco-do-host.md) | **Próxima — P1**, só diagnóstico | Mostrar causa e recuperação de `io-error` e alertar sobre pouco espaço; não prometer que uma checagem inicial impede esgotamento posterior. |
+| [Acessibilidade](ideias/acessibilidade.md) | **Próxima — P1** | Completar nomes, estados e ordem de foco; conferir com teclado e leitor de tela numa sessão real. |
+| [Ambientes no launcher](ideias/ambientes-no-launcher.md) | **Próxima — P2** | Validar uma entrada `.desktop` por ambiente, abertura da Box sem TTY e limpeza de atalhos ao remover/renomear. |
+| [Cor no terminal da Box](ideias/terminal-ptyxis.md) | **Próxima — P2**, parte simples | Validar se a identificação visual ajuda a reconhecer a Box; aviso ao fechar processo e nova sessão no mesmo diretório ficam condicionais à detecção confiável do contexto. |
+| [Cor no Nautilus](ideias/cor-no-nautilus.md) | **Próxima — P2**, integração opcional | Confirmar que o metadado GVFS aparece no Nautilus real sem transformar falha de `gio` em falha do ambiente. |
+| [CLI para agentes](ideias/cli-para-agentes.md) | **Próxima — contrato da CLI** | Definir e documentar códigos/JSON de erro antes da mudança; validar consumidores existentes, inclusive a GUI. |
+| [Machine descartável](ideias/machine-descartavel.md) | **Próxima jornada de produto — P3** | Provar iniciar, usar e encerrar uma sessão sem persistência; distinguir isso de criar um ambiente novo e bloquear snapshots que sumiriam no overlay. |
+| [SSH por vsock](ideias/vsock-ssh.md) | **Condicional — P3** | Validar guest systemd, autenticação e alcance por processos do host/Boxes; manter dispositivo opt-in e expor indisponibilidade em outros guests. |
+| [Arquivar e exportar/importar](ideias/arquivar-e-exportar.md) | **Condicional — P3** | Demonstrar necessidade de portabilidade/backup independente; decidir manifesto, snapshots, firmware, espaço temporário e recuperação de falha antes do formato. |
+| [Redimensionar e compactar disco](ideias/disco-do-host.md) | **Condicional — P3** | Separar crescimento de disco, expansão no guest e compactação; testar espaço temporário, snapshots e restauração antes de reescrever imagens. |
+| [Limites e Travel Mode para Boxes](ideias/box-limites-e-travel-mode.md) | **Condicional — P3** | Medir ganho na bateria e validar cgroups/`podman update` sem perder estado nem produzir OOM surpreendente. |
+| [Pasta compartilhada automática](ideias/pasta-compartilhada-automatica.md) | **Condicional — P3** | Validar um guest Linux suportado e o ajudante opt-in; manter instrução de montagem manual para os demais. |
+| [Windows 11 com TPM/Secure Boot](ideias/windows11-tpm-secureboot.md) | **Condicional — P3** | Validar instalação concreta; definir firmware/NVRAM e estado do TPM por Machine nova, sem alterar o boot das existentes. |
+| [Ações de Box e Distrobox v2](ideias/boxes-distrobox.md) | **Condicional — P3** | Validar demanda por Clone/Upgrade/uso; testar exportação de apps no v2 quando houver versão estável ou usuário do RC. |
+| [Preview e damage no display D-Bus](ideias/display-dbus.md) | **Condicional — P2/P3** | Reproduzir preview ausente em guest GL e medir custo do redraw antes de ampliar o viewer; registrar limites atuais de USB/clipboard de imagens. |
+| [Logs no journal](ideias/logs-no-journal.md) | **Condicional — manutenção** | Mostrar ganho concreto de diagnóstico; definir migração do destino documentado e fallback antes de trocar o log atual. |
+| [GPU native context](ideias/gpu-native-context.md) | **Adiar — compatibilidade** | Testar em hardware e guest suportados e medir ganho sobre Venus; não inferir suporte no host Intel atual. |
+| [Terminal sobre libvterm](ideias/terminal-libvterm.md) | **Adiar — decisão de arquitetura** | Reavaliar se lacunas medidas do emulador atual superarem custo da dependência e migração; não trocar como efeito colateral de bug. |
+| [Modelo C++ de ambientes](ideias/modelo-de-ambientes-em-cpp.md) | **Adiar — otimização** | Só considerar se a lista QML atual ficar lenta ou difícil de manter com quantidade real de ambientes. |
+| [Catálogo de imagens](ideias/catalogo-de-imagens.md) | **Adiar — conflito de escopo** | Manter ISO local como fluxo completo; avaliar fonte externa opcional somente se usuários demonstrarem a necessidade, sem catálogo próprio amplo. |
+
+A ideia de **disco do host** é deliberadamente dividida em duas linhas: explicar `io-error` é uma melhoria de recuperação do uso básico; redimensionar e compactar alteram imagens e exigem descoberta de segurança de dados. Na proposta do **Ptyxis**, a cor de identificação pode ser avaliada separadamente do aviso ao fechar e da nova sessão no mesmo diretório, que dependem de detectar o contexto dentro da Box.
+
+### Aplicativos de Machines integrados ao Omarchy — Blend Mode
+
+Detalhamento da direção discutida em 2026-09-27. O Linux oferece a base de virtualização com KVM, mas apresentar aplicações do guest como janelas individuais exige uma ponte gráfica e integração de sessão. O viewer atual apresenta o desktop inteiro; exportação de aplicações de Boxes não comprova suporte equivalente em Machines. Uma experiência completa deve ser definida por combinações de guest, aplicações e versões validadas, sem prometer compatibilidade universal ou paridade com o Parallels.
+
+Esta seção detalha a proposta de Blend Mode do catálogo; não constitui uma segunda fila de implementação. Reutilizar as tarefas de P1 para instalação/recuperação, P2 para launcher, preferências e integração cotidiana, e a frente QEMU para lifecycle e capacidades reais do guest. Manter o desktop completo acessível como alternativa.
+
+- [ ] **Definir a primeira combinação suportada.** Escolher uma Machine Linux, uma aplicação GTK e uma Qt, com versões e pré-requisitos registrados. Separar suporte a aplicações Wayland e X11; registrar uso de XWayland quando necessário.
+ - Aceite: matriz inicial identifica host/Hyprland, guest, aplicações, transporte e componentes instalados, distinguindo confirmado, falhou e não testado. A disponibilidade de KVM ou de um agente não comprova integração gráfica.
+- [ ] **Provar janelas individuais antes de escolher a infraestrutura.** Experimentar ferramentas existentes, como Xpra em modo seamless, para apresentar aplicações da Machine no Hyprland. Avaliar suporte Wayland/X11 na versão efetivamente testada; nenhuma ferramenta fica escolhida apenas pela documentação.
+ - Aceite: as duas aplicações aparecem em janelas separadas, sem exigir exibir o desktop do guest; títulos, identificação do ambiente, foco, teclado, mouse, menus e diálogos funcionam. Validar janelas filhas, redimensionamento, escala, acentos, atalhos, troca de workspace e dois monitores. Respeitar regras pessoais do compositor e não duplicar indicadores de sistema do host.
+- [ ] **Preparar o guest e estabelecer um canal de sessão autenticado.** Identificar usuário, dependências, instalação/configuração necessária e como detectar que a sessão está pronta. Reutilizar protocolos e componentes existentes; executar aplicações como usuário normal do guest.
+ - Aceite: distinguir Machine ligada, canal conectado e sessão capaz de abrir uma aplicação; falha de autenticação, dependência ausente e timeout têm diagnóstico e recuperação. Documentar credenciais e permissões necessárias sem expô-las em logs. Agente próprio ou daemon só entra após registrar uma função concreta que as ferramentas avaliadas não resolvam, conforme `CLAUDE.md`.
+- [ ] **Descobrir e exportar aplicações das Machines.** Obter identificadores, nomes e ícones do guest e permitir exportação seletiva para o launcher, com gerenciamento pelo Core/CLI e GUI.
+ - Aceite: atalhos distinguem ambientes com a mesma aplicação; remover do menu preserva a instalação no guest. Tratar aplicação desinstalada, ambiente removido e atualização de metadados, sem deixar atalhos apontando silenciosamente para outro ambiente.
+- [ ] **Completar abertura e recuperação da sessão pelo launcher.** Clicar numa aplicação deve iniciar a Machine parada, aguardar o canal e a sessão do usuário e abrir a janela correspondente. Mostrar progresso real e falhas recuperáveis.
+ - Aceite: definir o comportamento de cliques repetidos e múltiplas aplicações sem iniciar Machines duplicadas. Exercitar desconexão, reconexão, encerramento inesperado e reabertura; documentar se processos sobrevivem à desconexão. Fechar uma aplicação não desliga a Machine nem encerra outras aplicações; não prometer recuperação de trabalho não salvo após falha do guest.
+- [ ] **Integrar arquivos e abertura por aplicação.** Completar as propostas de transferência e abertura bidirecional do catálogo: configurar pasta compartilhada de forma assistida, mapear caminhos host/guest e encaminhar arquivos ao aplicativo escolhido. Quando não houver caminho compartilhado, usar transferência suportada com destino e retorno definidos.
+ - Aceite: abrir, editar e salvar um arquivo pelo aplicativo da Machine produz resultado acessível no host. Testar espaços/acentos, permissões, arquivo ausente, sobrescrita e falha de transferência; explicitar se a edição afeta o original ou uma cópia. Validar arrastar/soltar separadamente de pasta compartilhada e respeitar as preferências de P2.
+- [ ] **Completar as integrações da sessão por capacidade.** Reutilizar a matriz e os controles de P2 para clipboard, áudio, arquivos e abertura de links; avaliar encaminhamento de notificações e clipboard de imagens/arquivos como capacidades adicionais, sem inferir suporte a partir de texto ou áudio já configurado no QEMU.
+ - Aceite: validar cada direção aplicável, pré-requisitos e desativação persistente por ambiente. Links abrem no destino escolhido sem ciclos; notificações identificam ambiente/aplicação e não duplicam indicadores de sistema. Áudio funciona na sessão de aplicativos integrada, não apenas no viewer. Indicar claramente capacidades indisponíveis ou ainda não verificadas.
+- [ ] **Investigar Windows após validar o primeiro fluxo Linux.** Avaliar RemoteApp com FreeRDP, usando WinApps como referência de descoberta de aplicações, atalhos e apresentação das janelas. Registrar requisitos da edição/configuração do Windows, autenticação e componentes do host; não assumir suporte ao Hyprland por haver suporte documentado a outros desktops.
+ - Aceite: reproduzir a jornada do launcher com uma aplicação Windows escolhida, incluindo arquivo, clipboard, diálogos e reabertura. Registrar diferenças em relação ao Linux e decidir escopo com evidência antes de integrar um novo caminho ao produto.
+
+**Primeiro marco verificável:** com uma Machine Linux inicialmente desligada, abrir uma aplicação GTK e uma Qt pelo launcher, editar e salvar um arquivo compartilhado, copiar texto nos dois sentidos, fechar e reabrir as aplicações. Exercitar também uma falha de conexão e sua recuperação. Registrar versões, passos, resultados e limitações; medir tempo até a janela utilizável e recursos da sessão antes de otimizar. Só ampliar a matriz após demonstrar essa jornada.
+
+Referências para investigação, não comprovação de compatibilidade do OmaVM: [KVM](https://docs.kernel.org/virt/kvm/index.html), [Xpra seamless](https://github.com/Xpra-org/xpra/blob/master/docs/Usage/Seamless.md), [FreeRDP](https://www.freerdp.com/) e [WinApps](https://github.com/winapps-org/winapps).
+
+## Validação e critério de conclusão
+
+Marcar cada tarefa somente após registrar o comportamento entregue e a evidência relevante. Para mudanças de lógica, adicionar testes de regressão focados; para layout, capturas e teste interativo são necessários. Testes existentes do Core não comprovam usabilidade da GUI.
+
+- [ ] Registrar uma linha de base das telas atuais: lista vazia/preenchida, criação, configurações, snapshots, aplicações, viewer e terminal.
+- [ ] Validar temas claro/escuro, as três dimensões de janela e escalas definidas em P1, incluindo nomes e mensagens longos.
+- [ ] Exercitar dependência ausente, mídia inválida, falha de operação, clique repetido, troca de ambiente durante carregamento e falha de conexão do viewer.
+- [ ] Validar a jornada completa de uma Box a partir do launcher: criar → abrir terminal → acessar um arquivo da home → exportar e abrir uma aplicação pelo menu → remover o atalho → parar e reabrir. Verificar configurações persistidas e recuperação de uma falha compreensível.
+- [ ] Validar a jornada completa de uma Machine a partir do launcher: criar → instalar → desligar → desconectar ISO → iniciar pelo disco → acessar pasta compartilhada e testar clipboard/áudio em guest suportado → fechar viewer → reabrir → desligar. Confirmar que fechar viewer não desliga a Machine.
+- [ ] Registrar versão do OmaVM, Omarchy, Hyprland e shell, tema, escala, dependências e guest/agentes de cada validação de integração. Separar resultado confirmado, falha e recurso não testado; não inferir suporte a outros guests.
+- [ ] Validar alocação de workspaces com dois ambientes, reabertura, fechamento, movimento manual de janelas, nenhum destino elegível e dois monitores; registrar a política escolhida e confirmar que janelas alheias não são movidas.
+- [ ] Validar launcher, widget e notificações com a janela principal sem foco, incluindo retorno ao erro persistente no app. Confirmar que instalar o widget não o habilita e que as regras pessoais de workspace permanecem sob controle do usuário.
+- [ ] Validar snapshots com restauração confirmada, cancelada, falha e limite de retenção atingido.
+- [ ] Validar clipboard, arquivos e abertura de links/apps nos dois sentidos nas combinações suportadas; testar defaults, desativação por capacidade/direção, persistência após reinício e ausência de suporte. Confirmar que abrir links/arquivos não contorna uma preferência desativada.
+- [ ] Registrar os achados da auditoria QEMU e executar os cenários de falha em Machines e discos descartáveis, documentando versões de QEMU/KVM, guest, comandos de reprodução e estado final. Manter testes de unidade independentes de QEMU/KVM; identificar separadamente testes de integração e validações interativas.
+- [ ] Fazer uma rodada formativa com pelo menos três pessoas sem familiaridade com a implementação: escolher o tipo, criar, chegar ao primeiro terminal/instalador, configurar, concluir o ciclo da ISO e recuperar de um erro sem terminal no host. Registrar conclusão, tempo até o primeiro uso, passos, pedidos de ajuda e confusões; usar os resultados para repriorizar, sem tratá-los como prova estatística.
+- [ ] Atualizar capturas e documentação para refletir a experiência realmente entregue e suas limitações.
+
+## Ordem de entrega
+
+1. **Confiabilidade:** reproduzir as hipóteses de concorrência de P0, corrigir falhas confirmadas e validar os fluxos de recuperação já implementados. Priorizar achados de lifecycle e proteção de dados da auditoria QEMU.
+2. **Uso básico completo:** corrigir rolagem/reflow e concluir as jornadas de P1, incluindo teclado, instalação e reabertura.
+3. **Integração cotidiana:** concluir P2 com evidências das jornadas no Omarchy, do launcher ao trabalho dentro do ambiente e de volta ao gerenciador, incluindo capacidades do guest validadas e medições da integração QEMU. Usar a triagem acima para escolher lacunas concretas de terminal, launcher e acessibilidade.
+4. **Expansão:** usar os resultados e a rodada com usuários para decidir quais hipóteses de P3 justificam implementação. Avaliar primeiro a jornada descartável e programática; portabilidade, vsock e suporte a novos guests entram conforme demanda e validação. Para Blend Mode, demonstrar primeiro a jornada Linux com GTK/Qt acima; depois decidir a expansão para Windows e outras combinações, mantendo os critérios de integração e recuperação.
+
+A aproximação à experiência pretendida deve ser demonstrada por essas jornadas concluídas e recuperáveis, além das capturas da interface.
diff --git a/docs/discovery.md b/docs/discovery.md
new file mode 100644
index 0000000..d65624e
--- /dev/null
+++ b/docs/discovery.md
@@ -0,0 +1,79 @@
+# Propostas para descoberta
+
+Catálogo separado do trabalho ativo em [TODO.md](TODO.md). Preserva as propostas e critérios registrados em 2026-09-27; não autoriza implementação nem amplia o escopo de [CLAUDE.md](../CLAUDE.md).
+
+## P3 — Descoberta antes de ampliar o escopo
+
+Estes itens são hipóteses de evolução. Cada um exige um caso de uso demonstrado, análise das capacidades existentes e decisão registrada antes de virar implementação.
+
+- [ ] **Instalação mais assistida:** avaliar catálogo pequeno de imagens e download verificável, com origem, tamanho, licença e recuperação de falhas; manter ISO local como caminho completo.
+- [ ] **Blend Mode para Machines:** demonstrar um fluxo real de aplicação integrada antes de definir infraestrutura. A base de exportação das Boxes não comprova viabilidade para Machines; evitar duplicar indicadores de sistema do host.
+- [ ] **Transferência de arquivos e arrastar/soltar:** escolher uma combinação host/guest suportada, testar permissões e falhas e preferir capacidades existentes a um protocolo próprio.
+- [ ] **Clone e recuperação mais guiada:** validar demanda e capacidades do backend; explicar consumo de disco e dependências antes de oferecer modalidades de clone.
+- [ ] **Organização de grandes listas:** validar necessidade de favoritos, grupos e reordenação; quando implementados, persistir o comportamento de verdade.
+- [ ] **Integrações adicionais:** avaliar áudio, dispositivos e múltiplos monitores por jornada concreta, deixando explícita a matriz de suporte. Não assumir paridade com o Parallels por adotar sua referência de UX.
+
+### Catálogo de capacidades de virtualização a avaliar
+
+Este catálogo incorpora a lista de evolução proposta pelo usuário. Antes de implementar, inventariar o que já está configurado no backend, o que está exposto no Core/CLI e o que foi validado em guest real. “Não exposto na GUI” não significa “ausente no QEMU”. Os critérios abaixo orientam a descoberta e a futura entrega; não prometem todos os recursos nem alteram automaticamente o escopo de `CLAUDE.md`.
+
+Cada proposta deve registrar caso de uso, suporte do backend/guest, necessidade de privilégio, comportamento com a Machine ligada/desligada, recuperação de falhas e decisão de escopo. Começar com operações offline quando suficientes; hotplug exige necessidade demonstrada. Networking avançado e guest agent completo continuam exigindo revisão explícita das diretrizes antes de implementação.
+
+#### Storage e portabilidade de imagens
+
+- [ ] **Discos adicionais:** avaliar criar, anexar, listar e desanexar discos com identidade estável, distinguindo disco de sistema e dados. Aceite: desanexar não apaga o arquivo; exclusão é explícita; uma imagem em uso não é anexada para escrita concorrente indevida.
+- [ ] **Resize de disco:** começar pelo crescimento do disco virtual, com estado permitido e limites claros. Aceite: diferenciar capacidade do disco de partição/filesystem no guest e orientar a expansão interna; redução de tamanho fica fora do fluxo inicial até haver procedimento seguro validado.
+- [ ] **Thin provisioning e descarte:** inventariar formato e alocação usados; avaliar indicação de capacidade virtual versus espaço realmente ocupado e recuperação por discard/TRIM. Aceite: medir antes/depois em guest suportado e explicar risco de o host ficar sem espaço; não apresentar capacidade virtual como espaço reservado.
+- [ ] **Backing chains:** descobrir e validar dependências antes de mover, excluir ou exportar imagens. Aceite: operação não quebra um descendente; base ausente ou alterada gera diagnóstico; alterações de cadeia exigem plano de recuperação e estado de execução compatível.
+- [ ] **Snapshots internos versus externos:** documentar a estratégia atual e avaliar alternativas por restauração, portabilidade e custo. Aceite: distinguir snapshot de disco de captura de memória, consistência com Machine ligada/desligada e relação com backing chains; evitar expor duas modalidades sem caso de uso. Complementa a auditoria e as confirmações de snapshots, sem duplicá-las.
+- [ ] **Import/export de imagens:** definir formatos e configuração mínima suportados, incluindo discos existentes além de ISOs de instalação. Aceite: origem preservada, conversão com espaço estimado e falha recuperável; exportação identifica dependências ou gera imagem independente; importar o resultado em um novo ambiente comprova o fluxo.
+
+#### Networking
+
+- [ ] **NAT simples:** inventariar o modo atual e validar saída de rede e resolução de nomes em guests suportados. Aceite: a experiência básica funciona sem configuração manual de bridge e a UI explica o alcance da conectividade.
+- [ ] **Port forwarding:** avaliar regras por Machine com protocolo, porta do host, destino e endereço de escuta explícitos. Aceite: detectar conflito de portas, remover regras corretamente e usar loopback como padrão para serviços locais; exposição à LAN exige escolha visível.
+- [ ] **Bridge:** demonstrar um caso de acesso direto pela LAN, descobrir bridges existentes e documentar restrições do host. Aceite: permissões e mudanças são explícitas e reversíveis; não alterar a rede ativa do host silenciosamente.
+- [ ] **Redes privadas entre Machines:** definir isolamento, endereçamento e eventual saída para a internet. Aceite: duas Machines na mesma rede se comunicam e uma fora dela não recebe conectividade indevida; criação/remoção não deixa recursos órfãos.
+- [ ] **Perfis de rede:** avaliar apenas após os modos anteriores terem uso demonstrado. Preferir intenções como “internet”, “somente entre ambientes” e “rede local”; evitar um editor genérico de infraestrutura. Aceite: perfil descreve alcance e exposição reais, persiste e informa quando exige reinício.
+
+#### Hardware virtual
+
+- [ ] **CPU topology e memória:** inventariar controles atuais de CPU/RAM antes de ampliar opções; avaliar sockets/cores/threads e modelo de CPU quando houver necessidade de compatibilidade ou desempenho. Aceite: recursos efetivos correspondem ao configurado, limites são validados e mudanças pendentes de reinício aparecem claramente.
+- [ ] **Virtio para disco e rede:** registrar o uso atual de `virtio-blk`, `virtio-scsi` e `virtio-net`; comparar alternativas apenas por requisitos de guest, número de discos ou medições. Aceite: drivers necessários são documentados e mudança de controlador não torna uma instalação existente incapaz de iniciar sem aviso e recuperação.
+- [ ] **USB passthrough:** começar com um dispositivo e guest concretos, com seleção e liberação explícitas. Aceite: informar que o host pode perder acesso enquanto o dispositivo estiver entregue ao guest; testar desconexão física, reconexão e encerramento da Machine sem capturar automaticamente dispositivos de entrada do host.
+- [ ] **Dispositivos extras:** selecionar por jornada concreta, em vez de um campo de argumentos QEMU arbitrários. Aceite: cada dispositivo tem suporte, permissões, persistência e comportamento de remoção documentados; recursos maduros são integrados no adapter.
+
+#### Lifecycle e persistência
+
+- [ ] **ACPI e shutdown/reboot:** auditar o caminho atual e avaliar agente guest quando disponível. Aceite: distinguir pedido enviado de desligamento concluído; timeout mantém estado verdadeiro e oferece Force Stop separado. Vincular à auditoria QEMU.
+- [ ] **QMP, crash e recovery:** aproveitar a frente transversal para ampliar somente comandos/eventos necessários e reconciliar estado após falha do QEMU ou reinício do host. Aceite: PID ou socket antigo não basta para declarar ambiente ativo; recuperação não apaga discos nem entra em loop de reinício automático.
+- [ ] **Autostart:** definir se significa login do usuário ou boot do host e quais ambientes participam. Aceite: opt-in por Machine, prevenção de start duplicado, falhas consultáveis e desativação simples; usar o gerenciador de serviços existente quando adequado, sem criar daemon por convenção.
+- [ ] **Estado persistente:** revisar versões do registro, gravação e recuperação de interrupções, além do lock já previsto. Aceite: registros anteriores continuam legíveis ou têm migração documentada; corrupção é diagnosticada sem substituir silenciosamente o registro por uma lista vazia.
+
+#### Performance avançada, condicionada a medições
+
+- [ ] **Hugepages e CPU pinning:** investigar apenas para cargas reproduzíveis em que CPU/memória sejam gargalos. Aceite: ganho medido, custo para o host documentado, ausência de recursos tratada e reversão simples; não reservar recursos globalmente sem decisão explícita.
+- [ ] **`io_uring`/AIO e cache modes:** verificar combinações suportadas pelo QEMU, armazenamento e filesystem do host. Aceite: comparar throughput, latência e integridade diante de falhas; documentar semântica de persistência e não adotar modos menos seguros como otimização automática.
+- [ ] **NUMA:** manter como hipótese até haver host/carga que justifique topologia e afinidade específicas. Aceite: baseline e melhoria reproduzível superam a complexidade; hosts comuns não recebem configuração adicional por padrão.
+
+#### Integração guest
+
+- [ ] **Guest agent mais rico:** inventariar funções necessárias e suporte do QEMU Guest Agent e ferramentas existentes antes de propor componente próprio. Aceite: cada função expõe disponível/indisponível/não verificada e limitações por guest; atualizar o escopo se a proposta exigir um agente completo.
+- [ ] **Resize e clipboard:** completar as validações já previstas em P2 e na frente QEMU. Aceite: resolução aplicada e texto trocado são confirmados em sessões suportadas, com desligamento da integração respeitado; não confundir clipboard de texto com transferência de arquivos.
+- [ ] **File transfer bidirecional, opt-out:** selecionar mecanismo existente e uma combinação host/guest inicial, permitindo envio nos dois sentidos por padrão conforme a preferência do ambiente. Cada transferência parte de uma ação do usuário; não implica sincronização automática de diretórios nem compartilhamento irrestrito da home.
+ - Aceite: testar host → guest e guest → host, destino, permissões, sobrescrita, cancelamento e arquivo parcial; desabilitar a capacidade bloqueia novas transferências e persiste após reabertura. Pasta compartilhada mantém suas próprias permissões e continua sendo uma alternativa compreensível.
+- [ ] **Abrir links e aplicações entre host e guest, opt-out:** permitir encaminhar uma solicitação de abertura nos dois sentidos, habilitado por padrão por ambiente. Oferecer destinos identificáveis, como navegador do Omarchy ou aplicação de um ambiente específico; lembrar associações escolhidas explicitamente, sem substituir associações globais silenciosamente.
+ - Aceite: testar um link do guest no navegador do host e um link/arquivo do host em uma aplicação do guest, além do sentido inverso para arquivos quando suportado. Cada abertura decorre de uma ação do usuário; não executar comandos arbitrários embutidos em URLs. Evitar ciclos de encaminhamento e ambiguidades entre ambientes, tratar destino indisponível e respeitar opt-out após reinício.
+ - Dependências: abrir um arquivo do outro sistema exige transferência ou caminho compartilhado válido, com permissões e preferência próprias respeitadas; desabilitar transferência não pode ser contornado pelo fluxo de abertura. Usar handlers/protocolos existentes onde possível. Abrir uma aplicação dentro do guest não promete janela integrada ao host; Blend Mode de Machines continua sujeito à descoberta específica.
+- [ ] **Exec em Machines:** definir autenticação/canal, contexto de usuário, diretório, ambiente, saída, código de retorno, timeout e cancelamento. Aceite: sem interpolação de shell implícita, comportamento programático documentado e erro claro quando o guest não oferece suporte; não presumir equivalência com Exec em Boxes.
+- [ ] **Shutdown/reboot pelo guest:** integrar à mesma operação de lifecycle já auditada, com fallback documentado quando cabível. Aceite: ausência ou travamento do agente não bloqueia indefinidamente nem transforma shutdown em corte de energia.
+
+#### Lacunas adicionais para descoberta
+
+- [ ] **Firmware e boot:** avaliar BIOS/UEFI, persistência de NVRAM e ordem de boot por guest suportado; Secure Boot e TPM virtual apenas por requisito concreto. Aceite: configuração persiste e acompanha exportação/recuperação quando necessária; mudança incompatível não é aplicada silenciosamente.
+- [ ] **Backup e restauração:** distinguir backup independente de snapshot dependente do disco original. Aceite: restauração comprovada em outro diretório/ambiente, com discos, configuração e estado de firmware necessários; explicitar consistência e necessidade de parar ou coordenar o guest.
+- [ ] **Suspensão do host e estado salvo:** testar primeiro o comportamento existente ao suspender/retomar o notebook. Avaliar salvar/restaurar memória da Machine separadamente de Pause e snapshot de disco, apenas se houver demanda. Aceite: reconexão, relógio e rede são verificados; incompatibilidade de estado salvo após atualização tem recuperação documentada.
+- [ ] **Compatibilidade após atualização:** definir versões de QEMU e guests efetivamente testadas, com atenção ao tipo de máquina virtual, firmware e dispositivos persistidos. Aceite: ambientes existentes iniciam após atualização suportada ou recebem diagnóstico e procedimento de recuperação; upgrades não trocam hardware virtual silenciosamente.
+
+Sequência candidata após a auditoria: discos adicionais e crescimento, importação de discos e port forwarding simples; depois redes privadas, backup e integração guest orientada por uso. Bridge, passthrough, perfis e tuning avançado dependem de demanda e validação. Esta sequência deve ser repriorizada pelos achados de confiabilidade e pelos testes de usuário.
+
diff --git a/docs/ideias/README.md b/docs/ideias/README.md
new file mode 100644
index 0000000..2eea57a
--- /dev/null
+++ b/docs/ideias/README.md
@@ -0,0 +1,35 @@
+# Ideias
+
+Melhorias encontradas pesquisando projetos parecidos. Nada aqui é
+compromisso: cada arquivo diz onde a ideia cai no escopo do `CLAUDE.md`
+(Current Priorities, Scope/Non-Goals) antes de virar trabalho.
+
+Decisão de 2026-09-28: integrações com o host entram **ligadas por padrão**
+(opt-out por ambiente em Settings), nunca como opt-in. Os esboços abaixo
+que dizem "opt-in" valem com essa inversão; quando há custo de segurança
+(como no [vsock-ssh.md](vsock-ssh.md)), ele é dito na tela, não usado como
+motivo para desligar.
+
+| Ideia | Encaixe no escopo | Arquivo |
+|---|---|---|
+| SSH e port forwarding via vsock | **SSH feito 2026-09-28**, ligado por padrão com o custo dito na tela; port forwarding não | [vsock-ssh.md](vsock-ssh.md) |
+| GPU por native context | Encaixa depois do Venus; hoje só AMD | [gpu-native-context.md](gpu-native-context.md) |
+| Windows 11 sem ajustes manuais (TPM + Secure Boot) | Encaixa, com cuidado: a OmaVM não é "exclusiva para Windows" | [windows11-tpm-secureboot.md](windows11-tpm-secureboot.md) |
+| Distrobox v2 e ações de Box (Clone, Atualizar, uso) | Risco real no export de apps; Clone já é meta do Experience Center | [boxes-distrobox.md](boxes-distrobox.md) |
+| Próximos passos do display D-Bus | Encaixa: refina o viewer atual | [display-dbus.md](display-dbus.md) |
+| Ambientes no launcher do Omarchy (`.desktop` por ambiente) | **Feito 2026-09-28**, opt-out | [ambientes-no-launcher.md](ambientes-no-launcher.md) |
+| Terminal da Box sobre libvterm (MIT, usado pelo Qt Creator) | Encaixa, mas é decisão de arquitetura: pede acordo antes | [terminal-libvterm.md](terminal-libvterm.md) |
+| Copiar do terminal da Box (seleção e OSC 52 só de escrita) | **Feito 2026-09-28**; OSC 52 opt-out | [terminal-copiar.md](terminal-copiar.md) |
+| Terminal da Box à la Ptyxis (aviso ao fechar, cor do ambiente, nova sessão no mesmo diretório) | Encaixa: melhora o terminal atual sem daemon | [terminal-ptyxis.md](terminal-ptyxis.md) |
+| CLI para agentes: códigos de saída por classe de erro e erros em JSON | Encaixa: agentes são meta do `CLAUDE.md`; muda contrato, documentar antes | [cli-para-agentes.md](cli-para-agentes.md) |
+| Limites de CPU/memória e Travel Mode para Boxes (`podman update`) | **Travel Mode feito 2026-09-28**; limites fixos não | [box-limites-e-travel-mode.md](box-limites-e-travel-mode.md) |
+| Pasta compartilhada que monta sozinha no guest (tags virtiofs no sysfs) | Encaixa, opt-in no guest; sem agente próprio | [pasta-compartilhada-automatica.md](pasta-compartilhada-automatica.md) |
+| Cor do ambiente visível no Nautilus (metadados do GVFS em vez do xattr) | **Feito 2026-09-28** | [cor-no-nautilus.md](cor-no-nautilus.md) |
+| Arquivar (liberar espaço) e exportar/importar ambientes | Encaixa; o formato do manifesto esbarra numa decisão em aberto | [arquivar-e-exportar.md](arquivar-e-exportar.md) |
+| Progresso ao criar uma Box (pull separado, fora do lock do registro) | Encaixa: melhora UX e reduz o tempo com o registro travado | [progresso-ao-criar-box.md](progresso-ao-criar-box.md) |
+| Logs no journal do systemd (protocolo nativo, sem dependência) | Encaixa: substitui a rotação própria pelo journald | [logs-no-journal.md](logs-no-journal.md) |
+| Acessibilidade: leitor de tela (Orca/AT-SPI) e navegação por teclado | Encaixa: revisão com testes em `make test-qml` | [acessibilidade.md](acessibilidade.md) |
+| Lista de ambientes como `QAbstractListModel` no C++ | Opcional: a correção em QML já resolve o bug; vale se crescer | [modelo-de-ambientes-em-cpp.md](modelo-de-ambientes-em-cpp.md) |
+| Catálogo de sistemas para baixar | Conflita com o non-goal "dezenas de distros pré-empacotadas" | [catalogo-de-imagens.md](catalogo-de-imagens.md) |
+| Espaço em disco do host; redimensionar e compactar o disco | Encaixa: pequeno, melhora a experiência | [disco-do-host.md](disco-do-host.md) |
+| Machine descartável (`-snapshot` do QEMU) | Encaixa: ambientes descartáveis já são meta do `CLAUDE.md` | [machine-descartavel.md](machine-descartavel.md) |
diff --git a/docs/ideias/acessibilidade.md b/docs/ideias/acessibilidade.md
new file mode 100644
index 0000000..0755339
--- /dev/null
+++ b/docs/ideias/acessibilidade.md
@@ -0,0 +1,47 @@
+# Acessibilidade: leitor de tela e teclado
+
+## Situação
+
+O Qt 6 expõe a interface ao **Orca** (o leitor de tela do desktop Linux)
+pela ponte AT-SPI 2, mas só o que cada controle declara: nome, papel e
+estado. A QML da OmaVM tem poucas anotações `Accessible.*` (duas no card,
+duas em Settings, três no Main) e nenhuma navegação de teclado explícita
+(`KeyNavigation`, `activeFocusOnTab`).
+
+Corrigido em 2026-09-28: os botões de cor em Settings diziam só "red,
+button"… sem informar qual estava selecionado, porque a seleção era apenas
+uma borda mais grossa. Agora eles declaram `Accessible.checkable/checked`
+(teste `test_selectedColorIsAnnouncedToScreenReaders`).
+
+## O que revisar
+
+- **Card do ambiente:** a bolinha de status comunica só por cor; o texto ao
+ lado já diz o estado, mas o leitor não sabe que os dois se relacionam.
+ Nome e estado do card deveriam formar um único `Accessible.name`
+ ("Fedora, Box, rodando").
+- **Botões só com ícone** (novo ambiente, atualizar, menu "⋯") precisam de
+ `Accessible.name` em todos; hoje só parte tem.
+- **Teclado:** do topo da janela até a última ação do último card, tudo
+ alcançável com Tab, e o menu do card abrindo com Enter/Espaço. Os
+ diálogos já fecham com Esc; conferir o foco inicial de cada um.
+- **Viewer e terminal:** capturam o teclado de propósito (tudo vai para o
+ guest ou para o shell da Box). O atalho de saída (Ctrl+Alt+Q) precisa
+ estar anunciado no título ou numa dica, porque sem ele a pessoa fica
+ presa na janela.
+- **Wayland:** atalhos globais do Orca ainda dependem de protocolos em
+ discussão no Wayland; testar numa sessão Hyprland real antes de prometer
+ suporte.
+
+## Como testar
+
+O `make test-qml` já roda os componentes reais com um backend falso: dá
+para verificar `Accessible.name`/`role`/`checked` e a ordem de foco por
+Tab sem leitor de tela. O Accerciser (inspetor AT-SPI) serve para conferir
+o que o Orca realmente recebe numa sessão real.
+
+## Fontes
+
+- [Accessibility – freedesktop.org](https://www.freedesktop.org/wiki/Accessibility/)
+- [Wayland accessibility notes](https://github.com/splondike/wayland-accessibility-notes/blob/main/README.md)
+- [Keyboard issues with Orca on Wayland – wayland-devel](https://lists.freedesktop.org/hyperkitty/list/wayland-devel@lists.freedesktop.org/thread/T7V56JTKGTR7GTNQF4H2KWDQC6MUIA5J/)
+- [Keyboard navigation and screen-reader support in Qt Quick (exemplo de checklist)](https://github.com/altqx/hikari/issues/18)
diff --git a/docs/ideias/ambientes-no-launcher.md b/docs/ideias/ambientes-no-launcher.md
new file mode 100644
index 0000000..2bdf19c
--- /dev/null
+++ b/docs/ideias/ambientes-no-launcher.md
@@ -0,0 +1,40 @@
+# Ambientes no launcher do Omarchy
+
+## Contexto
+
+O Omarchy 4 "Quattro" (agosto de 2026) trouxe barra, launcher e menus para
+um único processo Quickshell com plugins; Walker e Elephant saíram do
+padrão. Os tipos de plugin aceitos são `bar-widget`, `panel`, `overlay`,
+`menu`, `service` e `bar` (conferido em
+`/usr/share/omarchy/shell/README.md` deste host). **Não existe** um tipo de
+plugin para acrescentar resultados de busca ao launcher. Os plugins `menu`
+recebem a biblioteca de aplicativos do host, ou seja, as entradas
+`.desktop`.
+
+## Ideia
+
+Hoje, para abrir um ambiente é preciso abrir o Experience Center primeiro.
+Uma entrada `.desktop` por ambiente ("Fedora — OmaVM") faz o ambiente
+aparecer no launcher do Omarchy, e em qualquer outro, como um app comum. É
+o mesmo mecanismo que o Distrobox usa (`distrobox generate-entry`) e que a
+OmaVM já usa para exportar apps de Boxes (Blend Mode base).
+
+## Esboço
+
+- Opt-in por ambiente ("Mostrar no launcher", Settings → Automation),
+ persistido no domínio como as outras preferências.
+- `Exec=` aponta para o caminho que já existe: `omavm open NAME` para
+ Machines (que lança o viewer) e `omavm-gui --terminal NAME` para Boxes (o
+ `omavm open` de Box é interativo e precisa de TTY).
+- Ícone por tipo e, quando houver, pela cor do ambiente (Color tags).
+- `Remove` e renomear apagam ou atualizam a entrada; nunca deixar atalho
+ órfão apontando para um ambiente que não existe.
+- Um painel no plugin de barra (`contrib/dev.omavm.bar`) listando os
+ ambientes com Open/Start é a alternativa sem arquivos no disco; exige o
+ plugin habilitado, que é sempre manual (ver `CLAUDE.md`).
+
+## Fontes
+
+- [Arch-Based Omarchy 4.0 "Quattro" – Linuxiac](https://linuxiac.com/arch-based-omarchy-4-0-quattro-is-here-with-its-biggest-desktop-overhaul-yet/)
+- [Omarchy Quattro gives Linux a desktop you can rearrange – Botmonster](https://botmonster.com/self-hosting/omarchy-quattro-release/)
+- [Custom Walker Menus with Lua – Hans Schnedlitz](https://www.hansschnedlitz.com/writing/2026/02/22/custom-walker-menus-with-lua)
diff --git a/docs/ideias/arquivar-e-exportar.md b/docs/ideias/arquivar-e-exportar.md
new file mode 100644
index 0000000..8fbdffd
--- /dev/null
+++ b/docs/ideias/arquivar-e-exportar.md
@@ -0,0 +1,45 @@
+# Arquivar e exportar ambientes
+
+## O que outros fazem
+
+- **Parallels Desktop — Archive:** uma VM pouco usada é compactada para
+ ocupar bem menos disco; enquanto arquivada, não inicia, e "Unarchive" a
+ devolve.
+- **UTM:** a VM inteira (disco + configuração) vira um único `.utm`,
+ compartilhado dentro de um `.zip`, que outro Mac importa.
+
+## Encaixe na OmaVM
+
+Hoje uma Machine são arquivos soltos no diretório de estado (qcow2, pid,
+sockets) mais uma entrada no `environments.json`. Não há como:
+- liberar espaço de uma Machine parada sem apagá-la;
+- levar uma Machine para outro computador ou guardá-la fora do host, além
+ de copiar o qcow2 à mão e recriar a configuração.
+
+## Esboço
+
+- **Arquivar (Machine parada):** `qemu-img convert -c` para um qcow2
+ compactado no mesmo diretório e marca no domínio (`Archived`) que
+ bloqueia o `Start` com uma mensagem clara e oferece "Restaurar". Mesmo
+ mecanismo da ideia de compactar disco ([disco-do-host.md](disco-do-host.md)),
+ com estado explícito.
+- **Exportar/Importar:** `omavm export NOME arquivo.omavm` gera um tar com o
+ qcow2 (snapshots internos incluídos) e um manifesto com a configuração
+ do ambiente, **sem** caminhos do host (ISO, pasta compartilhada) nem
+ estado de runtime. `omavm import` recria o ambiente com nome e ID novos.
+ O formato do manifesto esbarra em "Template format" das Open Technical
+ Decisions do `CLAUDE.md`: decidir antes, não de carona.
+- **Boxes:** o equivalente é `podman commit` + `podman save`; o `$HOME`
+ compartilhado não viaja junto, e isso precisa aparecer na UI.
+
+## Relacionado
+
+Desde 2026-09-28 o registro (`environments.json`) é gravado com `fsync` e
+mantém a versão anterior em `environments.json.bak`, para recuperação após
+queda de energia.
+
+## Fontes
+
+- [Parallels Desktop Help – Archive and Unarchive Virtual Machines](https://download.parallels.com/desktop/v19/docs/en_US/Parallels%20Desktop%20User's%20Guide/42000.htm)
+- [UTM on Mac: When to Consider Parallels Desktop](https://www.parallels.com/compare/utm/)
+- [UTM_to_Parallels_importer](https://github.com/MRX7999/UTM_to_Parralels_importer)
diff --git a/docs/ideias/box-limites-e-travel-mode.md b/docs/ideias/box-limites-e-travel-mode.md
new file mode 100644
index 0000000..a5e3fa5
--- /dev/null
+++ b/docs/ideias/box-limites-e-travel-mode.md
@@ -0,0 +1,49 @@
+# Limites de recurso e Travel Mode para Boxes
+
+## Situação
+
+O Travel Mode (`CLAUDE.md`, Omarchy Integration) reduz CPUs só das
+Machines: no `Start`, com o host na bateria, a Machine sobe com metade dos
+CPUs. Uma Box compila, roda testes e indexa como qualquer processo do host,
+sem limite nenhum, e na bateria é justamente ela que mais gasta.
+
+## O que o host oferece
+
+Conferido neste host (2026-09-28):
+- cgroups **v2** com gerenciador **systemd**, e o serviço do usuário recebe
+ delegação de `cpu`, `memory` e `pids`
+ (`/sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/cgroup.controllers`).
+ Sem essa delegação, o Podman rootless não aplica limites e o `crun` falha
+ com erro de controlador.
+- `podman update --cpus` e `--memory` ajustam **um container já criado**,
+ sem recriá-lo. Isso importa porque recriar uma Box perde o que foi
+ instalado nela.
+
+## Esboço
+
+- Limites opcionais por Box (CPU e memória) no domínio, como os da Machine
+ (`EnvironmentSettings.CPUs`/`MemoryMiB`), aplicados com `podman update`
+ (no `Start` e ao salvar nas Settings), sem recriar o container.
+- Travel Mode para Boxes: na bateria, `podman update --cpus` com metade dos
+ CPUs do host no `Start`, com a mesma regra da Machine (nunca sobrescrever
+ um limite que o usuário fixou) e o mesmo opt-out por ambiente.
+- `omavm host` passa a dizer se os limites de Box funcionam, lendo os
+ controladores delegados; sem delegação, a opção não aparece em vez de
+ falhar ao salvar.
+
+## Cuidados
+
+- A Box via Distrobox é criada com `distrobox create`, mas o container é
+ do Podman: o `podman update` age por baixo do Distrobox. É preciso
+ conferir que um `distrobox enter` depois do update não desfaz o limite.
+- Limite de memória baixo mata processos da Box com OOM, o que para quem
+ está compilando parece um erro misterioso. A UI deve explicar o limite e
+ mostrar o valor em uso.
+- Docker como engine tem outro caminho (`docker update`); começar só pelo
+ Podman, que é o preferencial no `CLAUDE.md`.
+
+## Fontes
+
+- [How to Use cgroups v2 with Rootless Podman – OneUptime](https://oneuptime.com/blog/post/2026-03-18-use-cgroups-v2-rootless-podman/view)
+- [Podman Resource Limits: CPU, Memory, PIDs & I/O](https://www.golinuxcloud.com/podman-resource-limits/)
+- [Cannot set --memory on rootless Podman – containers/podman #8330](https://github.com/containers/podman/issues/8330)
diff --git a/docs/ideias/boxes-distrobox.md b/docs/ideias/boxes-distrobox.md
new file mode 100644
index 0000000..dda3b73
--- /dev/null
+++ b/docs/ideias/boxes-distrobox.md
@@ -0,0 +1,53 @@
+# Boxes: Distrobox v2 e ações que faltam
+
+## Risco: Distrobox v2 quebra a exportação de apps
+
+O Distrobox v2 (reescrito em Go, em release candidate desde 2026) mantém os
+argumentos de `create`/`enter`/`stop`/`rm`/`list`, mas vira um binário
+único: **`distrobox-export` deixa de existir como executável separado**
+(passa a ser `distrobox export`). Apps e binários exportados por Boxes do
+v1 precisam que a Box seja recriada.
+
+Impacto na OmaVM: `internal/backend/distrobox/apps.go` executa
+`distrobox enter --name -- distrobox-export --app ` (e
+`--delete`). O v1 instalado aqui (1.8.2.5) não tem subcomando `export` no
+host; o export roda dentro da Box. O anúncio do v2 não diz como o export é
+chamado de dentro do container.
+
+Plano, quando houver necessidade real (v2 estável ou um usuário no RC):
+1. Testar o adapter contra o `v2.0.0-rc` num ambiente isolado, sem
+ substituir o Distrobox do host.
+2. Descobrir a forma certa de exportar no v2 e detectar a versão
+ (`distrobox version`), em vez de tentar os dois comandos às cegas.
+3. Avisar na UI quando apps exportadas no v1 precisarem que a Box seja
+ recriada, em vez de falhar em silêncio.
+
+Não implementar antes disso: seria código especulativo para uma versão
+ainda não estável (Coding Principles).
+
+## Ações de Box que outras GUIs oferecem
+
+BoxBuddy e DistroShelf (GUIs GTK4 para Distrobox) oferecem por Box: abrir
+terminal, **atualizar** (`distrobox upgrade`), **clonar**
+(`distrobox create --clone`), ver e exportar apps, parar e apagar, e uma
+linha de uso de CPU e memória.
+
+Para a OmaVM:
+- **Clone** já está na lista de ações do Experience Center (UX Principle
+ #5) e ainda não existe para nenhum dos dois tipos. Para Box é integração
+ direta com o `--clone` nativo; o custo (cópia da imagem do container)
+ precisa aparecer na UI (UX Principle #10).
+- **Atualizar** a Box (`distrobox upgrade`) cabe no menu do card; é longa,
+ então precisa do mesmo tratamento de ação em andamento que Restart já tem
+ (inclusive sobreviver ao fechamento da janela, corrigido em 2026-09-27).
+- **Uso de CPU e memória**: o `podman stats --no-stream --format json` dá o
+ número sem daemon. No Experience Center, só com a Box rodando e sem
+ polling pesado (o poll de 3 s já foi um problema de CPU).
+
+## Fontes
+
+- [Announcing the next generation of Distrobox](https://distrobox.it/posts/announcing_distrobox_next/)
+- [Distrobox changelog](https://whatsnew.fyi/product/distrobox)
+- [DistroShelf](https://github.com/ranfdev/DistroShelf)
+- [BoxBuddy](https://github.com/Dvlv/BoxBuddyRS)
+- [BoxBuddy vs DistroShelf – Linux Adictos](https://en.linuxadictos.com/BoxBuddy-vs.-DistroShelf:-A-complete-comparison-and-practical-guide-between-these-two-DistroBox-managers..html)
diff --git a/docs/ideias/catalogo-de-imagens.md b/docs/ideias/catalogo-de-imagens.md
new file mode 100644
index 0000000..5fe4290
--- /dev/null
+++ b/docs/ideias/catalogo-de-imagens.md
@@ -0,0 +1,25 @@
+# Catálogo de sistemas para baixar
+
+## O que outros fazem
+
+O Quickemu (`quickget`) e o Quickgui buscam e baixam quase 1000 sistemas
+(Windows, macOS, BSDs, centenas de distros) e criam a VM já configurada.
+
+## Encaixe no escopo
+
+**Conflita** com o non-goal "dezenas de distros pré-empacotadas" do
+`CLAUDE.md`. Manter um catálogo próprio é manutenção sem fim (URLs,
+checksums, versões).
+
+## Variante compatível
+
+Se a necessidade aparecer, integrar o `quickget` como fonte opcional, em
+vez de manter um catálogo: a OmaVM mostra "Baixar um sistema…" só quando o
+`quickget` está instalado, e o resto do fluxo continua sendo "criar Machine
+a partir de uma ISO". Precisa de necessidade real documentada antes (Rules
+for AI Agents #7).
+
+## Fontes
+
+- [Quickgui – AlternativeTo](https://alternativeto.net/software/quickgui/about/)
+- [Quickemu – Chris Titus Tech](https://christitus.com/quickemu/)
diff --git a/docs/ideias/cli-para-agentes.md b/docs/ideias/cli-para-agentes.md
new file mode 100644
index 0000000..35cdf4f
--- /dev/null
+++ b/docs/ideias/cli-para-agentes.md
@@ -0,0 +1,49 @@
+# CLI para agentes: códigos de saída e erros em JSON
+
+## Situação
+
+O `CLAUDE.md` quer a OmaVM "controlável por humanos e por agentes" e já
+trata o JSON do `list`/`status --json` como contrato estável (a barra do
+Omarchy consome). Mas os **erros** não têm contrato:
+
+- toda falha sai com código **1**, seja entrada inválida, ambiente
+ inexistente, recurso indisponível para aquele tipo ou pane real;
+- a mensagem vai só como texto para o stderr, em inglês, mesmo com
+ `--json`.
+
+Um agente precisa ler texto para saber se deve corrigir o pedido, criar o
+ambiente ou desistir. Desde 2026-09-28 a Core já classifica os erros
+(`ErrInvalidInput`, `ErrNotFound`, `ErrAlreadyExists`, `ErrUnsupported`,
+com todas as validações cobertas por
+`TestValidationErrorsAreInvalidInput`), então falta só expor isso.
+
+## Esboço
+
+Códigos de saída estáveis, no espírito do `sysexits.h`, mas poucos:
+
+| Classe | Código | Significa para quem chama |
+|---|---|---|
+| sucesso | 0 | — |
+| erro geral | 1 | falha do sistema ou do backend; talvez tentar de novo |
+| uso/entrada inválida (`ErrInvalidInput`, flags) | 2 | corrigir o pedido |
+| não encontrado (`ErrNotFound`) | 3 | o ambiente não existe |
+| já existe (`ErrAlreadyExists`) | 4 | escolher outro nome |
+| indisponível para este tipo (`ErrUnsupported`) | 5 | não adianta tentar de novo |
+
+Com `--json`, a falha também sai como JSON no stdout:
+`{"error": {"code": "not_found", "message": "environment not found: x"}}`,
+com `code` estável em snake_case e `message` para gente.
+
+## Cuidados
+
+- É uma mudança de contrato: scripts que tratam "qualquer não-zero" continuam
+ funcionando, mas quem compara com `1` precisa saber. Documentar no README
+ e na ajuda da CLI antes de publicar.
+- A GUI hoje só lê stderr; ela pode passar a usar o `code` para decidir
+ texto e ações (por exemplo, "criar ambiente" ao receber `not_found`).
+
+## Fontes
+
+- [Designing a CLI for AI agents – Arcjet](https://blog.arcjet.com/designing-a-cli-for-ai-agents/)
+- [Writing CLI Tools That AI Agents Actually Want to Use – DEV](https://dev.to/uenyioha/writing-cli-tools-that-ai-agents-actually-want-to-use-39no)
+- [A compact contract for CLIs for agents and development tools](https://gist.github.com/peterc/bef25ee122d233c53a851b9ace29efef)
diff --git a/docs/ideias/cor-no-nautilus.md b/docs/ideias/cor-no-nautilus.md
new file mode 100644
index 0000000..c21ff7d
--- /dev/null
+++ b/docs/ideias/cor-no-nautilus.md
@@ -0,0 +1,44 @@
+# Cor do ambiente visível no Nautilus
+
+## Situação
+
+Ao mudar a cor de uma Machine, a OmaVM cria `~/OmaVM/` (link para o
+disco) e grava a cor no xattr `user.xdg.tags`, como "best-effort"
+(`CLAUDE.md`, Omarchy Integration). O gerenciador de arquivos do Omarchy é
+o **Nautilus 50** (`SUPER + SHIFT + F` em
+`/usr/share/omarchy/default/hypr/bindings/applications.lua`), e o Nautilus
+não usa `user.xdg.tags`: ícones e marcas dele vêm dos **metadados do
+GVFS**. Na prática a cor não aparece em lugar nenhum no Omarchy padrão.
+
+## O que funciona
+
+Conferido neste host (2026-09-28): `gio set -t string
+metadata::custom-icon file:///…/icone.svg` grava o metadado **no próprio
+link** (não no disco apontado), e `gio info` o devolve. É o mesmo atributo
+que o Nautilus grava quando o usuário escolhe um ícone personalizado.
+
+## Esboço
+
+- Um SVG por cor da paleta fixa (`core.EnvironmentColors`), gerado a partir
+ do ícone da OmaVM, instalado junto com o app (sem gerar arquivos no
+ `$HOME`).
+- `Link` passa a gravar também `metadata::custom-icon` via `gio set`, com o
+ mesmo tratamento best-effort do xattr: sem `gio` ou sem o daemon de
+ metadados, a cor interna continua valendo e nada falha.
+- `Unlink` não precisa limpar: os metadados do GVFS vão embora com o link.
+- Manter o xattr para quem usa Dolphin/Baloo.
+
+## Cuidados
+
+- Há relatos de "Setting attribute metadata::custom-icon not supported" em
+ alguns sistemas (depende do `gvfsd-metadata` e do sistema de arquivos);
+ daí o best-effort.
+- Desde 2026-09-28 o `Link` recusa sobrescrever um arquivo que não seja o
+ link da própria OmaVM em `~/OmaVM`; o ícone só é gravado no link dela.
+
+## Fontes
+
+- [gio metadata::custom-icon – GNOME Discourse](https://discourse.gnome.org/t/gio-metadata-custom-icon-file-attribute-not-seen-by-shell-extension-code/7640)
+- [Command-line hacking: assigning folder icons – Kevin Boone](https://kevinboone.me/clh_foldericon.html)
+- [Folder Color: custom icons issue #35](https://github.com/costales/folder-color/issues/35)
+- [GNOME Files – Wikipedia](https://en.wikipedia.org/wiki/GNOME_Files)
diff --git a/docs/ideias/disco-do-host.md b/docs/ideias/disco-do-host.md
new file mode 100644
index 0000000..79b629f
--- /dev/null
+++ b/docs/ideias/disco-do-host.md
@@ -0,0 +1,51 @@
+# Espaço em disco real do host
+
+## O que outros fazem
+
+No Parallels Desktop 26, a VM Windows passa a ver o espaço realmente livre
+no Mac, para evitar travamentos quando o disco do host enche durante
+instalações grandes.
+
+## O problema na OmaVM
+
+A Machine usa um qcow2 esparso de tamanho fixo (`defaultDiskSize`). O guest
+vê o disco inteiro como livre mesmo quando o disco do host está quase cheio;
+quando o qcow2 não consegue crescer, o QEMU pausa a VM com `io-error`, e o
+card mostra só "Error".
+
+## Esboço
+
+**Primeiro item implementado (2026-09-29)**, junto com o disco padrão de
+1 TiB esparso: um `io-error` aparece como pausa com o motivo ("o disco
+deste computador está cheio; libere espaço e retome"), e Resume continua a
+Machine. O aviso antes do Start e o redimensionar/compactar abaixo seguem
+como ideia.
+
+- Ao pausar por `io-error` (o `statusFromQMP` já distingue esse estado), o
+ Core checa o espaço livre do sistema de arquivos do diretório de estado e
+ explica: "o disco do computador encheu; libere espaço e retome".
+- Aviso antes do Start quando o espaço livre do host for menor que o
+ crescimento possível do qcow2 (tamanho virtual menos o alocado).
+- Não repetir o que o Parallels faz dentro do guest: exigiria um agente
+ (`omavm-guest`), que continua fora do escopo.
+
+## Redimensionar e compactar o disco
+
+O UTM 4 permite, nas configurações do disco, **redimensionar** o qcow2 e
+**compactá-lo** (reescrevendo só os blocos em uso). Na OmaVM, os dois são
+comandos maduros do `qemu-img` (`resize`, `convert -c`) com a Machine
+parada:
+- aumentar o disco quando o guest encher, em vez de recriar a Machine
+ (o guest ainda precisa expandir a própria partição; a UI deve dizer isso);
+- devolver espaço ao host depois de apagar arquivos no guest, o que
+ combina com o aviso de disco cheio acima.
+
+O custo aparece na UI (UX Principle #10): compactar reescreve o arquivo
+inteiro e precisa de espaço livre equivalente enquanto roda.
+
+## Fontes
+
+- [UTM 4.0 release notes](https://docs.getutm.app/updates/v4.0/)
+
+- [Parallels Desktop 26 updates summary – Parallels KB](https://kb.parallels.com/en/131014)
+- [Parallels Desktop 26 – 9to5Mac](https://9to5mac.com/2025/08/26/parallels-desktop-26-brings-macos-26-support-and-new-tools-for-it/)
diff --git a/docs/ideias/display-dbus.md b/docs/ideias/display-dbus.md
new file mode 100644
index 0000000..e05ce98
--- /dev/null
+++ b/docs/ideias/display-dbus.md
@@ -0,0 +1,47 @@
+# Próximos passos do display D-Bus
+
+O viewer migrou para o D-Bus display do QEMU em 2026-09-28 (ver
+`CLAUDE.md`). Ideias levantadas na migração e na pesquisa:
+
+## Preview sem `screendump`
+
+O `screendump` via QMP falha com "no surface" em alguns guests (Haiku) com
+display GL. O viewer já recebe os quadros; o preview do Experience Center
+poderia vir de uma conexão D-Bus curta (um `ScanoutDMABUF`/`ScanoutMap`
+basta) em vez do `screendump`. Resolve o preview que falta hoje no Haiku.
+
+Evidência (2026-09-28): numa Machine Haiku iniciada pelo `Start` novo
+(`dbus,p2p=yes,gl=on`), o `screendump` falhou com "no surface" durante e
+depois do boot, igual ao que acontecia com `egl-headless`; o display em si
+funcionava (o console reportava 1280x800). Com o GL ligado, o scanout do
+guest é uma textura, sem a superfície 2D que o `screendump` lê. O custo da
+alternativa: no modo GL o quadro é um dma-buf (tiled na Intel), que só a GPU
+lê; a miniatura teria de ser gerada do lado Qt (onde a importação EGL já
+existe), não no Go.
+
+## Atualizações só da área alterada (damage)
+
+O viewer redesenha a textura inteira a cada `UpdateDMABUF`. O trabalho
+recente de "damage areas" no espaço VirtIO propaga só as regiões alteradas
+do guest até o cliente, reduzindo o custo por quadro. Com dma-buf a textura
+já é compartilhada, mas repassar o dano ao scene graph evita recompor a
+janela inteira.
+
+## Redirecionamento USB e clipboard com imagens
+
+O Boxes ainda depende do SPICE porque o libmks (cliente D-Bus) não tem
+redirecionamento USB. O `ui/dbus-display1.xml` também só define clipboard
+de texto (`text/plain;charset=utf-8`). Nenhum dos dois é possível hoje só
+com o D-Bus display: registrar como limite, sem prometer.
+
+## Áudio pelo próprio display
+
+Sem `-audiodev`, o QEMU usa o áudio D-Bus por padrão com `-display dbus`.
+A OmaVM usa PipeWire direto no host, que já funciona sem o viewer aberto.
+Manter assim; anotado só para não "corrigir" por engano.
+
+## Fontes
+
+- [D-Bus display — QEMU documentation](https://www.qemu.org/docs/master/interop/dbus-display)
+- [Damage areas across the VirtIO space – Bilal Elmoussaoui](https://belmoussaoui.com/blog/16-damage-areas-across-the-virtio-space/)
+- [qemu-display (rdw, libmks)](https://github.com/rustdesk-org/qemu-display)
diff --git a/docs/ideias/gpu-native-context.md b/docs/ideias/gpu-native-context.md
new file mode 100644
index 0000000..c384553
--- /dev/null
+++ b/docs/ideias/gpu-native-context.md
@@ -0,0 +1,42 @@
+# Aceleração de GPU por native context
+
+## O que é
+
+Além do virgl (OpenGL traduzido) e do Venus (Vulkan serializado), a
+virtio-gpu do QEMU agora suporta **DRM native context**: o guest usa o
+driver Mesa nativo da GPU do host, e a virtio-gpu só medeia a UAPI do
+kernel. Isso gasta menos CPU que virgl e Venus, e o guest ganha OpenGL,
+Vulkan e decodificação de vídeo (VA-API) do próprio driver nativo.
+
+## Situação em 2026
+
+- QEMU: a propriedade `drm_native_context` existe no `virtio-vga-gl` (o
+ QEMU 11.1.1 deste host já a lista), exigindo `blob=on` e `hostmem`.
+- virglrenderer ≥ 1.0 suporta o protocolo; o i915 pede ≥ 1.3.0 e kernel
+ 6.13+ no host, com Mesa recente e kernel 6.14+ no guest.
+- AMD e Qualcomm (msm) estão upstream. Intel i915 tem merge requests
+ abertos; **Intel Xe (GPUs novas) ainda não está upstream** em
+ virglrenderer nem Mesa, e ninguém assumiu esse trabalho.
+
+## Encaixe na OmaVM
+
+É o próximo passo natural depois do Venus (ligado por padrão desde
+2026-09-28): mesma detecção estática do host (`omavm host`), mesma opção
+por Machine. Mas hoje só vale para AMD. No host de desenvolvimento
+(Intel Tiger Lake, i915) depende de patches ainda não publicados.
+
+## Esboço
+
+- Estender `detectGraphics` com `nativeContext` para AMD (`amdgpu`), com o
+ mesmo tipo de checagem estática do Venus (versão do virglrenderer,
+ kernel).
+- Preferir native context ao Venus quando os dois estiverem disponíveis;
+ uma Machine usa um ou outro.
+- Não oferecer para Intel até o suporte ser upstream, mesmo existindo
+ scripts de terceiros que habilitam o Xe.
+
+## Fontes
+
+- [VirtIO GPU — QEMU documentation](https://www.qemu.org/docs/master/system/devices/virtio/virtio-gpu.html)
+- [Support virtio-gpu DRM native context (patch series, v6)](https://patchew.org/QEMU/20250126201121.470990-1-dmitry.osipenko@collabora.com/)
+- [xe-native-context-enablement](https://github.com/cmspam/xe-native-context-enablement)
diff --git a/docs/ideias/logs-no-journal.md b/docs/ideias/logs-no-journal.md
new file mode 100644
index 0000000..fadf12e
--- /dev/null
+++ b/docs/ideias/logs-no-journal.md
@@ -0,0 +1,39 @@
+# Logs no journal do systemd
+
+## Por que pensar nisso
+
+Em 2026-09-28 a OmaVM ganhou rotação própria de log (5 MiB, um `.1`) porque
+o arquivo crescia sem limite. Mas o Omarchy roda systemd, e o **journald**
+já faz exatamente isso, melhor: limite de tamanho global, compressão,
+consulta por campo e por tempo (`journalctl`), e visualização junto com o
+resto do sistema. É o caso típico de "integre, não reimplemente" (Backend
+Rules), aplicado à observabilidade.
+
+## Como seria
+
+- O journal aceita entradas pelo **protocolo nativo**: datagramas num
+ socket `AF_UNIX`/`SOCK_DGRAM` em `/run/systemd/journal/socket`, cada um
+ com pares `CAMPO=valor`. Dá para falar isso só com a biblioteca padrão do
+ Go, sem cgo e sem dependência nova (o projeto não tem `go.sum`); há
+ inclusive um handler `slog` oficial do projeto systemd
+ (`github.com/systemd/slog-journal`) como referência de implementação.
+- Campos estruturados do `slog` viram campos do journal (`OMAVM_CMD`,
+ `OMAVM_ENV`, …), e `SYSLOG_IDENTIFIER=omavm` permite
+ `journalctl --user -t omavm` ou `journalctl -t omavm -g create`.
+- Sem journal (outra init, container), cai no arquivo atual com rotação:
+ o comportamento de hoje continua sendo o fallback.
+
+## Cuidados
+
+- `/var/log/omavm` e o README documentam o arquivo como destino; mudar o
+ padrão é mudança visível que precisa de nota no README e no `CLAUDE.md`.
+- Comandos de leitura continuam fora do log (nível Debug), senão o journal
+ enche com poll do mesmo jeito.
+- Mensagens grandes: o datagrama tem limite; o protocolo nativo prevê
+ mandar o conteúdo num memfd selado quando passa do tamanho.
+
+## Fontes
+
+- [Native Journal Protocol – systemd.io](https://systemd.io/JOURNAL_NATIVE_PROTOCOL/)
+- [slogjournal – github.com/systemd/slog-journal](https://pkg.go.dev/github.com/systemd/slog-journal)
+- [go-systemd journal (pure Go)](https://pkg.go.dev/github.com/coreos/go-systemd/v22/journal)
diff --git a/docs/ideias/machine-descartavel.md b/docs/ideias/machine-descartavel.md
new file mode 100644
index 0000000..f324faa
--- /dev/null
+++ b/docs/ideias/machine-descartavel.md
@@ -0,0 +1,38 @@
+# Machine descartável com `-snapshot` do QEMU
+
+## O que outros fazem
+
+O UTM 4 tem um modo de VM descartável: a VM roda normalmente, e nada do
+que acontece nela sobrevive ao desligamento.
+
+## Encaixe na OmaVM
+
+O `CLAUDE.md` trata ambientes descartáveis como conceito de primeira classe
+(`omavm run arch --ephemeral`, seção Ephemeral Environments & Agentic
+Workflows), para Boxes e Machines "quando possível". Para Machines o QEMU já
+resolve isso: com `-snapshot`, as escritas no disco vão para um overlay
+temporário descartado quando a VM termina. É integração de um recurso
+maduro, não um mecanismo novo (Backend Rules).
+
+## Esboço
+
+- `omavm start NAME --ephemeral` (e depois `omavm run ... --ephemeral`)
+ passa `-snapshot` no Start daquela sessão, sem persistir nada no
+ domínio.
+- O card mostra que a sessão é descartável ("As alterações desta sessão
+ serão perdidas ao desligar"), sem esconder a consequência.
+- Casos de uso: testar um instalador, reproduzir um bug em sistema limpo,
+ deixar um agente mexer numa Machine sem risco para o disco.
+
+## Riscos
+
+- `savevm` (Snapshot Manager) durante uma sessão `-snapshot` grava no
+ overlay temporário: o snapshot sumiria ao desligar. O Snapshot Manager
+ precisa recusar ou avisar nessa sessão.
+- O overlay fica em `/var/tmp` por padrão: sessões longas podem encher o
+ disco do host (ver [disco-do-host.md](disco-do-host.md)).
+
+## Fontes
+
+- [UTM 4.0 release notes](https://docs.getutm.app/updates/v4.0/)
+- [UTM (software) – Wikipedia](https://en.wikipedia.org/wiki/UTM_(software))
diff --git a/docs/ideias/modelo-de-ambientes-em-cpp.md b/docs/ideias/modelo-de-ambientes-em-cpp.md
new file mode 100644
index 0000000..185040f
--- /dev/null
+++ b/docs/ideias/modelo-de-ambientes-em-cpp.md
@@ -0,0 +1,39 @@
+# Lista de ambientes como model C++
+
+## Situação
+
+Em 2026-09-28 o Experience Center parou de recriar todos os cards a cada
+mudança de status: `gui/EnvironmentListModel.qml` sincroniza um `ListModel`
+no lugar, por nome, a partir do `backend.environments` (array). A
+documentação do Qt confirma o motivo do bug: com um array JS como model, o
+`ListView` reseta e cria delegates novos para tudo; `ListModel` e
+`QAbstractListModel` atualizam no lugar.
+
+## Próximo passo possível
+
+O jeito idiomático do Qt é o `Backend` expor um `QAbstractListModel`:
+- o C++ já sabe exatamente qual ambiente e qual campo mudou
+ (`enrichEnvironment` atualiza status, guest tools e preview por índice);
+ hoje ele emite `environmentsChanged` para a lista inteira e o QML
+ reconstrói a diferença comparando nomes;
+- com um model C++, cada mudança vira um `dataChanged` só daquela linha e
+ daquele papel (`status`, `preview`…), sem cópia da lista nem comparação
+ em JS;
+- os diálogos (Snapshots, Settings) que hoje procuram o ambiente por nome
+ em `backend.environments` passariam a usar o mesmo model.
+
+## Custo e cuidado
+
+- Mais código C++ (papéis, `rowCount`, `data`, `beginInsertRows`…) e os
+ testes de `gui/tests/backend_refresh_test.cpp` passam a olhar sinais do
+ model em vez de `environmentsChanged`.
+- Há relatos de `dataChanged` não repintar delegates com os quais o usuário
+ interagiu; conferir com o card real (hover, menu aberto) antes de trocar.
+- Só vale a pena se a sincronização em QML ficar lenta ou complicada; com
+ até ~30 ambientes (limite de desenho do Experience Center) ela é barata.
+
+## Fontes
+
+- [Models and Views in Qt Quick – Qt 6.11](https://doc.qt.io/qt-6/qtquick-modelviewsdata-modelview.html)
+- [ListView dataChanged not updating all delegates – Qt Forum](https://forum.qt.io/topic/67523/listview-datachanged-not-updating-all-delegates)
+- [Model-View-Delegate – QML Book](https://qmlbook.github.io/ch07-modelview/modelview.html)
diff --git a/docs/ideias/pasta-compartilhada-automatica.md b/docs/ideias/pasta-compartilhada-automatica.md
new file mode 100644
index 0000000..cc62b6e
--- /dev/null
+++ b/docs/ideias/pasta-compartilhada-automatica.md
@@ -0,0 +1,43 @@
+# Pasta compartilhada que aparece sozinha no guest
+
+## Situação
+
+A Machine compartilha uma pasta do host via virtiofs, mas o guest precisa
+montar a tag `omavm-share` à mão (Settings: "Mount the tag omavm-share in
+the guest"). É o tipo de detalhe de infraestrutura (tag, virtiofs, mount)
+que o `CLAUDE.md` quer fora do fluxo básico (UX Principle #3).
+
+## O que mudou no kernel
+
+Desde a série de Stefan Hajnoczi (2024), o kernel expõe as tags em
+`/sys/fs/virtiofs//tag` e emite um uevent quando um dispositivo virtiofs
+aparece. Com isso, o userspace do guest consegue descobrir e montar as
+pastas sem configuração prévia do nome da tag, e o systemd consegue
+esperar a pasta durante o boot.
+
+## Esboço
+
+A OmaVM não roda nada dentro do guest (`omavm-guest` continua fora do
+escopo), então não pode montar sozinha. O que cabe:
+- Uma **regra udev + unidade systemd** pequena e documentada que o usuário
+ instala no guest uma vez, montando qualquer tag `omavm-*` em
+ `~/OmaVM/` ao ver o uevent. Entregue como arquivo em `contrib/`,
+ opt-in, como a regra do Hyprland.
+- Nas Settings, trocar o texto sobre a tag por "Para ver a pasta dentro do
+ sistema, instale o ajudante da OmaVM no guest" com link para as
+ instruções, e mostrar se o guest já montou a pasta quando o QGA estiver
+ conectado (o QGA pode listar montagens sem agente próprio).
+- Depende de kernel 6.9 ou mais novo no **guest**; em guests antigos, o
+ texto atual (montar à mão) continua valendo.
+
+## Relacionado
+
+Desde 2026-09-28, uma pasta que sumiu do host é avisada no Start com o
+caminho e onde corrigir, e o erro do `virtiofsd` fica em
+`/machines//virtiofsd.log`.
+
+## Fontes
+
+- [virtiofs: export filesystem tags through sysfs – LWN](https://lwn.net/Articles/961448/)
+- [virtiofs — The Linux Kernel documentation](https://docs.kernel.org/filesystems/virtiofs.html)
+- [virtiofs standalone usage (QEMU howto)](https://virtio-fs.gitlab.io/howto-qemu.html)
diff --git a/docs/ideias/progresso-ao-criar-box.md b/docs/ideias/progresso-ao-criar-box.md
new file mode 100644
index 0000000..fbe9c47
--- /dev/null
+++ b/docs/ideias/progresso-ao-criar-box.md
@@ -0,0 +1,44 @@
+# Progresso ao criar uma Box
+
+## Situação
+
+Criar uma Box de uma imagem que ainda não está no host baixa centenas de
+MB dentro do `distrobox create`. Durante esse tempo:
+- a GUI mostra só "Working: creating…", por minutos, sem sinal de avanço;
+- o registro (`environments.json`) fica travado durante todo o
+ `backend.Create`, então outro `create`, `rm`, `settings` ou `snapshot`
+ espera junto. Desde 2026-09-28 a CLI pelo menos avisa no terminal
+ ("waiting for another OmaVM operation to finish…").
+
+## O que o Podman oferece
+
+- `podman pull` mostra barra de progresso no terminal, mas só para humanos.
+- A API REST (`/libpod/images/pull` no socket rootless
+ `$XDG_RUNTIME_DIR/podman/podman.sock`) devolve um fluxo de JSON com
+ **etapas** ("Trying to pull", "Copying blob", "Writing manifest"), mas
+ não bytes baixados: o pedido para ter isso
+ ([containers/podman#24887](https://github.com/containers/podman/issues/24887))
+ continua aberto.
+
+## Esboço
+
+1. Separar o pull do create: `podman pull ` **antes** de travar o
+ registro e só então `distrobox create` (que acha a imagem local e não
+ baixa de novo). O registro fica travado segundos, não minutos, e uma
+ falha de rede aparece como falha de download, não como falha genérica
+ do create.
+2. Repassar as etapas do pull como status: a CLI imprime as linhas no
+ terminal; a GUI mostra "Baixando Fedora (etapa 2 de 4)…" a partir do
+ fluxo JSON da API, sem inventar porcentagem que o Podman não fornece.
+3. Checar antes se a imagem já existe (`podman image exists`) para não
+ mostrar "baixando" à toa.
+
+O pull fica no adapter do Distrobox/Podman (Backend Rules); a Core só vê
+"preparando" e "criando".
+
+## Fontes
+
+- [podman-pull — Podman documentation](https://docs.podman.io/en/latest/markdown/podman-pull.1.html)
+- [How to Use the Podman REST API to Pull Images – OneUptime](https://oneuptime.com/blog/post/2026-03-18-use-podman-rest-api-pull-images/view)
+- [Implement Progress Details in podman pull API – containers/podman#24887](https://github.com/containers/podman/issues/24887)
+- [No way to obtain image pull progress – containers/podman#12341](https://github.com/containers/podman/issues/12341)
diff --git a/docs/ideias/terminal-copiar.md b/docs/ideias/terminal-copiar.md
new file mode 100644
index 0000000..f6c3d09
--- /dev/null
+++ b/docs/ideias/terminal-copiar.md
@@ -0,0 +1,41 @@
+# Copiar do terminal da Box
+
+## Situação
+
+O terminal embutido das Boxes cola (Shift+Insert, Ctrl+Shift+V, bracketed
+paste, desde 2026-09-28) mas **não copia**: não há seleção com o mouse nem
+suporte a programas que copiam por conta própria. Ver também o item de P0
+do `docs/TODO.md` sobre Super+C, que depende de o terminal ter algo para
+copiar com Ctrl+Insert.
+
+## Seleção com o mouse
+
+O mínimo esperado de um terminal: arrastar seleciona, Ctrl+Insert (o que o
+Omarchy manda para terminais no Super+C) e Ctrl+Shift+C copiam, clique duplo
+seleciona uma palavra. A seleção precisa respeitar as células largas (uma
+seleção não pode cortar um CJK ao meio) e o scrollback.
+
+## OSC 52: programas copiando pelo terminal
+
+O OSC 52 é uma sequência de escape com a qual o programa pede ao terminal
+para pôr texto na área de transferência do sistema. tmux e Neovim (que tem
+um provedor OSC 52 embutido) usam isso, e é o que faz "copiar no vim"
+chegar ao Omarchy.
+
+Cuidados:
+- Só **escrita**. Ler a área de transferência via OSC 52 deixa qualquer
+ comando dentro da Box ler o que o usuário copiou no host; o xterm deixa o
+ OSC 52 desligado por padrão por esse motivo, e o suporte a leitura é
+ instável mesmo em tmux.
+- Mesmo a escrita vem de código que roda na Box: um comando não confiável
+ pode trocar o conteúdo da área de transferência. Uma Box compartilha o
+ kernel e o `$HOME` com o host (Security Model), então isso não abre um
+ canal novo, mas a opção deve ter limite de tamanho e poder ser desligada,
+ como o clipboard da Machine já é por padrão.
+
+## Fontes
+
+- [tmux wiki: Clipboard](https://github.com/tmux/tmux/wiki/Clipboard)
+- [On tmux OSC-52 support](https://kalnytskyi.com/posts/on-tmux-osc52-support/)
+- [How to use OSC 52 clipboard for copy only? – neovim discussion #28010](https://github.com/neovim/neovim/discussions/28010)
+- [osc 52 – seankhliao](https://seankhliao.com/blog/12020-05-14-osc-52/)
diff --git a/docs/ideias/terminal-libvterm.md b/docs/ideias/terminal-libvterm.md
new file mode 100644
index 0000000..45d1803
--- /dev/null
+++ b/docs/ideias/terminal-libvterm.md
@@ -0,0 +1,52 @@
+# Terminal da Box sobre libvterm
+
+## A premissa que mudou
+
+O `CLAUDE.md` explica o emulador próprio (`gui/terminal.*`) pela licença:
+"viewers de terminal maduros como QTermWidget são GPL" e o projeto é MIT.
+Mas existe um motor maduro com licença compatível:
+
+- **libvterm** (MIT), a biblioteca de emulação que o Neovim usa, mantida em
+ `neovim/libvterm`. Já está instalada neste host (0.3.3, dependência do
+ `neovim`, com `pkg-config vterm`).
+- O **Qt Creator** embute o libvterm 0.3.3 no terminal integrado dele, o
+ que mostra que a combinação Qt + libvterm é usada em produção.
+
+Isso segue a regra "integre, não reimplemente" (Backend Rules): o
+emulador próprio já precisou de correções que o libvterm resolve há anos,
+como caracteres largos, acentos combinantes e metade de caractere largo
+sobrescrita (corrigidos aqui em 2026-09-28).
+
+## O que mudaria
+
+- `TerminalSession` continua dono do PTY (`forkpty` + `omavm open NAME`);
+ só o parser e o modelo de tela passam para o libvterm (`vterm_input_write`,
+ callbacks de `damage`/`movecursor`/`settermprop`/`sb_pushline`).
+- `TerminalView` continua desenhando com QPainter a partir das células do
+ libvterm (`vterm_screen_get_cell`), que já trazem largura, atributos e
+ cores; a paleta continua vindo do `colors.toml`.
+- Ganhos: cobertura bem maior de sequências (mouse reporting, modos DEC,
+ OSC), reflow testado, menos código próprio para manter.
+
+## Custos e riscos
+
+- Nova dependência de sistema (`libvterm`, `libvterm-dev` no CI).
+- O scrollback é responsabilidade do cliente (callbacks `sb_pushline` e
+ `sb_popline`); o libvterm não faz reflow do histórico ao alargar a
+ janela.
+- É uma decisão de arquitetura: trocar o emulador precisa de acordo antes,
+ não de uma troca incidental numa rodada de bugs (Rules for AI Agents #9).
+- Os testes atuais (`make test-terminal`) viram testes de integração com o
+ libvterm; os de PTY real continuam valendo.
+
+Alternativa registrada: o **kvit-term** (Qt Quick, sobre libvterm) é
+MPL-2.0. O copyleft dele é por arquivo, compatível com um projeto MIT desde
+que os arquivos dele fiquem separados, mas é uma dependência bem maior que
+o libvterm puro.
+
+## Fontes
+
+- [neovim/libvterm](https://github.com/neovim/libvterm)
+- [libvterm 0.3.3 – Qt Creator Documentation (attribution)](https://doc.qt.io/qtcreator/qtcreator-attribution-libvterm.html)
+- [kvit-term](https://github.com/kvit-s/kvit-term)
+- [sff: a terminal using libvterm and Qt](https://github.com/jsbronder/sff)
diff --git a/docs/ideias/terminal-ptyxis.md b/docs/ideias/terminal-ptyxis.md
new file mode 100644
index 0000000..e95f500
--- /dev/null
+++ b/docs/ideias/terminal-ptyxis.md
@@ -0,0 +1,58 @@
+# Terminal da Box: o que o Ptyxis faz
+
+O Ptyxis é o terminal padrão do Fedora Workstation, do RHEL e do Ubuntu,
+feito para containers: descobre Podman, Toolbox e Distrobox sozinho (via
+`ptyxis-agent`), abre uma sessão direto num container e mantém o contexto
+(container ativo e diretório) em abas novas. Três ideias dele cabem no
+terminal embutido das Boxes.
+
+## 1. Avisar antes de fechar com um processo rodando
+
+O Ptyxis acompanha o processo em primeiro plano de cada sessão. Na OmaVM,
+fechar a janela do terminal (ou Ctrl+Alt+Q) no meio de um `dnf upgrade`
+dentro da Box mata o processo sem aviso.
+
+**O jeito óbvio não funciona aqui** (conferido em 2026-09-28): olhar o
+grupo de processos em primeiro plano do nosso PTY (`tcgetpgrp`) veria
+sempre o `podman`, porque o `distrobox enter` roda `podman exec
+--interactive --tty` (`/usr/bin/distrobox-enter`, linhas 379 e 402), que
+cria **outro** PTY dentro do container. O `dnf` fica atrás desse segundo
+terminal, invisível do lado da OmaVM. É por isso que o Ptyxis tem um
+agente (`ptyxis-agent`) e que o problema dele é outro.
+
+Caminhos possíveis, todos com custo:
+- perguntar ao container na hora de fechar (`podman top` ou `ps` via
+ `distrobox enter -- ps`), o que custa um `exec` e pode travar se o
+ engine estiver lento, justamente quando a pessoa quer fechar;
+- sinais do shell da Box via OSC 133/OSC 7 (marcadores de prompt que
+ bash/zsh/fish emitem com integração de shell): se o último evento foi
+ "comando começou" sem "comando terminou", há algo rodando. Não exige
+ processo extra, mas depende da configuração do shell na Box.
+
+Sem uma dessas, perguntar sempre ao fechar seria só incômodo. Precisa de
+decisão antes de implementar.
+
+## 2. Cor do ambiente na janela
+
+O Ptyxis muda a cor da barra conforme a sessão (container, root). A OmaVM
+já tem cor por ambiente (Color tags). Mostrar essa cor no terminal (uma
+faixa fina ou o fundo da barra de status) deixa claro em qual Box se está,
+o que também reforça que aquilo **não** é o host (Security Model: uma Box
+compartilha o kernel e o `$HOME`, e isso não deve ser escondido).
+
+## 3. Abrir outra sessão no mesmo contexto
+
+O Ptyxis abre abas novas no mesmo container e diretório. Um "Nova janela
+nesta Box" que já entre no diretório atual da sessão (lido de
+`/proc//cwd` do processo em primeiro plano, via `distrobox enter`)
+evita repetir o `cd`. Janelas separadas, não abas: o `CLAUDE.md` mantém o
+terminal simples e a organização de janelas é do Hyprland.
+
+Já feito em 2026-09-28, na linha do Ptyxis: a janela não fecha mais quando
+a sessão termina com erro; mostra o motivo e oferece "Try Again".
+
+## Fontes
+
+- [ptyxis(1) — a container-oriented terminal](https://www.mankier.com/1/ptyxis)
+- [7 Features I Like in Ptyxis – It's FOSS](https://itsfoss.com/ptyxis-terminal-features/)
+- [Ptyxis 49.3 with APX containers support – UbuntuHandbook](https://ubuntuhandbook.org/index.php/2026/01/ptyxis-49-3-apx-containers/)
diff --git a/docs/ideias/vsock-ssh.md b/docs/ideias/vsock-ssh.md
new file mode 100644
index 0000000..85d839d
--- /dev/null
+++ b/docs/ideias/vsock-ssh.md
@@ -0,0 +1,54 @@
+# SSH e port forwarding via vsock
+
+## O que outros fazem
+
+O GNOME Boxes reescrito (GTK4, 2026) adiciona um dispositivo VSOCK a cada
+VM. Guests com systemd v256 ou mais recente já expõem SSH nesse canal sem
+configuração de rede, e o Boxes começou a oferecer port forwarding para
+alcançar serviços do guest a partir do host.
+
+## Por que interessa à OmaVM
+
+- `omavm ssh radic` já está nos exemplos do CLI/GUI Contract do `CLAUDE.md`.
+- É integração de uma ferramenta madura (systemd `systemd-ssh-generator` no
+ guest, `systemd-ssh-proxy` no host: `ssh vsock/`), não um canal
+ próprio. Segue a regra "integre, não reimplemente".
+- Serve a agentes: `omavm exec` numa Machine hoje falha com `ErrUnsupported`
+ por falta de canal no guest. O SSH por vsock pode ser esse canal para
+ guests systemd, sem `omavm-guest`.
+
+## Esboço
+
+1. `internal/backend/qemu`: `-device vhost-vsock-pci,guest-cid=`, com CID
+ único por Machine (≥ 3) persistido no domínio ou derivado com checagem de
+ colisão. `/dev/vhost-vsock` precisa estar acessível: reportar em
+ `omavm host`.
+2. `omavm ssh NAME [-- args]` executa `ssh vsock/`. Falha com mensagem
+ clara quando o guest não tem systemd ≥ 256 ou o `sshd` não está ativo.
+3. `Exec` numa Machine: usar esse canal quando disponível, sem fingir suporte
+ quando não estiver.
+
+## Riscos e dúvidas
+
+- Guests sem systemd (Haiku, FreeBSD, Alpine) não ganham nada; a UI não deve
+ sugerir que ganham.
+- Autenticação: chaves do usuário do host; nunca gerar credencial silenciosa.
+- **Exposição a containers do host (oss-security, jan/2026).** O AF_VSOCK
+ não é isolado por namespace de rede: qualquer processo do host, inclusive
+ um container, alcança o `sshd` que o systemd ≥ 256 expõe no guest. Para a
+ OmaVM isso significa que uma **Box** consegue chegar ao SSH de uma
+ **Machine**, e só a autenticação separa as duas. Pelo Security Model, a
+ UI não pode esconder isso. Consequências para o desenho:
+ - dispositivo vsock **opt-in** por Machine, nunca adicionado a todas;
+ - explicar na UI que o canal é alcançável por outros processos do host,
+ incluindo Boxes;
+ - no guest, a mitigação é `systemctl mask sshd-vsock.socket`, citada como
+ alternativa de quem não quer o canal.
+ O mesmo vale para o CID: ele é global no host, não por usuário.
+
+## Fontes
+
+- [The Future of GNOME Boxes – Felipe Borges](https://blogs.gnome.org/feborges/future-of-boxes/)
+- [GNOME Boxes Preparing To Deliver Much Improved Virtualization Experience – Phoronix](https://www.phoronix.com/news/GNOME-Boxes-2026)
+- [systemd-vmspawn(1)](https://man7.org/linux/man-pages/man1/systemd-vmspawn.1.html)
+- [oss-security: Systemd vsock sshd (2026-01-02)](https://www.openwall.com/lists/oss-security/2026/01/02/1)
diff --git a/docs/ideias/windows11-tpm-secureboot.md b/docs/ideias/windows11-tpm-secureboot.md
new file mode 100644
index 0000000..8732ee5
--- /dev/null
+++ b/docs/ideias/windows11-tpm-secureboot.md
@@ -0,0 +1,37 @@
+# Windows 11 sem ajustes manuais (TPM + Secure Boot)
+
+## O que outros fazem
+
+O novo GNOME Boxes instala o Windows 11 sem workarounds: configura Secure
+Boot (firmware UEFI/OVMF com chaves) e um TPM virtual automaticamente. O
+Quickemu também cria VMs Windows e macOS "out of the box".
+
+## Encaixe no escopo
+
+A OmaVM "não é uma ferramenta exclusiva para Windows" (Scope/Non-Goals),
+mas Windows é um caso real de Machine. O instalador do Windows 11 recusa
+máquinas sem TPM 2.0 e Secure Boot. Hoje a Machine usa BIOS (SeaBIOS) e não
+tem TPM, então essa instalação falha, e o usuário não tem como descobrir o
+motivo pela UI.
+
+## Esboço
+
+- Firmware UEFI (OVMF) como padrão das Machines novas, com `OVMF_VARS`
+ próprio por Machine no diretório de estado.
+- `swtpm` por Machine (processo auxiliar, como o `virtiofsd` já é), ligado
+ por `-tpmdev emulator`.
+- `omavm host` reporta se OVMF e `swtpm` estão instalados.
+- A escolha entre BIOS e UEFI é detalhe interno, não uma pergunta na criação
+ (UX Principle #4); Machines existentes continuam como estão.
+
+## Riscos
+
+- Trocar BIOS por UEFI numa Machine já instalada quebra o boot: só vale para
+ Machines novas.
+- O `swtpm` guarda estado sensível (chaves do BitLocker, por exemplo): o
+ diretório precisa de permissões restritas e entrar no Remove e no Clone.
+
+## Fontes
+
+- [The Future of GNOME Boxes – Felipe Borges](https://blogs.gnome.org/feborges/future-of-boxes/)
+- [Quickemu – Chris Titus Tech](https://christitus.com/quickemu/)
diff --git a/docs/review-history.md b/docs/review-history.md
new file mode 100644
index 0000000..bbc006f
--- /dev/null
+++ b/docs/review-history.md
@@ -0,0 +1,239 @@
+# Histórico da revisão de UI/UX — 2026-09-27
+
+Registros da revisão anterior, preservados para consulta. Os builds e testes interativos descritos abaixo não foram repetidos na limpeza editorial. As pendências atuais estão em [TODO.md](TODO.md).
+
+## P0 — Confiança nas ações e proteção dos dados
+
+Todos os sete itens abaixo foram implementados em 2026-09-27 (sessão anterior a esta). Evidência comum: `make build-gui` limpo, `go vet ./...`/`gofmt -l .` limpos (nenhum arquivo Go tocado), e um lançamento real do `omavm-gui` no desktop Omarchy do usuário confirmando visualmente o novo estado vazio/erro renderizando sem erros de QML. Layout/resize contínuo e leitor de tela permanecem para P1 — aqui só o comportamento de confiança/recuperação de dados foi coberto.
+
+- [x] **Eliminar ações ignoradas durante operações.** Sincronizar a disponibilidade dos controles com `backend.busy`; informar o motivo de bloqueio. Começar com o bloqueio global existente, sem introduzir fila ou concorrência nova.
+ - Aceite: clicar novamente em criar, salvar ou iniciar nunca produz sucesso aparente sem execução; a operação em andamento fica identificada.
+ - Base: `gui/backend.cpp`, `gui/Main.qml`, diálogos e cards.
+ - Evidência: `Backend::busyAction`/`beginBusy` (gui/backend.h,cpp); botões e itens de menu com `enabled: !backend.busy` em `EnvironmentCard.qml`/`Main.qml`; rejeição por busy emite `message()` explicando o que está em andamento em vez de retornar em silêncio.
+- [x] **Preservar formulários até a confirmação de sucesso.** Criação e configurações devem apresentar espera e erro no próprio fluxo; fechar após sucesso e permitir nova tentativa com os dados preenchidos.
+ - Aceite: nome inválido, dependência ausente e falha de criação/salvamento não apagam o trabalho do usuário.
+ - Base: `gui/CreateDialog.qml`, `gui/SettingsDialog.qml`, `gui/backend.cpp`.
+ - Evidência: `Backend::actionFinished(tag, ok, text)` correlaciona a ação do próprio diálogo; `CreateDialog`/`SettingsDialog` só fecham (`dialog.close()`) quando `ok===true` para a tag "create"/"configure", mantendo campos e mostrando `errorText` no próprio rodapé caso contrário.
+- [x] **Tornar erros persistentes e acionáveis.** Diferenciar sucesso, aviso e erro; reservar toast temporário para informação não crítica. Disponibilizar detalhes copiáveis e recuperação contextual.
+ - Aceite: a causa e o próximo passo continuam consultáveis após 4,5 segundos; mensagens técnicas ficam em detalhes. Uma notificação nativa recebida com a janela sem foco não é o único registro do erro: ao retornar ao app, o usuário encontra contexto e recuperação.
+ - Base: `gui/Main.qml` e emissão de mensagens do backend.
+ - Evidência: banner persistente (`errorBanner` em `Main.qml`) substitui o toast para `error===true`, com botão "Copy details" (`Backend::copyToClipboard`, `QGuiApplication::clipboard()`) e dispensa manual; só se limpa quando uma ação subsequente termina com sucesso (`onActionFinished`). Não há notificação nativa implementada ainda (`CLAUDE.md` só lista toast in-app), então o banner é hoje o único e persistente registro — a cláusula fica satisfeita por ausência de conflito, não por integração com notificações do sistema.
+- [x] **Proteger restauração e exclusão de snapshots.** Confirmar ambiente, snapshot e consequência antes de executar; manter o histórico em caso de falha.
+ - Aceite: nenhuma restauração ou exclusão ocorre por um clique acidental; cancelar não modifica o ambiente.
+ - Decisão de linguagem: avaliar “Restaurar…” contra o atual “Go To”. `CLAUDE.md`, UX Principle 9, prescreve “Go To”; qualquer mudança do verbo deve atualizar essa diretriz. A confirmação pode ser entregue mantendo o verbo atual.
+ - Evidência: `confirmGoTo`/`confirmDeleteSnapshot` em `SnapshotsDialog.qml`, diálogos modais com `Dialog.Cancel | Dialog.Yes`; verbo "Go To" mantido, `CLAUDE.md` não precisou mudar.
+- [x] **Atualizar snapshots dentro do diálogo aberto.** Reconciliar o ambiente selecionado com o resultado atualizado, usando identidade estável.
+ - Aceite: criar/excluir atualiza a lista sem fechar o diálogo; falha mantém nome digitado e itens válidos.
+ - Base: `gui/SnapshotsDialog.qml`, `gui/Main.qml`, `gui/backend.cpp`.
+ - Evidência: `Connections.onEnvironmentsChanged` re-busca `dialog.environment` por `name` (identidade estável) em `backend.environments` sem fechar o diálogo; `newLabel.text` só é limpo em `onActionFinished("snapshot-create", true, ...)`, nunca antes de confirmar sucesso.
+- [x] **Explicar a retenção de snapshots.** Exibir o limite e avisar quando a criação descartará o mais antigo, conforme a política já existente no Core.
+ - Aceite: o usuário sabe qual ponto de recuperação será removido antes de confirmar a criação que atinge o limite.
+ - Evidência: `retentionLimit` em `SnapshotsDialog.qml` (usa `settings.snapshot_limit`, com fallback 10 espelhando `defaultSnapshotLimit` em `internal/core/environment.go`, já que o CLI só emite o campo quando customizado); aviso nomeando o snapshot mais antigo quando `snapshots.length >= retentionLimit`.
+- [x] **Distinguir carregamento, vazio e falha.** Cobrir lista de ambientes e aplicações; limpar ou associar os resultados ao ambiente correto ao trocar de seleção.
+ - Aceite: erro ao carregar não aparece como “nenhum ambiente”; aplicações de uma Box não aparecem como pertencentes a outra.
+ - Evidência: `backend.listError` (Main.qml, estado de erro distinto do vazio, com "Try Again"); `backend.appsEnvironment`/`appsError`/`appsLoading` (AppsDialog.qml) — a lista só é exibida quando `appsEnvironment === dialog.environment.name`, então uma resposta atrasada de uma Box anterior nunca aparece associada à Box atual.
+
+## Implementações parciais
+
+Em progresso (2026-09-27): `SettingsDialog.qml` agora limita `height` a `parent.height - 32` e envolve o conteúdo num `ScrollView` (Salvar/Cancelar ficam no `footer`, fora da área rolável); "Installation media" (desconectar ISO) virou grupo próprio, separado de "Shared folder". Build (`make build-gui`) e um lançamento real confirmam que a janela carrega sem erro de QML, mas o redimensionamento em 320×420/640×480/960×640 e escalas de 150–200% ainda não foi exercitado interativamente — não marcar concluído até essa validação.
+
+Em progresso (2026-09-27): antes, o botão principal (`EnvironmentCard.qml`) desaparecia completamente abaixo de 500px, restando só o menu "⋮" — corrigido para nunca desaparecer, virando um botão ícone-apenas ("▶", com `Accessible.name`/tooltip mantendo o rótulo) abaixo de 500px. Verificado visualmente com dados de teste numa janela larga (botão em texto completo); o comportamento exato em 320px ainda não foi capturado interativamente.
+
+Em progresso (2026-09-27): `AppsDialog.qml` troca "Remove" por "Remove from menu"; o diálogo de exclusão de ambiente (`Main.qml`, `confirmDelete`) agora diferencia a consequência por kind ("disco virtual e cada snapshot são removidos" para Machine vs. "o container é removido; arquivos na home não são tocados" para Box) em vez do texto genérico anterior. Revisão de Desktop/Development Box em todo o restante da interface e dos demais verbos de confirmação ainda não foi feita.
+
+Em progresso (2026-09-27): `▣` foi trocado por `iconComponent` (o slot que `/usr/share/omarchy/shell/Ui/BarIconButton.qml` já expõe para isso) renderizando `contrib/dev.omavm.bar/icon.svg` — uma variante monocromática derivada de `data/icons/dev.omavm.app.svg` — recolorida via `MultiEffect` (`QtQuick.Effects`) para seguir `button.foreground`/`activeColor` como qualquer ícone nativo da barra, em vez de uma cor fixa. `qmllint` não acusa erro estrutural (os avisos restantes são só sobre os módulos `Quickshell`/`qs.*`, que ele não enxerga fora do ambiente do shell). Não testado dentro do Quickshell real (exige `omarchy plugin enable`, um passo manual do usuário) nem nos temas/escalas de P1 — não marcar concluído até essa validação interativa.
+
+Junto (mesmo commit): todos os glifos de fonte usados como ícone na própria GUI Qt (`+`, `↻`, `▣`/`>_` dos cards, `▶` do botão compacto, `⋮`, `⚠`, `✕`) foram trocados por SVGs reais em `gui/icons/`, via um componente reutilizável `gui/Icon.qml` (Image + MultiEffect, mesmo mecanismo do widget) para os que são ilustração, e via `icon.source`/`icon.color` nativo do Qt Quick Controls para os que são `Button`/`ToolButton`. Verificado com `qmllint` (sem erros) e um lançamento real sandboxed (`XDG_STATE_HOME` isolado, sem tocar dados reais) confirmando os ícones renderizando e tintados corretamente por tema.
+
+Implementado e verificado (2026-09-27): P1 "Atualizar estados sem depender do botão Refresh" — `Main.qml` ganhou um `Timer` (3000ms, `running: win.active`) que chama `backend.refresh()` enquanto a janela tem foco; não roda quando `backend.busy` (o próprio `refresh()` já rejeitaria com uma mensagem, mas o Timer evita nem tentar). Antes de ligar isso, corrigi um bug latente que o polling tornaria fácil de disparar: `Backend::enrichEnvironment` (`gui/backend.h,cpp`) escrevia em `m_environments[index]` por índice cru quando um `status`/`integration`/`preview` terminava — como `refresh()` já libera `busy` antes de esperar essas sub-chamadas, um novo ciclo de poll podia substituir `m_environments` inteiro enquanto sub-chamadas do ciclo anterior ainda estavam voando, e um resultado atrasado podia gravar no índice errado do array novo. Corrigido com um contador `m_environmentsGeneration`, incrementado a cada `refresh()` bem-sucedido; cada `enrichEnvironment`/sub-chamada carrega a geração em que nasceu e descarta o resultado se a geração mudou. Verificado com um teste automatizado (sem GUI/humano no loop): Machine criada e iniciada só via CLI, com a GUI aberta e nunca tocada por mim, apontando pra um `XDG_STATE_HOME` isolado; o card foi de "Stopped"/"Start" para "Running"/"Open" com preview real do framebuffer em ~4s, dentro do limite de 5s do aceite. `qmllint` sem erros, `make build-gui` limpo, `go test ./...` (suite inteira) passa.
+
+Correção posterior do flickering periódico (2026-09-27): o relato indicou piscada em todas as telas enquanto o Experience Center permanecia aberto, inclusive com a janela parada; o viewer sozinho não piscava. O polling de 3s acima substituía a lista inteira por valores ainda sem status/preview, emitia repetidamente `environmentsChanged` e alternava `busy`, recriando cards, miniaturas e estados visuais. `Main.qml` agora chama `backend.poll()`; a consulta não altera `busy`, preserva os dados enriquecidos pelo mesmo ID/nome/kind e emite mudanças apenas quando há diferença. Uma operação iniciada durante a consulta invalida sua resposta atrasada. Previews ficam estáticos enquanto a Machine permanece ligada, evitando recaptura/recarga periódica; ao parar, o preview é removido. `gui/tests/backend_refresh_test.cpp` verifica que duas consultas idênticas não emitem `busyChanged` nem uma atualização redundante do modelo. `make test-backend`, `make build-gui`, `git diff --check` passaram; binário iniciou por 4s em modo offscreen sem erros QML. A confirmação visual na sessão real continua pendente.
+
+Em progresso (2026-09-27, resposta a "sem animação nem nada"): adicionadas transições pontuais onde antes tudo trocava de estado instantaneamente — `gui/Icon.qml` anima a cor de recolorização (`Behavior on colorizationColor`) em vez de trocar de tom abruptamente ao mudar tema/estado; `EnvironmentCard.qml` anima a cor do indicador/rótulo de status, faz o ícone de tipo (machine/box) e a miniatura (`preview`) alternarem com crossfade em vez de aparecer/sumir de repente, pulsa suavemente o ponto de status enquanto `transitioning` (starting…/stopping…) e eleva a `Material.elevation` do card ao passar o mouse; `Main.qml` anima a entrada/saída do banner de erro (opacidade + leve deslocamento vertical) e do `BusyIndicator` (fade), e a `ListView` de ambientes ganhou transições `populate`/`add`/`remove`/`displaced` (fade + leve slide) em vez de cards aparecendo/sumindo/pulando de posição sem aviso; `CreateDialog.qml` faz um fade-in ao trocar de passo no assistente em vez de cortar direto para o próximo. Nenhuma dessas mudanças toca lógica/backend — só apresentação. Verificado com `qmllint` (sem erros), `make build-gui` limpo e um lançamento sandboxed confirmando que a tela carrega sem quebrar; as animações em si (hover, pulso, fade) não podem ser confirmadas por captura estática — pendente de validação visual interativa por quem consegue ver o app rodando.
+
+### Achados da auditoria (2026-09-27, leitura de código — não reproduzido em host real)
+
+Auditoria de código de `internal/backend/qemu/` e `internal/core/service.go`. Os itens abaixo não marcam nenhum item acima como concluído (o aceite de cada um exige reprodução, não só leitura); registram caminho de código, reprodução proposta, impacto e prioridade para quando a reprodução acontecer.
+
+- **Concorrência Start/Start — reproduzida e corrigida (2026-09-27).** Confirmado em ambiente descartável (`XDG_STATE_HOME` isolado, Machine `racetest` sem ISO, `--image ""`): dois `omavm start racetest` disparados em paralelo contra uma Machine parada. Resultado real (não a hipótese original de "dois processos QEMU corrompendo o disco"): **apenas um** `qemu-system-x86_64 -daemonize -pidfile qemu.pid` venceu; o outro falhou rápido com `qemu-system-x86_64: cannot create PID file: Cannot lock pid file: Resource temporarily unavailable` — o próprio `-pidfile` do QEMU usa `flock`, então nenhum segundo processo chegou a existir de fato. O gap real não era corrupção de disco, era esse erro cru vazando para quem perdeu a corrida (parecia uma falha real de start, não "a Machine já está subindo"). Corrigido em `qemu.go`'s `Start()`: se `qemu-system-x86_64` falha, checar `isRunning()` de novo antes de propagar o erro — se a Machine está rodando (a outra chamada venceu), tratar como sucesso idempotente em vez de repassar o erro cru. Reproduzido de novo após a correção: as duas chamadas retornam limpo, um único processo QEMU. `go test ./internal/backend/qemu/...` continua passando.
+ - Aceite (parcial): a parte Start/Start do item de P0 está reproduzida, corrigida e reverificada. A parte de snapshots (GoToSnapshot concorrente com CreateSnapshot/RemoveSnapshot) ainda não foi reproduzida — ver item abaixo.
+- **`GoToSnapshot` vs `CreateSnapshot`/`RemoveSnapshot` — reproduzido e corrigido (2026-09-27).** Confirmado em ambiente descartável, Machine parada (`snaprace`, sem ISO): `omavm snapshot create` e `omavm snapshot go-to` disparados em paralelo. Resultado real: nenhuma corrupção nem inconsistência de registro — `qemu-img` tem locking de imagem próprio, então quem perdeu a corrida falhou limpo com `qemu-img: Could not open '...disk.qcow2': Failed to get "write" lock. Is another process using the image?`. O registro (`environments.json`) ficou correto (a criação que falhou nunca foi persistida). O gap real, de novo, era um erro técnico cru vazando para quem perdesse a corrida, não perda de dados. Corrigido fazendo `Service.GoToSnapshot` (`service.go`) segurar o mesmo `store.Lock()` que `CreateSnapshot`/`RemoveSnapshot` já seguram durante toda a chamada ao backend — serializa as três operações no nível do Core em vez de deixar a corrida chegar ao `qemu-img`. Reproduzido de novo após a correção, numa Machine nova: as duas chamadas (`create`/`go-to`) concorrentes terminam com exit 0 e o registro reflete os dois snapshots corretamente. `go test ./...` (suite inteira) continua passando.
+ - Caminho com a Machine **rodando** (savevm/loadvm/delvm via QMP em vez de `qemu-img` direto) também verificado: Machine real ligada (`snaprun`, sem ISO), `create`+`go-to` concorrentes terminam com exit 0 nos dois, registro com os dois snapshots e Machine de volta a "running" após o go-to (o ciclo `stop`/`loadvm`/`cont` de `GoToSnapshot` completou corretamente mesmo serializado atrás do lock). Considerar o item de P0 fechado para os cenários testados; `go test ./...` (suite inteira) passa.
+- **Comunicação QMP (item "Auditar comunicação QMP") já está bem coberta.** `qmpExecute` (`qmp.go:15-65`) já lida com o handshake de capabilities, ignora eventos intercalados até achar `return`/`error` (loop explícito), e usa `SetDeadline` para não bloquear indefinidamente. `lifecycle_test.go` já testa isso com um servidor QMP falso (`net.Listen("unix", ...)`), sem depender de QEMU real — cobre desligamento lento, falha de desligamento e snapshot com Machine rodando. Não achei um teste que force especificamente "resposta ausente" (timeout) ou "conexão cai no meio do comando"; considerar item fechado para o que já existe, com essas duas lacunas pontuais registradas caso vire prioridade.
+- **Falha de inicialização tem diagnóstico inconsistente (item "Antecipar falhas de inicialização").** `virtiofsdPath()` (`qemu.go:156-164`) dá um erro amigável ("virtiofsd not found (install the virtiofsd package)") quando o binário não existe. `qemu-system-x86_64`/`qemu-img` não têm o mesmo tratamento: se o binário não existir, `runOutput` (`qemu.go:536-540`) devolve o erro cru do Go (`exec: "qemu-system-x86_64": executable file not found in $PATH`) embrulhado em `fmt.Errorf("qemu-system-x86_64: %w: %s", err, out)` — sem a mesma dica de instalação. Falta de acesso a `/dev/kvm` não é verificada antes; o próprio QEMU recusa e o stderr é repassado (`%s` no erro), então isso não fica escondido, só não é "antecipado".
+ - Impacto: baixo-médio — mensagem tecnicamente correta, mas menos acionável que o padrão já usado para `virtiofsd`/`omavm-gui`.
+ - Prioridade: P1 (alimenta a tarefa "Tornar pré-requisitos e recursos compreensíveis").
+- **Limpeza de socket incompleta em `Start` (item "Antecipar falhas de inicialização").** `qemu.go:87-91` remove sockets VNC e QGA obsoletos antes de iniciar, mas não remove `qmpPath(name)` da mesma forma — um `qmp.sock` deixado por uma saída suja pode impedir o bind do listener QMP na próxima inicialização. Não confirmei em host real se isso já causa falha (depende de como QEMU/glib tratam um socket path existente), só que a assimetria de tratamento existe no código.
+ - Prioridade: P1, correção pontual e pequena quando priorizada.
+- **Capacidades do guest (item "Verificar capacidades reais do guest") parcialmente instrumentadas.** `Integration()` (`qemu.go:458-470`) já distingue Machine parada, QGA inacessível e QGA conectado — mas só reporta o *canal* QGA, não valida clipboard/pasta compartilhada/áudio individualmente (o comentário em `qga.go` e o histórico em `CLAUDE.md` já deixam isso explícito: "QGA conectado não comprova clipboard"). Nenhuma matriz de guests/drivers testados existe no repositório — isso exige testes manuais com um guest real, fora do alcance desta auditoria de código.
+- **Diagnóstico de falhas (item "Melhorar diagnóstico") já herda o trabalho de P0.** Erros do backend qemu (`fmt.Errorf(..., err, out)`) chegam à CLI/GUI como texto técnico completo; com o P0 já implementado, a GUI expõe isso no banner persistente com botão de copiar. Não há redação de um "resumo compreensível" separado da causa técnica — hoje é a mesma string nos dois lugares. Considerar suficiente por ora (não esconde nada), mas registrar como possível melhoria de P2 se usuários reais acharem o texto denso demais.
+- **Medição de desempenho (item "Medir recursos e desempenho") não foi feita.** Não existe nenhuma baseline registrada (tempo até QMP disponível, uso de CPU/memória em repouso, etc.) em nenhum lugar do repositório ou deste documento. Isso exige execução em host real com hardware/guest documentados — não é uma tarefa de leitura de código.
+- **Display/input durante transições (item "Validar display e entrada")** depende do viewer (`gui/vncclient.cpp`, `gui/vncview.cpp`), já parcialmente coberto por `make test-viewer` (protocolo) segundo `CLAUDE.md`, mas a validação com um guest gráfico real (resize, teclado acentuado, reconexão) não foi executada nesta sessão.
+
+## Sessão de 2026-09-27 (continuação): diagnóstico QEMU e fluxo de criação
+
+Duas lacunas pontuais já registradas na auditoria acima foram corrigidas nesta sessão:
+
+- **Diagnóstico de binário ausente.** `internal/backend/qemu/qemu.go` ganhou `qemuBinaryPath`/`runQEMU`/`qemuErr`, mesmo padrão de `virtiofsdPath`: `qemu-img`/`qemu-system-x86_64` ausentes agora falham com `" not found (install it with: sudo pacman -S qemu-desktop)"` (nome do pacote conforme `packaging/omavm/PKGBUILD`'s `optdepends`) em vez do erro cru do Go. Aplicado nos cinco pontos de chamada (`Create`, `Start`, `CreateSnapshot`, `GoToSnapshot`, `RemoveSnapshot`). Teste novo: `TestMissingBinaryDiagnostic` (isola `PATH` para um diretório vazio via `t.Setenv`).
+- **Limpeza de socket incompleta.** `Start()` agora remove `qmpPath(name)` obsoleto junto com VNC/QGA, fechando a assimetria identificada.
+
+Trabalho novo em P1, seguindo a ordem domínio → backend → Core → CLI → GUI:
+
+- **Recursos no momento da criação.** `internal/core/service.go`'s `Create` valida `Settings.CPUs`/`MemoryMiB` com as mesmas faixas que `Configure` já aplica (1–64 CPUs, 256–262144 MiB) e recusa com `ErrUnsupported` se usado com Box — mesma disciplina de "Machines only" já usada para `DisconnectISO`/`SharedPath`. CLI (`cmd/omavm/main.go`) ganhou `create --cpus`/`--memory-mib`. Teste novo: `TestCreateHardwareSettingsRequireMachine`. Verificado manualmente via CLI real (binário compilado, `XDG_STATE_HOME` isolado): `create --kind machine --cpus 4 --memory-mib 4096` seguido de `settings --json` confirma persistência (`{"cpus":4,"memory_mib":4096,...}`); `create --kind box --cpus 4` falha limpo com a mensagem `ErrUnsupported`.
+- **`CreateDialog.qml` — resumo, validação de nome e explicação do fluxo.** Novo passo final "Ready to create" mostra tipo, imagem/ISO, nome e (para Machine) `SpinBox` de CPUs/memória com os mesmos limites de `SettingsDialog.qml`, alimentando `backend.createEnvironment(...)` (assinatura estendida em `gui/backend.h,cpp` para `cpus`/`memoryMiB`, só enviados ao CLI quando `kind=="machine"`). Validação de nome (`validateName()`) espelha `validateEnvironmentName` do Core, erro exibido junto ao campo com foco devolvido a ele; Enter e o botão "Continue" passam pelo mesmo handler, então seguem a mesma checagem. O passo de resumo também explica o ciclo de instalação (iniciar abre o instalador → desligar → desconectar ISO em Settings → iniciar pelo disco) antes da criação. Os passos 0/1 ganharam exemplos concretos por tipo e deixaram de sugerir que Box não abre aplicação gráfica.
+ - Evidência: `go build ./...`, `go vet ./...`, `gofmt -l .` e `go test ./...` (suite inteira) limpos; `qmllint gui/CreateDialog.qml` sem erro estrutural (só os avisos de contexto `backend` já esperados, mesmo padrão dos demais diálogos). `make build-gui` não pôde rodar nesta sessão: `build/gui` ficou root-owned por uma sessão anterior e o usuário optou por corrigir a posse depois — build real e validação visual/interativa (resize, temas, jornada completa de instalação) ficam pendentes.
+- Corrigido de junto: `TestConfigureMachineSettings` (`internal/core/service_test.go`) usava `Image: "system.iso"` sem esse arquivo existir — funcionava antes da validação de ISO existente ter sido adicionada a `Create` (mudança não commitada de sessão anterior) e quebrava `go test ./...`. Ajustado para criar um arquivo ISO falso real em `t.TempDir()`.
+
+## Sessão de 2026-09-27 (continuação): `make install` não substituía a versão antiga do plugin Quickshell
+
+Pedido do usuário: evitar que uma versão antiga "prevaleça" sobre a nova após `make install`. Investigação: binários (`install -Dm755`) e o `.desktop`/ícone já são substituição atômica de arquivo único (confirmado com `stat -c %i` antes/depois de um `install` real — inode muda, então um processo já em execução usando o binário antigo continua seguro, só um próximo lançamento pega o novo). O real ponto fraco era `install-quickshell-plugin`: `cp -r contrib/dev.omavm.bar/. $(QS_PLUGIN_DIR)/` só adiciona/sobrescreve, nunca remove — um arquivo renomeado ou removido da origem entre duas instalações ficava para sempre em `~/.config/omarchy/plugins/dev.omavm.bar/`. Confirmado ao vivo nesta sessão: o diretório instalado (de 2026-09-26) ainda tinha o `OmaVM.qml` antigo (2905 bytes) e não tinha `icon.svg` (adicionado depois, parte do trabalho de ícone do widget já registrado acima), enquanto a árvore de código já tinha os dois arquivos atualizados.
+
+Corrigido em `Makefile`'s `install-quickshell-plugin`: `rm -rf $(QS_PLUGIN_DIR)` antes de recriar e copiar, tornando o alvo um espelho exato de `contrib/dev.omavm.bar/` a cada instalação, em vez de uma cópia aditiva. `uninstall-quickshell-plugin` já fazia remoção completa (sem mudança). Comportamento de habilitação manual (nunca `omarchy plugin enable` automático) preservado sem alteração.
+
+Evidência: `make install-quickshell-plugin` executado de verdade nesta sessão; `diff -rq contrib/dev.omavm.bar/ ~/.config/omarchy/plugins/dev.omavm.bar/` não acusa nenhuma diferença após a correção (antes, o `OmaVM.qml` divergia e faltava `icon.svg`). Não há estado do usuário dentro desse diretório para preservar — `manifest.json`/`README.md`/QML/ícone são só o que este projeto publica; o estado de habilitação do plugin vive no registro do próprio Quickshell (`PluginRegistry.qml`), fora dessa pasta.
+
+## Sessão de 2026-09-27 (continuação): `make uninstall` não removia Environments (Boxes/Machines)
+
+Pedido do usuário: "os distrobox criados pelo omavm não são deletados junto do uninstall". Primeiro verifiquei se havia um bug funcional em `omavm remove` em si (mais grave que uma lacuna do Makefile): criei uma Box real (`alpine:latest`) via CLI e removi — confirmado que `Service.Remove`/`distrobox.Backend.Remove` já funcionam corretamente (`distrobox list`/`podman ps -a` ficam vazios depois). O gap real era o alegado: `make uninstall` (desinstalar o app) nunca tocava em Environments — por design (desinstalar o app não deve destruir containers/discos do usuário silenciosamente), mas sem nenhum aviso, então um usuário não tinha como saber que sobrou algo nem um caminho pronto para limpar.
+
+Adicionado ao `Makefile`:
+- `uninstall` agora avisa (sem apagar nada) quando ainda existem Environments registrados, apontando para o novo alvo.
+- `uninstall-environments` (novo, não encadeado em `install`/`uninstall`): lista os Environments via `omavm list --json`/`list`, explica a consequência por kind (Box: só o container, home intocada; Machine: disco e snapshots), pede confirmação textual (`digite 'yes'`) e só então chama `omavm remove ` — nunca comandos brutos de `podman`/`qemu-img` — para cada um. `CONFIRM=1` pula o prompt para uso não interativo. Falha fechada: sem TTY (`read` recebe EOF), aborta sem remover nada.
+
+Evidência: exercitado de ponta a ponta com `XDG_STATE_HOME` isolado — criada uma Box real (`alpine:latest`) e uma Machine real; `make uninstall-environments` sem `CONFIRM` e respondendo "no" preservou as duas (confirmado via `omavm list`, `distrobox list`, `podman ps -a`); com `CONFIRM=1` removeu as duas de verdade — `distrobox list`/`podman ps -a` ficaram vazios e o diretório de estado da Machine (`.../machines/mtest2`) deixou de existir (disco incluído), registro (`environments.json`) ficou vazio. `go build/vet/test` (suite inteira) continuam limpos — nenhum arquivo Go tocado nesta mudança. README atualizado explicando a separação `uninstall`/`uninstall-environments`.
+
+## Sessão de 2026-09-27 (continuação): overflow de texto no `CreateDialog` e animações ausentes em três diálogos
+
+Pedido do usuário: "os textos estão dando overflow, e não temos animações". `build/gui` já estava com posse corrigida pelo usuário nesta sessão, permitindo um `make build-gui` real pela primeira vez desde o início dessa frente de trabalho.
+
+- **Overflow confirmado e corrigido.** Os dois botões de escolha de intenção do passo 0 do `CreateDialog.qml` (texto expandido com exemplos numa sessão anterior desta mesma frente) usavam `text: "Título\nDescrição\nExemplos..."` com `Layout.preferredHeight: 128` fixo. Um `Button` do Qt Quick Controls não quebra linha automaticamente (só respeita `\n` literal) — na largura real do diálogo (`680 - 24*2 ≈ 632px` de conteúdo), a frase de exemplos do Development Box era mais larga que o botão e vazava pela borda direita. Confirmado renderizando o layout exato (cópia fiel da estrutura real, largura idêntica) via `qml6` + captura de tela (`grim`) antes e depois da correção — nenhuma alteração nos dados reais do usuário, só um harness isolado em `/tmp`. Corrigido substituindo `text:` por um `contentItem` próprio (`ColumnLayout` com `Label`s `wrapMode: Text.Wrap`), removendo a altura fixa (agora segue o conteúdo). Reconfirmado sem overflow na mesma largura. `qmllint` sem erro estrutural; `make build-gui` limpo.
+- **Animações ausentes em `SettingsDialog.qml`, `SnapshotsDialog.qml` e `AppsDialog.qml`.** A rodada anterior de "adicionar animações" (ver acima) só tocou `Icon.qml`, `EnvironmentCard.qml`, `Main.qml` e `CreateDialog.qml` — esses três diálogos, prováveis os mais usados no dia a dia (Settings sempre; Snapshots/Apps sempre que existe Machine/Box), ficaram de fora e trocavam de estado instantaneamente. Adicionado, no mesmo padrão já usado em `Main.qml`: `SnapshotsDialog.qml` e `AppsDialog.qml` ganharam as mesmas transições `populate`/`add`/`remove`/`displaced` (fade + leve slide) na `ListView` de snapshots/apps; o erro de criação de snapshot e o erro do rodapé de Settings passaram a ter `Behavior on opacity` (fade) em vez de aparecer/sumir sem transição; as bolinhas de cor em Settings ganharam `Behavior on border.width` na seleção. Nenhuma lógica de negócio tocada — só apresentação, mesma disciplina da rodada anterior.
+
+Evidência: `qmllint` sem erro estrutural nos quatro arquivos tocados; `make build-gui` limpo. O overflow foi reproduzido e reverificado visualmente via harness isolado (`qml6`/`grim`, fora do app real). As transições de lista em si (como as de `Main.qml` já registradas antes) não são verificáveis por captura estática — pendente de validação visual interativa por quem consegue ver o app rodando ao vivo.
+
+**Observação à parte, não resolvida:** durante a investigação, testar navegação por teclado no app real (`wtype -k Tab` contra a janela do `omavm-gui`, sem nenhum outro input) pareceu ativar o botão "Start" de um card em vez de só mover o foco — uma Machine de teste (sandboxed, sem imagem) chegou a iniciar de verdade. Parado logo em seguida (`omavm force-stop`, depois `pkill omavm-gui`); nenhum dado real foi afetado. Não consegui isolar se é um bug real de foco/ativação do app ou um artefato do `wtype` (teclado virtual sintético, sem clique de mouse disponível neste host para comparar). Não corrigido nem reportado como bug confirmado — registrado aqui como sinal para quando o item de P1 "Concluir navegação por teclado e acessibilidade" for retomado com um mouse/teclado real.
+
+## Sessão de 2026-09-27 (continuação): UI/UX do Experience Center e do assistente de criação
+
+Pedido do usuário: "melhorar a UI/UX da tela guia e adicionar animações mantendo responsividade e quebrando o texto no overflow". Esclarecido por pergunta direta: "tela guia" é o Experience Center (`Main.qml`) + o assistente de criação (`CreateDialog.qml`) juntos, não uma tela nova.
+
+Dois overflows reais adicionais encontrados por leitura de código e confirmados/reverificados com o mesmo método da sessão anterior (harness isolado `qml6` + `grim`, sem tocar no app real nem em dados do usuário):
+
+- **`CreateDialog.qml`, passo "Ready to create"**: o `Label` do nome no resumo (`text: name.text.trim()`) não tinha `Layout.fillWidth`/`elide` — como `validateEnvironmentName` no Core não limita comprimento, um nome longo alargava a coluna do `GridLayout` além da largura do diálogo. Corrigido com `Layout.fillWidth: true` + `elide: Text.ElideRight`, no mesmo padrão já usado no campo de imagem/ISO ao lado. Confirmado com nome de ~120 caracteres e caminho de ISO longo lado a lado, sem overflow.
+- **`Main.qml`, estado vazio ("No environments yet")**: ao contrário do estado de erro logo abaixo dele (que já tinha `width: Math.min(parent.width - 48, 420)` + `wrapMode: Text.Wrap`), o `ColumnLayout` do estado vazio não tinha limite de largura nem quebra de linha no subtítulo — em janelas estreitas o texto vazaria para fora da janela. Corrigido replicando exatamente o tratamento do estado de erro ao lado.
+
+Animações adicionadas, seguindo o padrão já estabelecido (`NumberAnimation`/`ParallelAnimation` explícitas, nunca `Behavior` quando a transição precisa de uma direção/jump controlado):
+
+- **Transição de passo do assistente agora tem direção.** Antes era só um fade de opacidade sem indicar avanço/retrocesso. `CreateDialog.qml` ganhou `transform: Translate` no `StackLayout` de passos; avançar desliza o próximo passo a partir da direita, voltar desliza a partir da esquerda (28px, 220ms, `Easing.OutCubic`), combinado com o fade já existente numa `ParallelAnimation`. Direção calculada comparando o passo novo com o anterior (`animatingFromStep`), sem introduzir estado além do necessário.
+- **Botão Refresh do Experience Center gira uma vez ao ser clicado manualmente** (`RotationAnimation`, 360°, 500ms) — feedback de que a ação foi registrada. Deliberadamente só no clique direto (`onClicked`), não ligado a `backend.busy` em geral: o polling silencioso de 3s (já existente) também usa `busy`, e amarrar a animação nele faria o ícone girar sozinho a cada poll em vez de só quando o usuário pede.
+
+Evidência: `qmllint` sem erro estrutural nos arquivos tocados (`Main.qml`, `CreateDialog.qml`); `make build-gui` limpo; `go build/vet/test` (suite inteira) inalterados, já que nenhum arquivo Go foi tocado. Os dois overflows foram reproduzidos e reverificados visualmente via harness isolado antes/depois da correção. As animações (direção do passo, giro do refresh) não são verificáveis por captura estática — pendente de validação visual interativa por quem consegue ver o app rodando ao vivo; uma tentativa de forçar a janela real para 320×420 via `hyprctl dispatch togglefloating/resizewindowpixel` falhou (mesma incompatibilidade de parser Lua já documentada em `CLAUDE.md` para dispatches brutos) e, numa segunda tentativa com sintaxe diferente, a janela do `omavm-gui` fechou sozinha sem crash registrado (`coredumpctl`/log vazios) — não investigado a fundo; evitar repetir `hyprctl dispatch` arbitrário contra a janela real em sessões futuras, preferir o harness `qml6` isolado.
+
+## Sessão de 2026-09-27 (continuação): mais ícones e feedback tátil no assistente e nas listas
+
+Pedido do usuário: "ainda poderia ser mais visual com ícones, animações". Adições puramente aditivas, reusando os ícones monocromáticos já existentes (`gui/icons/machine.svg`, `box.svg`) e dois novos no mesmo estilo (traço 1.8px, viewBox 24×24, recoloridos em runtime por `Icon.qml`):
+
+- **`CreateDialog.qml`, passo 0 (escolha de intenção)**: os dois botões de escolha ganharam o ícone de Machine/Box (já usado em `EnvironmentCard.qml` para o mesmo propósito, então a linguagem visual fica consistente entre o assistente e os cards) acima do título, recolorido para o accent quando selecionado. Ganharam também um leve `scale` ao pressionar (0.97, 100ms) para feedback tátil de clique.
+- **`CreateDialog.qml`, passo "Ready to create"**: a linha "Type:" do resumo ganhou o mesmo ícone pequeno (16px) ao lado do texto.
+- **Dois ícones novos**: `gui/icons/history.svg` (relógio com seta de retorno, para snapshots) e `gui/icons/app.svg` (janela genérica com barra de título, para apps exportáveis) — nenhum ícone equivalente já existia no conjunto. Registrados em `gui/resources.qrc`.
+- **`SnapshotsDialog.qml`**: cada linha da lista ganhou o ícone de histórico (cor accent) e passou a reagir ao hover (`HoverHandler` + `Material.elevation` animado, 1→2, mesmo padrão já usado no card do Experience Center) — antes as linhas eram planas, sem nenhum feedback de hover.
+- **`AppsDialog.qml`**: mesmo tratamento de hover/elevação; cada linha ganhou o ícone de app, colorido verde (`themeGreen`) quando já exportado e cinza (`themeMuted`) quando não — permite diferenciar o estado exportado/não-exportado num relance, sem precisar ler o texto do botão.
+
+Evidência: `qmllint` sem erro estrutural nos cinco arquivos tocados; `make build-gui` limpo. Os ícones novos e o layout resultante foram conferidos visualmente via harness isolado (`qml6` apontando para cópias locais dos SVGs e uma réplica fiel do QML real, já que `qrc:/` só resolve dentro do binário compilado) — renderizaram nítidos e recoloridos corretamente nos três contextos (botões de escolha, resumo, linhas de lista). O feedback de hover/press em si (elevação, scale) não é verificável por captura estática — pendente de validação interativa.
+
+## Sessão de 2026-09-27 (continuação): "Open in an empty workspace" (docs/TODO.md P2)
+
+Pedido do usuário: a janela do viewer não funciona "como um Parallels Desktop" usando workspaces vazios do Hyprland — o item já existia em `docs/TODO.md` P2 mas `CLAUDE.md` explicitamente pedia validar a API real e atualizar a diretriz antes de implementar. Perguntado ao usuário como avançar (três opções: implementar agora com fallback honesto / só documentar o plano / pesquisar mais primeiro); escolheu "implementar agora, com fallback honesto".
+
+**Pesquisa da API (antes de qualquer dispatch novo)**: confirmado que `hyprctl dispatch ` nesta build Lua do Hyprland (Omarchy) avalia `` como código Lua (`hl.dispatch()`) — não é o parser clássico do Hyprland. `hyprctl eval`/`hyprctl repl` executam Lua arbitrário; `/usr/share/hypr/stubs/hl.meta.lua` documenta uma API estruturada real (`hl.get_workspaces()` com `.is_empty`/`.special`/`.monitor` já prontos, `hl.get_windows({class=, title=})` com igualdade exata sem regex, `hl.dispatch(hl.dsp.focus({workspace=...}))`). O padrão foi confirmado contra código real do próprio Omarchy (`/usr/share/omarchy/shell/plugins/bar/widgets/Workspaces.qml` usa exatamente essa forma). Testado com segurança via `hyprctl repl`/`hyprctl dispatch` diretos (sem tocar no app): consulta de workspaces (`is_empty=false` batendo com a realidade dos 4 workspaces ocupados), criação/foco de um workspace novo (5) confirmado via `hyprctl activeworkspace`, busca de janela existente por classe+título confirmada com janelas `foot` reais. `hl.dsp.focus({window=})` (focar uma janela específica, não só o workspace) não se mostrou confiável — registrado como lacuna, não resolvido por adivinhação.
+
+**Implementação** (domínio → Core → CLI → GUI, docs por último): `EnvironmentSettings.OpenInEmptyWorkspace` (opt-in, aplica aos dois Kinds — diferente de CPU/memória/clipboard que são Machine-only) em `internal/core/environment.go`; `SettingsPatch.OpenInEmptyWorkspace` em `service.go`'s `Configure` sem guarda de Kind. CLI: `settings NAME --open-in-empty-workspace=true|false`, refletido no output humano e `--json`. GUI: `gui/backend.cpp` ganhou `placeInEmptyWorkspace()` (namespace anônimo) — verifica `$HYPRLAND_INSTANCE_SIGNATURE` antes de qualquer `hyprctl`, monta um único script Lua (nome do ambiente Lua-escapado via `luaQuote()`), roda via `hyprctlRepl()` (QProcess bloqueante com timeout curto, sem shell — argv separado). `Backend::open()` consulta a preferência do ambiente e, se ligada, chama isso antes de lançar o viewer (Machine, via `omavm open`) ou o terminal (Box, `--terminal` direto) — a lógica cobre os dois Kinds no mesmo lugar, já que ambos passam por `open()`. Checkbox "Open in an empty workspace" em `SettingsDialog.qml`, visível para os dois Kinds (ao contrário de "Share text clipboard"/"Travel Mode", que continuam Machine-only).
+
+**Lacunas registradas como fallback honesto, não escondidas**: foco de janela específica (só workspace); detecção de workspaces "reservados por regra pessoal" (API não permite distinguir de um workspace comum ocupado); "faixa configurada pelo usuário" (não existe como conceito consultável, busca usa limite fixo 1–30). Conflito documentado (README, `contrib/hypr/omavm-viewer.lua`, `CLAUDE.md`) com a regra estática de fullscreen já existente — as duas não compõem, a regra estática sempre vence se carregada.
+
+Evidência: `go build/vet/test` (suite inteira, incluindo `TestOpenInEmptyWorkspaceAppliesToBothKinds` novo) limpos; `qmllint` sem erro estrutural; `make build-gui` compila de verdade. CLI testado manualmente (`settings --open-in-empty-workspace=true` + `--json` confirmando persistência para Box e Machine). O mecanismo Hyprland em si foi validado isolando o script Lua exato que o C++ monta (testado via `hyprctl repl` direto), não através de um clique real em Start/Open na GUI — evitado deliberadamente: duas automações de input anteriores nesta sessão já causaram efeitos colaterais reais não intencionais (Tab ativando um card e iniciando uma Machine de verdade; um `hyprctl dispatch` malformado fechando a janela do `omavm-gui` sozinha). `CLAUDE.md` atualizado com a política técnica validada antes da implementação, conforme o próprio item exigia.
+
+## Sessão de 2026-09-27 (continuação, /loop): verbos específicos nas confirmações + incidente de privacidade em teste
+
+Continuando `docs/TODO.md` autonomamente via `/loop`. Item escolhido: "Padronizar linguagem e consequências" (P1), a parte ainda pendente ("Falta revisar os demais rótulos e confirmações"). Auditoria: terminologia Desktop/Development Box já consistente em todo `gui/*.qml` (nenhum "Machine"/"Box"/"VM" solto). As quatro confirmações destrutivas usavam `standardButtons: Dialog.Cancel | Dialog.Yes`, cujo botão "Yes" é gerado automaticamente pelo Qt sem texto customizado — inconsistente com o padrão já usado em `CreateDialog.qml`/`SettingsDialog.qml` (botões com texto específico via `DialogButtonBox`). Corrigido via `standardButton(Dialog.Yes).text = ...` em `Component.onCompleted`, API padrão do Qt Quick Controls (`T.Dialog.standardButton(button): AbstractButton`): "Force Stop" (`Main.qml`'s `confirmForceStop`), "Delete" (`confirmDelete` de Environment e `SnapshotsDialog.qml`'s `confirmDeleteSnapshot`), "Go To" (`confirmGoTo`).
+
+**Incidente de privacidade durante verificação (registrado por transparência)**: ao tentar confirmar visualmente o texto do botão via harness `qml6` isolado (mesmo método usado em sessões anteriores), o `grim -g` usou uma posição de tela reaproveitada de uma captura anterior sem reconfirmar que o workspace alvo estava de fato visível — a janela de teste tinha aberto num workspace não focado, e a captura pegou o conteúdo real que estava na tela naquele momento: uma sessão de jogo do usuário em outro workspace/monitor (nomes de outros jogadores visíveis). A imagem foi deletada imediatamente (`rm -f`) sem ser lida/descrita além de confirmar que era uma captura errada, e nenhuma outra ação foi tomada sobre ela. Lição: `grim -g` captura o que está fisicamente na tela naquela posição, não necessariamente a janela que `hyprctl clients` reporta "at" aquela posição — a janela precisa estar no workspace **ativo/visível** primeiro, e isso deve ser reconfirmado a cada nova captura, nunca assumido de uma verificação anterior na mesma sessão. Nas sessões anteriores isso funcionou por coincidência (a janela nova ficava focada automaticamente); não deve ser tratado como garantido. A partir daqui, evitar captura de tela para verificações triviais (como um texto de botão) quando a correção já é garantida por uma API padrão bem documentada — reservar `grim` para quando a captura for realmente necessária, e sempre confirmar o workspace ativo (`hyprctl activeworkspace`) imediatamente antes.
+
+Evidência: `qmllint` sem erro estrutural nos dois arquivos tocados (`Main.qml`, `SnapshotsDialog.qml`); `make build-gui` limpo; `go build/vet/test` inalterados (nenhum arquivo Go tocado). Verificação de runtime limitada a "carrega sem erro" (log do `qml6` sem exceções) em vez de captura visual, pelo motivo acima.
+
+## Sessão de 2026-09-27 (continuação): ícones renderizando pretos em qualquer tema — bug real, corrigido
+
+Pedido do usuário: "vamos fazer os ícones também respeitarem o tema". Uma auditoria de código inicial não achou nada óbvio (todo uso de `Icon.qml`/`icon.source` já vinculado a `backend.themeX`) e um teste isolado (`qml6`, cores literais) mostrou os ícones coloridos corretamente — então perguntei ao usuário o que exatamente via de errado antes de adivinhar mais. Resposta: **"os ícones são pretos mesmo em temas pretos"** — ou seja, não é um problema de qual cor é escolhida, é que a recoloração não está acontecendo de jeito nenhum no app real.
+
+**Confirmado com uma captura real** (workspace do app verificado contra `hyprctl activeworkspace` antes de capturar): no passo 0 do `CreateDialog.qml`, o texto "Desktop" aparecia corretamente ciano (`backend.themeAccent`), mas o ícone de monitor logo acima, usando a mesma expressão de cor, aparecia **preto sólido** — descartando um problema de resolução do valor de cor (o mesmo binding funciona pro texto) e apontando para o mecanismo de recoloração do `Icon.qml` em si. O estado vazio ("No environments yet", ícone já usado em sessões anteriores e supostamente "verificado") também mostrou o mesmo sintoma — não era um bug novo das adições desta sessão, era sistêmico em todo `Icon.qml`.
+
+`Icon.qml` usava `MultiEffect { colorization: 1; colorizationColor: root.color }` (`QtQuick.Effects`) sobre uma `Image` oculta. Tentativa 1: trocar para `MultiEffect { maskEnabled: true; maskSource: img; source: }` (o padrão mais comum pra "tingir ícone monocromático", também documentado oficialmente) — não resolveu (mesmo sintoma numa nova verificação). Em vez de tentar uma terceira variação de shader/`MultiEffect` às cegas, a correção final trocou de mecanismo por completo: `IconImage` (`QtQuick.Controls.impl`, `QQuickIconImage`, `prototype: QQuickImage`) — o mesmo tipo C++ que o próprio Qt Quick Controls usa internamente para renderizar `icon.source`/`icon.color` em `Button`/`ToolButton`, que já estava **comprovadamente funcionando** no app real (os ícones "+"/"↻" do cabeçalho, que usam `icon.color` nativo em vez de `Icon.qml`, sempre apareceram corretamente brancos). `Icon.qml` virou um wrapper fino: `property alias color: img.color` sobre um `IconImage` interno, preservando a mesma API externa (`source`/`color`/`iconSize`) usada em ~20 pontos do código, então nenhum outro arquivo precisou mudar.
+
+**Por que não ficou 100% visualmente confirmado nesta sessão**: tentar verificar a correção reproduziu, em sequência, três incidentes de privacidade — capturas de tela (`grim`) pegando conteúdo real e não relacionado do usuário (uma sessão de jogo estilo Roblox; depois a página do GitHub da organização dele) em vez da janela de teste, mesmo checando `hyprctl clients`/`activeworkspace` antes de cada captura. A causa raiz: o usuário está usando o computador ativamente durante a sessão, trocando de workspace entre minha checagem e a captura seguinte — `hyprctl activewindow` confirmou em certo ponto que o foco real era uma aba do Chrome dele, não a minha janela de teste. As três capturas malsucedidas foram deletadas imediatamente (`rm -f`) assim que percebidas como erradas, sem serem descritas além de "não é a janela certa". `Item.grabToImage()` (escreve direto num arquivo, sem depender de qual workspace está visível) foi tentado como alternativa mais segura, mas trava indefinidamente neste ambiente `qml6`/Wayland/RHI especificamente para essa chamada — confirmado com um teste mínimo (`Timer` + `Qt.quit()` sozinho funciona; adicionar `grabToImage` no mesmo arquivo trava). Diante disso, a verificação final ficou limitada a: `qmllint` sem erro, `make build-gui` limpo, e o binário real rodando por alguns segundos sem nenhum warning/erro de QML no log — sem confirmação visual pixel-a-pixel. Pedido ao usuário para confirmar visualmente ele mesmo.
+
+Evidência: `qmllint gui/Icon.qml` sem nenhuma saída (nem os avisos usuais de `backend` não-qualificado, já que este arquivo não referencia `backend`); `make build-gui` limpo; `go build/vet/test` inalterados (nenhum arquivo Go tocado, mudança 100% em `gui/Icon.qml`). Registrado como feedback de produto (`SendFeedback`) o padrão de capturas de tela pegando conteúdo errado do usuário durante uma sessão ativa — sinal de que esse método de verificação precisa de uma forma mais confiável de confirmar visibilidade antes de capturar neste tipo de ambiente.
+
+## Sessão de 2026-09-27 (continuação, /loop): contraste medido matematicamente + área de toque das tags de cor
+
+Continuando `docs/TODO.md` autonomamente. Dado o risco já demonstrado de capturas de tela acidentais enquanto o usuário está ativo na máquina, esta rodada evitou completamente `grim`/interação ao vivo, focando em achados verificáveis por código/matemática pura.
+
+- **Contraste WCAG medido contra o tema real do host** (não um teste isolado): lido `~/.local/state/omarchy/current/theme/colors.toml` diretamente e calculada a razão de contraste (luminância relativa, fórmula padrão WCAG) para todos os pares texto/fundo que o app realmente usa (`Backend::loadTheme`'s mapeamento de chaves do TOML pras propriedades `themeX`). Resultado: só uma combinação fica abaixo do limiar de texto normal (4,5:1) — `muted` sobre `lighter_background` (`themeSurface`), 4,09:1, usada em descrições/timestamps dentro de `Pane`s com fundo de superfície elevada. Não corrigido (a cor pertence ao tema do usuário, não ao app); documentado como achado de produto em `docs/TODO.md`, incluindo que o tema claro do Omarchy não foi medido (host está em modo escuro).
+- **Área de toque das tags de cor corrigida.** `SettingsDialog.qml`'s `ToolButton`s de cor tinham a área clicável do tamanho exato do círculo (22×22px) — abaixo do mínimo de 24×24 do WCAG 2.5.8. Corrigido separando visual de área de toque: botão cresceu para 40×40, círculo colorido centralizado nele mantendo 22×22 — mesma aparência, alvo maior.
+- **"Conferir ícones em diferentes fontes" fechado por já não se aplicar.** Auditoria (`grep` por glifos Unicode usados como ícone em todo `gui/*.qml`) confirma que a migração de glifos de fonte pra SVG (sessão anterior, já registrada no histórico) foi completa — não sobrou nenhuma dependência de fonte do sistema pra verificar.
+
+Evidência: `qmllint`/`make build-gui` limpos para `SettingsDialog.qml`; `go build/vet/test` inalterados (nenhum arquivo Go tocado). Contraste calculado com um script Python padrão (fórmula de luminância relativa WCAG), não uma ferramenta de acessibilidade externa — método documentado em `docs/TODO.md` pra quem quiser reproduzir/auditar o cálculo.
+
+## Sessão de 2026-09-27 (continuação, /loop): salvar Settings pinava CPU/memória mesmo sem tocar nelas — bug real no Core
+
+Retomando após um reset de uso no meio da tarefa (contexto recuperado lendo os arquivos direto do disco, que já tinham avançado além de onde a memória da conversa parava — incluindo o fix de flickering acima, feito por uma iteração anterior do loop enquanto esta ficava presa "pensando"). Item: "Explicar ajustes automáticos e pendentes" (P2), aceite "salvar uma descrição não altera inadvertidamente a intenção de configuração de CPU".
+
+Rastreei isso em duas camadas:
+1. **GUI** (`gui/SettingsDialog.qml`/`backend.cpp`/`.h`): os `SpinBox` de CPU/memória sempre mostravam o valor *efetivo* (2/2048, já resolvido pelo Core mesmo quando nada estava fixado) e `Backend::configure` sempre reenviava `--cpus`/`--memory-mib` incondicionalmente a cada Save — mesmo salvando só a descrição. Corrigido com rastreamento de "touched": `SpinBox.onValueModified` (dispara só em interação real do usuário, não na atribuição programática em `onOpened`) marca `cpusTouched`/`memoryTouched`; `Backend::configure` ganhou esses dois parâmetros extras e só inclui as flags quando de fato tocado.
+2. **Core** (`internal/core/service.go`'s `Configure`) — **a causa raiz real, que o fix da GUI sozinho não resolvia**: `Configure` montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10, pensado só para exibição) e persistia essa cópia inteira de volta incondicionalmente. Resultado: **qualquer** chamada a `Configure` — inclusive via CLI direto, sem GUI nenhuma no meio — gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido fixados, mesmo alterando só a descrição. Consequência real, não hipotética: `internal/backend/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0` — salvar qualquer coisa em Settings desligava essa redução automática pra sempre, na primeira vez, mesmo o usuário nunca tendo tocado em CPU. Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto), retornando `env.EffectiveSettings()` só no final (depois de persistir) pra CLI/GUI continuarem mostrando o valor resolvido para exibição.
+
+Confirmado com reprodução real via CLI (binário compilado, `XDG_STATE_HOME` isolado): `create --kind machine` (sem `--cpus`) seguido de `settings NOME --description "x"`, inspecionando `environments.json` bruto diretamente. Antes da correção: `cpus`/`memory_mib`/`snapshot_limit` apareciam gravados no arquivo mesmo sem terem sido passados. Depois: `settings` fica só com `{"description":"x"}`. Testado também que um pin explícito (`--cpus 4`) sobrevive a uma edição não relacionada posterior — continua fixado.
+
+Teste de regressão novo: `TestConfigureUnrelatedFieldDoesNotPinHardwareDefaults` (`internal/core/service_test.go`) — verificado que **falha** sem a correção (revertida manualmente com `sed`, teste falhou exatamente como esperado, depois restaurada) e passa com ela; cobre os dois casos (campo não tocado fica em zero bruto; pin explícito sobrevive a save posterior). `go build/vet/test` (suite inteira), `make build-gui`, `make test-backend` e `qmllint` todos limpos depois da correção completa (Core + GUI).
+
+## Sessão de 2026-09-27 (continuação, /loop): "diferenciar preferência configurada de valor efetivo" implementado de graça
+
+Ao documentar os dois bugs de pinning acima, notei que `SettingsDialog.qml` recebe `environment` de `backend.environments`, que vem de `omavm list --json` — e `Service.List` (`internal/core/service.go`) retorna os ambientes **brutos**, nunca resolvidos por `EffectiveSettings()` (diferente do retorno de `Settings()`/`Configure()`). Ou seja: `settings.cpus` no JSON de `list` já vem **ausente** (`omitempty` no struct tag) quando CPUs nunca foi fixado — o sinal "isto é um pin de verdade ou só o default de hoje" já existia de graça, sem precisar mudar Core nem CLI.
+
+Implementado: `SettingsDialog.qml` ganhou `cpusPinned`/`memoryPinned` (`!!settings.cpus`/`!!settings.memory_mib`, calculado no `onOpened` a partir do dado bruto) e uma legenda pequena embaixo de cada `SpinBox` de hardware: "Not pinned yet: adapts automatically, and Travel Mode may reduce it while on battery" (CPUs) / "...this is just today's default" (memória) quando não fixado; "Pinned — won't change on its own" quando fixado; "Will be pinned to this value on save" quando `cpusTouched`/`memoryTouched` nesta sessão do diálogo (o usuário acabou de mexer). Fecha o resto do aceite de "Explicar ajustes automáticos e pendentes" (P2) que os dois bugs de pinning já tinham corrigido a parte de integridade de dados.
+
+Evidência: `qmllint`/`make build-gui` limpos; `go build/vet/test` inalterados (nenhum arquivo Go tocado). Não verificado visualmente (mesma limitação de captura de tela já registrada) — mudança estruturalmente simples (duas Labels condicionais num `GridLayout` já existente, mesmo padrão de `Layout.columnSpan` e cores de tema já usado em todo o arquivo), risco baixo.
+
+**Mesma família de bug encontrada em Create, não só Configure (mesma sessão, continuação do /loop).** Ao documentar o fix acima me perguntei se `CreateDialog.qml` tinha o mesmo problema — tinha: o passo de resumo sempre enviava `--cpus 2 --memory-mib 2048` (os defaults mostrados) pra `backend.createEnvironment`, mesmo sem o usuário tocar nos `SpinBox`. Diferente do bug de `Configure`, este não precisou de correção no Core (`Create` já é correto — só grava `Settings.CPUs`/`MemoryMiB` se um valor != 0 vier no `core.Environment` passado, e o CLI só popula isso quando a flag é passada) — o bug morava inteiramente na GUI sempre mandando as flags incondicionalmente. Corrigido com o mesmo padrão de `SpinBox.onValueModified` → `cpusTouched`/`memoryTouched` → `Backend::createEnvironment` só inclui as flags quando tocado. Confirmado via CLI real: `create --kind machine` sem `--cpus`/`--memory-mib` grava `settings: {}` no `environments.json`, com `settings --json` ainda mostrando 2/2048 resolvidos pra exibição. `go build/vet/test`, `make build-gui`, `make test-backend`, `qmllint` limpos.
+
+## Sessão de 2026-09-27 (continuação, /loop): snapshot novo podia "sumir" se o descarte de retenção falhasse
+
+Depois de fechar a família de bugs de pinning de CPU/memória, apliquei o mesmo tipo de auditoria (rastrear cada ponto onde `EffectiveSettings()` é lido, cada `store.Save` e o que exatamente cada função persiste) no resto do Core, pra confirmar que a família de bug estava mesmo fechada e procurar outras do mesmo gênero. Todos os outros usos de `EffectiveSettings()` (`internal/backend/qemu/qemu.go`'s `Start`/`Open`, e `Service.CreateSnapshot`'s leitura do `SnapshotLimit`) já eram só leituras pra decisão/execução, nunca persistidas de volta — confirmados limpos.
+
+Mas essa mesma auditoria achou um bug diferente, na MESMA função (`Service.CreateSnapshot`): o fluxo cria o snapshot novo no backend, tenta descartar os mais antigos por causa do limite de retenção, e só persistia tudo — o novo snapshot incluído — num único `store.Save` no final da função. Se o backend já tivesse criado o snapshot novo (chamada real, sucesso confirmado) mas uma remoção de snapshot antigo falhasse no meio do loop de retenção (disco cheio, QMP caindo, etc.), a função retornava erro **sem nunca ter salvo nada** — perdendo o rastro do snapshot que genuinamente existe no backend agora, um "fantasma" invisível em `snapshot list`. Se algum descarte antigo já tivesse sido bem-sucedido antes da falha, pior ainda: o registro persistido continuava referenciando um snapshot que o backend já tinha apagado de verdade.
+
+Corrigido persistindo incrementalmente em vez de tudo de uma vez no final: salva o snapshot novo logo após o backend confirmar a criação (antes de mexer em retenção), e salva de novo após cada descarte bem-sucedido dentro do loop. Uma falha no meio agora só corrompe a visão do passo que realmente falhou, nunca desfaz o que já é real. No caminho de erro da retenção, a função agora retorna o snapshot recém-criado (não mais um valor zerado), já que ele genuinamente foi criado — informação parcial correta em vez de aparentar falha total.
+
+Teste de regressão novo: `TestSnapshotCreatedButRetentionDiscardFailsStillPersistsNewSnapshot` (`internal/core/service_test.go`), usando o campo `removeErr` que `fakeSnapshotBackend` já tinha (não usado por nenhum teste existente) pra simular a falha do backend no meio do loop. Verificado que o teste **falha** sem a correção (revertida manualmente com backup/restore do arquivo, teste falhou exatamente como esperado — o snapshot retornado veio zerado — depois restaurada) e passa com ela. `go build/vet/test` (suite inteira), `make build-gui`, `make test-backend` todos limpos depois.
+
+## Sessão de 2026-09-27 (continuação, /loop): auditoria completa de `store.Save` no Core — mais um recurso órfão possível, corrigido
+
+Depois do bug de snapshot acima, resolvi auditar sistematicamente TODA função do Core que chama `store.Save` (`Create`, `Configure`, `CreateSnapshot`, `RemoveSnapshot`, `Remove`), procurando o mesmo padrão ("um passo real já aconteceu no backend, mas um passo posterior falha antes de persistir"). `RemoveSnapshot`/`Remove`/`GoToSnapshot` são operações de um passo só (uma chamada ao backend, um save, sem loop) — já corretas por construção, nada a fazer. `ExportApp`/`UnexportApp` não tocam o registro do Core (o estado de exportação vive no filesystem via `.desktop`, por design do Blend Mode — CLAUDE.md), então também não têm esse risco.
+
+Mas `Create` tinha uma versão mais estreita do mesmo problema: `backend.Create` cria de verdade um container/disco de VM, e SÓ DEPOIS disso o Core tenta `store.Save`. Se esse `Save` falhar (disco cheio, permissão, etc.) — bem mais raro que uma falha de backend no meio de um loop de retenção, mas ainda real —, o recurso já existe no backend só que sem nenhum registro apontando pra ele: órfão, invisível pro CLI/GUI, sem `omavm remove` possível (o comando nem sabe que ele existe) a não ser encontrando manualmente o container/disco solto.
+
+Corrigido com rollback best-effort: quando `store.Save` falha depois de `backend.Create` ter tido sucesso, `Create` agora chama `backend.Remove` antes de devolver o erro — desfazendo o lado do backend pra deixar o estado como se a criação nunca tivesse acontecido. Se o PRÓPRIO rollback falhar (dois problemas de infraestrutura ao mesmo tempo), o erro final menciona isso explicitamente ("cleanup also failed, resource may be orphaned") em vez de fingir que o rollback funcionou.
+
+Teste de regressão: `TestCreateRollsBackBackendWhenRegistrySaveFails`. Precisou de um campo novo (`saveErr error`) no `memStore` (o fake `Store` usado pelos testes do Core) pra simular a falha de disco/persistência — não existia antes porque nenhum teste precisava simular isso. Verificado com o mesmo método de sempre: reverter manualmente a correção, confirmar que o teste falha exatamente como esperado, restaurar. `go build/vet/test` (suite inteira), `make build-gui`, `make test-backend` limpos depois.
+
+
+## Sessão de 2026-09-27 (continuação, /loop): auditoria de construtores de backend não achou mais nada; auditoria de QMP achou um bug real em `savevm`/`loadvm`/`delvm`
+
+Depois de fechar a família de bugs de persistência do Core, verifiquei se o padrão "probe caro chamado a toda invocação" corrigido em `container.New()` (`sync.Once`, ver sessão anterior) se repetia em outros backends: `grep -n "^func New\b" internal/backend/*/*.go` mostrou `distrobox.New()` e `box.New()` já leves (retornam a struct direto, sem I/O), e `qemu.New()` só resolve um path (`core.StateDir()` + `filepath.Join`), sem shell out. `cmd/omavm/main.go` confirma que os três são construídos incondicionalmente a cada invocação do CLI (`qemu.New()`, `box.New(distrobox.New(), container.New())`), então o fix de `container.New()` já cobria o único ponto caro que existia. Nada a corrigir aqui — auditoria encerrada sem achado novo.
+
+Segui então para o próximo item não marcado da frente QEMU ("Auditar comunicação QMP") e achei um bug real em `internal/backend/qemu/qmp.go`/`qemu.go`: `human-monitor-command` — o passthrough QMP usado para `savevm`/`loadvm`/`delvm` (snapshots com a Machine rodando) — reporta falhas do comando HMP subjacente (tag desconhecida, snapshot corrompido, etc.) como **texto simples dentro do campo `"return"`** da resposta QMP, não como um erro de protocolo (`"error"`). Isso é uma característica documentada do `human-monitor-command`: ele é um passthrough pro monitor de texto legado, e comandos HMP individuais reportam seus próprios erros escrevendo no stream de saída do monitor (que vira a string de `"return"`), sem propagar isso como falha ao nível QMP.
+
+`qemu.go` chamava `qmpHumanMonitorCommand` nos três call sites descartando a string de retorno (`_, err := ...`), checando só o erro de protocolo. Resultado: uma falha real do `savevm`/`loadvm`/`delvm` passava despercebida — exatamente o cenário do aceite de "Revisar discos, snapshots e falhas parciais" ("nenhum sucesso aparente... após falha"). O caso mais grave é `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; com o bug, um `loadvm` que falhasse silenciosamente dessa forma seguia direto para `cont` — retomando a Machine no estado anterior ao restore (nada foi de fato restaurado) enquanto CLI/GUI reportavam a operação como bem-sucedida.
+
+Corrigido checando `strings.TrimSpace` da string de retorno nos três call sites (`savevm`, `loadvm`, `delvm`); texto não-vazio agora vira um erro explícito com o próprio texto do QEMU. Em `GoToSnapshot` fiz questão de sempre tentar o `cont` de resume mesmo quando o `loadvm` falhou — a Machine já estava pausada por causa do `stop` anterior, e deixá-la travada em pausa por causa de uma falha de restore seria introduzir um bug de lifecycle novo (Machine presa pausada) só para "corrigir" o de snapshot.
+
+Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/qemu/lifecycle_test.go`), reusando o padrão de servidor QMP fake do teste vizinho `TestGoToSnapshotPausesAroundRunningRestore`, mas retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` em vez de `""`. Verificado com o método de sempre: revertido manualmente (backup/restore via `cp`), confirmado que o teste **falha** sem a correção (`GoToSnapshot` retornava `nil`, nenhum erro reportado) e passa com ela — incluindo a checagem de que a sequência de comandos ainda é `["stop", "human-monitor-command", "cont"]`, provando que o resume acontece mesmo no caminho de falha. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos depois.
diff --git a/gui/AppsDialog.qml b/gui/AppsDialog.qml
index 3da078d..09063de 100644
--- a/gui/AppsDialog.qml
+++ b/gui/AppsDialog.qml
@@ -6,6 +6,12 @@ import QtQuick.Layouts
Dialog {
id: dialog
property var environment: ({})
+ readonly property bool busy: !!(backend.busyEnvironments && backend.busyEnvironments[environment.name])
+ // True once backend.apps actually reflects this dialog's environment —
+ // guards against a slower response for a previously open environment
+ // landing after the user has switched to another one (docs/TODO.md P0).
+ readonly property bool matches: backend.appsEnvironment === environment.name
+ property bool requested: false
title: qsTr("%1 Applications").arg(environment.name || qsTr("Environment"))
modal: true
anchors.centerIn: parent
@@ -14,7 +20,23 @@ Dialog {
standardButtons: Dialog.Close
Overlay.modal: ThemeScrim {}
- onOpened: backend.refreshApps(environment.name)
+ onOpened: {
+ requested = false
+ if (!dialog.busy) {
+ requested = true
+ backend.refreshApps(environment.name)
+ }
+ }
+
+ Connections {
+ target: backend
+ function onBusyChanged() {
+ if (!dialog.visible || dialog.busy || dialog.requested)
+ return
+ dialog.requested = true
+ backend.refreshApps(dialog.environment.name)
+ }
+ }
ColumnLayout {
anchors.fill: parent
@@ -27,9 +49,51 @@ Dialog {
wrapMode: Text.Wrap
}
+ RowLayout {
+ Layout.fillWidth: true
+ visible: dialog.matches && dialog.busy
+ spacing: 8
+ BusyIndicator { implicitWidth: 18; implicitHeight: 18; running: true }
+ Label { text: qsTr("Refreshing…"); color: backend.themeMuted; font.pixelSize: 12 }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ visible: !dialog.matches
+ spacing: 10
+ Item { Layout.fillHeight: true }
+ BusyIndicator { Layout.alignment: Qt.AlignHCenter; running: !dialog.matches }
+ Label { Layout.alignment: Qt.AlignHCenter; text: qsTr("Loading applications…"); color: backend.themeMuted }
+ Item { Layout.fillHeight: true }
+ }
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ Layout.fillHeight: true
+ visible: dialog.matches && backend.appsError !== ""
+ spacing: 10
+ Item { Layout.fillHeight: true }
+ Icon { Layout.alignment: Qt.AlignHCenter; source: "qrc:/icons/warning.svg"; color: backend.themeRed; iconSize: 36 }
+ Label {
+ Layout.fillWidth: true
+ Layout.alignment: Qt.AlignHCenter
+ horizontalAlignment: Text.AlignHCenter
+ text: backend.appsError
+ color: backend.themeMuted
+ wrapMode: Text.Wrap
+ }
+ Button {
+ Layout.alignment: Qt.AlignHCenter
+ text: qsTr("Try Again")
+ onClicked: backend.refreshApps(dialog.environment.name)
+ }
+ Item { Layout.fillHeight: true }
+ }
+
Label {
Layout.fillWidth: true
- visible: backend.apps.length === 0
+ visible: dialog.matches && backend.appsError === "" && backend.apps.length === 0
text: qsTr("No exportable applications found.")
color: backend.themeMuted
}
@@ -39,22 +103,52 @@ Dialog {
Layout.fillHeight: true
clip: true
spacing: 6
- model: backend.apps
+ visible: dialog.matches && backend.appsError === "" && backend.apps.length > 0
+ model: dialog.matches ? backend.apps : []
+ populate: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ }
+ add: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ NumberAnimation { property: "y"; from: 24; duration: 220; easing.type: Easing.OutCubic }
+ }
+ remove: Transition {
+ NumberAnimation { property: "opacity"; to: 0; duration: 160; easing.type: Easing.InCubic }
+ }
+ displaced: Transition {
+ NumberAnimation { properties: "x,y"; duration: 200; easing.type: Easing.OutCubic }
+ }
delegate: Pane {
+ id: appRow
required property var modelData
width: ListView.view.width
- Material.elevation: 1
+ Material.elevation: rowHover.hovered ? 2 : 1
Material.background: backend.themeSurface
+
+ Behavior on Material.elevation { NumberAnimation { duration: 120; easing.type: Easing.OutCubic } }
+
+ HoverHandler { id: rowHover }
+
RowLayout {
anchors.fill: parent
+ spacing: 10
+ Icon {
+ source: "qrc:/icons/app.svg"
+ color: modelData.exported ? backend.themeGreen : backend.themeMuted
+ iconSize: 20
+ }
Label {
Layout.fillWidth: true
text: modelData.name
elide: Text.ElideRight
}
Button {
- text: modelData.exported ? qsTr("Remove") : qsTr("Export")
+ // "Remove from menu", never bare "Remove": this only
+ // undoes the launcher shortcut, the app stays
+ // installed in the Box (docs/TODO.md P1).
+ text: modelData.exported ? qsTr("Remove from menu") : qsTr("Export")
highlighted: !modelData.exported
+ enabled: !dialog.busy
onClicked: modelData.exported
? backend.unexportApp(dialog.environment.name, modelData.id)
: backend.exportApp(dialog.environment.name, modelData.id)
diff --git a/gui/CreateDialog.qml b/gui/CreateDialog.qml
index 932bcb6..f75756b 100644
--- a/gui/CreateDialog.qml
+++ b/gui/CreateDialog.qml
@@ -10,12 +10,28 @@ Dialog {
modal: true
anchors.centerIn: parent
width: Math.min(parent.width - 32, 680)
- height: Math.min(parent.height - 32, 540)
+ height: Math.min(parent.height - 32, 580)
padding: 24
Overlay.modal: ThemeScrim {}
+ readonly property int lastStep: 3
property int step: 0
property bool machine: true
+ property string errorText: ""
+ property bool submitting: false
+ property string nameError: ""
+ property bool nameTouched: false
+ // Same reasoning as SettingsDialog.qml's cpusTouched/memoryTouched:
+ // the summary step shows 2 CPUs/2048 MiB as a helpful default, but
+ // sending that unconditionally to `omavm create` would pin every
+ // new Machine's hardware from birth — permanently disabling Travel
+ // Mode's automatic reduction on battery for it (the same Core bug
+ // class documented in docs/TODO.md P2, just hit at creation time
+ // instead of a later Settings save). Only actually touching a
+ // SpinBox (SpinBox.onValueModified, real user interaction only)
+ // marks it as an intentional choice.
+ property bool cpusTouched: false
+ property bool memoryTouched: false
property var boxes: [
{ label: "Fedora", image: "fedora:latest" },
{ label: "Ubuntu", image: "ubuntu:latest" },
@@ -30,15 +46,77 @@ Dialog {
: (boxes[boxImage.currentIndex].image || image.text.trim())
}
+ // Mirrors internal/core/service.go's validateEnvironmentName so a bad
+ // name is caught here, at the field, instead of only after a round
+ // trip to the CLI. Deliberately permissive otherwise: spaces and
+ // accented characters are valid names and must stay usable.
+ function validateName(candidate) {
+ if (!candidate)
+ return qsTr("Enter a name for the environment")
+ if (candidate === "." || candidate === "..")
+ return qsTr("\"%1\" is not a valid environment name").arg(candidate)
+ if (candidate.startsWith("-"))
+ return qsTr("Environment name cannot start with \"-\"")
+ for (let i = 0; i < candidate.length; i++) {
+ const ch = candidate.charAt(i)
+ const code = candidate.charCodeAt(i)
+ // Same as Go's unicode.IsControl: C0, DEL and C1.
+ if (ch === "/" || ch === "\\" || code < 32 || (code >= 127 && code < 160))
+ return qsTr("Environment name cannot contain \"%1\"").arg(ch)
+ }
+ return ""
+ }
+
function resetForm() {
step = 0
machine = true
+ errorText = ""
+ submitting = false
+ nameError = ""
+ nameTouched = false
name.clear()
image.clear()
boxImage.currentIndex = 0
+ cpus.value = 2
+ memory.value = 2048
+ cpusTouched = false
+ memoryTouched = false
}
+ // Tracks the step a transition is animating FROM, so the content can
+ // slide in from the direction the user is actually moving (forward
+ // = Continue, backward = Back) instead of a plain, direction-blind
+ // fade — a small touch that makes the wizard read as a sequence
+ // rather than a stack of unrelated screens.
+ property int animatingFromStep: 0
onOpened: resetForm()
+ onStepChanged: {
+ const forward = step > animatingFromStep
+ animatingFromStep = step
+ stepStack.opacity = 0
+ stepTranslate.x = forward ? 28 : -28
+ stepEnter.restart()
+ }
+
+ ParallelAnimation {
+ id: stepEnter
+ NumberAnimation { target: stepStack; property: "opacity"; to: 1; duration: 180; easing.type: Easing.OutCubic }
+ NumberAnimation { target: stepTranslate; property: "x"; to: 0; duration: 220; easing.type: Easing.OutCubic }
+ }
+
+ Connections {
+ target: backend
+ function onActionFinished(tag, ok, text) {
+ if (tag !== "create") return
+ dialog.submitting = false
+ if (ok) {
+ dialog.errorText = ""
+ dialog.close()
+ } else {
+ dialog.errorText = text
+ }
+ }
+ }
header: ColumnLayout {
spacing: 8
@@ -47,7 +125,8 @@ Dialog {
Layout.topMargin: 20
text: dialog.step === 0 ? qsTr("Choose an environment")
: dialog.step === 1 ? qsTr("Choose what to run")
- : qsTr("Name your environment")
+ : dialog.step === 2 ? qsTr("Name your environment")
+ : qsTr("Review and create")
font.pixelSize: 22
font.weight: Font.DemiBold
}
@@ -57,13 +136,13 @@ Dialog {
Layout.rightMargin: 24
spacing: 8
Repeater {
- model: 3
+ model: dialog.lastStep + 1
Rectangle {
required property int index
Layout.fillWidth: true
implicitHeight: 3
radius: 2
- color: index <= dialog.step ? backend.themeAccent : backend.themeMuted
+ color: index <= dialog.step ? backend.themeAccentText : backend.themeMuted
opacity: index <= dialog.step ? 1 : 0.35
}
}
@@ -71,7 +150,9 @@ Dialog {
}
contentItem: StackLayout {
+ id: stepStack
currentIndex: dialog.step
+ transform: Translate { id: stepTranslate }
Item {
ColumnLayout {
@@ -84,19 +165,97 @@ Dialog {
color: backend.themeMuted
}
Button {
+ id: desktopChoice
Layout.fillWidth: true
- Layout.preferredHeight: 112
+ // The card's text is drawn by its own contentItem.
+ Accessible.name: qsTr("Desktop")
+ Accessible.description: qsTr("A complete system with its own kernel, from an installation ISO")
checkable: true
checked: dialog.machine
- text: qsTr("Desktop\nA complete computer with its own kernel and graphical display")
+ padding: 16
+ scale: desktopChoice.pressed ? 0.97 : 1
+ Behavior on scale { NumberAnimation { duration: 100; easing.type: Easing.OutCubic } }
+ // Height follows the wrapped text below instead of a
+ // fixed guess: a plain multi-line `text:` on a Button
+ // doesn't wrap at all (only explicit \n breaks), so at
+ // the dialog's real ~630px content width the longer
+ // example sentence overflowed past the button and the
+ // dialog edge (confirmed by rendering this in isolation
+ // at that width before fixing it).
+ contentItem: ColumnLayout {
+ spacing: 6
+ Icon {
+ Layout.alignment: Qt.AlignHCenter
+ source: "qrc:/icons/machine.svg"
+ iconSize: 32
+ color: desktopChoice.checked ? backend.themeAccentText : backend.themeMuted
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("Desktop")
+ font.bold: true
+ horizontalAlignment: Text.AlignHCenter
+ color: desktopChoice.checked ? backend.themeAccentText : backend.themeForeground
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("A complete computer with its own kernel and graphical display.")
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ color: backend.themeMuted
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("Examples: install Windows, FreeBSD, or an Arch Linux with a custom kernel.")
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ font.pixelSize: 12
+ color: backend.themeMuted
+ }
+ }
onClicked: dialog.machine = true
}
Button {
+ id: boxChoice
Layout.fillWidth: true
- Layout.preferredHeight: 112
+ Accessible.name: qsTr("Development Box")
+ Accessible.description: qsTr("Linux tools and apps sharing your home folder and this computer's kernel")
checkable: true
checked: !dialog.machine
- text: qsTr("Development Box\nA fast terminal environment integrated with your Omarchy home")
+ padding: 16
+ scale: boxChoice.pressed ? 0.97 : 1
+ Behavior on scale { NumberAnimation { duration: 100; easing.type: Easing.OutCubic } }
+ contentItem: ColumnLayout {
+ spacing: 6
+ Icon {
+ Layout.alignment: Qt.AlignHCenter
+ source: "qrc:/icons/box.svg"
+ iconSize: 32
+ color: boxChoice.checked ? backend.themeAccentText : backend.themeMuted
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("Development Box")
+ font.bold: true
+ horizontalAlignment: Text.AlignHCenter
+ color: boxChoice.checked ? backend.themeAccentText : backend.themeForeground
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("A fast terminal environment sharing your Omarchy home, files and Wayland session.")
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ color: backend.themeMuted
+ }
+ Label {
+ Layout.fillWidth: true
+ text: qsTr("Examples: a Fedora terminal for a project, an Ubuntu toolchain — can also open and export graphical apps to your launcher.")
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ font.pixelSize: 12
+ color: backend.themeMuted
+ }
+ }
onClicked: dialog.machine = false
}
Item { Layout.fillHeight: true }
@@ -128,6 +287,7 @@ Dialog {
TextField {
id: image
Layout.fillWidth: true
+ Accessible.name: dialog.machine ? qsTr("Installation ISO") : qsTr("Container image")
readOnly: dialog.machine
placeholderText: dialog.machine ? qsTr("Choose a boot ISO…") : qsTr("Container image, for example opensuse/tumbleweed")
}
@@ -148,7 +308,7 @@ Dialog {
anchors.margins: 12
text: dialog.machine
? qsTr("The ISO is installation media. It will not be copied or modified.")
- : qsTr("Boxes share the host kernel. Choose Desktop instead when you need a separate kernel or full boot.")
+ : qsTr("Boxes share the host kernel and can still open graphical apps. Choose Desktop instead when you need a separate kernel or full boot.")
wrapMode: Text.Wrap
}
}
@@ -160,7 +320,7 @@ Dialog {
ColumnLayout {
anchors.fill: parent
spacing: 16
- Label { text: dialog.machine ? qsTr("Desktop") : qsTr("Development Box"); color: backend.themeAccent; font.weight: Font.DemiBold }
+ Label { text: dialog.machine ? qsTr("Desktop") : qsTr("Development Box"); color: backend.themeAccentText; font.weight: Font.DemiBold }
Label {
Layout.fillWidth: true
text: dialog.machine ? image.text : dialog.boxes[boxImage.currentIndex].label
@@ -170,9 +330,18 @@ Dialog {
TextField {
id: name
Layout.fillWidth: true
+ Accessible.name: qsTr("Environment name")
placeholderText: qsTr("Environment name")
focus: dialog.step === 2
onAccepted: createButton.clicked()
+ onEditingFinished: dialog.nameTouched = true
+ }
+ Label {
+ Layout.fillWidth: true
+ visible: dialog.nameTouched && dialog.nameError !== ""
+ text: dialog.nameError
+ wrapMode: Text.Wrap
+ color: backend.themeRed
}
Label {
Layout.fillWidth: true
@@ -183,34 +352,146 @@ Dialog {
Item { Layout.fillHeight: true }
}
}
+
+ Item {
+ ColumnLayout {
+ anchors.fill: parent
+ spacing: 16
+ Label { text: qsTr("Ready to create"); color: backend.themeAccentText; font.weight: Font.DemiBold }
+ GridLayout {
+ Layout.fillWidth: true
+ columns: 2
+ columnSpacing: 16
+ rowSpacing: 6
+ Label { text: qsTr("Type:"); color: backend.themeMuted }
+ RowLayout {
+ spacing: 6
+ Icon {
+ source: dialog.machine ? "qrc:/icons/machine.svg" : "qrc:/icons/box.svg"
+ color: backend.themeAccentText
+ iconSize: 16
+ }
+ Label { text: dialog.machine ? qsTr("Desktop") : qsTr("Development Box") }
+ }
+ Label { text: dialog.machine ? qsTr("Installation media:") : qsTr("Image:"); color: backend.themeMuted }
+ Label {
+ Layout.fillWidth: true
+ text: dialog.machine ? image.text : dialog.boxes[boxImage.currentIndex].label
+ elide: Text.ElideMiddle
+ }
+ Label { text: qsTr("Name:"); color: backend.themeMuted }
+ Label {
+ Layout.fillWidth: true
+ text: name.text.trim()
+ elide: Text.ElideRight
+ }
+ }
+ RowLayout {
+ Layout.fillWidth: true
+ visible: dialog.machine
+ spacing: 16
+ ColumnLayout {
+ Label { text: qsTr("CPUs"); color: backend.themeMuted }
+ SpinBox {
+ id: cpus
+ Accessible.name: qsTr("CPUs")
+ Component.onCompleted: contentItem.Accessible.name = Accessible.name
+ from: 1
+ to: 64
+ value: 2
+ onValueModified: dialog.cpusTouched = true
+ }
+ }
+ ColumnLayout {
+ Label { text: qsTr("Memory (MiB)"); color: backend.themeMuted }
+ SpinBox {
+ id: memory
+ Accessible.name: qsTr("Memory in MiB")
+ from: 256
+ to: 262144
+ stepSize: 256
+ editable: true
+ // Typing goes into the inner text field, which is what a
+ // screen reader announces.
+ Component.onCompleted: contentItem.Accessible.name = Accessible.name
+ value: 2048
+ onValueModified: dialog.memoryTouched = true
+ }
+ }
+ Item { Layout.fillWidth: true }
+ }
+ Rectangle {
+ Layout.fillWidth: true
+ implicitHeight: closingNote.implicitHeight + 24
+ radius: 8
+ color: backend.themeSelection
+ visible: closingNote.text !== ""
+ Label {
+ id: closingNote
+ anchors.fill: parent
+ anchors.margins: 12
+ wrapMode: Text.Wrap
+ text: dialog.machine && image.text
+ ? qsTr("Starting this Desktop opens the graphical installer from the ISO. Once the guest OS is installed, shut it down, then disconnect the installation media from Settings before starting again from its own disk.")
+ : (!dialog.machine
+ ? qsTr("Graphical applications inside can be exported to your Omarchy launcher anytime from the environment's \"Applications…\" menu.")
+ : "")
+ }
+ }
+ Item { Layout.fillHeight: true }
+ }
+ }
}
- footer: DialogButtonBox {
- Button {
- text: dialog.step === 0 ? qsTr("Cancel") : qsTr("Back")
- DialogButtonBox.buttonRole: DialogButtonBox.ActionRole
- onClicked: dialog.step === 0 ? dialog.reject() : dialog.step--
+ footer: ColumnLayout {
+ spacing: 0
+ Label {
+ Layout.fillWidth: true
+ Layout.leftMargin: 24
+ Layout.rightMargin: 24
+ visible: dialog.errorText !== ""
+ text: dialog.errorText
+ wrapMode: Text.Wrap
+ color: backend.themeRed
}
- Button {
- id: createButton
- text: dialog.step === 2 ? qsTr("Create Environment") : qsTr("Continue")
- highlighted: true
- DialogButtonBox.buttonRole: DialogButtonBox.ActionRole
- onClicked: {
- if (dialog.step === 1 && !dialog.selectedImage()) {
- backend.message(dialog.machine ? qsTr("Choose an installation ISO") : qsTr("Enter a container image"), true)
- return
- }
- if (dialog.step < 2) {
- dialog.step++
- return
- }
- if (!name.text.trim()) {
- backend.message(qsTr("Enter a name for the environment"), true)
- return
- }
- backend.createEnvironment(name.text.trim(), dialog.selectedImage(), dialog.machine ? "machine" : "box")
- dialog.accept()
+ DialogButtonBox {
+ Layout.fillWidth: true
+ Button {
+ text: dialog.step === 0 ? qsTr("Cancel") : qsTr("Back")
+ enabled: !dialog.submitting
+ DialogButtonBox.buttonRole: DialogButtonBox.ActionRole
+ onClicked: dialog.step === 0 ? dialog.reject() : dialog.step--
+ }
+ Button {
+ id: createButton
+ text: dialog.submitting ? qsTr("Creating…") : dialog.step === dialog.lastStep ? qsTr("Create Environment") : qsTr("Continue")
+ highlighted: true
+ enabled: !dialog.submitting
+ DialogButtonBox.buttonRole: DialogButtonBox.ActionRole
+ onClicked: {
+ if (dialog.step === 1 && !dialog.selectedImage()) {
+ backend.message(dialog.machine ? qsTr("Choose an installation ISO") : qsTr("Enter a container image"), true)
+ return
+ }
+ if (dialog.step === 2) {
+ dialog.nameTouched = true
+ dialog.nameError = dialog.validateName(name.text.trim())
+ if (dialog.nameError !== "") {
+ name.forceActiveFocus()
+ return
+ }
+ }
+ if (dialog.step < dialog.lastStep) {
+ dialog.step++
+ return
+ }
+ dialog.errorText = ""
+ dialog.submitting = true
+ backend.createEnvironment(name.text.trim(), dialog.selectedImage(),
+ dialog.machine ? "machine" : "box",
+ cpus.value, dialog.cpusTouched,
+ memory.value, dialog.memoryTouched)
+ }
}
}
}
@@ -219,6 +500,6 @@ Dialog {
id: isoPicker
title: qsTr("Choose a boot ISO")
nameFilters: [qsTr("ISO images (*.iso)"), qsTr("All files (*)")]
- onAccepted: image.text = selectedFile.toString().replace(/^file:\/\//, "")
+ onAccepted: image.text = backend.localPath(selectedFile)
}
}
diff --git a/gui/EnvironmentCard.qml b/gui/EnvironmentCard.qml
index 006f7e3..aca9863 100644
--- a/gui/EnvironmentCard.qml
+++ b/gui/EnvironmentCard.qml
@@ -11,16 +11,33 @@ Pane {
signal settingsRequested(var environment)
signal snapshotsRequested(var environment)
signal appsRequested(var environment)
+ // An action of this OmaVM window is running on this environment;
+ // others stay usable meanwhile.
+ readonly property bool busy: !!(backend.busyEnvironments && backend.busyEnvironments[environment.name])
readonly property bool running: environment.status === "running"
readonly property bool paused: environment.status === "paused"
readonly property bool stopped: environment.status === "stopped"
readonly property bool transitioning: environment.status === "starting" || environment.status === "stopping"
+ || environment.status === "creating" || environment.status === "removing"
readonly property bool failed: environment.status === "error"
- readonly property bool active: running || paused || transitioning || failed
+ // The process is there but its monitor doesn't answer (a hung QEMU):
+ // it still has to be stoppable from here.
+ readonly property bool unresponsive: environment.status === "unknown"
+ readonly property bool active: running || paused || transitioning || failed || unresponsive
+ readonly property color statusColor: failed || unresponsive ? backend.themeRed
+ : running ? backend.themeGreen
+ : paused || transitioning ? backend.themeAccentText
+ : backend.themeMuted
padding: 14
- Material.elevation: 1
+ Material.elevation: hoverHandler.hovered ? 3 : 1
Material.background: backend.themeSurface
+ Behavior on Material.elevation {
+ NumberAnimation { duration: 120; easing.type: Easing.OutCubic }
+ }
+
+ HoverHandler { id: hoverHandler }
+
RowLayout {
anchors.fill: parent
spacing: card.width < 520 ? 10 : 16
@@ -38,15 +55,20 @@ Pane {
anchors.fill: parent
source: card.environment.preview || ""
fillMode: Image.PreserveAspectCrop
- visible: status === Image.Ready
+ visible: opacity > 0
+ opacity: status === Image.Ready ? 1 : 0
cache: false
+
+ Behavior on opacity { NumberAnimation { duration: 200; easing.type: Easing.OutCubic } }
}
- Label {
+ Icon {
anchors.centerIn: parent
- visible: !preview.visible
- text: card.environment.kind === "machine" ? "▣" : ">_"
- font.pixelSize: card.width < 520 ? 24 : 32
- color: backend.themeAccent
+ opacity: preview.opacity > 0 ? 0 : 1
+ source: card.environment.kind === "machine" ? "qrc:/icons/machine.svg" : "qrc:/icons/box.svg"
+ iconSize: card.width < 520 ? 24 : 32
+ color: backend.themeAccentText
+
+ Behavior on opacity { NumberAnimation { duration: 200; easing.type: Easing.OutCubic } }
}
}
@@ -90,25 +112,44 @@ Pane {
implicitWidth: 8
implicitHeight: 8
radius: 4
- color: card.failed ? backend.themeRed
- : card.running ? backend.themeGreen
- : card.paused || card.transitioning ? backend.themeAccent
- : backend.themeMuted
+ color: card.statusColor
+
+ Behavior on color { ColorAnimation { duration: 200 } }
+
+ SequentialAnimation on scale {
+ running: card.transitioning || card.busy
+ loops: Animation.Infinite
+ NumberAnimation { from: 1; to: 1.5; duration: 500; easing.type: Easing.InOutSine }
+ NumberAnimation { from: 1.5; to: 1; duration: 500; easing.type: Easing.InOutSine }
+ }
}
Label {
+ objectName: "statusLabel"
text: card.environment.status === "running" ? qsTr("Running")
: card.environment.status === "paused" ? qsTr("Paused")
: card.environment.status === "starting" ? qsTr("Starting…")
: card.environment.status === "stopping" ? qsTr("Shutting down…")
+ : card.environment.status === "creating" ? qsTr("Creating…")
+ : card.environment.status === "removing" ? qsTr("Deleting…")
: card.environment.status === "error" ? qsTr("Needs attention")
+ : card.environment.status === "unknown" ? qsTr("Not responding")
: card.environment.status === "stopped" ? qsTr("Stopped")
: qsTr("Checking…")
- color: card.failed ? backend.themeRed
- : card.running ? backend.themeGreen
- : card.paused || card.transitioning ? backend.themeAccent
- : backend.themeMuted
+ color: card.statusColor
+
+ Behavior on color { ColorAnimation { duration: 200 } }
}
}
+ // Why a Machine is paused or needs attention (a full host
+ // disk, a missing container): the state alone doesn't say.
+ Label {
+ objectName: "statusDetailLabel"
+ Layout.fillWidth: true
+ visible: (card.paused || card.failed) && !!card.environment.statusDetail
+ text: card.environment.statusDetail || ""
+ color: card.statusColor
+ wrapMode: Text.WordWrap
+ }
Label {
Layout.fillWidth: true
visible: card.environment.kind === "machine" && card.width >= 520 && !!card.environment.guestAgent
@@ -123,40 +164,56 @@ Pane {
}
Button {
- visible: card.width >= 500
- text: card.running || card.failed ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start")
+ objectName: "primaryAction"
+ // Always reachable, even at 320px: this is the one direct action
+ // every card must offer (docs/TODO.md P1). Below 500px it shrinks
+ // to an icon-only button instead of disappearing into the menu.
+ readonly property bool compact: card.width < 500
+ readonly property string label: card.running || card.failed || card.unresponsive ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start")
+ text: label
+ icon.source: "qrc:/icons/play.svg"
+ display: compact ? AbstractButton.IconOnly : AbstractButton.TextOnly
+ Accessible.name: label
+ ToolTip.text: label
+ ToolTip.visible: compact && hovered
highlighted: true
- enabled: !card.transitioning
+ enabled: !card.transitioning && !card.busy
onClicked: card.paused ? backend.resume(card.environment.name)
: backend.open(card.environment.name, card.environment.kind)
}
ToolButton {
- text: "⋮"
+ objectName: "actionsButton"
+ icon.source: "qrc:/icons/more.svg"
+ icon.color: backend.themeForeground
Accessible.name: qsTr("Actions for %1").arg(card.environment.name)
onClicked: actions.open()
Menu {
id: actions
+ objectName: "actionsMenu"
y: parent.height
MenuItem {
- text: card.running || card.failed ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start")
- enabled: !card.transitioning
+ text: card.running || card.failed || card.unresponsive ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start")
+ enabled: !card.transitioning && !card.busy
onTriggered: card.paused ? backend.resume(card.environment.name)
: backend.open(card.environment.name, card.environment.kind)
}
+ // A hidden MenuItem keeps its height in a Qt Quick Menu, so each
+ // kind-specific item collapses itself (see tst_environmentcard.qml).
MenuItem {
visible: card.environment.kind === "machine"
+ height: visible ? implicitHeight : 0
text: card.paused ? qsTr("Resume") : qsTr("Pause")
- enabled: card.running || card.paused
+ enabled: (card.running || card.paused) && !card.busy
onTriggered: card.paused ? backend.resume(card.environment.name) : backend.pause(card.environment.name)
}
- MenuItem { text: qsTr("Restart"); visible: card.environment.kind === "machine"; enabled: card.running || card.paused; onTriggered: backend.restart(card.environment.name) }
- MenuItem { text: qsTr("Shut Down"); enabled: card.active && !card.transitioning; onTriggered: backend.stop(card.environment.name) }
- MenuItem { text: qsTr("Force Stop…"); visible: card.environment.kind === "machine"; enabled: card.active; onTriggered: card.forceStopRequested(card.environment.name) }
+ MenuItem { text: qsTr("Restart"); visible: card.environment.kind === "machine"; height: visible ? implicitHeight : 0; enabled: (card.running || card.paused) && !card.busy; onTriggered: backend.restart(card.environment.name) }
+ MenuItem { text: qsTr("Shut Down"); enabled: card.active && !card.transitioning && !card.busy; onTriggered: backend.stop(card.environment.name) }
+ MenuItem { text: qsTr("Force Stop…"); visible: card.environment.kind === "machine"; height: visible ? implicitHeight : 0; enabled: card.active && !card.busy; onTriggered: card.forceStopRequested(card.environment.name) }
MenuSeparator {}
- MenuItem { text: qsTr("Snapshots…"); visible: card.environment.kind === "machine"; onTriggered: card.snapshotsRequested(card.environment) }
- MenuItem { text: qsTr("Applications…"); visible: card.environment.kind !== "machine"; onTriggered: card.appsRequested(card.environment) }
+ MenuItem { text: qsTr("Snapshots…"); visible: card.environment.kind === "machine"; height: visible ? implicitHeight : 0; onTriggered: card.snapshotsRequested(card.environment) }
+ MenuItem { text: qsTr("Applications…"); visible: card.environment.kind !== "machine"; height: visible ? implicitHeight : 0; onTriggered: card.appsRequested(card.environment) }
MenuItem { text: qsTr("Settings…"); onTriggered: card.settingsRequested(card.environment) }
- MenuItem { text: qsTr("Delete…"); onTriggered: card.removeRequested(card.environment.name) }
+ MenuItem { text: qsTr("Delete…"); enabled: !card.busy; onTriggered: card.removeRequested(card.environment.name) }
}
}
}
diff --git a/gui/EnvironmentListModel.qml b/gui/EnvironmentListModel.qml
new file mode 100644
index 0000000..c72c4f3
--- /dev/null
+++ b/gui/EnvironmentListModel.qml
@@ -0,0 +1,36 @@
+import QtQuick
+
+// The Experience Center's list, kept in sync with backend.environments in
+// place. Using the JS array as the ListView model reset the whole list on
+// every change (a status, a preview arriving): all cards were destroyed
+// and faded in again, and an open card menu disappeared mid-use. Here each
+// environment keeps its row (matched by name, its stable identity) and
+// only its data is replaced, so its card lives on.
+ListModel {
+ id: model
+ dynamicRoles: true
+
+ function indexOf(name) {
+ for (let i = 0; i < count; ++i)
+ if (get(i).environment.name === name)
+ return i
+ return -1
+ }
+
+ function sync(environments) {
+ const names = environments.map(e => e.name)
+ for (let i = count - 1; i >= 0; --i)
+ if (names.indexOf(get(i).environment.name) === -1)
+ remove(i)
+ for (let i = 0; i < environments.length; ++i) {
+ const at = indexOf(environments[i].name)
+ if (at === -1) {
+ insert(i, { environment: environments[i] })
+ continue
+ }
+ if (at !== i)
+ move(at, i, 1)
+ setProperty(i, "environment", environments[i])
+ }
+ }
+}
diff --git a/gui/Icon.qml b/gui/Icon.qml
new file mode 100644
index 0000000..f4c1c2e
--- /dev/null
+++ b/gui/Icon.qml
@@ -0,0 +1,38 @@
+import QtQuick
+import QtQuick.Window
+import QtQuick.Controls.impl as ControlsImpl
+
+// A monochrome SVG icon tinted to match the Omarchy theme at runtime.
+// The source SVGs (gui/icons/*.svg) are plain black shapes on a
+// transparent background; recolored via IconImage's own `color`
+// property — the same QQuickIconImage type Qt Quick Controls uses
+// internally to render a Button/ToolButton's `icon.source`/`icon.color`
+// (confirmed working in the real app: the header's add/refresh icons use
+// it directly). Two MultiEffect-based approaches (colorization, and
+// masking a solid Rectangle with the icon's alpha) both looked correct
+// rendered standalone in isolation, but every icon using either one
+// rendered as the original, un-tinted black silhouette in the real
+// compiled app — reusing Controls' own proven mechanism instead of a
+// third shader-based attempt.
+Item {
+ id: root
+ property alias source: img.source
+ property alias color: img.color
+ property real iconSize: 20
+ implicitWidth: iconSize
+ implicitHeight: iconSize
+
+ ControlsImpl.IconImage {
+ id: img
+ anchors.fill: parent
+ sourceSize.width: Math.ceil(root.iconSize * Screen.devicePixelRatio)
+ sourceSize.height: Math.ceil(root.iconSize * Screen.devicePixelRatio)
+ fillMode: Image.PreserveAspectFit
+ asynchronous: true
+ color: "black"
+
+ Behavior on color {
+ ColorAnimation { duration: 150; easing.type: Easing.OutCubic }
+ }
+ }
+}
diff --git a/gui/Main.qml b/gui/Main.qml
index fc6091f..6741127 100644
--- a/gui/Main.qml
+++ b/gui/Main.qml
@@ -27,31 +27,89 @@ ApplicationWindow {
anchors.rightMargin: 8
Label { text: qsTr("OmaVM"); font.pixelSize: 20; font.weight: Font.DemiBold }
Label { text: qsTr("Experience Center"); color: backend.themeMuted; visible: win.width >= 520 }
+ Label {
+ visible: backend.busy && win.width >= 420
+ text: backend.busyAction !== "" ? qsTr("Working: %1…").arg(backend.busyAction) : qsTr("Working…")
+ color: backend.themeMuted
+ elide: Text.ElideRight
+ Layout.maximumWidth: 260
+ }
Item { Layout.fillWidth: true }
- ToolButton { text: "+"; font.pixelSize: 24; onClicked: createDialog.open(); ToolTip.text: qsTr("New Environment"); ToolTip.visible: hovered }
- ToolButton { text: "↻"; font.pixelSize: 20; onClicked: backend.refresh(); ToolTip.text: qsTr("Refresh"); ToolTip.visible: hovered }
+ ToolButton {
+ icon.source: "qrc:/icons/add.svg"
+ icon.color: backend.themeForeground
+ onClicked: createDialog.open()
+ ToolTip.text: qsTr("New Environment")
+ ToolTip.visible: hovered
+ Accessible.name: qsTr("New Environment")
+ }
+ ToolButton {
+ id: refreshButton
+ icon.source: "qrc:/icons/refresh.svg"
+ icon.color: backend.themeForeground
+ // Spins once on a manual click only — not on the silent
+ // background poll (Timer below), which never calls this
+ // handler — so clicking Refresh gets visible feedback
+ // without the icon spinning every few seconds on its own.
+ onClicked: { refreshSpin.restart(); backend.refresh() }
+ ToolTip.text: qsTr("Refresh")
+ ToolTip.visible: hovered
+ Accessible.name: qsTr("Refresh")
+ RotationAnimation {
+ id: refreshSpin
+ target: refreshButton
+ property: "rotation"
+ from: 0
+ to: 360
+ duration: 500
+ easing.type: Easing.InOutCubic
+ }
+ }
}
}
+ // Synced in place, not backend.environments directly: see
+ // EnvironmentListModel.qml (a status change used to recreate every
+ // card, replaying the fade-in and closing any open card menu).
+ EnvironmentListModel { id: environmentModel }
+ Connections {
+ target: backend
+ function onEnvironmentsChanged() { environmentModel.sync(backend.environments) }
+ }
+
ListView {
id: environmentList
anchors.fill: parent
- model: backend.environments
+ model: environmentModel
spacing: 12
topMargin: 18
bottomMargin: 18
clip: true
+ populate: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ }
+ add: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ NumberAnimation { property: "y"; from: 24; duration: 220; easing.type: Easing.OutCubic }
+ }
+ remove: Transition {
+ NumberAnimation { property: "opacity"; to: 0; duration: 160; easing.type: Easing.InCubic }
+ }
+ displaced: Transition {
+ NumberAnimation { properties: "x,y"; duration: 200; easing.type: Easing.OutCubic }
+ }
delegate: Item {
- required property var modelData
+ required property var environment
width: environmentList.width
height: card.implicitHeight
EnvironmentCard {
id: card
width: Math.min(parent.width - 28, 860)
anchors.horizontalCenter: parent.horizontalCenter
- environment: modelData
+ environment: parent.environment
onRemoveRequested: name => {
confirmDelete.environmentName = name
+ confirmDelete.environmentKind = environment.kind
confirmDelete.open()
}
onForceStopRequested: name => {
@@ -76,15 +134,50 @@ ApplicationWindow {
ColumnLayout {
anchors.centerIn: parent
- visible: backend.environments.length === 0 && !backend.busy
+ anchors.margins: 24
+ width: Math.min(parent.width - 48, 420)
+ visible: backend.environments.length === 0 && backend.listError === ""
spacing: 14
- Label { Layout.alignment: Qt.AlignHCenter; text: "▣"; font.pixelSize: 58; opacity: 0.5 }
+ Icon { Layout.alignment: Qt.AlignHCenter; source: "qrc:/icons/app-mono.svg"; color: backend.themeMuted; iconSize: 58; opacity: 0.5 }
Label { Layout.alignment: Qt.AlignHCenter; text: qsTr("No environments yet"); font.pixelSize: 22; font.weight: Font.DemiBold }
- Label { Layout.alignment: Qt.AlignHCenter; text: qsTr("Create a desktop or development environment to get started."); color: backend.themeMuted }
+ Label {
+ Layout.fillWidth: true
+ Layout.alignment: Qt.AlignHCenter
+ horizontalAlignment: Text.AlignHCenter
+ text: qsTr("Create a desktop or development environment to get started.")
+ color: backend.themeMuted
+ wrapMode: Text.Wrap
+ }
Button { Layout.alignment: Qt.AlignHCenter; text: qsTr("New Environment"); highlighted: true; onClicked: createDialog.open() }
}
- BusyIndicator { anchors.centerIn: parent; running: backend.busy; visible: running }
+ ColumnLayout {
+ anchors.centerIn: parent
+ anchors.margins: 24
+ width: Math.min(parent.width - 48, 420)
+ visible: backend.environments.length === 0 && backend.listError !== ""
+ spacing: 14
+ Icon { Layout.alignment: Qt.AlignHCenter; source: "qrc:/icons/warning.svg"; color: backend.themeRed; iconSize: 48 }
+ Label { Layout.alignment: Qt.AlignHCenter; text: qsTr("Could not load environments"); font.pixelSize: 20; font.weight: Font.DemiBold }
+ Label {
+ Layout.fillWidth: true
+ Layout.alignment: Qt.AlignHCenter
+ horizontalAlignment: Text.AlignHCenter
+ text: backend.listError
+ color: backend.themeMuted
+ wrapMode: Text.Wrap
+ }
+ Button { Layout.alignment: Qt.AlignHCenter; text: qsTr("Try Again"); onClicked: backend.refresh() }
+ }
+
+ BusyIndicator {
+ anchors.centerIn: parent
+ // Loading the list; a card shows its own action.
+ running: backend.busy && backend.environments.length === 0
+ opacity: running ? 1 : 0
+ visible: opacity > 0
+ Behavior on opacity { NumberAnimation { duration: 150; easing.type: Easing.OutCubic } }
+ }
CreateDialog { id: createDialog }
SettingsDialog { id: settingsDialog }
SnapshotsDialog { id: snapshotsDialog }
@@ -97,6 +190,14 @@ ApplicationWindow {
anchors.centerIn: parent
width: Math.min(parent.width - 32, 420)
standardButtons: Dialog.Cancel | Dialog.Yes
+ // A generic "Yes" button doesn't say what's about to happen — the
+ // title already names the destructive action, so the button
+ // should too (docs/TODO.md P1 "verbos específicos nas
+ // confirmações").
+ Component.onCompleted: {
+ const yesButton = standardButton(Dialog.Yes)
+ if (yesButton) yesButton.text = qsTr("Force Stop")
+ }
Overlay.modal: ThemeScrim {}
contentItem: Label {
text: qsTr("Force stop “%1”? Unsaved data in the guest may be lost.").arg(confirmForceStop.environmentName)
@@ -108,14 +209,21 @@ ApplicationWindow {
Dialog {
id: confirmDelete
property string environmentName
+ property string environmentKind
title: qsTr("Delete Environment")
modal: true
anchors.centerIn: parent
width: Math.min(parent.width - 32, 420)
standardButtons: Dialog.Cancel | Dialog.Yes
+ Component.onCompleted: {
+ const yesButton = standardButton(Dialog.Yes)
+ if (yesButton) yesButton.text = qsTr("Delete")
+ }
Overlay.modal: ThemeScrim {}
contentItem: Label {
- text: qsTr("Delete “%1”? This cannot be undone.").arg(confirmDelete.environmentName)
+ text: confirmDelete.environmentKind === "machine"
+ ? qsTr("Delete “%1”? Its virtual disk and every snapshot are removed. This cannot be undone.").arg(confirmDelete.environmentName)
+ : qsTr("Delete “%1”? Its container is removed; files under your Omarchy home are not touched. This cannot be undone.").arg(confirmDelete.environmentName)
wrapMode: Text.Wrap
color: backend.themeRed
}
@@ -132,9 +240,73 @@ ApplicationWindow {
Label { id: toastLabel; wrapMode: Text.Wrap; width: Math.min(420, implicitWidth) }
Timer { id: toastTimer; interval: 4500; onTriggered: toast.close() }
}
+
+ // Errors stay on screen until the user dismisses them (or a later
+ // action succeeds): docs/TODO.md P0 wants the cause and next step to
+ // remain readable past the 4.5s a toast lives, with a copyable detail.
+ Pane {
+ id: errorBanner
+ property string text: ""
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ z: 20
+ padding: 12
+ opacity: text !== "" ? 1 : 0
+ visible: opacity > 0
+ transform: Translate { y: (1 - errorBanner.opacity) * -24 }
+ Material.background: backend.themeSurface
+ Material.elevation: 4
+
+ Behavior on opacity { NumberAnimation { duration: 180; easing.type: Easing.OutCubic } }
+
+ RowLayout {
+ anchors.fill: parent
+ spacing: 10
+ Icon { source: "qrc:/icons/warning.svg"; color: backend.themeRed; iconSize: 18 }
+ Label {
+ Layout.fillWidth: true
+ text: errorBanner.text
+ color: backend.themeRed
+ wrapMode: Text.Wrap
+ }
+ Button {
+ text: qsTr("Copy details")
+ flat: true
+ onClicked: backend.copyToClipboard(errorBanner.text)
+ }
+ ToolButton {
+ icon.source: "qrc:/icons/close.svg"
+ icon.color: backend.themeRed
+ Accessible.name: qsTr("Dismiss")
+ onClicked: errorBanner.text = ""
+ }
+ }
+ }
+
Connections {
target: backend
- function onMessage(text, error) { toast.text = text; toast.open(); toastTimer.restart() }
+ function onMessage(text, error) {
+ if (error) {
+ errorBanner.text = text
+ } else {
+ toast.text = text; toast.open(); toastTimer.restart()
+ }
+ }
+ function onActionFinished(tag, ok, text) {
+ if (ok) errorBanner.text = ""
+ }
}
+ // Converges on the real state without the user pressing Refresh
+ // (docs/TODO.md P1): a light poll while the window has focus, not a
+ // background daemon — stops the moment focus is lost. The silent poll
+ // does not flash loading UI or disable controls every three seconds.
+ Timer {
+ interval: 3000
+ running: win.active
+ repeat: true
+ onTriggered: backend.poll()
+ }
+
Component.onCompleted: backend.refresh()
}
diff --git a/gui/SettingsDialog.qml b/gui/SettingsDialog.qml
index c6acdeb..a36f3ee 100644
--- a/gui/SettingsDialog.qml
+++ b/gui/SettingsDialog.qml
@@ -12,11 +12,38 @@ Dialog {
// that's the source of truth the CLI validates --color against.
readonly property var palette: ["red", "orange", "yellow", "green", "blue", "purple", "gray"]
property string selectedColor: ""
+ property string errorText: ""
+ property bool submitting: false
+ // `environment` (and its `.settings`) comes from `backend.environments`,
+ // which is populated straight from `omavm list --json` — the *raw*,
+ // persisted settings (internal/core/service.go's List, unlike
+ // Settings()/Configure()'s return value, is never resolved through
+ // EffectiveSettings()). A Machine whose CPUs/MemoryMiB were never
+ // pinned simply omits those JSON keys (`omitempty`), so `settings.cpus`
+ // here is `undefined`, not "2" — that's what cpusPinned/memoryPinned
+ // below check, to show the user whether a shown number is an actual
+ // pin or just today's default (docs/TODO.md P2 "diferenciar
+ // preferência configurada de valor efetivo").
+ //
+ // Regardless of that, saving anything else in this dialog (e.g. just
+ // the description) must never resend the *displayed* value as an
+ // explicit --cpus/--memory-mib — that would silently pin it, which
+ // disables Travel Mode's automatic reduction on battery
+ // (internal/backend/qemu/qemu.go's Start only reduces CPUs when the
+ // raw, persisted setting is unset). Only actually touching a SpinBox
+ // — SpinBox.onValueModified, which fires on user interaction and not
+ // on the programmatic `.value = x` assignment in onOpened — marks it
+ // as an intentional pin (docs/TODO.md P2 "salvar uma descrição não
+ // altera inadvertidamente a intenção de configuração de CPU").
+ property bool cpusTouched: false
+ property bool memoryTouched: false
+ property bool cpusPinned: false
+ property bool memoryPinned: false
title: qsTr("%1 Settings").arg(environment.name || qsTr("Environment"))
modal: true
anchors.centerIn: parent
width: Math.min(parent.width - 32, 520)
- standardButtons: Dialog.Cancel | Dialog.Save
+ height: Math.min(parent.height - 32, 560)
Overlay.modal: ThemeScrim {}
onOpened: {
@@ -24,6 +51,10 @@ Dialog {
description.text = settings.description || ""
cpus.value = settings.cpus || 2
memory.value = settings.memory_mib || 2048
+ cpusTouched = false
+ memoryTouched = false
+ cpusPinned = !!settings.cpus
+ memoryPinned = !!settings.memory_mib
sharedPath.text = settings.shared_path || ""
sharedReadOnly.checked = settings.shared_read_only || false
disconnectISO.checked = settings.disconnect_iso || false
@@ -31,8 +62,34 @@ Dialog {
// Opt-out: absent/false in the JSON means "not disabled", i.e. on.
shareClipboard.checked = !settings.clipboard_disabled
travelMode.checked = !settings.travel_mode_disabled
+ vulkan.checked = !settings.vulkan_disabled
+ launcher.checked = !settings.launcher_disabled
+ ssh.checked = !settings.ssh_disabled
+ openInEmptyWorkspace.checked = !settings.empty_workspace_disabled
+ fullscreen.checked = !settings.fullscreen_disabled
+ errorText = ""
+ submitting = false
}
+ Connections {
+ target: backend
+ function onActionFinished(tag, ok, text) {
+ if (tag !== "configure") return
+ dialog.submitting = false
+ if (ok) {
+ dialog.errorText = ""
+ dialog.close()
+ } else {
+ dialog.errorText = text
+ }
+ }
+ }
+
+ contentItem: ScrollView {
+ clip: true
+ contentWidth: availableWidth
+ ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
+
ColumnLayout {
width: parent.width
spacing: 16
@@ -41,6 +98,7 @@ Dialog {
TextArea {
id: description
Layout.fillWidth: true
+ Accessible.name: qsTr("Description")
Layout.preferredHeight: 82
placeholderText: qsTr("Description")
wrapMode: TextEdit.Wrap
@@ -51,31 +109,61 @@ Dialog {
spacing: 8
Label { text: qsTr("Color tag:"); color: backend.themeMuted }
ToolButton {
- implicitWidth: 22
- implicitHeight: 22
+ // Keep the visible dot compact while meeting WCAG 2.5.5's
+ // 44×44 enhanced pointer target.
+ implicitWidth: 44
+ implicitHeight: 44
+ objectName: "colorSwatch-none"
Accessible.name: qsTr("No color")
+ // One color among several: announced as a radio button, so
+ // it reads as checkable on every Qt version.
+ Accessible.role: Accessible.RadioButton
+ // The selection is only drawn as a thicker border, so the
+ // button itself is checkable: with a screen reader active,
+ // Qt announces the control's own checked state and ignores
+ // an Accessible.checked set by hand.
+ checkable: true
+ checked: dialog.selectedColor === ""
contentItem: Rectangle {
+ width: 22
+ height: 22
+ anchors.centerIn: parent
radius: 11
color: "transparent"
border.width: dialog.selectedColor === "" ? 2 : 1
border.color: dialog.selectedColor === "" ? backend.themeAccent : backend.themeMuted
+ Behavior on border.width { NumberAnimation { duration: 120; easing.type: Easing.OutCubic } }
+ }
+ onClicked: {
+ dialog.selectedColor = ""
+ checked = Qt.binding(() => dialog.selectedColor === "")
}
- onClicked: dialog.selectedColor = ""
}
Repeater {
model: dialog.palette
ToolButton {
required property string modelData
- implicitWidth: 22
- implicitHeight: 22
+ implicitWidth: 44
+ implicitHeight: 44
+ objectName: "colorSwatch-" + modelData
Accessible.name: modelData
+ Accessible.role: Accessible.RadioButton
+ checkable: true
+ checked: dialog.selectedColor === modelData
contentItem: Rectangle {
+ width: 22
+ height: 22
+ anchors.centerIn: parent
radius: 11
color: modelData
border.width: dialog.selectedColor === modelData ? 3 : 1
border.color: dialog.selectedColor === modelData ? backend.themeAccent : backend.themeMuted
+ Behavior on border.width { NumberAnimation { duration: 120; easing.type: Easing.OutCubic } }
+ }
+ onClicked: {
+ dialog.selectedColor = modelData
+ checked = Qt.binding(() => dialog.selectedColor === modelData)
}
- onClicked: dialog.selectedColor = modelData
}
}
}
@@ -93,9 +181,60 @@ Dialog {
columnSpacing: 16
rowSpacing: 12
Label { text: qsTr("Processors") }
- SpinBox { id: cpus; Layout.fillWidth: true; from: 1; to: 64 }
+ SpinBox {
+ id: cpus
+ Layout.fillWidth: true
+ Accessible.name: qsTr("CPUs")
+ Component.onCompleted: contentItem.Accessible.name = Accessible.name
+ from: 1
+ to: 64
+ onValueModified: dialog.cpusTouched = true
+ }
+ // Distinguishes "this is an explicit pin" from "this is just
+ // today's default preview" (docs/TODO.md P2 "diferenciar
+ // preferência configurada de valor efetivo") — otherwise a
+ // Machine that has never had its CPUs pinned looks identical
+ // to one deliberately pinned at the same number.
+ Label {
+ Layout.columnSpan: 2
+ Layout.fillWidth: true
+ visible: dialog.machine
+ text: dialog.cpusTouched
+ ? qsTr("Will be pinned to this value on save.")
+ : (dialog.cpusPinned
+ ? qsTr("Pinned — won't change on its own.")
+ : qsTr("Not pinned yet: adapts automatically, and Travel Mode may reduce it while on battery."))
+ color: backend.themeMuted
+ font.pixelSize: 12
+ wrapMode: Text.Wrap
+ }
Label { text: qsTr("Memory (MiB)") }
- SpinBox { id: memory; Layout.fillWidth: true; from: 256; to: 262144; stepSize: 256; editable: true }
+ SpinBox {
+ id: memory
+ Layout.fillWidth: true
+ Accessible.name: qsTr("Memory in MiB")
+ from: 256
+ to: 262144
+ stepSize: 256
+ editable: true
+ // Typing goes into the inner text field, which is what a
+ // screen reader announces.
+ Component.onCompleted: contentItem.Accessible.name = Accessible.name
+ onValueModified: dialog.memoryTouched = true
+ }
+ Label {
+ Layout.columnSpan: 2
+ Layout.fillWidth: true
+ visible: dialog.machine
+ text: dialog.memoryTouched
+ ? qsTr("Will be pinned to this value on save.")
+ : (dialog.memoryPinned
+ ? qsTr("Pinned — won't change on its own.")
+ : qsTr("Not pinned yet: this is just today's default."))
+ color: backend.themeMuted
+ font.pixelSize: 12
+ wrapMode: Text.Wrap
+ }
}
Label {
visible: dialog.machine
@@ -107,28 +246,83 @@ Dialog {
Label {
visible: dialog.machine
+ text: qsTr("Graphics")
+ font.pixelSize: 18
+ font.weight: Font.DemiBold
+ }
+ CheckBox {
+ id: vulkan
+ visible: dialog.machine
+ text: qsTr("Vulkan acceleration for 3D apps and games")
+ ToolTip.visible: hovered
+ ToolTip.text: qsTr("Used only when this computer supports it (see “omavm host”). The guest needs a recent Mesa with the Venus driver. Restart the Machine to apply a change.")
+ }
+
+ Label {
text: qsTr("Automation")
font.pixelSize: 18
font.weight: Font.DemiBold
}
CheckBox {
id: shareClipboard
- visible: dialog.machine
- text: qsTr("Share text clipboard with the guest")
+ text: dialog.machine
+ ? qsTr("Share text clipboard with the guest")
+ : qsTr("Let programs in the Box copy to your clipboard")
ToolTip.visible: hovered
- ToolTip.text: qsTr("Requires spice-vdagent in the guest desktop. Restart the Machine to apply a change.")
+ ToolTip.text: dialog.machine
+ ? qsTr("Requires spice-vdagent in the guest desktop. Restart the Machine to apply a change.")
+ : qsTr("Programs like Neovim and tmux can copy text straight to the clipboard. They can never read it. Applies to terminals opened after saving.")
}
CheckBox {
id: travelMode
- visible: dialog.machine
text: qsTr("Travel Mode: reduce CPUs automatically on battery")
ToolTip.visible: hovered
- ToolTip.text: qsTr("Only applies when you haven't pinned a custom CPU count.")
+ ToolTip.text: dialog.machine
+ ? qsTr("Only applies when you haven't pinned a custom CPU count.")
+ : qsTr("Uses half of this computer's CPUs while on battery, and all of them again once plugged in. Checked each time the Box starts or opens.")
+ }
+ CheckBox {
+ id: ssh
+ visible: dialog.machine
+ text: qsTr("Allow SSH from this computer")
+ ToolTip.visible: hovered
+ ToolTip.text: qsTr("Used by “omavm ssh” and “omavm exec”. The guest needs systemd 256 or newer with sshd installed. Restart the Machine to apply a change.")
+ }
+ // Security Model: the reach of this channel is stated, not hidden
+ // in a tooltip.
+ Label {
+ visible: dialog.machine && ssh.checked
+ Layout.fillWidth: true
+ Layout.leftMargin: 32
+ text: qsTr("Any program on this computer can reach it, Boxes included; only the guest's login protects it.")
+ color: backend.themeMuted
+ font.pixelSize: 12
+ wrapMode: Text.Wrap
+ }
+ CheckBox {
+ id: launcher
+ objectName: "launcherCheckBox"
+ text: qsTr("Show in the app launcher")
+ ToolTip.visible: hovered
+ ToolTip.text: qsTr("Lists %1 among your applications, so it opens without going through OmaVM first.").arg(environment.name || "")
+ }
+ CheckBox {
+ id: openInEmptyWorkspace
+ text: qsTr("Open in an empty workspace")
+ ToolTip.visible: hovered
+ ToolTip.text: qsTr("If it is already open, switches to it instead. Needs Omarchy's Hyprland; a window rule of your own for OmaVM's viewer takes precedence.")
+ }
+ CheckBox {
+ id: fullscreen
+ visible: dialog.machine
+ text: qsTr("Open the display fullscreen")
+ ToolTip.visible: hovered
+ ToolTip.text: qsTr("Leave fullscreen with Hyprland's own fullscreen key. A window rule of your own for OmaVM's viewer takes precedence.")
}
Label {
visible: dialog.machine
- text: qsTr("Shared folder")
+ text: qsTr("Installation media")
font.pixelSize: 18
font.weight: Font.DemiBold
}
@@ -137,12 +331,20 @@ Dialog {
visible: dialog.machine
text: qsTr("Installation finished — disconnect ISO on next start")
}
+
+ Label {
+ visible: dialog.machine
+ text: qsTr("Shared folder")
+ font.pixelSize: 18
+ font.weight: Font.DemiBold
+ }
RowLayout {
visible: dialog.machine
Layout.fillWidth: true
TextField {
id: sharedPath
Layout.fillWidth: true
+ Accessible.name: qsTr("Shared folder")
placeholderText: qsTr("Host folder (optional)")
selectByMouse: true
}
@@ -164,12 +366,47 @@ Dialog {
wrapMode: Text.Wrap
}
}
+ }
FolderDialog {
id: folderPicker
title: qsTr("Choose a folder to share")
- onAccepted: sharedPath.text = selectedFolder.toString().replace(/^file:\/\//, "")
+ onAccepted: sharedPath.text = backend.localPath(selectedFolder)
}
- onAccepted: backend.configure(environment.name, description.text.trim(), cpus.value, memory.value, dialog.machine, sharedPath.text.trim(), sharedReadOnly.checked, disconnectISO.checked, dialog.selectedColor, shareClipboard.checked, travelMode.checked)
+ footer: ColumnLayout {
+ spacing: 0
+ Label {
+ Layout.fillWidth: true
+ Layout.leftMargin: 24
+ Layout.rightMargin: 24
+ opacity: dialog.errorText !== "" ? 1 : 0
+ visible: opacity > 0
+ text: dialog.errorText
+ wrapMode: Text.Wrap
+ color: backend.themeRed
+ Behavior on opacity { NumberAnimation { duration: 180; easing.type: Easing.OutCubic } }
+ }
+ DialogButtonBox {
+ Layout.fillWidth: true
+ Button {
+ text: qsTr("Cancel")
+ enabled: !dialog.submitting
+ DialogButtonBox.buttonRole: DialogButtonBox.RejectRole
+ onClicked: dialog.reject()
+ }
+ Button {
+ objectName: "saveButton"
+ text: dialog.submitting ? qsTr("Saving…") : qsTr("Save")
+ highlighted: true
+ enabled: !dialog.submitting
+ DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole
+ onClicked: {
+ dialog.errorText = ""
+ dialog.submitting = true
+ backend.configure(environment.name, description.text.trim(), cpus.value, dialog.cpusTouched, memory.value, dialog.memoryTouched, dialog.machine, sharedPath.text.trim(), sharedReadOnly.checked, disconnectISO.checked, dialog.selectedColor, shareClipboard.checked, travelMode.checked, vulkan.checked, openInEmptyWorkspace.checked, launcher.checked, ssh.checked, fullscreen.checked)
+ }
+ }
+ }
+ }
}
diff --git a/gui/SnapshotsDialog.qml b/gui/SnapshotsDialog.qml
index 5afa16c..dbe7e4f 100644
--- a/gui/SnapshotsDialog.qml
+++ b/gui/SnapshotsDialog.qml
@@ -6,7 +6,17 @@ import QtQuick.Layouts
Dialog {
id: dialog
property var environment: ({})
+ readonly property bool busy: !!(backend.busyEnvironments && backend.busyEnvironments[environment.name])
readonly property var snapshots: environment.snapshots || []
+ // Mirrors internal/core/environment.go's defaultSnapshotLimit: the CLI
+ // only emits snapshot_limit in JSON when it was explicitly customized
+ // (omitempty), so an absent value means the Core-side default applies.
+ readonly property int retentionLimit: (environment.settings && environment.settings.snapshot_limit) || 10
+ // Going to a snapshot replaces the disk, which QEMU only does with
+ // the Machine shut down.
+ readonly property bool canGoTo: environment.status === "stopped"
+ property string createError: ""
+ property bool creating: false
title: qsTr("%1 Snapshots").arg(environment.name || qsTr("Environment"))
modal: true
anchors.centerIn: parent
@@ -15,7 +25,40 @@ Dialog {
standardButtons: Dialog.Close
Overlay.modal: ThemeScrim {}
- onOpened: newLabel.text = ""
+ onOpened: {
+ newLabel.text = ""
+ createError = ""
+ creating = false
+ }
+
+ // Keeps the list current without closing the dialog after create/go-to/
+ // delete (docs/TODO.md P0): backend.environments refreshes after every
+ // action, so re-find this same environment by name (its stable identity)
+ // and re-bind to the fresh snapshot list.
+ Connections {
+ target: backend
+ function onEnvironmentsChanged() {
+ if (!dialog.visible)
+ return
+ for (const env of backend.environments) {
+ if (env.name === dialog.environment.name) {
+ dialog.environment = env
+ return
+ }
+ }
+ }
+ function onActionFinished(tag, ok, text) {
+ if (tag !== "snapshot-create")
+ return
+ dialog.creating = false
+ if (ok) {
+ dialog.createError = ""
+ newLabel.text = ""
+ } else {
+ dialog.createError = text
+ }
+ }
+ }
ColumnLayout {
anchors.fill: parent
@@ -26,22 +69,56 @@ Dialog {
TextField {
id: newLabel
Layout.fillWidth: true
+ Accessible.name: qsTr("Snapshot label")
placeholderText: qsTr("Label (e.g. Before system upgrade)")
selectByMouse: true
+ enabled: !dialog.creating
onAccepted: createButton.clicked()
}
Button {
id: createButton
- text: qsTr("Create")
+ text: dialog.creating ? qsTr("Creating…") : qsTr("Create")
highlighted: true
- enabled: newLabel.text.trim().length > 0
+ enabled: !dialog.creating && !dialog.busy && newLabel.text.trim().length > 0
onClicked: {
+ dialog.createError = ""
+ dialog.creating = true
backend.createSnapshot(dialog.environment.name, newLabel.text.trim())
- newLabel.text = ""
}
}
}
+ Label {
+ Layout.fillWidth: true
+ opacity: dialog.createError !== "" ? 1 : 0
+ visible: opacity > 0
+ text: dialog.createError
+ color: backend.themeRed
+ wrapMode: Text.Wrap
+ Behavior on opacity { NumberAnimation { duration: 180; easing.type: Easing.OutCubic } }
+ }
+
+ Label {
+ Layout.fillWidth: true
+ text: dialog.snapshots.length >= dialog.retentionLimit
+ ? qsTr("Keeping the most recent %1 snapshots. Creating another one will remove the oldest: “%2”.")
+ .arg(dialog.retentionLimit).arg(dialog.snapshots.length > 0 ? dialog.snapshots[0].label : "")
+ : qsTr("Keeping up to %1 snapshots; the oldest is removed automatically after that.").arg(dialog.retentionLimit)
+ color: backend.themeMuted
+ wrapMode: Text.Wrap
+ font.pixelSize: 12
+ }
+
+ Label {
+ Layout.fillWidth: true
+ visible: !dialog.canGoTo
+ objectName: "runningHint"
+ text: qsTr("While %1 is running, a snapshot saves its disk as if the power had been cut, without open windows or memory. Shut it down to go to a snapshot.").arg(dialog.environment.name || "")
+ color: backend.themeMuted
+ wrapMode: Text.Wrap
+ font.pixelSize: 12
+ }
+
Label {
Layout.fillWidth: true
visible: dialog.snapshots.length === 0
@@ -56,13 +133,34 @@ Dialog {
clip: true
spacing: 6
model: dialog.snapshots
+ populate: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ }
+ add: Transition {
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ NumberAnimation { property: "y"; from: 24; duration: 220; easing.type: Easing.OutCubic }
+ }
+ remove: Transition {
+ NumberAnimation { property: "opacity"; to: 0; duration: 160; easing.type: Easing.InCubic }
+ }
+ displaced: Transition {
+ NumberAnimation { properties: "x,y"; duration: 200; easing.type: Easing.OutCubic }
+ }
delegate: Pane {
+ id: snapshotRow
required property var modelData
width: ListView.view.width
- Material.elevation: 1
+ Material.elevation: rowHover.hovered ? 2 : 1
Material.background: backend.themeSurface
+
+ Behavior on Material.elevation { NumberAnimation { duration: 120; easing.type: Easing.OutCubic } }
+
+ HoverHandler { id: rowHover }
+
RowLayout {
anchors.fill: parent
+ spacing: 10
+ Icon { source: "qrc:/icons/history.svg"; color: backend.themeAccentText; iconSize: 20 }
ColumnLayout {
Layout.fillWidth: true
spacing: 2
@@ -73,21 +171,85 @@ Dialog {
elide: Text.ElideRight
}
Label {
+ Layout.fillWidth: true
+ // Taken while running without guest tools: the
+ // guest couldn't flush its disks first.
text: Qt.formatDateTime(new Date(modelData.created_at), "yyyy-MM-dd hh:mm")
+ + (modelData.crash_consistent
+ ? qsTr(" · taken while running without guest tools: going to it is like restarting after a power cut")
+ : "")
color: backend.themeMuted
font.pixelSize: 12
+ wrapMode: Text.WordWrap
}
}
Button {
+ objectName: "goToButton"
text: qsTr("Go To")
- onClicked: backend.goToSnapshot(dialog.environment.name, modelData.id)
+ enabled: !dialog.busy && dialog.canGoTo
+ onClicked: {
+ confirmGoTo.snapshotId = modelData.id
+ confirmGoTo.snapshotLabel = modelData.label
+ confirmGoTo.open()
+ }
}
ToolButton {
text: qsTr("Delete")
- onClicked: backend.removeSnapshot(dialog.environment.name, modelData.id)
+ enabled: !dialog.busy
+ onClicked: {
+ confirmDeleteSnapshot.snapshotId = modelData.id
+ confirmDeleteSnapshot.snapshotLabel = modelData.label
+ confirmDeleteSnapshot.open()
+ }
}
}
}
}
}
+
+ Dialog {
+ id: confirmGoTo
+ property string snapshotId
+ property string snapshotLabel
+ title: qsTr("Go To Snapshot")
+ modal: true
+ anchors.centerIn: parent
+ width: Math.min(parent.width - 32, 380)
+ standardButtons: Dialog.Cancel | Dialog.Yes
+ // Specific verb instead of a generic "Yes" (docs/TODO.md P1).
+ Component.onCompleted: {
+ const yesButton = standardButton(Dialog.Yes)
+ if (yesButton) yesButton.text = qsTr("Go To")
+ }
+ Overlay.modal: ThemeScrim {}
+ contentItem: Label {
+ text: qsTr("Go to “%1” for %2? Anything that happened after this snapshot in %2 will be lost.")
+ .arg(confirmGoTo.snapshotLabel).arg(dialog.environment.name)
+ wrapMode: Text.Wrap
+ color: backend.themeRed
+ }
+ onAccepted: backend.goToSnapshot(dialog.environment.name, snapshotId)
+ }
+
+ Dialog {
+ id: confirmDeleteSnapshot
+ property string snapshotId
+ property string snapshotLabel
+ title: qsTr("Delete Snapshot")
+ modal: true
+ anchors.centerIn: parent
+ width: Math.min(parent.width - 32, 380)
+ standardButtons: Dialog.Cancel | Dialog.Yes
+ Component.onCompleted: {
+ const yesButton = standardButton(Dialog.Yes)
+ if (yesButton) yesButton.text = qsTr("Delete")
+ }
+ Overlay.modal: ThemeScrim {}
+ contentItem: Label {
+ text: qsTr("Delete “%1”? This cannot be undone.").arg(confirmDeleteSnapshot.snapshotLabel)
+ wrapMode: Text.Wrap
+ color: backend.themeRed
+ }
+ onAccepted: backend.removeSnapshot(dialog.environment.name, snapshotId)
+ }
}
diff --git a/gui/TerminalViewer.qml b/gui/TerminalViewer.qml
index fbcec67..da70034 100644
--- a/gui/TerminalViewer.qml
+++ b/gui/TerminalViewer.qml
@@ -1,4 +1,7 @@
import QtQuick
+import QtQuick.Controls
+import QtQuick.Controls.Material
+import QtQuick.Layouts
import QtQuick.Window
import OmaVM 1.0
@@ -8,11 +11,16 @@ Window {
height: 640
visible: true
title: terminalTitle
- color: "black"
+ color: backend.themeBackground
+ Material.theme: backend.themeMode === "light" ? Material.Light : Material.Dark
+ Material.accent: backend.themeAccent
+ Material.primary: backend.themeBackground
+ Material.background: backend.themeBackground
+ Material.foreground: backend.themeForeground
// Same reasoning as Viewer.qml: no client-side fullscreen request.
// The Hyprland window rule (contrib/hypr/omavm-viewer.lua) matches
- // this window's app id — shared with the Machine VNC viewer — so a
+ // this window's app id — shared with the Machine display viewer — so a
// Box's terminal and a Machine's display fullscreen the same way on
// the same dedicated workspace without a second rule to maintain.
@@ -21,22 +29,88 @@ Window {
anchors.fill: parent
focus: true
envName: terminalEnvName
+ shareClipboard: terminalShareClipboard
onTitleChanged: title => win.title = title
- onFinished: exitCode => win.close()
+ // Close only after a clean exit. When `omavm open` fails (the Box
+ // can't start, its engine is down) or the session dies, closing
+ // would take the error printed above with it.
+ onFinished: exitCode => {
+ if (exitCode === 0) {
+ win.close()
+ return
+ }
+ endedBar.exitCode = exitCode
+ endedBar.visible = true
+ }
onErrorOccurred: message => {
errorLabel.text = message
- errorLabel.visible = true
+ errorPanel.visible = true
+ }
+ }
+
+ Connections {
+ target: backend
+ function onThemeChanged() { view.reloadPalette() }
+ }
+
+ // Once mapped, so Omarchy's Super+C/Super+V treat this window as a
+ // terminal (Ctrl+Insert/Shift+Insert) instead of sending Ctrl+C.
+ property bool taggedAsTerminal: false
+ onActiveChanged: if (active && !taggedAsTerminal) {
+ taggedAsTerminal = true
+ backend.markAsTerminalWindow()
+ }
+
+ Rectangle {
+ id: endedBar
+ property int exitCode: 0
+ visible: false
+ anchors { left: parent.left; right: parent.right; bottom: parent.bottom }
+ height: endedRow.implicitHeight + 16
+ color: backend.themeSurface
+
+ RowLayout {
+ id: endedRow
+ anchors { fill: parent; leftMargin: 12; rightMargin: 12 }
+ Label {
+ Layout.fillWidth: true
+ color: backend.themeForeground
+ wrapMode: Text.Wrap
+ text: endedBar.exitCode > 128
+ ? qsTr("The session was terminated (signal %1).").arg(endedBar.exitCode - 128)
+ : qsTr("The session ended with an error (exit code %1).").arg(endedBar.exitCode)
+ }
+ Button {
+ text: qsTr("Try Again")
+ onClicked: {
+ endedBar.visible = false
+ view.restart()
+ }
+ }
+ Button {
+ text: qsTr("Close")
+ onClicked: win.close()
+ }
}
}
- Text {
- id: errorLabel
+ Rectangle {
+ id: errorPanel
anchors.centerIn: parent
- color: "white"
visible: false
- wrapMode: Text.Wrap
width: Math.min(parent.width - 80, 480)
- horizontalAlignment: Text.AlignHCenter
+ height: errorLabel.implicitHeight + 32
+ radius: 8
+ color: backend.themeSurface
+ border.color: backend.themeRed
+
+ Text {
+ id: errorLabel
+ anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter; margins: 16 }
+ color: backend.themeForeground
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ }
}
Shortcut {
diff --git a/gui/Viewer.qml b/gui/Viewer.qml
index 17dde3f..fa65cfd 100644
--- a/gui/Viewer.qml
+++ b/gui/Viewer.qml
@@ -1,60 +1,67 @@
import QtQuick
import QtQuick.Window
import QtQuick.Controls
+import QtQuick.Controls.Material
import OmaVM 1.0
Window {
id: win
width: 1280
height: 800
- visible: true
- title: vncTitle
- color: "black"
+ visible: false
+ title: displayTitle
+ color: backend.themeBackground
+ Material.theme: backend.themeMode === "light" ? Material.Light : Material.Dark
+ Material.accent: backend.themeAccent
+ Material.primary: backend.themeBackground
+ Material.background: backend.themeBackground
+ Material.foreground: backend.themeForeground
- // No client-side fullscreen request here on purpose: a Hyprland
- // window rule (contrib/hypr/omavm-viewer.lua) is the intended way to
- // fullscreen this on its own workspace. If both the client and the
- // compositor's rule request fullscreen independently, Wayland treats
- // the second request as a toggle, so the two fight and the window can
- // end up NOT fullscreen. Without that opt-in rule, this just opens as
- // an ordinary window — see README.md.
+ // Fullscreen is a Machine setting (on by default). main.cpp turns it
+ // off here when a personal Hyprland rule for the viewer
+ // (contrib/hypr/omavm-viewer.lua) already makes it fullscreen: two
+ // independent requests act as a toggle and cancel each other.
+ Component.onCompleted: {
+ if (displayFullscreen)
+ showFullScreen()
+ else
+ show()
+ }
// Clipboard sharing is a Machine Settings toggle (opt-out, on by
// default — see gui/SettingsDialog.qml), not a per-window checkbox:
// the user shouldn't have to remember to re-enable it every time
// they open the viewer. main.cpp passes the Machine's current
- // setting in as vncShareClipboard.
- VncView {
+ // setting in as displayShareClipboard.
+ DisplayView {
id: view
anchors.fill: parent
focus: true
- shareClipboard: vncShareClipboard
- onClipboardWarning: message => { clipboardNote.text = message; clipboardNote.visible = true }
- socketPath: vncSocketPath
+ shareClipboard: displayShareClipboard
+ connectionFd: displayConnectionFd
onConnectionFailed: message => {
errorLabel.text = message
- errorLabel.visible = true
+ errorPanel.visible = true
}
}
- Label {
- id: clipboardNote
- visible: false
- anchors { top: parent.top; horizontalCenter: parent.horizontalCenter; topMargin: 8 }
- width: Math.min(parent.width - 32, 600)
- wrapMode: Text.Wrap
- color: "white"
- background: Rectangle { color: "#333333" }
- }
-
- Text {
- id: errorLabel
+ Rectangle {
+ id: errorPanel
anchors.centerIn: parent
- color: "white"
visible: false
- wrapMode: Text.Wrap
width: Math.min(parent.width - 80, 480)
- horizontalAlignment: Text.AlignHCenter
+ height: errorLabel.implicitHeight + 32
+ radius: 8
+ color: backend.themeSurface
+ border.color: backend.themeRed
+
+ Text {
+ id: errorLabel
+ anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter; margins: 16 }
+ color: backend.themeForeground
+ wrapMode: Text.Wrap
+ horizontalAlignment: Text.AlignHCenter
+ }
}
Shortcut {
diff --git a/gui/backend.cpp b/gui/backend.cpp
index 9cecc42..9378106 100644
--- a/gui/backend.cpp
+++ b/gui/backend.cpp
@@ -1,14 +1,185 @@
#include "backend.h"
#include "colorstoml.h"
+#include
#include
+#include
#include
+#include
#include
+#include
#include
#include
#include
#include
+#include
+
+namespace {
+
+// "Open in an empty workspace" (docs/TODO.md P2, CLAUDE.md's validated
+// Hyprland policy). This whole block is desktop integration, deliberately
+// kept out of the Core/Go backends (CLAUDE.md: "a política pertence à
+// integração com o desktop, sem acoplar o Core ao Hyprland").
+//
+// This Omarchy Hyprland fork evaluates `hyprctl dispatch ` as Lua
+// source (`hl.dispatch()`, verbatim, not shell-tokenized) — classic
+// Hyprland selector strings like "class:^(...)$" don't parse there. The
+// validated pattern (confirmed against a real session, and matching how
+// Omarchy's own bar widget QML dispatches workspace switches — see
+// /usr/share/omarchy/shell/plugins/bar/widgets/Workspaces.qml) is a
+// single Lua expression string, using the structured `hl` API
+// (hl.get_workspaces()/hl.get_windows()/hl.dispatch(hl.dsp...)) instead
+// of regex window selectors.
+
+// True only when a Hyprland session is actually running — checked via
+// the env var alone (no process spawn) before ever touching hyprctl.
+bool hyprlandAvailable() {
+ return qEnvironmentVariableIsSet("HYPRLAND_INSTANCE_SIGNATURE");
+}
+
+// Escapes text for embedding inside a single-quoted Lua string literal.
+QString luaQuote(const QString &text) {
+ QString escaped = text;
+ escaped.replace(QLatin1Char('\\'), QStringLiteral("\\\\"));
+ escaped.replace(QLatin1Char('\''), QStringLiteral("\\'"));
+ return QLatin1Char('\'') + escaped + QLatin1Char('\'');
+}
+
+// Runs a Lua snippet through hyprctl's synchronous "repl" command and
+// returns its printed result. Blocking, with a short timeout: this is a
+// local socket round-trip that only runs right before opening an
+// environment, and the caller needs an answer before deciding where to
+// launch — there is no async equivalent of "decide, then launch" here
+// without a much larger restructure, so this stays a bounded, occasional
+// stall rather than pretending to be non-blocking.
+QString hyprctlRepl(const QString &luaCode, bool *ok) {
+ QProcess proc;
+ proc.start(QStringLiteral("hyprctl"), {QStringLiteral("repl"), luaCode});
+ const bool started = proc.waitForStarted(500);
+ const bool finished = started && proc.waitForFinished(1500);
+ if (!finished) {
+ proc.kill();
+ proc.waitForFinished(200);
+ }
+ if (ok)
+ *ok = finished && proc.exitCode() == 0;
+ return QString::fromUtf8(proc.readAllStandardOutput()).trimmed();
+}
+
+
+} // namespace
+
+// Finds this environment's already-open viewer/terminal window by class
+// + title (the shared `dev.omavm.viewer` app id alone can't tell two
+// Machines or Boxes apart — both gui/main.cpp's --display-fd/--terminal modes
+// title the window " — OmaVM"). If none exists, picks the
+// lowest-numbered eligible workspace on the currently active monitor:
+// empty (HL.Workspace.is_empty), not special, and not already claimed by
+// another monitor — including a workspace ID that doesn't exist yet
+// (materializing it is exactly what Hyprland does when you focus an
+// unused number). Known, deliberate gaps versus the full P2 policy:
+// workspaces "reserved by personal rules" can't be distinguished from any
+// other non-empty workspace by this API, so they're simply skipped
+// because they're non-empty, not recognized as reserved; and there is no
+// queryable "configured workspace range" to respect, so the search is
+// capped at a fixed, generous bound (30) instead.
+WorkspacePlacement placeInEmptyWorkspace(const QString &title) {
+ if (!hyprlandAvailable() || hasPersonalViewerRule(hyprConfigDir()))
+ return WorkspacePlacement::NotApplicable;
+
+ const QString script =
+ QStringLiteral(
+ "local title = %1\n"
+ "local existing = hl.get_windows({ class = 'dev.omavm.viewer', title "
+ "= title })\n"
+ "if #existing > 0 then\n"
+ " hl.dispatch(hl.dsp.focus({ workspace = existing[1].workspace.id "
+ "}))\n"
+ " return 'focused'\n"
+ "end\n"
+ "local mon = hl.get_active_monitor()\n"
+ "local byId = {}\n"
+ "for _, w in ipairs(hl.get_workspaces()) do\n"
+ " if w.monitor == nil or (mon ~= nil and w.monitor.id == mon.id) "
+ "then\n"
+ " byId[w.id] = w\n"
+ " end\n"
+ "end\n"
+ "for i = 1, 30 do\n"
+ " local w = byId[i]\n"
+ " if w == nil or (w.is_empty and not w.special) then\n"
+ " hl.dispatch(hl.dsp.focus({ workspace = tostring(i) }))\n"
+ " return 'switched'\n"
+ " end\n"
+ "end\n"
+ "return 'none'\n")
+ .arg(luaQuote(title));
+
+ bool ok = false;
+ const QString result = hyprctlRepl(script, &ok);
+ if (!ok)
+ return WorkspacePlacement::Unavailable;
+ if (result == QStringLiteral("focused"))
+ return WorkspacePlacement::AlreadyFocusedExisting;
+ if (result == QStringLiteral("switched"))
+ return WorkspacePlacement::LaunchNormally;
+ return WorkspacePlacement::Unavailable;
+}
+
+// Whether the user's Hyprland config has a window rule of its own for the
+// viewer (contrib/hypr/omavm-viewer.lua, or anything else naming
+// dev.omavm.viewer). Such a rule moves the window after it opens, so
+// switching to an empty workspace first would only leave the user
+// looking at an empty workspace. The rule is theirs and wins.
+QString hyprConfigDir() {
+ return QStandardPaths::writableLocation(
+ QStandardPaths::GenericConfigLocation) +
+ QStringLiteral("/hypr");
+}
+
+bool hasPersonalViewerRule(const QString &hyprConfigDir) {
+ QDirIterator it(hyprConfigDir, {QStringLiteral("*.lua"), QStringLiteral("*.conf")},
+ QDir::Files, QDirIterator::Subdirectories);
+ while (it.hasNext()) {
+ QFile file(it.next());
+ if (file.size() > 1024 * 1024 || !file.open(QIODevice::ReadOnly))
+ continue;
+ for (const QByteArray &raw : file.readAll().split('\n')) {
+ // A commented-out rule (Lua "--", hyprlang "#") isn't active.
+ QByteArray line = raw;
+ const int luaComment = line.indexOf("--");
+ if (luaComment >= 0)
+ line.truncate(luaComment);
+ if (line.trimmed().startsWith('#'))
+ continue;
+ if (line.contains("dev.omavm.viewer"))
+ return true;
+ }
+ }
+ return false;
+}
+
+QString terminalTagScript(qint64 pid) {
+ // Omarchy's Super+C/Super+V send Ctrl+Insert/Shift+Insert only to windows
+ // tagged "terminal" (default/hypr/bindings/clipboard.lua), and tag
+ // terminals by app id. The Box terminal shares dev.omavm.viewer with the
+ // Machine viewer, where Ctrl+C is right, so its own window is tagged at
+ // runtime instead: without the tag, Super+C reached the program in the
+ // Box as Ctrl+C and interrupted it. Found by pid: the shell can retitle
+ // the window, and the viewer process owns only this one.
+ return QStringLiteral(
+ "for _, w in ipairs(hl.get_windows()) do\n"
+ " if w.pid == %1 and w.class == 'dev.omavm.viewer' then\n"
+ " hl.dispatch(hl.dsp.window.tag({ tag = '+terminal', window "
+ "= 'address:' .. w.address }))\n"
+ " return 'tagged'\n"
+ " end\n"
+ "end\n"
+ "return 'none'\n")
+ .arg(pid);
+}
+
Backend::Backend(QObject *parent) : QObject(parent) {
connect(&m_themeWatcher, &QFileSystemWatcher::fileChanged, this,
&Backend::loadTheme);
@@ -29,263 +200,469 @@ QString Backend::cliPath() const {
return sibling;
}
-void Backend::setBusy(bool busy) {
- if (m_busy == busy)
- return;
- m_busy = busy;
+QString Backend::busyAction() const {
+ if (m_busy.size() == 1)
+ return m_busy.first();
+ return m_busy.isEmpty() ? QString()
+ : QStringLiteral("%1 actions").arg(m_busy.size());
+}
+
+QVariantMap Backend::busyEnvironments() const {
+ QVariantMap names;
+ for (auto it = m_busy.cbegin(); it != m_busy.cend(); ++it)
+ if (!it.key().isEmpty())
+ names.insert(it.key(), it.value());
+ return names;
+}
+
+QString Backend::busyMessage(const QString &key) const {
+ const QString action = m_busy.value(key);
+ return action.isEmpty()
+ ? QStringLiteral("Still working — please wait.")
+ : QStringLiteral("Still %1 — please wait.").arg(action);
+}
+
+// Actions run concurrently, one per environment: the Core serializes the
+// operations on one environment itself (a lock per environment), so a Box
+// pulling its image for minutes no longer holds every other card. key is
+// the environment's name, or "" for reloading the list.
+bool Backend::beginBusy(const QString &key, const QString &label) {
+ if (m_busy.contains(key)) {
+ // Identify what's already running instead of silently dropping the
+ // new request (docs/TODO.md P0: no action may look like it succeeded
+ // without executing). Not an error — the user just needs to wait.
+ emit message(busyMessage(key), false);
+ return false;
+ }
+ m_busy.insert(key, label);
+ ++m_pollGeneration; // Discard a background poll started before this action.
+ emit busyChanged();
+ return true;
+}
+
+void Backend::endBusy(const QString &key) {
+ m_busy.remove(key);
emit busyChanged();
+ if (m_quitRequested && m_busy.isEmpty())
+ emit readyToQuit();
+}
+
+void Backend::requestQuit() {
+ m_quitRequested = true;
+ if (m_busy.isEmpty())
+ QMetaObject::invokeMethod(this, &Backend::readyToQuit,
+ Qt::QueuedConnection);
}
-void Backend::refresh() {
- if (m_busy)
+void Backend::refresh() { refreshImpl(false); }
+
+void Backend::poll() {
+ if (m_busy.contains(QString()) || m_polling)
return;
- setBusy(true);
- auto *process = new QProcess(this);
- connect(process, &QProcess::errorOccurred, this,
- [this, process](QProcess::ProcessError error) {
- if (error != QProcess::FailedToStart)
- return;
- setBusy(false);
- emit message(QStringLiteral("Could not start omavm: ") +
- process->errorString(),
- true);
- process->deleteLater();
- });
- connect(process, &QProcess::finished, this, [this, process](int code) {
- const QByteArray output = process->readAllStandardOutput();
- const QString errorText =
- QString::fromUtf8(process->readAllStandardError()).trimmed();
- process->deleteLater();
- setBusy(false);
- if (code != 0) {
- emit message(errorText.isEmpty()
- ? QStringLiteral("Could not load environments")
- : errorText,
- true);
- return;
- }
- const QJsonDocument document = QJsonDocument::fromJson(output);
- QVariantList next;
- for (const QJsonValue &value : document.array())
- next.append(value.toObject().toVariantMap());
- m_environments = next;
- emit environmentsChanged();
- for (int i = 0; i < m_environments.size(); ++i)
- enrichEnvironment(i);
- });
- process->start(cliPath(), {QStringLiteral("list"), QStringLiteral("--json")});
+ refreshImpl(true);
}
-void Backend::enrichEnvironment(int index) {
- if (index < 0 || index >= m_environments.size())
+// After an action: a reload that is already running may have read the
+// registry before the action ended, so one more follows it.
+void Backend::refreshSoon() {
+ if (m_polling || m_busy.contains(QString())) {
+ m_refreshPending = true;
return;
- const QString name =
- m_environments.at(index).toMap().value("name").toString();
- auto *status = new QProcess(this);
- connect(
- status, &QProcess::finished, this, [this, status, index, name](int code) {
- const QJsonDocument document =
- QJsonDocument::fromJson(status->readAllStandardOutput());
- status->deleteLater();
- if (code != 0 || index >= m_environments.size())
- return;
- QVariantMap environment = m_environments.at(index).toMap();
- const QString state = document.object().value("state").toString();
- environment.insert(QStringLiteral("status"), state);
- m_environments[index] = environment;
- emit environmentsChanged();
+ }
+ refreshImpl(true);
+}
+
+void Backend::listLoaded() {
+ if (m_refreshPending && !m_quitRequested) {
+ m_refreshPending = false;
+ refreshImpl(true);
+ }
+}
- if (environment.value("kind").toString() != QStringLiteral("machine"))
+void Backend::refreshImpl(bool silent) {
+ if (silent) {
+ m_polling = true;
+ } else if (!beginBusy(QString(), QStringLiteral("loading environments"))) {
+ return;
+ }
+ const int pollGeneration = m_pollGeneration;
+ auto *process = new QProcess(this);
+ connect(
+ process, &QProcess::errorOccurred, this,
+ [this, process, silent, pollGeneration](QProcess::ProcessError error) {
+ if (error != QProcess::FailedToStart)
return;
- auto *integration = new QProcess(this);
- connect(integration, &QProcess::finished, this,
- [this, integration, index](int integrationCode) {
- const QJsonDocument report = QJsonDocument::fromJson(
- integration->readAllStandardOutput());
- integration->deleteLater();
- if (integrationCode != 0 || index >= m_environments.size())
- return;
- QVariantMap current = m_environments.at(index).toMap();
- current.insert(QStringLiteral("guestAgent"),
- report.object()
- .value(QStringLiteral("guest_agent"))
- .toString());
- current.insert(
- QStringLiteral("integrationHint"),
- report.object().value(QStringLiteral("hint")).toString());
- m_environments[index] = current;
- emit environmentsChanged();
- });
- integration->start(cliPath(), {QStringLiteral("integration"), name,
- QStringLiteral("--json")});
-
- if (state != QStringLiteral("running"))
+ if (silent)
+ m_polling = false;
+ else
+ endBusy(QString());
+ QMetaObject::invokeMethod(this, &Backend::listLoaded,
+ Qt::QueuedConnection);
+ if (silent && pollGeneration != m_pollGeneration) {
+ process->deleteLater();
return;
- auto *preview = new QProcess(this);
- connect(
- preview, &QProcess::finished, this,
- [this, preview, index](int previewCode) {
- const QString path =
- QString::fromUtf8(preview->readAllStandardOutput()).trimmed();
- preview->deleteLater();
- if (previewCode != 0 || path.isEmpty() ||
- index >= m_environments.size())
- return;
- QVariantMap current = m_environments.at(index).toMap();
- current.insert(QStringLiteral("preview"),
- QUrl::fromLocalFile(path));
+ }
+ const QString text =
+ QStringLiteral("Could not start omavm: ") + process->errorString();
+ if (m_listError != text) {
+ m_listError = text;
+ emit listErrorChanged();
+ emit message(text, true);
+ }
+ process->deleteLater();
+ });
+ connect(process, &QProcess::finished, this,
+ [this, process, silent, pollGeneration](int code) {
+ const QByteArray output = process->readAllStandardOutput();
+ const QString errorText =
+ QString::fromUtf8(process->readAllStandardError()).trimmed();
+ process->deleteLater();
+ if (silent)
+ m_polling = false;
+ else
+ endBusy(QString());
+ QMetaObject::invokeMethod(this, &Backend::listLoaded,
+ Qt::QueuedConnection);
+ if (silent && pollGeneration != m_pollGeneration)
+ return;
+ if (code != 0) {
+ const QString text =
+ errorText.isEmpty()
+ ? QStringLiteral("Could not load environments")
+ : errorText;
+ if (m_listError != text) {
+ m_listError = text;
+ emit listErrorChanged();
+ emit message(text, true);
+ }
+ return;
+ }
+ if (!m_listError.isEmpty()) {
+ m_listError.clear();
+ emit listErrorChanged();
+ }
+ const QJsonDocument document = QJsonDocument::fromJson(output);
+ QVariantList next;
+ for (const QJsonValue &value : document.array()) {
+ // `list --status` nests what the backend reports; the cards
+ // read it as flat fields.
+ QVariantMap current = value.toObject().toVariantMap();
+ const QVariantMap status =
+ current.take(QStringLiteral("status")).toMap();
+ current.insert(QStringLiteral("status"),
+ status.value(QStringLiteral("state")));
+ current.insert(QStringLiteral("statusDetail"),
+ status.value(QStringLiteral("detail")));
+ const QVariantMap integration =
+ current.take(QStringLiteral("integration")).toMap();
+ if (!integration.isEmpty()) {
+ current.insert(QStringLiteral("guestAgent"),
+ integration.value(QStringLiteral("guest_agent")));
+ current.insert(QStringLiteral("integrationHint"),
+ integration.value(QStringLiteral("hint")));
+ }
+ // Keep the previous preview while the Machine keeps running:
+ // recapturing it every poll made cards flash. The list is
+ // small (the UI is designed around up to 30 environments),
+ // so a lookup here is simpler than another index.
+ if (current.value(QStringLiteral("status")) ==
+ QStringLiteral("running")) {
+ for (const QVariant &previousItem :
+ std::as_const(m_environments)) {
+ const QVariantMap previous = previousItem.toMap();
+ if (previous.value(QStringLiteral("id")) ==
+ current.value(QStringLiteral("id")) &&
+ previous.contains(QStringLiteral("preview"))) {
+ current.insert(QStringLiteral("preview"),
+ previous.value(QStringLiteral("preview")));
+ break;
+ }
+ }
+ }
+ next.append(current);
+ }
+ const int generation = ++m_environmentsGeneration;
+ if (next != m_environments) {
+ m_environments = next;
+ emit environmentsChanged();
+ }
+ for (int i = 0; i < m_environments.size(); ++i)
+ capturePreview(i, generation);
+ });
+ process->start(cliPath(), {QStringLiteral("list"), QStringLiteral("--status"),
+ QStringLiteral("--json")});
+}
+
+// capturePreview asks for a thumbnail of a running Machine that has none
+// yet. Status and guest tools already came with the list.
+void Backend::capturePreview(int index, int generation) {
+ if (generation != m_environmentsGeneration || index < 0 ||
+ index >= m_environments.size())
+ return;
+ const QVariantMap environment = m_environments.at(index).toMap();
+ const QString id = environment.value(QStringLiteral("id")).toString();
+ if (environment.value(QStringLiteral("kind")).toString() !=
+ QStringLiteral("machine") ||
+ environment.value(QStringLiteral("status")).toString() !=
+ QStringLiteral("running")) {
+ m_previewRetryAt.remove(id);
+ return;
+ }
+ if (environment.contains(QStringLiteral("preview")) ||
+ QDateTime::currentMSecsSinceEpoch() < m_previewRetryAt.value(id))
+ return;
+ auto *preview = new QProcess(this);
+ connect(preview, &QProcess::finished, this,
+ [this, preview, index, generation, id](int previewCode) {
+ const QString path =
+ QString::fromUtf8(preview->readAllStandardOutput()).trimmed();
+ preview->deleteLater();
+ if (previewCode != 0 || path.isEmpty()) {
+ m_previewRetryAt.insert(
+ id, QDateTime::currentMSecsSinceEpoch() + 60000);
+ return;
+ }
+ m_previewRetryAt.remove(id);
+ // A poll that landed meanwhile may have reordered the list:
+ // never write by a stale index.
+ if (generation != m_environmentsGeneration ||
+ index >= m_environments.size())
+ return;
+ QVariantMap current = m_environments.at(index).toMap();
+ const QUrl previewUrl = QUrl::fromLocalFile(path);
+ if (current.value(QStringLiteral("preview")).toUrl() !=
+ previewUrl) {
+ current.insert(QStringLiteral("preview"), previewUrl);
m_environments[index] = current;
emit environmentsChanged();
- });
- preview->start(cliPath(), {QStringLiteral("preview"), name});
- });
- status->start(cliPath(),
- {QStringLiteral("status"), name, QStringLiteral("--json")});
+ }
+ });
+ preview->start(cliPath(), {QStringLiteral("preview"),
+ environment.value(QStringLiteral("name")).toString()});
}
-void Backend::run(const QStringList &arguments, bool refreshAfter) {
- if (m_busy)
+void Backend::run(const QString &key, const QStringList &arguments,
+ const QString &label, const QString &tag,
+ bool refreshAfter) {
+ if (!beginBusy(key, label)) {
+ if (!tag.isEmpty())
+ emit actionFinished(tag, false, busyMessage(key));
return;
- setBusy(true);
+ }
auto *process = new QProcess(this);
connect(process, &QProcess::errorOccurred, this,
- [this, process](QProcess::ProcessError error) {
+ [this, process, tag, key](QProcess::ProcessError error) {
if (error != QProcess::FailedToStart)
return;
- setBusy(false);
- emit message(QStringLiteral("Could not start omavm: ") +
- process->errorString(),
- true);
+ endBusy(key);
+ const QString text = QStringLiteral("Could not start omavm: ") +
+ process->errorString();
+ emit message(text, true);
+ if (!tag.isEmpty())
+ emit actionFinished(tag, false, text);
process->deleteLater();
});
connect(process, &QProcess::finished, this,
- [this, process, refreshAfter](int code) {
+ [this, process, refreshAfter, tag, key](int code) {
const QString output =
QString::fromUtf8(process->readAllStandardOutput()).trimmed();
const QString errorText =
QString::fromUtf8(process->readAllStandardError()).trimmed();
process->deleteLater();
- setBusy(false);
+ endBusy(key);
+ // Even a failed action may have changed the state (a Start
+ // that got halfway).
+ if (refreshAfter && !m_quitRequested)
+ refreshSoon();
if (code != 0) {
- emit message(errorText.isEmpty() ? QStringLiteral("Action failed")
- : errorText,
- true);
+ const QString text = errorText.isEmpty()
+ ? QStringLiteral("Action failed")
+ : errorText;
+ emit message(text, true);
+ if (!tag.isEmpty())
+ emit actionFinished(tag, false, text);
return;
}
if (!output.isEmpty())
emit message(output, false);
- if (refreshAfter)
- refresh();
+ if (!tag.isEmpty())
+ emit actionFinished(tag, true, output);
});
process->start(cliPath(), arguments);
}
void Backend::createEnvironment(const QString &name, const QString &image,
- const QString &kind) {
- run({QStringLiteral("create"), QStringLiteral("--name"), name,
- QStringLiteral("--kind"), kind, QStringLiteral("--image"), image});
+ const QString &kind, int cpus,
+ bool cpusTouched, int memoryMiB,
+ bool memoryTouched) {
+ QStringList arguments{QStringLiteral("create"),
+ QStringLiteral("--name"),
+ name,
+ QStringLiteral("--kind"),
+ kind,
+ QStringLiteral("--image"),
+ image};
+ // Only pin hardware the user actually adjusted in the summary step —
+ // sending the shown default (2 CPUs/2048 MiB) unconditionally would
+ // pin every new Machine's hardware from birth, permanently disabling
+ // Travel Mode's automatic reduction on battery for it (same bug class
+ // as Backend::configure, docs/TODO.md P2).
+ if (kind == QStringLiteral("machine")) {
+ if (cpusTouched)
+ arguments << QStringLiteral("--cpus") << QString::number(cpus);
+ if (memoryTouched)
+ arguments << QStringLiteral("--memory-mib") << QString::number(memoryMiB);
+ }
+ run(name, arguments, QStringLiteral("creating %1").arg(name),
+ QStringLiteral("create"));
}
void Backend::start(const QString &name) {
- run({QStringLiteral("start"), name});
+ run(name, {QStringLiteral("start"), name}, QStringLiteral("starting %1").arg(name),
+ QStringLiteral("start"));
+}
+void Backend::stop(const QString &name) {
+ run(name, {QStringLiteral("stop"), name}, QStringLiteral("stopping %1").arg(name),
+ QStringLiteral("stop"));
}
-void Backend::stop(const QString &name) { run({QStringLiteral("stop"), name}); }
void Backend::restart(const QString &name) {
- run({QStringLiteral("restart"), name});
+ run(name, {QStringLiteral("restart"), name},
+ QStringLiteral("restarting %1").arg(name), QStringLiteral("restart"));
}
void Backend::pause(const QString &name) {
- run({QStringLiteral("pause"), name});
+ run(name, {QStringLiteral("pause"), name}, QStringLiteral("pausing %1").arg(name),
+ QStringLiteral("pause"));
}
void Backend::resume(const QString &name) {
- run({QStringLiteral("resume"), name});
+ run(name, {QStringLiteral("resume"), name}, QStringLiteral("resuming %1").arg(name),
+ QStringLiteral("resume"));
}
void Backend::forceStop(const QString &name) {
- run({QStringLiteral("force-stop"), name});
+ run(name, {QStringLiteral("force-stop"), name},
+ QStringLiteral("force stopping %1").arg(name),
+ QStringLiteral("force-stop"));
}
void Backend::configure(const QString &name, const QString &description,
- int cpus, int memoryMiB, bool machine,
+ int cpus, bool cpusTouched, int memoryMiB,
+ bool memoryTouched, bool machine,
const QString &sharedPath, bool sharedReadOnly,
bool disconnectISO, const QString &color,
- bool shareClipboard, bool travelMode) {
+ bool shareClipboard, bool travelMode, bool vulkan,
+ bool openInEmptyWorkspace, bool launcher, bool ssh,
+ bool fullscreen) {
QStringList arguments{QStringLiteral("settings"), name,
QStringLiteral("--description"), description,
QStringLiteral("--color"), color};
+ arguments << (openInEmptyWorkspace
+ ? QStringLiteral("--open-in-empty-workspace=true")
+ : QStringLiteral("--open-in-empty-workspace=false"));
+ arguments << (launcher ? QStringLiteral("--launcher=true")
+ : QStringLiteral("--launcher=false"));
+ // Both kinds: the guest's clipboard for a Machine, programs copying from
+ // the terminal (OSC 52) for a Box.
+ arguments << (shareClipboard ? QStringLiteral("--share-clipboard=true")
+ : QStringLiteral("--share-clipboard=false"));
+ arguments << (travelMode ? QStringLiteral("--travel-mode=true")
+ : QStringLiteral("--travel-mode=false"));
if (machine) {
arguments << (disconnectISO ? QStringLiteral("--disconnect-iso=true")
: QStringLiteral("--disconnect-iso=false"));
- arguments << QStringLiteral("--cpus") << QString::number(cpus)
- << QStringLiteral("--memory-mib") << QString::number(memoryMiB)
- << QStringLiteral("--shared-path") << sharedPath;
+ // Only send --cpus/--memory-mib when the SpinBox was actually
+ // touched: the value shown is Core's *effective* default (2/2048)
+ // even when nothing is pinned, so resending it unconditionally on
+ // every save (e.g. just editing the description) would silently
+ // pin it — permanently turning off Travel Mode's automatic
+ // reduction on battery for this Machine (docs/TODO.md P2).
+ if (cpusTouched)
+ arguments << QStringLiteral("--cpus") << QString::number(cpus);
+ if (memoryTouched)
+ arguments << QStringLiteral("--memory-mib") << QString::number(memoryMiB);
+ arguments << QStringLiteral("--shared-path") << sharedPath;
arguments << (sharedReadOnly ? QStringLiteral("--shared-read-only")
: QStringLiteral("--shared-writable"));
- arguments << (shareClipboard ? QStringLiteral("--share-clipboard=true")
- : QStringLiteral("--share-clipboard=false"));
- arguments << (travelMode ? QStringLiteral("--travel-mode=true")
- : QStringLiteral("--travel-mode=false"));
+ arguments << (vulkan ? QStringLiteral("--vulkan=true")
+ : QStringLiteral("--vulkan=false"));
+ arguments << (ssh ? QStringLiteral("--ssh=true")
+ : QStringLiteral("--ssh=false"));
+ arguments << (fullscreen ? QStringLiteral("--fullscreen=true")
+ : QStringLiteral("--fullscreen=false"));
}
- run(arguments);
+ run(name, arguments, QStringLiteral("saving settings for %1").arg(name),
+ QStringLiteral("configure"));
}
void Backend::remove(const QString &name) {
- run({QStringLiteral("remove"), name});
+ run(name, {QStringLiteral("remove"), name}, QStringLiteral("deleting %1").arg(name),
+ QStringLiteral("remove"));
}
-void Backend::runForApps(const QStringList &arguments, const QString &name) {
- if (m_busy)
+void Backend::runForApps(const QStringList &arguments, const QString &name,
+ const QString &label, const QString &tag) {
+ if (!beginBusy(name, label)) {
+ emit actionFinished(tag, false, busyMessage(name));
return;
- setBusy(true);
+ }
auto *process = new QProcess(this);
connect(process, &QProcess::errorOccurred, this,
- [this, process](QProcess::ProcessError error) {
+ [this, process, tag, name](QProcess::ProcessError error) {
if (error != QProcess::FailedToStart)
return;
- setBusy(false);
- emit message(QStringLiteral("Could not start omavm: ") +
- process->errorString(),
- true);
+ endBusy(name);
+ const QString text = QStringLiteral("Could not start omavm: ") +
+ process->errorString();
+ emit message(text, true);
+ emit actionFinished(tag, false, text);
process->deleteLater();
});
- connect(process, &QProcess::finished, this, [this, process, name](int code) {
- const QString errorText =
- QString::fromUtf8(process->readAllStandardError()).trimmed();
- process->deleteLater();
- setBusy(false);
- if (code != 0) {
- emit message(errorText.isEmpty() ? QStringLiteral("Action failed")
- : errorText,
- true);
- return;
- }
- refreshApps(name);
- });
+ connect(
+ process, &QProcess::finished, this, [this, process, name, tag](int code) {
+ const QString errorText =
+ QString::fromUtf8(process->readAllStandardError()).trimmed();
+ process->deleteLater();
+ endBusy(name);
+ if (code != 0) {
+ const QString text =
+ errorText.isEmpty() ? QStringLiteral("Action failed") : errorText;
+ emit message(text, true);
+ emit actionFinished(tag, false, text);
+ return;
+ }
+ emit actionFinished(tag, true, QString());
+ refreshApps(name);
+ });
process->start(cliPath(), arguments);
}
void Backend::refreshApps(const QString &name) {
- if (m_busy)
+ if (!beginBusy(name,
+ QStringLiteral("loading applications for %1").arg(name)))
return;
- setBusy(true);
auto *process = new QProcess(this);
connect(process, &QProcess::errorOccurred, this,
- [this, process](QProcess::ProcessError error) {
+ [this, process, name](QProcess::ProcessError error) {
if (error != QProcess::FailedToStart)
return;
- setBusy(false);
- emit message(QStringLiteral("Could not start omavm: ") +
- process->errorString(),
- true);
+ endBusy(name);
+ const QString text = QStringLiteral("Could not start omavm: ") +
+ process->errorString();
+ m_appsError = text;
+ m_appsEnvironment = name;
+ emit appsChanged();
+ emit message(text, true);
process->deleteLater();
});
- connect(process, &QProcess::finished, this, [this, process](int code) {
+ connect(process, &QProcess::finished, this, [this, process, name](int code) {
const QByteArray output = process->readAllStandardOutput();
const QString errorText =
QString::fromUtf8(process->readAllStandardError()).trimmed();
process->deleteLater();
- setBusy(false);
+ endBusy(name);
if (code != 0) {
- emit message(errorText.isEmpty()
- ? QStringLiteral("Could not list applications")
- : errorText,
- true);
+ m_appsError = errorText.isEmpty()
+ ? QStringLiteral("Could not list applications")
+ : errorText;
+ m_appsEnvironment = name;
+ emit appsChanged();
+ emit message(m_appsError, true);
return;
}
const QJsonDocument document = QJsonDocument::fromJson(output);
@@ -293,6 +670,8 @@ void Backend::refreshApps(const QString &name) {
for (const QJsonValue &value : document.array())
next.append(value.toObject().toVariantMap());
m_apps = next;
+ m_appsError.clear();
+ m_appsEnvironment = name;
emit appsChanged();
});
process->start(cliPath(),
@@ -301,40 +680,86 @@ void Backend::refreshApps(const QString &name) {
void Backend::exportApp(const QString &name, const QString &id) {
runForApps({QStringLiteral("apps"), name, QStringLiteral("--export"), id},
- name);
+ name, QStringLiteral("exporting an application from %1").arg(name),
+ QStringLiteral("apps-export"));
}
void Backend::unexportApp(const QString &name, const QString &id) {
- runForApps({QStringLiteral("apps"), name, QStringLiteral("--unexport"), id},
- name);
+ runForApps(
+ {QStringLiteral("apps"), name, QStringLiteral("--unexport"), id}, name,
+ QStringLiteral("removing an application shortcut from %1").arg(name),
+ QStringLiteral("apps-unexport"));
}
void Backend::createSnapshot(const QString &name, const QString &label) {
- run({QStringLiteral("snapshot"), QStringLiteral("create"), name,
- QStringLiteral("--label"), label});
+ run(name, {QStringLiteral("snapshot"), QStringLiteral("create"), name,
+ QStringLiteral("--label"), label},
+ QStringLiteral("creating a snapshot of %1").arg(name),
+ QStringLiteral("snapshot-create"));
}
void Backend::goToSnapshot(const QString &name, const QString &id) {
- run({QStringLiteral("snapshot"), QStringLiteral("go-to"), name, id});
+ run(name, {QStringLiteral("snapshot"), QStringLiteral("go-to"), name, id},
+ QStringLiteral("going to a snapshot of %1").arg(name),
+ QStringLiteral("snapshot-goto"));
}
void Backend::removeSnapshot(const QString &name, const QString &id) {
- run({QStringLiteral("snapshot"), QStringLiteral("remove"), name, id});
+ run(name, {QStringLiteral("snapshot"), QStringLiteral("remove"), name, id},
+ QStringLiteral("deleting a snapshot of %1").arg(name),
+ QStringLiteral("snapshot-remove"));
+}
+
+void Backend::markAsTerminalWindow() const {
+ if (!hyprlandAvailable())
+ return;
+ QProcess::startDetached(
+ QStringLiteral("hyprctl"),
+ {QStringLiteral("repl"),
+ terminalTagScript(QCoreApplication::applicationPid())});
+}
+
+void Backend::copyToClipboard(const QString &text) const {
+ if (auto *clipboard = QGuiApplication::clipboard())
+ clipboard->setText(text);
}
void Backend::open(const QString &name, const QString &kind) {
+ // The viewer itself picks the workspace (and goes fullscreen) when it
+ // starts, so it happens however the environment is opened: here, from
+ // its launcher entry or with `omavm open`.
+ bool emptyWorkspace = true;
+ bool shareClipboard = true;
+ for (const QVariant &item : m_environments) {
+ const QVariantMap env = item.toMap();
+ if (env.value(QStringLiteral("name")).toString() == name) {
+ const QVariantMap settings =
+ env.value(QStringLiteral("settings")).toMap();
+ emptyWorkspace =
+ !settings.value(QStringLiteral("empty_workspace_disabled")).toBool();
+ shareClipboard =
+ !settings.value(QStringLiteral("clipboard_disabled")).toBool();
+ break;
+ }
+ }
if (kind == QStringLiteral("box")) {
// Relaunch this same omavm-gui binary in its embedded terminal mode
// (gui/main.cpp's --terminal, gui/TerminalViewer.qml) — same pattern
- // as a Machine's Open spawning omavm-gui --viewer
+ // as a Machine's Open spawning omavm-gui --display-fd
// (internal/backend/qemu/qemu.go), so a Box opens inside OmaVM's own
// window instead of whatever external terminal emulator the user has
// configured.
- QProcess::startDetached(QCoreApplication::applicationFilePath(),
- {QStringLiteral("--terminal"), name,
- QStringLiteral("--title"),
- name + QStringLiteral(" — OmaVM")});
+ const auto flag = [](bool on) {
+ return on ? QStringLiteral("true") : QStringLiteral("false");
+ };
+ QProcess::startDetached(
+ QCoreApplication::applicationFilePath(),
+ {QStringLiteral("--terminal"), name, QStringLiteral("--title"),
+ name + QStringLiteral(" — OmaVM"), QStringLiteral("--share-clipboard"),
+ flag(shareClipboard), QStringLiteral("--empty-workspace"),
+ flag(emptyWorkspace)});
return;
}
- run({QStringLiteral("open"), name});
+ run(name, {QStringLiteral("open"), name}, QStringLiteral("opening %1").arg(name),
+ QStringLiteral("open"));
}
void Backend::loadTheme() {
@@ -370,6 +795,21 @@ void Backend::loadTheme() {
take(QStringLiteral("green"), m_themeGreen);
take(QStringLiteral("red"), m_themeRed);
+ const QColor background(m_themeBackground), surface(m_themeSurface);
+ m_themeForeground = readableTextColor(QColor(m_themeForeground), background,
+ surface).name();
+ m_themeMuted = readableTextColor(QColor(m_themeMuted), background, surface)
+ .name();
+ // Status colors are read as text ("Running", errors) and icons: WCAG
+ // 1.4.6 (7:1) with their hue kept. The raw accent stays for Material
+ // controls, which draw their own text on it.
+ m_themeGreen = accessibleColor(QColor(m_themeGreen), background, surface)
+ .name();
+ m_themeRed =
+ accessibleColor(QColor(m_themeRed), background, surface).name();
+ m_themeAccentText =
+ accessibleColor(QColor(m_themeAccent), background, surface).name();
+
const QStringList watched =
m_themeWatcher.files() + m_themeWatcher.directories();
if (!watched.isEmpty())
diff --git a/gui/backend.h b/gui/backend.h
index 4f0a7fe..4a19813 100644
--- a/gui/backend.h
+++ b/gui/backend.h
@@ -1,8 +1,12 @@
#pragma once
#include
+#include
+#include
+#include
#include
#include
+#include
#include
class Backend final : public QObject {
@@ -10,11 +14,22 @@ class Backend final : public QObject {
Q_PROPERTY(
QVariantList environments READ environments NOTIFY environmentsChanged)
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ Q_PROPERTY(QString busyAction READ busyAction NOTIFY busyChanged)
+ // Environment name -> what is running on it right now.
+ Q_PROPERTY(
+ QVariantMap busyEnvironments READ busyEnvironments NOTIFY busyChanged)
+ Q_PROPERTY(QString listError READ listError NOTIFY listErrorChanged)
Q_PROPERTY(QVariantList apps READ apps NOTIFY appsChanged)
+ Q_PROPERTY(bool appsLoading READ appsLoading NOTIFY appsChanged)
+ Q_PROPERTY(QString appsEnvironment READ appsEnvironment NOTIFY appsChanged)
+ Q_PROPERTY(QString appsError READ appsError NOTIFY appsChanged)
Q_PROPERTY(QString themeMode READ themeMode NOTIFY themeChanged)
Q_PROPERTY(QString themeBackground READ themeBackground NOTIFY themeChanged)
Q_PROPERTY(QString themeForeground READ themeForeground NOTIFY themeChanged)
Q_PROPERTY(QString themeAccent READ themeAccent NOTIFY themeChanged)
+ // The accent where it is text or an icon, at 7:1 (WCAG AAA).
+ Q_PROPERTY(
+ QString themeAccentText READ themeAccentText NOTIFY themeChanged)
Q_PROPERTY(QString themeSelection READ themeSelection NOTIFY themeChanged)
Q_PROPERTY(QString themeMuted READ themeMuted NOTIFY themeChanged)
Q_PROPERTY(QString themeSurface READ themeSurface NOTIFY themeChanged)
@@ -27,11 +42,18 @@ class Backend final : public QObject {
QVariantList environments() const { return m_environments; }
QVariantList apps() const { return m_apps; }
- bool busy() const { return m_busy; }
+ bool busy() const { return !m_busy.isEmpty(); }
+ QString busyAction() const;
+ QVariantMap busyEnvironments() const;
+ QString listError() const { return m_listError; }
+ bool appsLoading() const { return m_appsLoading; }
+ QString appsEnvironment() const { return m_appsEnvironment; }
+ QString appsError() const { return m_appsError; }
QString themeMode() const { return m_themeMode; }
QString themeBackground() const { return m_themeBackground; }
QString themeForeground() const { return m_themeForeground; }
QString themeAccent() const { return m_themeAccent; }
+ QString themeAccentText() const { return m_themeAccentText; }
QString themeSelection() const { return m_themeSelection; }
QString themeMuted() const { return m_themeMuted; }
QString themeSurface() const { return m_themeSurface; }
@@ -39,9 +61,17 @@ class Backend final : public QObject {
QString themeGreen() const { return m_themeGreen; }
QString themeRed() const { return m_themeRed; }
+ // Quitting while an action runs would destroy its QProcess, which kills
+ // `omavm` mid-operation (a Restart cut between Stop and Start leaves the
+ // Machine off). readyToQuit fires now if idle, else once the action ends.
+ void requestQuit();
+
Q_INVOKABLE void refresh();
+ Q_INVOKABLE void poll();
Q_INVOKABLE void createEnvironment(const QString &name, const QString &image,
- const QString &kind);
+ const QString &kind, int cpus,
+ bool cpusTouched, int memoryMiB,
+ bool memoryTouched);
Q_INVOKABLE void start(const QString &name);
Q_INVOKABLE void open(const QString &name, const QString &kind);
Q_INVOKABLE void stop(const QString &name);
@@ -50,10 +80,13 @@ class Backend final : public QObject {
Q_INVOKABLE void resume(const QString &name);
Q_INVOKABLE void forceStop(const QString &name);
Q_INVOKABLE void configure(const QString &name, const QString &description,
- int cpus, int memoryMiB, bool machine,
+ int cpus, bool cpusTouched, int memoryMiB,
+ bool memoryTouched, bool machine,
const QString &sharedPath, bool sharedReadOnly,
bool disconnectISO, const QString &color,
- bool shareClipboard, bool travelMode);
+ bool shareClipboard, bool travelMode, bool vulkan,
+ bool openInEmptyWorkspace, bool launcher,
+ bool ssh, bool fullscreen);
Q_INVOKABLE void remove(const QString &name);
Q_INVOKABLE void createSnapshot(const QString &name, const QString &label);
Q_INVOKABLE void goToSnapshot(const QString &name, const QString &id);
@@ -61,30 +94,81 @@ class Backend final : public QObject {
Q_INVOKABLE void refreshApps(const QString &name);
Q_INVOKABLE void exportApp(const QString &name, const QString &id);
Q_INVOKABLE void unexportApp(const QString &name, const QString &id);
+ Q_INVOKABLE void copyToClipboard(const QString &text) const;
+ // Tags this process's window as a terminal for Omarchy's universal
+ // copy/paste shortcuts (Box terminal mode).
+ Q_INVOKABLE void markAsTerminalWindow() const;
+ // A file picker's URL as a filesystem path, spaces and accents decoded.
+ Q_INVOKABLE QString localPath(const QUrl &url) const {
+ return url.toLocalFile();
+ }
signals:
+ void readyToQuit();
void environmentsChanged();
void appsChanged();
void busyChanged();
+ void listErrorChanged();
void themeChanged();
void message(const QString &text, bool error);
+ // Correlates with the `tag` passed to run()/runForApps() so a dialog that
+ // started an action (create, configure, a snapshot or app operation) can
+ // tell its own request apart from any other action finishing, and keep
+ // itself open with the user's input intact until its own tag reports ok.
+ void actionFinished(const QString &tag, bool ok, const QString &text);
private:
- void run(const QStringList &arguments, bool refreshAfter = true);
- void runForApps(const QStringList &arguments, const QString &name);
- void enrichEnvironment(int index);
+ // Returns false (and emits an explanatory message instead of silently
+ // no-opping) when an action on the same key (environment name, or ""
+ // for reloading the list) is already in flight. Different environments
+ // run concurrently; the Core serializes one environment's operations.
+ bool beginBusy(const QString &key, const QString &label);
+ void endBusy(const QString &key);
+ QString busyMessage(const QString &key) const;
+ void run(const QString &key, const QStringList &arguments,
+ const QString &label, const QString &tag = QString(),
+ bool refreshAfter = true);
+ void refreshSoon();
+ void listLoaded();
+ void runForApps(const QStringList &arguments, const QString &name,
+ const QString &label, const QString &tag);
+ void capturePreview(int index, int generation);
+ void refreshImpl(bool silent);
void loadTheme();
QString cliPath() const;
- void setBusy(bool busy);
QVariantList m_environments;
+ // Bumped every time a list response is accepted. Each capturePreview()
+ // call captures the generation valid when it was spawned; a periodic
+ // poll (gui/Main.qml) can start a fresh refresh() while a previous
+ // cycle's preview is still in flight, so a stale result landing late
+ // must never mutate the current array by raw index — that index may now
+ // point at a different environment (docs/TODO.md P1 "impedir resultados
+ // atrasados de atualizar o ambiente errado").
+ int m_environmentsGeneration = 0;
+ // A silent poll never changes busy UI state. A foreground action bumps
+ // this token so a list response started before it cannot overwrite it.
+ int m_pollGeneration = 0;
+ bool m_polling = false;
+ bool m_quitRequested = false;
+ // Environment id -> earliest time (ms since epoch) to retry a preview
+ // that failed. Some guests never expose a surface QEMU can screendump
+ // ("no surface"), and without this every 3 s poll re-ran the capture.
+ QHash m_previewRetryAt;
QVariantList m_apps;
QFileSystemWatcher m_themeWatcher;
- bool m_busy = false;
+ // Key (environment name, "" for the list) -> action label.
+ QMap m_busy;
+ bool m_refreshPending = false;
+ QString m_listError;
+ bool m_appsLoading = false;
+ QString m_appsEnvironment;
+ QString m_appsError;
QString m_themeMode = QStringLiteral("dark");
QString m_themeBackground = QStringLiteral("#101010");
QString m_themeForeground = QStringLiteral("#eeeeee");
QString m_themeAccent = QStringLiteral("#5584aa");
+ QString m_themeAccentText = QStringLiteral("#5584aa");
QString m_themeSelection = QStringLiteral("#186a9a");
QString m_themeMuted = QStringLiteral("#777777");
QString m_themeSurface = QStringLiteral("#202020");
@@ -92,3 +176,23 @@ class Backend final : public QObject {
QString m_themeGreen = QStringLiteral("#65a765");
QString m_themeRed = QStringLiteral("#d35f5f");
};
+
+// Hyprland integration, exposed for tests.
+bool hasPersonalViewerRule(const QString &hyprConfigDir);
+
+enum class WorkspacePlacement {
+ NotApplicable, // no Hyprland session, or the user's own window
+ // rule places OmaVM's viewer: open as usual,
+ // silently
+ LaunchNormally, // switched to an empty workspace; go ahead and open
+ AlreadyFocusedExisting, // an existing window for this environment was
+ // found and focused; do not open another
+ Unavailable // no eligible workspace, or the dispatch failed:
+ // open on the current workspace
+};
+// Run by a viewer (Machine display or Box terminal) before its window
+// exists, so the window opens on the workspace it switched to.
+WorkspacePlacement placeInEmptyWorkspace(const QString &title);
+// The user's Hyprland config directory.
+QString hyprConfigDir();
+QString terminalTagScript(qint64 pid);
diff --git a/gui/colorstoml.cpp b/gui/colorstoml.cpp
index f3e59e6..98f076f 100644
--- a/gui/colorstoml.cpp
+++ b/gui/colorstoml.cpp
@@ -3,6 +3,85 @@
#include
#include
+#include
+#include
+
+namespace {
+double luminance(const QColor &color) {
+ const auto channel = [](int value) {
+ const double s = value / 255.0;
+ return s <= 0.04045 ? s / 12.92 : std::pow((s + 0.055) / 1.055, 2.4);
+ };
+ return 0.2126 * channel(color.red()) +
+ 0.7152 * channel(color.green()) +
+ 0.0722 * channel(color.blue());
+}
+
+double contrast(const QColor &a, const QColor &b) {
+ const double x = luminance(a), y = luminance(b);
+ return (std::max(x, y) + 0.05) / (std::min(x, y) + 0.05);
+}
+
+double minimumContrast(const QColor &text, const QColor &background,
+ const QColor &surface) {
+ return std::min(contrast(text, background), contrast(text, surface));
+}
+} // namespace
+
+QColor readableTextColor(const QColor &preferred, const QColor &background,
+ const QColor &surface) {
+ if (preferred.isValid() &&
+ minimumContrast(preferred, background, surface) >= 7.0)
+ return preferred;
+ const QColor black(Qt::black), white(Qt::white);
+ return minimumContrast(black, background, surface) >=
+ minimumContrast(white, background, surface)
+ ? black
+ : white;
+}
+
+double minimumContrastRatio(const QColor &text, const QColor &background,
+ const QColor &surface) {
+ return minimumContrast(text, background, surface);
+}
+
+QColor accessibleColor(const QColor &preferred, const QColor &background,
+ const QColor &surface, double ratio) {
+ if (!preferred.isValid())
+ return readableTextColor(preferred, background, surface);
+ if (minimumContrast(preferred, background, surface) >= ratio)
+ return preferred;
+ // Toward whichever extreme contrasts more with both surfaces. Mixing in
+ // more of it only increases the contrast, so the smallest mix that is
+ // enough can be found by bisection.
+ const QColor black(Qt::black), white(Qt::white);
+ const QColor target = minimumContrast(white, background, surface) >=
+ minimumContrast(black, background, surface)
+ ? white
+ : black;
+ const auto mix = [&](double t) {
+ return QColor::fromRgbF(
+ float(preferred.redF() + (target.redF() - preferred.redF()) * t),
+ float(preferred.greenF() + (target.greenF() - preferred.greenF()) * t),
+ float(preferred.blueF() + (target.blueF() - preferred.blueF()) * t));
+ };
+ if (minimumContrast(target, background, surface) < ratio)
+ return target; // the best there is
+ double low = 0, high = 1;
+ for (int i = 0; i < 24; ++i) {
+ const double middle = (low + high) / 2;
+ (minimumContrast(mix(middle), background, surface) >= ratio ? high : low) =
+ middle;
+ }
+ // Rounding to 8-bit channels can land just under the ratio.
+ QColor result = mix(high);
+ for (double t = high; minimumContrast(result, background, surface) < ratio &&
+ t < 1;
+ t = std::min(1.0, t + 0.01))
+ result = mix(t);
+ return result;
+}
+
QHash loadColorsToml(const QString &path) {
QHash values;
QFile file(path);
diff --git a/gui/colorstoml.h b/gui/colorstoml.h
index 41da7c3..82e4d93 100644
--- a/gui/colorstoml.h
+++ b/gui/colorstoml.h
@@ -1,6 +1,7 @@
#pragma once
#include
+#include
#include
// Parses Omarchy's flat `key = "value"` colors.toml (no sections, no
@@ -8,3 +9,20 @@
// Material palette) and the embedded terminal's ANSI palette — both just
// need a handful of named colors out of the same file.
QHash loadColorsToml(const QString &path);
+
+// Reach WCAG 1.4.6's 7:1 target for normal UI text when either black or
+// white can contrast with both app surfaces.
+QColor readableTextColor(const QColor &preferred, const QColor &background,
+ const QColor &surface);
+
+// Like readableTextColor, for colors that carry meaning (a red error, a
+// green "Running", the accent): keeps the hue and moves it toward white
+// or black only as far as needed for `ratio` against both surfaces,
+// instead of replacing it with plain black or white.
+QColor accessibleColor(const QColor &preferred, const QColor &background,
+ const QColor &surface, double ratio = 7.0);
+
+// WCAG contrast ratio of the lower of text-on-background and
+// text-on-surface. Exposed for tests.
+double minimumContrastRatio(const QColor &text, const QColor &background,
+ const QColor &surface);
diff --git a/gui/displayclient.cpp b/gui/displayclient.cpp
new file mode 100644
index 0000000..864e484
--- /dev/null
+++ b/gui/displayclient.cpp
@@ -0,0 +1,752 @@
+#include "displayclient.h"
+
+// GLib names a struct member "signals", which Qt defines as a macro.
+#pragma push_macro("signals")
+#undef signals
+#include
+#include
+#pragma pop_macro("signals")
+
+#include
+#include
+
+#include
+#include
+#include
+#include
+
+namespace {
+constexpr const char *ListenerPath = "/org/qemu/Display1/Listener";
+constexpr const char *ClipboardPath = "/org/qemu/Display1/Clipboard";
+constexpr const char *TextMime = "text/plain;charset=utf-8";
+// A paste larger than this is almost certainly not something the user
+// meant to share (the limit documented in README.md).
+constexpr gsize MaxClipboard = 1024 * 1024;
+
+// The subset of ui/dbus-display1.xml this client implements.
+constexpr const char *InterfaceXml = R"(
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+)";
+
+GDBusNodeInfo *interfaces() {
+ static GDBusNodeInfo *info =
+ g_dbus_node_info_new_for_xml(InterfaceXml, nullptr);
+ return info;
+}
+
+GDBusInterfaceInfo *interfaceInfo(const char *name) {
+ return g_dbus_node_info_lookup_interface(interfaces(), name);
+}
+
+// pixman format codes QEMU uses for 2D surfaces (little-endian host).
+QImage::Format imageFormat(quint32 pixman) {
+ switch (pixman) {
+ case 0x20020888: // PIXMAN_x8r8g8b8
+ return QImage::Format_RGB32;
+ case 0x20028888: // PIXMAN_a8r8g8b8
+ return QImage::Format_ARGB32;
+ case 0x20030888: // PIXMAN_x8b8g8r8
+ return QImage::Format_RGBX8888;
+ case 0x20038888: // PIXMAN_a8b8g8r8
+ return QImage::Format_RGBA8888;
+ case 0x10020565: // PIXMAN_r5g6b5
+ return QImage::Format_RGB16;
+ default:
+ return QImage::Format_Invalid;
+ }
+}
+
+// Returns the fd at index handle of the call's fd list, owned by the caller.
+int takeFd(GDBusMethodInvocation *invocation, gint32 handle) {
+ GUnixFDList *list =
+ g_dbus_message_get_unix_fd_list(g_dbus_method_invocation_get_message(
+ invocation));
+ if (!list)
+ return -1;
+ return g_unix_fd_list_get(list, handle, nullptr);
+}
+
+// A read-only memory mapping of a guest surface, kept alive by every
+// QImage that points into it.
+struct Mapping {
+ void *address = MAP_FAILED;
+ size_t size = 0;
+ ~Mapping() {
+ if (address != MAP_FAILED)
+ munmap(address, size);
+ }
+};
+
+void releaseMapping(void *mapping) {
+ delete static_cast *>(mapping);
+}
+
+GDBusConnection *connectionOnFd(int fd, GError **error) {
+ GSocket *socket = g_socket_new_from_fd(fd, error);
+ if (!socket) {
+ close(fd);
+ return nullptr;
+ }
+ GSocketConnection *stream = g_socket_connection_factory_create_connection(socket);
+ g_object_unref(socket);
+ // Synchronous on purpose: the handshake is a few bytes over a local
+ // socket QEMU is already waiting on, and objects must be exported
+ // before the first message is processed.
+ GDBusConnection *connection = g_dbus_connection_new_sync(
+ G_IO_STREAM(stream), nullptr,
+ GDBusConnectionFlags(G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
+ G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
+ nullptr, nullptr, error);
+ g_object_unref(stream);
+ return connection;
+}
+
+void onListenerCall(GDBusConnection *, const gchar *, const gchar *,
+ const gchar *, const gchar *method, GVariant *parameters,
+ GDBusMethodInvocation *invocation, gpointer self) {
+ static_cast(self)->handleListenerCall(method, parameters,
+ invocation);
+}
+
+void onClipboardCall(GDBusConnection *, const gchar *, const gchar *,
+ const gchar *, const gchar *method, GVariant *parameters,
+ GDBusMethodInvocation *invocation, gpointer self) {
+ static_cast(self)->handleClipboardCall(method, parameters,
+ invocation);
+}
+
+GVariant *onGetInterfaces(GDBusConnection *, const gchar *, const gchar *,
+ const gchar *interface, const gchar *property,
+ GError **, gpointer) {
+ if (g_strcmp0(property, "Interfaces") != 0)
+ return nullptr;
+ if (g_strcmp0(interface, "org.qemu.Display1.Listener") == 0) {
+ const gchar *extra[] = {"org.qemu.Display1.Listener.Unix.Map", nullptr};
+ return g_variant_new_strv(extra, -1);
+ }
+ return g_variant_new_strv(nullptr, 0);
+}
+
+const GDBusInterfaceVTable ListenerVTable = {onListenerCall, onGetInterfaces,
+ nullptr, {}};
+const GDBusInterfaceVTable ClipboardVTable = {onClipboardCall, onGetInterfaces,
+ nullptr, {}};
+
+void onClosed(GDBusConnection *, gboolean, GError *, gpointer self) {
+ static_cast(self)->fail(
+ QStringLiteral("The Machine's display was closed."));
+}
+
+// Replies are ignored for input events: QEMU answers each one, and a
+// failure (e.g. a key while the guest is paused) has nothing to show.
+void ignoreReply(GObject *source, GAsyncResult *result, gpointer) {
+ GVariant *reply =
+ g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, nullptr);
+ if (reply)
+ g_variant_unref(reply);
+}
+} // namespace
+
+DisplayClient::DisplayClient(QObject *parent) : QObject(parent) {
+ qRegisterMetaType();
+ m_cancellable = g_cancellable_new();
+ m_updateTimeout.setSingleShot(true);
+ m_updateTimeout.setInterval(50);
+ connect(&m_updateTimeout, &QTimer::timeout, this,
+ &DisplayClient::completePendingUpdates);
+ // GDBus dispatches into the GLib main context. Qt drives it on Linux
+ // unless built or run without GLib (QT_NO_GLIB); pump it ourselves then.
+ auto *dispatcher = QAbstractEventDispatcher::instance();
+ if (!dispatcher || !dispatcher->inherits("QEventDispatcherGlib")) {
+ auto *pump = new QTimer(this);
+ connect(pump, &QTimer::timeout, this,
+ [] { while (g_main_context_iteration(nullptr, FALSE)) {} });
+ pump->start(4);
+ }
+}
+
+DisplayClient::~DisplayClient() {
+ g_cancellable_cancel(m_cancellable);
+ completePendingUpdates();
+ if (m_propertiesSubscription)
+ g_dbus_connection_signal_unsubscribe(m_connection, m_propertiesSubscription);
+ for (GDBusConnection *connection : {m_connection, m_listener}) {
+ if (!connection)
+ continue;
+ g_signal_handlers_disconnect_by_data(connection, this);
+ g_dbus_connection_close_sync(connection, nullptr, nullptr);
+ }
+ if (m_listener) {
+ for (unsigned id : m_listenerObjects)
+ if (id)
+ g_dbus_connection_unregister_object(m_listener, id);
+ g_object_unref(m_listener);
+ }
+ if (m_connection) {
+ if (m_clipboardObject)
+ g_dbus_connection_unregister_object(m_connection, m_clipboardObject);
+ g_object_unref(m_connection);
+ }
+ g_object_unref(m_cancellable);
+}
+
+void DisplayClient::connectToFd(int fd) {
+ GError *error = nullptr;
+ GDBusConnection *connection = connectionOnFd(fd, &error);
+ if (!connection) {
+ fail(QStringLiteral("Could not connect to the Machine's display: ") +
+ QString::fromUtf8(error ? error->message : "unknown error"));
+ g_clear_error(&error);
+ return;
+ }
+ handleConnection(connection, false);
+}
+
+void DisplayClient::handleConnection(GDBusConnection *connection,
+ bool listener) {
+ g_signal_connect(connection, "closed", G_CALLBACK(onClosed), this);
+ if (listener) {
+ m_listener = connection;
+ m_listenerObjects[0] = g_dbus_connection_register_object(
+ connection, ListenerPath, interfaceInfo("org.qemu.Display1.Listener"),
+ &ListenerVTable, this, nullptr, nullptr);
+ m_listenerObjects[1] = g_dbus_connection_register_object(
+ connection, ListenerPath,
+ interfaceInfo("org.qemu.Display1.Listener.Unix.Map"), &ListenerVTable,
+ this, nullptr, nullptr);
+ g_dbus_connection_start_message_processing(connection);
+ return;
+ }
+
+ m_connection = connection;
+ m_clipboardObject = g_dbus_connection_register_object(
+ connection, ClipboardPath, interfaceInfo("org.qemu.Display1.Clipboard"),
+ &ClipboardVTable, this, nullptr, nullptr);
+ g_dbus_connection_start_message_processing(connection);
+ g_dbus_connection_call(
+ connection, nullptr, "/org/qemu/Display1/VM",
+ "org.freedesktop.DBus.Properties", "Get",
+ g_variant_new("(ss)", "org.qemu.Display1.VM", "ConsoleIDs"), nullptr,
+ G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ [](GObject *source, GAsyncResult *result, gpointer self) {
+ GError *error = nullptr;
+ GVariant *reply = g_dbus_connection_call_finish(
+ G_DBUS_CONNECTION(source), result, &error);
+ if (!reply) {
+ if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ static_cast(self)->fail(
+ QStringLiteral("The Machine's display did not answer: ") +
+ QString::fromUtf8(error->message));
+ g_error_free(error);
+ return;
+ }
+ GVariant *value = nullptr;
+ g_variant_get(reply, "(v)", &value);
+ static_cast(self)->handleConsoleIds(value);
+ g_variant_unref(value);
+ g_variant_unref(reply);
+ },
+ this);
+}
+
+void DisplayClient::handleConsoleIds(GVariant *ids) {
+ gsize count = 0;
+ const guint32 *values =
+ static_cast(g_variant_get_fixed_array(ids, &count, 4));
+ if (count == 0) {
+ fail(QStringLiteral("This Machine has no display."));
+ return;
+ }
+ m_consolePath = "/org/qemu/Display1/Console_" + QByteArray::number(values[0]);
+ registerListener();
+
+ m_propertiesSubscription = g_dbus_connection_signal_subscribe(
+ m_connection, nullptr, "org.freedesktop.DBus.Properties",
+ "PropertiesChanged", m_consolePath.constData(), nullptr,
+ G_DBUS_SIGNAL_FLAGS_NONE,
+ [](GDBusConnection *, const gchar *, const gchar *, const gchar *,
+ const gchar *, GVariant *parameters, gpointer self) {
+ const gchar *interface = nullptr;
+ GVariant *changed = nullptr;
+ g_variant_get(parameters, "(&s@a{sv}@as)", &interface, &changed,
+ nullptr);
+ gboolean absolute = FALSE;
+ if (g_strcmp0(interface, "org.qemu.Display1.Mouse") == 0 &&
+ g_variant_lookup(changed, "IsAbsolute", "b", &absolute))
+ static_cast(self)->handleMouseAbsolute(absolute);
+ g_variant_unref(changed);
+ },
+ this, nullptr);
+ g_dbus_connection_call(
+ m_connection, nullptr, m_consolePath.constData(),
+ "org.freedesktop.DBus.Properties", "Get",
+ g_variant_new("(ss)", "org.qemu.Display1.Mouse", "IsAbsolute"), nullptr,
+ G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ [](GObject *source, GAsyncResult *result, gpointer self) {
+ GVariant *reply = g_dbus_connection_call_finish(
+ G_DBUS_CONNECTION(source), result, nullptr);
+ if (!reply)
+ return;
+ GVariant *value = nullptr;
+ g_variant_get(reply, "(v)", &value);
+ static_cast(self)->handleMouseAbsolute(
+ g_variant_get_boolean(value));
+ g_variant_unref(value);
+ g_variant_unref(reply);
+ },
+ this);
+ // Claim the clipboard session. A second viewer of the same Machine is
+ // refused (QEMU accepts one clipboard peer) and simply goes without.
+ g_dbus_connection_call(m_connection, nullptr, ClipboardPath,
+ "org.qemu.Display1.Clipboard", "Register", nullptr,
+ nullptr, G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ ignoreReply, nullptr);
+}
+
+void DisplayClient::registerListener() {
+ int pair[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair) != 0) {
+ fail(QStringLiteral("Could not create the display listener socket."));
+ return;
+ }
+ GUnixFDList *list = g_unix_fd_list_new();
+ const gint index = g_unix_fd_list_append(list, pair[1], nullptr);
+ close(pair[1]);
+ // QEMU answers RegisterListener only after authenticating on the other
+ // end of this socket, so the call must be in flight before our side
+ // of the handshake blocks.
+ g_dbus_connection_call_with_unix_fd_list(
+ m_connection, nullptr, m_consolePath.constData(),
+ "org.qemu.Display1.Console", "RegisterListener",
+ g_variant_new("(h)", index), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, list,
+ m_cancellable,
+ [](GObject *source, GAsyncResult *result, gpointer self) {
+ GError *error = nullptr;
+ GVariant *reply = g_dbus_connection_call_with_unix_fd_list_finish(
+ G_DBUS_CONNECTION(source), nullptr, result, &error);
+ if (reply) {
+ g_variant_unref(reply);
+ return;
+ }
+ if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ static_cast(self)->fail(
+ QStringLiteral("The Machine refused the display connection: ") +
+ QString::fromUtf8(error->message));
+ g_error_free(error);
+ },
+ this);
+ g_object_unref(list);
+ g_dbus_connection_flush_sync(m_connection, nullptr, nullptr);
+
+ GError *error = nullptr;
+ GDBusConnection *listener = connectionOnFd(pair[0], &error);
+ if (!listener) {
+ fail(QStringLiteral("Could not open the display listener: ") +
+ QString::fromUtf8(error ? error->message : "unknown error"));
+ g_clear_error(&error);
+ return;
+ }
+ handleConnection(listener, true);
+}
+
+void DisplayClient::handleListenerCall(const char *method,
+ GVariant *parameters,
+ GDBusMethodInvocation *invocation) {
+ const QByteArray name(method);
+ if (name == "UpdateDMABUF") {
+ gint32 x, y, w, h;
+ g_variant_get(parameters, "(iiii)", &x, &y, &w, &h);
+ // QEMU blocks the guest's GPU until this is answered: hold the reply
+ // until the frame is drawn so the guest renders at the viewer's pace.
+ m_pendingUpdates.append(invocation);
+ if (!m_updateTimeout.isActive())
+ m_updateTimeout.start();
+ emit frameUpdated(QRect(x, y, w, h));
+ return;
+ }
+
+ if (name == "ScanoutDMABUF") {
+ gint32 handle;
+ Dmabuf buffer;
+ gboolean y0Top;
+ g_variant_get(parameters, "(huuuutb)", &handle, &buffer.width,
+ &buffer.height, &buffer.stride, &buffer.fourcc,
+ &buffer.modifier, &y0Top);
+ buffer.y0Top = y0Top;
+ buffer.fd = takeFd(invocation, handle);
+ m_frame = QImage();
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ if (buffer.fd >= 0)
+ emit dmabufScanout(buffer);
+ return;
+ }
+
+ if (name == "Scanout" || name == "Update") {
+ const bool full = name == "Scanout";
+ gint32 x = 0, y = 0, w = 0, h = 0;
+ guint32 stride, format;
+ GVariant *data = nullptr;
+ if (full) {
+ guint32 uw, uh;
+ g_variant_get(parameters, "(uuuu@ay)", &uw, &uh, &stride, &format,
+ &data);
+ w = gint32(uw);
+ h = gint32(uh);
+ } else {
+ g_variant_get(parameters, "(iiiiuu@ay)", &x, &y, &w, &h, &stride,
+ &format, &data);
+ }
+ gsize size = 0;
+ const uchar *bytes =
+ static_cast(g_variant_get_fixed_array(data, &size, 1));
+ const QImage::Format qformat = imageFormat(format);
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ const int bytesPerPixel = qformat == QImage::Format_RGB16 ? 2 : 4;
+ if (qformat == QImage::Format_Invalid || w <= 0 || h <= 0 ||
+ stride < guint32(w * bytesPerPixel) ||
+ size < gsize(stride) * gsize(h - 1) + gsize(w) * bytesPerPixel) {
+ g_variant_unref(data);
+ return;
+ }
+ const QImage update =
+ QImage(bytes, w, h, qsizetype(stride), qformat).copy();
+ g_variant_unref(data);
+ if (full) {
+ m_frame = update;
+ emit imageScanout();
+ return;
+ }
+ if (m_frame.isNull() || m_frame.format() != qformat || x < 0 || y < 0 ||
+ x >= m_frame.width())
+ return;
+ for (int row = 0; row < h && y + row < m_frame.height(); ++row) {
+ const int count = qMin(w, m_frame.width() - x) * bytesPerPixel;
+ memcpy(m_frame.scanLine(y + row) + x * bytesPerPixel,
+ update.constScanLine(row), size_t(count));
+ }
+ emit frameUpdated(QRect(x, y, w, h));
+ return;
+ }
+
+ if (name == "ScanoutMap") {
+ gint32 handle;
+ guint32 offset, w, h, stride, format;
+ g_variant_get(parameters, "(huuuuu)", &handle, &offset, &w, &h, &stride,
+ &format);
+ const int fd = takeFd(invocation, handle);
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ const QImage::Format qformat = imageFormat(format);
+ if (fd < 0 || qformat == QImage::Format_Invalid || w == 0 || h == 0) {
+ if (fd >= 0)
+ close(fd);
+ return;
+ }
+ auto mapping = std::make_shared();
+ mapping->size = size_t(offset) + size_t(stride) * h;
+ mapping->address =
+ mmap(nullptr, mapping->size, PROT_READ, MAP_SHARED, fd, 0);
+ close(fd);
+ if (mapping->address == MAP_FAILED)
+ return;
+ m_frame = QImage(static_cast(mapping->address) + offset,
+ int(w), int(h), qsizetype(stride), qformat,
+ releaseMapping, new std::shared_ptr(mapping));
+ emit imageScanout();
+ return;
+ }
+
+ if (name == "UpdateMap") {
+ gint32 x, y, w, h;
+ g_variant_get(parameters, "(iiii)", &x, &y, &w, &h);
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ emit frameUpdated(QRect(x, y, w, h));
+ return;
+ }
+
+ if (name == "Disable") {
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ m_frame = QImage();
+ emit displayDisabled();
+ return;
+ }
+
+ if (name == "MouseSet") {
+ gint32 x, y, on;
+ g_variant_get(parameters, "(iii)", &x, &y, &on);
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ emit cursorVisibilityChanged(on != 0);
+ return;
+ }
+
+ if (name == "CursorDefine") {
+ gint32 w, h, hotX, hotY;
+ GVariant *data = nullptr;
+ g_variant_get(parameters, "(iiii@ay)", &w, &h, &hotX, &hotY, &data);
+ gsize size = 0;
+ const uchar *bytes =
+ static_cast(g_variant_get_fixed_array(data, &size, 1));
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ if (w > 0 && h > 0 && w <= 512 && h <= 512 && size >= gsize(w) * h * 4)
+ emit cursorChanged(QImage(bytes, w, h, QImage::Format_ARGB32).copy(),
+ QPoint(hotX, hotY));
+ g_variant_unref(data);
+ return;
+ }
+
+ g_dbus_method_invocation_return_dbus_error(
+ invocation, "org.qemu.Display1.Error.Unsupported",
+ "Not implemented by this viewer");
+}
+
+void DisplayClient::handleClipboardCall(const char *method,
+ GVariant *parameters,
+ GDBusMethodInvocation *invocation) {
+ const QByteArray name(method);
+ if (name == "Register") {
+ // QEMU resets the grab serials (e.g. after a guest reboot).
+ m_clipboardSerial = 0;
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ return;
+ }
+ if (name == "Grab") {
+ guint32 selection, serial;
+ const gchar **mimes = nullptr;
+ g_variant_get(parameters, "(uu^a&s)", &selection, &serial, &mimes);
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ const bool text = mimes && g_strv_contains(mimes, TextMime);
+ g_free(mimes);
+ // The guest copied something: fetch it while it is still current.
+ if (selection != 0 || serial < m_clipboardSerial || !text)
+ return;
+ m_clipboardSerial = serial;
+ if (!m_clipboardEnabled)
+ return;
+ const gchar *wanted[] = {TextMime, nullptr};
+ g_dbus_connection_call(
+ m_connection, nullptr, ClipboardPath, "org.qemu.Display1.Clipboard",
+ "Request", g_variant_new("(u^as)", 0u, wanted),
+ G_VARIANT_TYPE("(say)"), G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ [](GObject *source, GAsyncResult *result, gpointer self) {
+ GVariant *reply = g_dbus_connection_call_finish(
+ G_DBUS_CONNECTION(source), result, nullptr);
+ if (!reply)
+ return;
+ const gchar *mime = nullptr;
+ GVariant *data = nullptr;
+ g_variant_get(reply, "(&s@ay)", &mime, &data);
+ gsize size = 0;
+ const char *bytes = static_cast(
+ g_variant_get_fixed_array(data, &size, 1));
+ if (g_strcmp0(mime, TextMime) == 0 && size <= MaxClipboard)
+ static_cast(self)->handleGuestClipboard(
+ QByteArray(bytes, qsizetype(size)));
+ g_variant_unref(data);
+ g_variant_unref(reply);
+ },
+ this);
+ return;
+ }
+ if (name == "Request") {
+ // QEMU waits for this reply synchronously: answer immediately.
+ guint32 selection;
+ const gchar **mimes = nullptr;
+ g_variant_get(parameters, "(u^a&s)", &selection, &mimes);
+ const bool text = mimes && g_strv_contains(mimes, TextMime);
+ g_free(mimes);
+ if (selection != 0 || !text || !m_clipboardEnabled) {
+ g_dbus_method_invocation_return_dbus_error(
+ invocation, "org.qemu.Display1.Error.Failed",
+ "Clipboard not shared");
+ return;
+ }
+ g_dbus_method_invocation_return_value(
+ invocation,
+ g_variant_new("(s@ay)", TextMime,
+ g_variant_new_fixed_array(
+ G_VARIANT_TYPE_BYTE, m_hostClipboard.constData(),
+ gsize(m_hostClipboard.size()), 1)));
+ return;
+ }
+ // Unregister, Release: nothing to clean up on this side.
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+}
+
+void DisplayClient::handleMouseAbsolute(bool absolute) {
+ if (m_mouseAbsolute == absolute)
+ return;
+ m_mouseAbsolute = absolute;
+ emit mouseAbsoluteChanged();
+}
+
+void DisplayClient::handleGuestClipboard(const QByteArray &text) {
+ if (m_clipboardEnabled)
+ emit clipboardReceived(QString::fromUtf8(text));
+}
+
+void DisplayClient::fail(const QString &message) {
+ if (m_failed)
+ return;
+ m_failed = true;
+ completePendingUpdates();
+ emit errorOccurred(message);
+}
+
+void DisplayClient::call(const char *interface, const char *method,
+ GVariant *parameters) {
+ if (!m_connection || m_consolePath.isEmpty() || m_failed) {
+ if (parameters)
+ g_variant_unref(g_variant_ref_sink(parameters));
+ return;
+ }
+ g_dbus_connection_call(m_connection, nullptr, m_consolePath.constData(),
+ interface, method, parameters, nullptr,
+ G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ ignoreReply, nullptr);
+}
+
+void DisplayClient::pressKey(quint32 qnum) {
+ call("org.qemu.Display1.Keyboard", "Press", g_variant_new("(u)", qnum));
+}
+
+void DisplayClient::releaseKey(quint32 qnum) {
+ call("org.qemu.Display1.Keyboard", "Release", g_variant_new("(u)", qnum));
+}
+
+void DisplayClient::movePointer(int x, int y) {
+ call("org.qemu.Display1.Mouse", "SetAbsPosition",
+ g_variant_new("(uu)", guint32(qMax(0, x)), guint32(qMax(0, y))));
+}
+
+void DisplayClient::movePointerBy(int dx, int dy) {
+ if (dx != 0 || dy != 0)
+ call("org.qemu.Display1.Mouse", "RelMotion", g_variant_new("(ii)", dx, dy));
+}
+
+void DisplayClient::pressButton(int button) {
+ call("org.qemu.Display1.Mouse", "Press", g_variant_new("(u)", guint32(button)));
+}
+
+void DisplayClient::releaseButton(int button) {
+ call("org.qemu.Display1.Mouse", "Release",
+ g_variant_new("(u)", guint32(button)));
+}
+
+void DisplayClient::resizeDisplay(int width, int height, int widthMM,
+ int heightMM) {
+ if (width < 1 || height < 1)
+ return;
+ call("org.qemu.Display1.Console", "SetUIInfo",
+ g_variant_new("(qqiiuu)", guint16(qBound(0, widthMM, 65535)),
+ guint16(qBound(0, heightMM, 65535)), 0, 0,
+ guint32(width), guint32(height)));
+}
+
+void DisplayClient::setClipboardEnabled(bool enabled) {
+ m_clipboardEnabled = enabled;
+}
+
+void DisplayClient::sendClipboard(const QString &text) {
+ const QByteArray utf8 = text.toUtf8();
+ if (!m_clipboardEnabled || !m_connection || text.isEmpty() ||
+ utf8.size() > qsizetype(MaxClipboard) || utf8 == m_hostClipboard)
+ return;
+ m_hostClipboard = utf8;
+ const gchar *mimes[] = {TextMime, nullptr};
+ g_dbus_connection_call(m_connection, nullptr, ClipboardPath,
+ "org.qemu.Display1.Clipboard", "Grab",
+ g_variant_new("(uu^as)", 0u, ++m_clipboardSerial,
+ mimes),
+ nullptr, G_DBUS_CALL_FLAGS_NONE, -1, m_cancellable,
+ ignoreReply, nullptr);
+}
+
+void DisplayClient::frameRendered() { completePendingUpdates(); }
+
+void DisplayClient::completePendingUpdates() {
+ m_updateTimeout.stop();
+ for (GDBusMethodInvocation *invocation : std::as_const(m_pendingUpdates))
+ g_dbus_method_invocation_return_value(invocation, nullptr);
+ m_pendingUpdates.clear();
+}
diff --git a/gui/displayclient.h b/gui/displayclient.h
new file mode 100644
index 0000000..1e1bd07
--- /dev/null
+++ b/gui/displayclient.h
@@ -0,0 +1,120 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+struct _GCancellable;
+struct _GDBusConnection;
+struct _GDBusMethodInvocation;
+struct _GVariant;
+
+// A peer-to-peer client for QEMU's D-Bus display (-display dbus,p2p=yes),
+// the successor of the RFB client this viewer used before: frames arrive
+// as dma-bufs the host GPU can sample directly (or, without a usable host
+// GPU, as shared memory mappings), instead of pixels copied over a socket.
+//
+// The protocol is spoken with GDBus rather than QtDBus because every
+// connection here is an already-connected socket handed over by someone
+// else (QEMU gets the other end through QMP), which QtDBus cannot adopt.
+// The interface is documented in QEMU's ui/dbus-display1.xml.
+class DisplayClient : public QObject {
+ Q_OBJECT
+
+public:
+ // A dma-buf scanout. The receiver of dmabufScanout owns fd.
+ struct Dmabuf {
+ int fd = -1;
+ quint32 width = 0;
+ quint32 height = 0;
+ quint32 stride = 0;
+ quint32 fourcc = 0;
+ quint64 modifier = 0;
+ bool y0Top = true;
+ };
+
+ explicit DisplayClient(QObject *parent = nullptr);
+ ~DisplayClient() override;
+
+ // Adopts fd, a socket QEMU accepted through QMP add_client.
+ void connectToFd(int fd);
+
+ // The current frame when it is shared as memory (Scanout/ScanoutMap);
+ // null while frames come as dma-bufs.
+ QImage frame() const { return m_frame; }
+ bool mouseAbsolute() const { return m_mouseAbsolute; }
+
+ void pressKey(quint32 qnum);
+ void releaseKey(quint32 qnum);
+ // Guest framebuffer coordinates; only valid while mouseAbsolute().
+ void movePointer(int x, int y);
+ void movePointerBy(int dx, int dy);
+ // QEMU button numbers: 0 left, 1 middle, 2 right, 3 wheel up,
+ // 4 wheel down, 5 side, 6 extra.
+ void pressButton(int button);
+ void releaseButton(int button);
+ // Asks the guest to adopt this resolution (virtio-gpu honors it).
+ void resizeDisplay(int width, int height, int widthMM, int heightMM);
+
+ // Text clipboard sharing with the guest; off until enabled.
+ void setClipboardEnabled(bool enabled);
+ void sendClipboard(const QString &text);
+
+ // Acknowledges dma-buf updates once they reached the screen. QEMU holds
+ // the guest's GPU until then, which paces rendering to the viewer.
+ void frameRendered();
+
+ // Called from GDBus callbacks.
+ void handleConnection(_GDBusConnection *connection, bool listener);
+ void handleListenerCall(const char *method, _GVariant *parameters,
+ _GDBusMethodInvocation *invocation);
+ void handleClipboardCall(const char *method, _GVariant *parameters,
+ _GDBusMethodInvocation *invocation);
+ void handleConsoleIds(_GVariant *ids);
+ void handleMouseAbsolute(bool absolute);
+ void handleGuestClipboard(const QByteArray &text);
+ void fail(const QString &message);
+
+signals:
+ void dmabufScanout(DisplayClient::Dmabuf buffer);
+ // frame() was replaced (new size or format).
+ void imageScanout();
+ void frameUpdated(const QRect &rect);
+ void displayDisabled();
+ void cursorChanged(const QImage &image, const QPoint &hotSpot);
+ void cursorVisibilityChanged(bool visible);
+ void mouseAbsoluteChanged();
+ void clipboardReceived(const QString &text);
+ void errorOccurred(const QString &message);
+
+private:
+ void registerListener();
+ void call(const char *interface, const char *method, _GVariant *parameters);
+ void completePendingUpdates();
+
+ _GCancellable *m_cancellable = nullptr;
+ _GDBusConnection *m_connection = nullptr;
+ _GDBusConnection *m_listener = nullptr;
+ unsigned m_listenerObjects[2] = {0, 0};
+ unsigned m_clipboardObject = 0;
+ unsigned m_propertiesSubscription = 0;
+ QByteArray m_consolePath;
+ QImage m_frame;
+ bool m_mouseAbsolute = false;
+ bool m_failed = false;
+ // UpdateDMABUF calls answered by frameRendered(), or by m_updateTimeout
+ // when nothing is being drawn (a hidden window never renders).
+ QList<_GDBusMethodInvocation *> m_pendingUpdates;
+ QTimer m_updateTimeout;
+
+ bool m_clipboardEnabled = false;
+ quint32 m_clipboardSerial = 0;
+ QByteArray m_hostClipboard;
+};
+
+Q_DECLARE_METATYPE(DisplayClient::Dmabuf)
diff --git a/gui/displayview.cpp b/gui/displayview.cpp
new file mode 100644
index 0000000..54bc019
--- /dev/null
+++ b/gui/displayview.cpp
@@ -0,0 +1,482 @@
+#include "displayview.h"
+#include "keymap.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define EGL_NO_X11
+#include
+#include
+
+#include
+
+namespace {
+// DRM_FORMAT_MOD_INVALID: the buffer's layout is implied, not declared.
+constexpr quint64 ModifierInvalid = 0x00ffffffffffffffULL;
+
+using ImageTargetTexture = void (*)(GLenum target, void *image);
+
+struct Egl {
+ PFNEGLCREATEIMAGEKHRPROC createImage = nullptr;
+ PFNEGLDESTROYIMAGEKHRPROC destroyImage = nullptr;
+ ImageTargetTexture imageTargetTexture = nullptr;
+};
+
+const Egl &egl() {
+ static const Egl functions = [] {
+ Egl f;
+ f.createImage = reinterpret_cast(
+ eglGetProcAddress("eglCreateImageKHR"));
+ f.destroyImage = reinterpret_cast(
+ eglGetProcAddress("eglDestroyImageKHR"));
+ f.imageTargetTexture = reinterpret_cast(
+ eglGetProcAddress("glEGLImageTargetTexture2DOES"));
+ return f;
+ }();
+ return functions;
+}
+
+int qemuButton(Qt::MouseButton button) {
+ switch (button) {
+ case Qt::LeftButton:
+ return 0;
+ case Qt::MiddleButton:
+ return 1;
+ case Qt::RightButton:
+ return 2;
+ case Qt::BackButton:
+ return 5;
+ case Qt::ForwardButton:
+ return 6;
+ default:
+ return -1;
+ }
+}
+
+quint32 qnumFor(const QKeyEvent *event) {
+ // X11/Wayland keycodes are evdev codes offset by 8.
+ const quint32 native = event->nativeScanCode();
+ return native > 8 ? evdevToQnum(native - 8) : 0;
+}
+} // namespace
+
+// Frees a frame's GPU resources on the render thread, where its GL
+// context is current.
+class GpuFrameCleanup : public QRunnable {
+public:
+ explicit GpuFrameCleanup(std::function cleanup)
+ : m_cleanup(std::move(cleanup)) {}
+ void run() override { m_cleanup(); }
+
+private:
+ std::function m_cleanup;
+};
+
+DisplayView::DisplayView(QQuickItem *parent) : QQuickItem(parent) {
+ setFlag(ItemHasContents, true);
+ setFlag(ItemAcceptsInputMethod, true);
+ setAcceptedMouseButtons(Qt::AllButtons);
+ setAcceptHoverEvents(true);
+ // Until the guest defines a cursor it may be drawing its own into the
+ // framebuffer; a host arrow on top would be a second, lagging pointer.
+ setCursor(m_guestCursor);
+
+ connect(&m_client, &DisplayClient::dmabufScanout, this,
+ [this](DisplayClient::Dmabuf buffer) {
+ if (m_pendingDmabuf.fd >= 0)
+ close(m_pendingDmabuf.fd);
+ m_pendingDmabuf = buffer;
+ m_dmabuf = buffer;
+ m_dmabufMode = true;
+ sendResize();
+ update();
+ });
+ connect(&m_client, &DisplayClient::imageScanout, this, [this] {
+ m_dmabufMode = false;
+ m_imageDirty = true;
+ sendResize();
+ update();
+ });
+ connect(&m_client, &DisplayClient::frameUpdated, this, [this] {
+ if (!m_dmabufMode)
+ m_imageDirty = true;
+ update();
+ });
+ connect(&m_client, &DisplayClient::displayDisabled, this, [this] {
+ m_dmabufMode = false;
+ m_dmabuf = {};
+ m_imageDirty = true;
+ update();
+ });
+ connect(&m_client, &DisplayClient::cursorChanged, this,
+ [this](const QImage &image, const QPoint &hotSpot) {
+ m_guestCursor =
+ QCursor(QPixmap::fromImage(image), hotSpot.x(), hotSpot.y());
+ if (m_guestCursorVisible)
+ setCursor(m_guestCursor);
+ });
+ connect(&m_client, &DisplayClient::cursorVisibilityChanged, this,
+ [this](bool visible) {
+ m_guestCursorVisible = visible;
+ setCursor(visible ? m_guestCursor : QCursor(Qt::BlankCursor));
+ });
+ connect(&m_client, &DisplayClient::errorOccurred, this,
+ &DisplayView::connectionFailed);
+ connect(&m_client, &DisplayClient::clipboardReceived, this,
+ [this](const QString &text) {
+ if (!m_shareClipboard || !window() || !window()->isActive())
+ return;
+ QScopedValueRollback receiving(m_receivingClipboard, true);
+ QGuiApplication::clipboard()->setText(text);
+ });
+ connect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this,
+ &DisplayView::syncClipboard);
+ connect(this, &QQuickItem::windowChanged, this, [this](QQuickWindow *win) {
+ if (!win)
+ return;
+ connect(win, &QWindow::activeChanged, this, &DisplayView::syncClipboard);
+ // Emitted on the render thread once a frame is on screen.
+ connect(win, &QQuickWindow::frameSwapped, this,
+ [this] { m_client.frameRendered(); }, Qt::QueuedConnection);
+ });
+
+ m_resizeTimer.setSingleShot(true);
+ m_resizeTimer.setInterval(250);
+ connect(&m_resizeTimer, &QTimer::timeout, this, &DisplayView::sendResize);
+}
+
+DisplayView::~DisplayView() {
+ if (m_pendingDmabuf.fd >= 0)
+ close(m_pendingDmabuf.fd);
+}
+
+void DisplayView::setConnectionFd(int fd) {
+ if (m_connectionFd >= 0 || fd < 0)
+ return;
+ m_connectionFd = fd;
+ emit connectionFdChanged();
+ m_client.connectToFd(fd);
+ forceActiveFocus();
+}
+
+void DisplayView::setShareClipboard(bool enabled) {
+ if (m_shareClipboard == enabled)
+ return;
+ m_shareClipboard = enabled;
+ emit shareClipboardChanged();
+ syncClipboard();
+}
+
+void DisplayView::syncClipboard() {
+ const bool active = m_shareClipboard && window() && window()->isActive();
+ m_client.setClipboardEnabled(active);
+ if (active && !m_receivingClipboard)
+ m_client.sendClipboard(QGuiApplication::clipboard()->text());
+}
+
+QSize DisplayView::frameSize() const {
+ if (m_dmabufMode)
+ return QSize(int(m_dmabuf.width), int(m_dmabuf.height));
+ return m_client.frame().size();
+}
+
+QRectF DisplayView::displayRect() const {
+ const QSize frame = frameSize();
+ if (frame.isEmpty())
+ return {};
+ QSizeF size = frame;
+ size.scale(boundingRect().size(), Qt::KeepAspectRatio);
+ return QRectF(
+ QPointF((width() - size.width()) / 2, (height() - size.height()) / 2),
+ size);
+}
+
+bool DisplayView::importDmabuf() {
+ const int fd = m_pendingDmabuf.fd;
+ const DisplayClient::Dmabuf buffer = m_pendingDmabuf;
+ m_pendingDmabuf = {};
+ QOpenGLContext *context = QOpenGLContext::currentContext();
+ const EGLDisplay display = eglGetCurrentDisplay();
+ const Egl &f = egl();
+ if (!context || display == EGL_NO_DISPLAY || !f.createImage ||
+ !f.imageTargetTexture) {
+ close(fd);
+ return false;
+ }
+ QList attributes = {
+ EGL_WIDTH,
+ EGLAttrib(buffer.width),
+ EGL_HEIGHT,
+ EGLAttrib(buffer.height),
+ EGL_LINUX_DRM_FOURCC_EXT,
+ EGLAttrib(buffer.fourcc),
+ EGL_DMA_BUF_PLANE0_FD_EXT,
+ EGLAttrib(fd),
+ EGL_DMA_BUF_PLANE0_OFFSET_EXT,
+ 0,
+ EGL_DMA_BUF_PLANE0_PITCH_EXT,
+ EGLAttrib(buffer.stride),
+ };
+ if (buffer.modifier != ModifierInvalid) {
+ attributes << EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT
+ << EGLAttrib(buffer.modifier & 0xffffffff)
+ << EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT
+ << EGLAttrib(buffer.modifier >> 32);
+ }
+ QList intAttributes;
+ for (EGLAttrib a : std::as_const(attributes))
+ intAttributes << EGLint(a);
+ intAttributes << EGL_NONE;
+ const EGLImageKHR image =
+ f.createImage(display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr,
+ intAttributes.constData());
+ // EGL holds its own reference to the buffer.
+ close(fd);
+ if (image == EGL_NO_IMAGE_KHR)
+ return false;
+
+ QOpenGLFunctions *gl = context->functions();
+ GLuint texture = 0;
+ gl->glGenTextures(1, &texture);
+ gl->glBindTexture(GL_TEXTURE_2D, texture);
+ gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ gl->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ f.imageTargetTexture(GL_TEXTURE_2D, image);
+ gl->glBindTexture(GL_TEXTURE_2D, 0);
+ // Raw GL calls above: tell the scene graph its cached state is stale.
+ QQuickOpenGLUtils::resetOpenGLState();
+
+ m_gpu.eglImage = image;
+ m_gpu.texture = texture;
+ m_gpu.sgTexture = QNativeInterface::QSGOpenGLTexture::fromNative(
+ texture, window(), QSize(int(buffer.width), int(buffer.height)),
+ QQuickWindow::TextureIsOpaque);
+ return true;
+}
+
+void DisplayView::destroyGpuFrame(GpuFrame frame) {
+ delete frame.sgTexture;
+ if (QOpenGLContext *context = QOpenGLContext::currentContext()) {
+ if (frame.texture)
+ context->functions()->glDeleteTextures(1, &frame.texture);
+ }
+ if (frame.eglImage && egl().destroyImage)
+ egl().destroyImage(eglGetCurrentDisplay(), frame.eglImage);
+}
+
+QSGNode *DisplayView::updatePaintNode(QSGNode *oldNode,
+ UpdatePaintNodeData *) {
+ // Runs on the render thread while the GUI thread is blocked, so the
+ // client's state is safe to read here.
+ if (m_pendingDmabuf.fd >= 0) {
+ const GpuFrame previous = m_gpu;
+ m_gpu = {};
+ if (!importDmabuf()) {
+ QMetaObject::invokeMethod(
+ this,
+ [this] {
+ emit connectionFailed(
+ QStringLiteral("This display needs a GPU with EGL dma-buf "
+ "import (Wayland session with Mesa)."));
+ },
+ Qt::QueuedConnection);
+ }
+ if (oldNode)
+ static_cast(oldNode)->setTexture(nullptr);
+ destroyGpuFrame(previous);
+ }
+
+ QSGTexture *texture = nullptr;
+ if (m_dmabufMode) {
+ texture = m_gpu.sgTexture;
+ } else {
+ if (m_imageDirty) {
+ m_imageDirty = false;
+ if (oldNode)
+ static_cast(oldNode)->setTexture(nullptr);
+ delete m_imageTexture;
+ m_imageTexture = nullptr;
+ // A shallow copy: it keeps a shared mapping alive until uploaded.
+ const QImage frame = m_client.frame();
+ if (!frame.isNull())
+ m_imageTexture = window()->createTextureFromImage(
+ frame, QQuickWindow::TextureIsOpaque);
+ }
+ texture = m_imageTexture;
+ }
+ if (!texture) {
+ delete oldNode;
+ return nullptr;
+ }
+
+ auto *node = static_cast(oldNode);
+ if (!node) {
+ node = new QSGSimpleTextureNode;
+ node->setFiltering(QSGTexture::Linear);
+ }
+ node->setTexture(texture);
+ node->setRect(displayRect());
+ // QEMU's y0_top is relative to GL's bottom-up window framebuffer (its
+ // own GTK UI flips when it is false); the scene graph samples top-down,
+ // so the flip is needed in the opposite case.
+ node->setTextureCoordinatesTransform(
+ m_dmabufMode && m_dmabuf.y0Top ? QSGSimpleTextureNode::MirrorVertically
+ : QSGSimpleTextureNode::NoTransform);
+ // The dma-buf's contents change in place: redraw even when the texture
+ // object is the same.
+ node->markDirty(QSGNode::DirtyMaterial);
+ return node;
+}
+
+void DisplayView::releaseResources() {
+ const GpuFrame gpu = m_gpu;
+ QSGTexture *image = m_imageTexture;
+ m_gpu = {};
+ m_imageTexture = nullptr;
+ if (window())
+ window()->scheduleRenderJob(new GpuFrameCleanup([gpu, image] {
+ destroyGpuFrame(gpu);
+ delete image;
+ }),
+ QQuickWindow::BeforeSynchronizingStage);
+}
+
+void DisplayView::geometryChange(const QRectF &newGeometry,
+ const QRectF &oldGeometry) {
+ QQuickItem::geometryChange(newGeometry, oldGeometry);
+ if (newGeometry.size() != oldGeometry.size()) {
+ m_resizeTimer.start();
+ update();
+ }
+}
+
+void DisplayView::sendResize() {
+ const int w = qRound(width());
+ const int h = qRound(height());
+ if (w < 1 || h < 1 || frameSize() == QSize(w, h))
+ return;
+ // Physical size lets the guest pick a sensible DPI for this monitor.
+ int widthMM = 0, heightMM = 0;
+ if (window() && window()->screen()) {
+ const QScreen *screen = window()->screen();
+ const qreal dpi = screen->physicalDotsPerInch();
+ if (dpi > 0) {
+ const qreal pixels = screen->devicePixelRatio() * 25.4 / dpi;
+ widthMM = qRound(w * pixels);
+ heightMM = qRound(h * pixels);
+ }
+ }
+ m_client.resizeDisplay(w, h, widthMM, heightMM);
+}
+
+void DisplayView::sendPointer(const QPointF &position) {
+ const QSize frame = frameSize();
+ const QRectF rect = displayRect();
+ if (frame.isEmpty() || rect.isEmpty())
+ return;
+ const int x = qBound(0,
+ int((position.x() - rect.x()) * frame.width() /
+ rect.width()),
+ frame.width() - 1);
+ const int y = qBound(0,
+ int((position.y() - rect.y()) * frame.height() /
+ rect.height()),
+ frame.height() - 1);
+ if (m_client.mouseAbsolute()) {
+ m_client.movePointer(x, y);
+ } else if (m_havePointer) {
+ m_client.movePointerBy(x - int(m_lastPointer.x()),
+ y - int(m_lastPointer.y()));
+ }
+ m_lastPointer = QPointF(x, y);
+ m_havePointer = true;
+}
+
+void DisplayView::mousePressEvent(QMouseEvent *event) {
+ forceActiveFocus();
+ sendPointer(event->position());
+ const int button = qemuButton(event->button());
+ if (button >= 0)
+ m_client.pressButton(button);
+}
+
+void DisplayView::mouseReleaseEvent(QMouseEvent *event) {
+ sendPointer(event->position());
+ const int button = qemuButton(event->button());
+ if (button >= 0)
+ m_client.releaseButton(button);
+}
+
+void DisplayView::mouseMoveEvent(QMouseEvent *event) {
+ sendPointer(event->position());
+}
+
+void DisplayView::hoverMoveEvent(QHoverEvent *event) {
+ sendPointer(event->position());
+}
+
+void DisplayView::wheelEvent(QWheelEvent *event) {
+ sendPointer(event->position());
+ // Touchpads report small high-resolution steps; the guest wants notches.
+ m_wheelDelta += event->angleDelta().y();
+ while (qAbs(m_wheelDelta) >= 120) {
+ const int button = m_wheelDelta > 0 ? 3 : 4;
+ m_client.pressButton(button);
+ m_client.releaseButton(button);
+ m_wheelDelta += m_wheelDelta > 0 ? -120 : 120;
+ }
+}
+
+void DisplayView::keyPressEvent(QKeyEvent *event) {
+ const quint32 qnum = qnumFor(event);
+ if (qnum == 0) {
+ event->ignore();
+ return;
+ }
+ // Auto-repeated presses are forwarded (the emulated keyboard has no
+ // typematic repeat of its own); their paired releases are not.
+ m_pressedKeys.insert(qnum);
+ m_client.pressKey(qnum);
+}
+
+void DisplayView::keyReleaseEvent(QKeyEvent *event) {
+ const quint32 qnum = qnumFor(event);
+ if (qnum == 0) {
+ event->ignore();
+ return;
+ }
+ if (event->isAutoRepeat())
+ return;
+ m_pressedKeys.remove(qnum);
+ m_client.releaseKey(qnum);
+}
+
+void DisplayView::focusOutEvent(QFocusEvent *event) {
+ // A key held while switching away (Super+number) never gets its release
+ // here; left pressed, the guest would see it stuck.
+ releaseKeys();
+ QQuickItem::focusOutEvent(event);
+}
+
+void DisplayView::releaseKeys() {
+ for (quint32 qnum : std::as_const(m_pressedKeys))
+ m_client.releaseKey(qnum);
+ m_pressedKeys.clear();
+}
diff --git a/gui/displayview.h b/gui/displayview.h
new file mode 100644
index 0000000..a490357
--- /dev/null
+++ b/gui/displayview.h
@@ -0,0 +1,88 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include "displayclient.h"
+
+class QSGTexture;
+
+// Shows a Machine's display and drives it: frames from a DisplayClient
+// are drawn as GPU textures (dma-bufs imported through EGL, zero-copy) or,
+// without a host GPU, uploaded from shared memory; keyboard, pointer,
+// clipboard and window size go back to the guest.
+class DisplayView : public QQuickItem {
+ Q_OBJECT
+ Q_PROPERTY(int connectionFd READ connectionFd WRITE setConnectionFd NOTIFY
+ connectionFdChanged)
+ Q_PROPERTY(bool shareClipboard READ shareClipboard WRITE setShareClipboard
+ NOTIFY shareClipboardChanged)
+
+public:
+ explicit DisplayView(QQuickItem *parent = nullptr);
+ ~DisplayView() override;
+
+ int connectionFd() const { return m_connectionFd; }
+ void setConnectionFd(int fd);
+ bool shareClipboard() const { return m_shareClipboard; }
+ void setShareClipboard(bool enabled);
+
+signals:
+ void connectionFdChanged();
+ void shareClipboardChanged();
+ void connectionFailed(const QString &message);
+
+protected:
+ QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) override;
+ void releaseResources() override;
+ void geometryChange(const QRectF &newGeometry,
+ const QRectF &oldGeometry) override;
+ void mousePressEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent *event) override;
+ void mouseMoveEvent(QMouseEvent *event) override;
+ void hoverMoveEvent(QHoverEvent *event) override;
+ void wheelEvent(QWheelEvent *event) override;
+ void keyPressEvent(QKeyEvent *event) override;
+ void keyReleaseEvent(QKeyEvent *event) override;
+ void focusOutEvent(QFocusEvent *event) override;
+
+private:
+ // GPU resources, touched only on the render thread.
+ struct GpuFrame {
+ void *eglImage = nullptr;
+ unsigned texture = 0;
+ QSGTexture *sgTexture = nullptr;
+ };
+
+ QSize frameSize() const;
+ QRectF displayRect() const;
+ void sendPointer(const QPointF &position);
+ void sendResize();
+ void syncClipboard();
+ void releaseKeys();
+ bool importDmabuf();
+ static void destroyGpuFrame(GpuFrame frame);
+
+ DisplayClient m_client;
+ int m_connectionFd = -1;
+ bool m_shareClipboard = false;
+ bool m_receivingClipboard = false;
+
+ // Latest dma-buf scanout, waiting to be imported on the render thread.
+ DisplayClient::Dmabuf m_pendingDmabuf;
+ DisplayClient::Dmabuf m_dmabuf;
+ bool m_dmabufMode = false;
+ bool m_imageDirty = false;
+ GpuFrame m_gpu;
+ QSGTexture *m_imageTexture = nullptr;
+
+ QTimer m_resizeTimer;
+ QPointF m_lastPointer;
+ bool m_havePointer = false;
+ int m_wheelDelta = 0;
+ QSet m_pressedKeys;
+ QCursor m_guestCursor = QCursor(Qt::BlankCursor);
+ bool m_guestCursorVisible = true;
+};
diff --git a/gui/icons/add.svg b/gui/icons/add.svg
new file mode 100644
index 0000000..9cefdbe
--- /dev/null
+++ b/gui/icons/add.svg
@@ -0,0 +1,3 @@
+
diff --git a/gui/icons/app-mono.svg b/gui/icons/app-mono.svg
new file mode 100644
index 0000000..357d7d5
--- /dev/null
+++ b/gui/icons/app-mono.svg
@@ -0,0 +1,6 @@
+
diff --git a/gui/icons/app.svg b/gui/icons/app.svg
new file mode 100644
index 0000000..bc8ce74
--- /dev/null
+++ b/gui/icons/app.svg
@@ -0,0 +1,5 @@
+
diff --git a/gui/icons/box.svg b/gui/icons/box.svg
new file mode 100644
index 0000000..5758e60
--- /dev/null
+++ b/gui/icons/box.svg
@@ -0,0 +1,5 @@
+
diff --git a/gui/icons/close.svg b/gui/icons/close.svg
new file mode 100644
index 0000000..4eea8ba
--- /dev/null
+++ b/gui/icons/close.svg
@@ -0,0 +1,3 @@
+
diff --git a/gui/icons/history.svg b/gui/icons/history.svg
new file mode 100644
index 0000000..9b36e5a
--- /dev/null
+++ b/gui/icons/history.svg
@@ -0,0 +1,5 @@
+
diff --git a/gui/icons/machine.svg b/gui/icons/machine.svg
new file mode 100644
index 0000000..f3114b8
--- /dev/null
+++ b/gui/icons/machine.svg
@@ -0,0 +1,4 @@
+
diff --git a/gui/icons/more.svg b/gui/icons/more.svg
new file mode 100644
index 0000000..2cd78fe
--- /dev/null
+++ b/gui/icons/more.svg
@@ -0,0 +1,5 @@
+
diff --git a/gui/icons/play.svg b/gui/icons/play.svg
new file mode 100644
index 0000000..c40d8af
--- /dev/null
+++ b/gui/icons/play.svg
@@ -0,0 +1,3 @@
+
diff --git a/gui/icons/refresh.svg b/gui/icons/refresh.svg
new file mode 100644
index 0000000..975bbb2
--- /dev/null
+++ b/gui/icons/refresh.svg
@@ -0,0 +1,4 @@
+
diff --git a/gui/icons/warning.svg b/gui/icons/warning.svg
new file mode 100644
index 0000000..95efdee
--- /dev/null
+++ b/gui/icons/warning.svg
@@ -0,0 +1,5 @@
+
diff --git a/gui/keymap.h b/gui/keymap.h
new file mode 100644
index 0000000..d17209d
--- /dev/null
+++ b/gui/keymap.h
@@ -0,0 +1,91 @@
+#pragma once
+
+#include
+
+// Maps a Linux evdev key code (what Qt reports as nativeScanCode() - 8 on
+// Wayland and X11) to QEMU's "qnum": the PC/XT set 1 scancode, with
+// 0xe0-prefixed extended keys folded into the high bit. Sending physical
+// key positions instead of characters keeps the guest's own keyboard
+// layout in charge, so dead keys, AltGr and non-US layouts work as they
+// would on real hardware. Returns 0 for keys with no PC equivalent.
+inline quint32 evdevToQnum(quint32 evdev) {
+ // KEY_ESC (1) through KEY_KPDOT (83) are numbered exactly like set 1.
+ if (evdev >= 1 && evdev <= 83)
+ return evdev;
+ switch (evdev) {
+ case 85: // KEY_ZENKAKUHANKAKU
+ return 0x76;
+ case 86: // KEY_102ND (ISO key between left Shift and Z)
+ return 0x56;
+ case 87: // KEY_F11
+ return 0x57;
+ case 88: // KEY_F12
+ return 0x58;
+ case 89: // KEY_RO
+ return 0x73;
+ case 92: // KEY_HENKAN
+ return 0x79;
+ case 93: // KEY_KATAKANAHIRAGANA
+ return 0x70;
+ case 94: // KEY_MUHENKAN
+ return 0x7b;
+ case 96: // KEY_KPENTER
+ return 0x9c;
+ case 97: // KEY_RIGHTCTRL
+ return 0x9d;
+ case 98: // KEY_KPSLASH
+ return 0xb5;
+ case 99: // KEY_SYSRQ (Print Screen)
+ return 0x54;
+ case 100: // KEY_RIGHTALT (AltGr)
+ return 0xb8;
+ case 102: // KEY_HOME
+ return 0xc7;
+ case 103: // KEY_UP
+ return 0xc8;
+ case 104: // KEY_PAGEUP
+ return 0xc9;
+ case 105: // KEY_LEFT
+ return 0xcb;
+ case 106: // KEY_RIGHT
+ return 0xcd;
+ case 107: // KEY_END
+ return 0xcf;
+ case 108: // KEY_DOWN
+ return 0xd0;
+ case 109: // KEY_PAGEDOWN
+ return 0xd1;
+ case 110: // KEY_INSERT
+ return 0xd2;
+ case 111: // KEY_DELETE
+ return 0xd3;
+ case 113: // KEY_MUTE
+ return 0xa0;
+ case 114: // KEY_VOLUMEDOWN
+ return 0xae;
+ case 115: // KEY_VOLUMEUP
+ return 0xb0;
+ case 116: // KEY_POWER
+ return 0xde;
+ case 117: // KEY_KPEQUAL
+ return 0x59;
+ case 119: // KEY_PAUSE
+ return 0xc6;
+ case 121: // KEY_KPCOMMA
+ return 0x7e;
+ case 122: // KEY_HANGEUL
+ return 0xf2;
+ case 123: // KEY_HANJA
+ return 0xf1;
+ case 124: // KEY_YEN
+ return 0x7d;
+ case 125: // KEY_LEFTMETA
+ return 0xdb;
+ case 126: // KEY_RIGHTMETA
+ return 0xdc;
+ case 127: // KEY_COMPOSE (Menu)
+ return 0xdd;
+ default:
+ return 0;
+ }
+}
diff --git a/gui/main.cpp b/gui/main.cpp
index a1e5746..cce8ad8 100644
--- a/gui/main.cpp
+++ b/gui/main.cpp
@@ -1,6 +1,6 @@
#include "backend.h"
#include "terminalview.h"
-#include "vncview.h"
+#include "displayview.h"
#include
#include
@@ -8,27 +8,60 @@
#include
#include
#include
+#include
namespace {
-// A Machine's display: a single fullscreen VNC view, launched by the
-// qemu backend's Open() rather than by the user picking it from the
+// Placement shared by both viewer modes, done before the window exists so
+// it opens on the workspace switched to. Returns false when a window for
+// this environment is already open (and was focused): no second one.
+bool placeViewer(const QString &title, bool emptyWorkspace) {
+ if (!emptyWorkspace)
+ return true;
+ switch (placeInEmptyWorkspace(title)) {
+ case WorkspacePlacement::AlreadyFocusedExisting:
+ return false;
+ case WorkspacePlacement::Unavailable:
+ qWarning("omavm: no empty workspace found; opening on the current one");
+ break;
+ case WorkspacePlacement::NotApplicable:
+ case WorkspacePlacement::LaunchNormally:
+ break;
+ }
+ return true;
+}
+
+// A Machine's display: a single view of QEMU's D-Bus display, launched by
+// the qemu backend's Open() rather than by the user picking it from the
// Experience Center. Kept as a mode of this same binary so there's one
-// Qt app to build and package instead of two.
-int runViewer(QGuiApplication &app, const QString &socketPath,
- const QString &title, bool shareClipboard) {
+// Qt app to build and package instead of two. connectionFd is a socket
+// QEMU already accepted (the backend hands it over as an inherited fd).
+int runViewer(QGuiApplication &app, int connectionFd, const QString &title,
+ bool shareClipboard, bool emptyWorkspace, bool fullscreen) {
+ if (!placeViewer(title, emptyWorkspace))
+ return 0;
app.setApplicationName(QStringLiteral("dev.omavm.viewer"));
app.setDesktopFileName(QStringLiteral("dev.omavm.viewer"));
+ // Guest frames are imported as dma-bufs through EGL into GL textures.
+ QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
- qmlRegisterType("OmaVM", 1, 0, "VncView");
+ qmlRegisterType("OmaVM", 1, 0, "DisplayView");
+ Backend backend;
QQmlApplicationEngine engine;
- engine.rootContext()->setContextProperty(QStringLiteral("vncSocketPath"),
- socketPath);
- engine.rootContext()->setContextProperty(QStringLiteral("vncTitle"), title);
+ engine.rootContext()->setContextProperty(QStringLiteral("backend"), &backend);
+ engine.rootContext()->setContextProperty(
+ QStringLiteral("displayConnectionFd"), connectionFd);
+ engine.rootContext()->setContextProperty(QStringLiteral("displayTitle"),
+ title);
// The Machine's own Settings (opt-out, on by default) decide this —
// not a per-window checkbox the user has to remember to re-check.
- engine.rootContext()->setContextProperty(QStringLiteral("vncShareClipboard"),
- shareClipboard);
+ engine.rootContext()->setContextProperty(
+ QStringLiteral("displayShareClipboard"), shareClipboard);
+ // A personal window rule for the viewer (contrib/hypr/omavm-viewer.lua)
+ // already makes it fullscreen: asking too would toggle it back off.
+ engine.rootContext()->setContextProperty(
+ QStringLiteral("displayFullscreen"),
+ fullscreen && !hasPersonalViewerRule(hyprConfigDir()));
engine.load(QUrl(QStringLiteral("qrc:/Viewer.qml")));
if (engine.rootObjects().isEmpty())
return -1;
@@ -42,17 +75,26 @@ int runViewer(QGuiApplication &app, const QString &socketPath,
// "dev.omavm.viewer" app id so the same opt-in Hyprland window rule
// (contrib/hypr/omavm-viewer.lua) covers both.
int runTerminal(QGuiApplication &app, const QString &envName,
- const QString &title) {
+ const QString &title, bool shareClipboard,
+ bool emptyWorkspace) {
+ if (!placeViewer(title, emptyWorkspace))
+ return 0;
app.setApplicationName(QStringLiteral("dev.omavm.viewer"));
app.setDesktopFileName(QStringLiteral("dev.omavm.viewer"));
qmlRegisterType("OmaVM", 1, 0, "TerminalView");
+ Backend backend;
QQmlApplicationEngine engine;
+ engine.rootContext()->setContextProperty(QStringLiteral("backend"), &backend);
engine.rootContext()->setContextProperty(QStringLiteral("terminalEnvName"),
envName);
engine.rootContext()->setContextProperty(QStringLiteral("terminalTitle"),
title);
+ // Lets programs in the Box copy to the clipboard (OSC 52); the Box's
+ // own opt-out setting.
+ engine.rootContext()->setContextProperty(
+ QStringLiteral("terminalShareClipboard"), shareClipboard);
engine.load(QUrl(QStringLiteral("qrc:/TerminalViewer.qml")));
if (engine.rootObjects().isEmpty())
return -1;
@@ -68,8 +110,9 @@ int main(int argc, char *argv[]) {
QCommandLineParser parser;
QCommandLineOption viewerOption(
- QStringLiteral("viewer"), QStringLiteral("Open a Machine's VNC display"),
- QStringLiteral("socket-path"));
+ QStringLiteral("display-fd"),
+ QStringLiteral("Show a Machine's display over an inherited connection"),
+ QStringLiteral("fd"));
QCommandLineOption terminalOption(
QStringLiteral("terminal"),
QStringLiteral("Open a Development Box's terminal"),
@@ -79,27 +122,49 @@ int main(int argc, char *argv[]) {
QStringLiteral("title"), QStringLiteral("OmaVM"));
QCommandLineOption shareClipboardOption(
QStringLiteral("share-clipboard"),
- QStringLiteral("Whether to share the text clipboard with the guest"),
+ QStringLiteral("Whether to share the text clipboard with the guest, "
+ "or let programs in a Box copy to it"),
QStringLiteral("bool"), QStringLiteral("true"));
parser.addOption(viewerOption);
parser.addOption(terminalOption);
parser.addOption(titleOption);
+ QCommandLineOption emptyWorkspaceOption(
+ QStringLiteral("empty-workspace"),
+ QStringLiteral("Open in an empty Hyprland workspace"),
+ QStringLiteral("bool"), QStringLiteral("true"));
+ QCommandLineOption fullscreenOption(
+ QStringLiteral("fullscreen"),
+ QStringLiteral("Open a Machine's display fullscreen"),
+ QStringLiteral("bool"), QStringLiteral("true"));
parser.addOption(shareClipboardOption);
+ parser.addOption(emptyWorkspaceOption);
+ parser.addOption(fullscreenOption);
parser.process(app);
+ const auto on = [&parser](const QCommandLineOption &option) {
+ return parser.value(option) != QStringLiteral("false");
+ };
if (parser.isSet(viewerOption))
- return runViewer(app, parser.value(viewerOption), parser.value(titleOption),
- parser.value(shareClipboardOption) !=
- QStringLiteral("false"));
+ return runViewer(app, parser.value(viewerOption).toInt(),
+ parser.value(titleOption), on(shareClipboardOption),
+ on(emptyWorkspaceOption), on(fullscreenOption));
if (parser.isSet(terminalOption))
return runTerminal(app, parser.value(terminalOption),
- parser.value(titleOption));
+ parser.value(titleOption), on(shareClipboardOption),
+ on(emptyWorkspaceOption));
app.setApplicationName(QStringLiteral("dev.omavm.app"));
app.setDesktopFileName(QStringLiteral("dev.omavm.app"));
app.setWindowIcon(QIcon::fromTheme(QStringLiteral("dev.omavm.app")));
Backend backend;
+ // Closing the window hides it, but an in-flight action (Restart,
+ // Create, ...) still finishes before the process exits.
+ app.setQuitOnLastWindowClosed(false);
+ QObject::connect(&app, &QGuiApplication::lastWindowClosed, &backend,
+ &Backend::requestQuit);
+ QObject::connect(&backend, &Backend::readyToQuit, &app,
+ &QCoreApplication::quit);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty(QStringLiteral("backend"), &backend);
engine.load(QUrl(QStringLiteral("qrc:/Main.qml")));
diff --git a/gui/resources.qrc b/gui/resources.qrc
index 1d06290..5e2e627 100644
--- a/gui/resources.qrc
+++ b/gui/resources.qrc
@@ -2,12 +2,25 @@
Main.qmlEnvironmentCard.qml
+ EnvironmentListModel.qmlCreateDialog.qmlSettingsDialog.qmlSnapshotsDialog.qmlAppsDialog.qmlThemeScrim.qml
+ Icon.qmlViewer.qmlTerminalViewer.qml
+ icons/add.svg
+ icons/refresh.svg
+ icons/warning.svg
+ icons/close.svg
+ icons/more.svg
+ icons/play.svg
+ icons/machine.svg
+ icons/box.svg
+ icons/app-mono.svg
+ icons/history.svg
+ icons/app.svg
diff --git a/gui/terminal.cpp b/gui/terminal.cpp
index efed620..55f061d 100644
--- a/gui/terminal.cpp
+++ b/gui/terminal.cpp
@@ -4,6 +4,7 @@
#include
#include
#include
+#include
#include
#include
@@ -58,6 +59,8 @@ TerminalSession::TerminalSession(QObject *parent) : QObject(parent) {
TerminalSession::~TerminalSession() {
if (m_notifier)
m_notifier->setEnabled(false);
+ if (m_writeNotifier)
+ m_writeNotifier->setEnabled(false);
if (m_masterFd >= 0)
::close(m_masterFd);
if (m_childPid > 0) {
@@ -133,6 +136,12 @@ void TerminalSession::onReadyRead() {
}
void TerminalSession::reap() {
+ m_pendingInput.clear();
+ if (m_writeNotifier) {
+ m_writeNotifier->setEnabled(false);
+ m_writeNotifier->deleteLater();
+ m_writeNotifier = nullptr;
+ }
if (m_notifier) {
m_notifier->setEnabled(false);
m_notifier->deleteLater();
@@ -146,9 +155,14 @@ void TerminalSession::reap() {
if (m_childPid > 0) {
int status = 0;
if (::waitpid(static_cast(m_childPid), &status, 0) ==
- static_cast(m_childPid) &&
- WIFEXITED(status))
- code = WEXITSTATUS(status);
+ static_cast(m_childPid)) {
+ // Death by a signal reads as 128 + signal, as in a shell: it must
+ // not look like the clean exit (0) the viewer closes itself on.
+ if (WIFEXITED(status))
+ code = WEXITSTATUS(status);
+ else if (WIFSIGNALED(status))
+ code = 128 + WTERMSIG(status);
+ }
m_childPid = -1;
}
emit finished(code);
@@ -157,9 +171,38 @@ void TerminalSession::reap() {
void TerminalSession::write(const QByteArray &bytes) {
if (m_masterFd < 0 || bytes.isEmpty())
return;
- const ssize_t written =
- ::write(m_masterFd, bytes.constData(), static_cast(bytes.size()));
- (void)written;
+ m_pendingInput.append(bytes);
+ flushInput();
+}
+
+void TerminalSession::flushInput() {
+ while (m_masterFd >= 0 && !m_pendingInput.isEmpty()) {
+ const ssize_t written =
+ ::write(m_masterFd, m_pendingInput.constData(),
+ static_cast(m_pendingInput.size()));
+ if (written > 0) {
+ m_pendingInput.remove(0, static_cast(written));
+ continue;
+ }
+ if (written < 0 && errno == EINTR)
+ continue;
+ if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+ // Full: wait until the program reads some.
+ if (!m_writeNotifier) {
+ m_writeNotifier =
+ new QSocketNotifier(m_masterFd, QSocketNotifier::Write, this);
+ connect(m_writeNotifier, &QSocketNotifier::activated, this,
+ &TerminalSession::flushInput);
+ }
+ m_writeNotifier->setEnabled(true);
+ return;
+ }
+ // The program is gone; reap() reports it.
+ m_pendingInput.clear();
+ break;
+ }
+ if (m_writeNotifier)
+ m_writeNotifier->setEnabled(false);
}
void TerminalSession::resize(int cols, int rows) {
@@ -322,7 +365,10 @@ void TerminalSession::handleByte(unsigned char byte) {
m_state = ParseState::OscEscape;
return;
}
- m_oscBuffer.append(char(byte));
+ if (m_oscBuffer.size() < kMaxOscLength)
+ m_oscBuffer.append(char(byte));
+ else
+ m_oscOverflow = true;
return;
case ParseState::OscEscape:
@@ -368,20 +414,84 @@ void TerminalSession::handleUtf8Byte(unsigned char byte) {
}
}
+namespace {
+// Columns a character occupies, like wcwidth() but from Qt's Unicode
+// tables instead of the C library's, whose answer depends on the process
+// locale (-1 for everything non-ASCII under LANG=C).
+int cellWidth(const QString &ch) {
+ if (ch.isEmpty())
+ return 1;
+ const char32_t cp = ch.toUcs4().value(0);
+ const QChar::Category category = QChar::category(cp);
+ if (category == QChar::Mark_NonSpacing ||
+ category == QChar::Mark_Enclosing || (cp >= 0x200b && cp <= 0x200d) ||
+ (cp >= 0xfe00 && cp <= 0xfe0f))
+ return 0;
+ // East Asian Wide/Fullwidth ranges and emoji.
+ if ((cp >= 0x1100 && cp <= 0x115f) ||
+ (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
+ (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xf900 && cp <= 0xfaff) ||
+ (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) ||
+ (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1f64f) ||
+ (cp >= 0x1f680 && cp <= 0x1f6ff) || (cp >= 0x1f900 && cp <= 0x1f9ff) ||
+ (cp >= 0x1fa70 && cp <= 0x1faff) || (cp >= 0x20000 && cp <= 0x3fffd))
+ return 2;
+ return 1;
+}
+
+// A wide character is a head cell followed by a continuation cell with an
+// empty ch. Writing over either half leaves the other half blank.
+void breakWideCharacterAt(QVector &row, int col) {
+ if (col < 0 || col >= row.size())
+ return;
+ if (row[col].ch.isEmpty()) {
+ if (col > 0)
+ row[col - 1].ch = QStringLiteral(" ");
+ } else if (col + 1 < row.size() && row[col + 1].ch.isEmpty()) {
+ row[col + 1].ch = QStringLiteral(" ");
+ }
+}
+} // namespace
+
void TerminalSession::putChar(const QString &ch) {
auto &grid = activeGrid();
if (grid.isEmpty())
return;
+ const int width = cellWidth(ch);
+ if (width == 0) {
+ // Combining mark: part of the character just written.
+ if (m_cursorRow < 0 || m_cursorRow >= grid.size())
+ return;
+ auto &row = grid[m_cursorRow];
+ int col = m_wrapPending ? m_cursorCol : m_cursorCol - 1;
+ if (col > 0 && col < row.size() && row[col].ch.isEmpty())
+ --col;
+ if (col >= 0 && col < row.size())
+ row[col].ch += ch;
+ return;
+ }
if (m_wrapPending) {
m_wrapPending = false;
newline();
carriageReturn();
}
+ if (width == 2 && m_cursorCol + 1 >= m_cols) {
+ // No room for both halves on this line.
+ if (m_autoWrap) {
+ newline();
+ carriageReturn();
+ } else {
+ m_cursorCol = qMax(0, m_cols - 2);
+ }
+ }
if (m_cursorRow < 0 || m_cursorRow >= grid.size())
return;
auto &row = grid[m_cursorRow];
- if (m_cursorCol < 0 || m_cursorCol >= row.size())
+ if (m_cursorCol < 0 || m_cursorCol + width - 1 >= row.size())
return;
+ breakWideCharacterAt(row, m_cursorCol);
+ if (width == 2)
+ breakWideCharacterAt(row, m_cursorCol + 1);
TerminalCell &cell = row[m_cursorCol];
cell.ch = ch;
cell.fg = m_curFg;
@@ -390,11 +500,17 @@ void TerminalSession::putChar(const QString &ch) {
cell.underline = m_curUnderline;
cell.reverse = m_curReverse;
cell.faint = m_curFaint;
- if (m_cursorCol + 1 >= m_cols) {
+ if (width == 2) {
+ row[m_cursorCol + 1] = cell;
+ row[m_cursorCol + 1].ch = QString();
+ }
+ const int last = m_cursorCol + width - 1;
+ if (last + 1 >= m_cols) {
+ m_cursorCol = last;
if (m_autoWrap)
m_wrapPending = true;
} else {
- ++m_cursorCol;
+ m_cursorCol = last + 1;
}
}
@@ -549,8 +665,10 @@ void TerminalSession::scrollRegionUp(int n) {
if (!m_altScreenActive && m_scrollTop == 0) {
for (int i = 0; i < n; ++i) {
m_scrollback.append(grid[i]);
- if (m_scrollback.size() > kMaxScrollback)
+ if (m_scrollback.size() > kMaxScrollback) {
m_scrollback.removeFirst();
+ ++m_droppedLines;
+ }
}
}
for (int r = m_scrollTop; r + n <= m_scrollBottom; ++r)
@@ -643,7 +761,9 @@ QVector TerminalSession::splitParams(const QByteArray &raw) {
value = 0;
any = true;
}
- value = value * 10 + (c - '0');
+ // Capped like xterm: ESC[2147483647C made cursor + n overflow to a
+ // negative column, and the next erase wrote outside the row.
+ value = qMin(value * 10 + (c - '0'), 65535);
}
}
result.append(any ? value : -1);
@@ -741,9 +861,15 @@ void TerminalSession::setPrivateMode(const QVector ¶ms, bool enable) {
return;
for (int mode : params) {
switch (mode) {
+ case 1:
+ m_applicationCursorKeys = enable;
+ break;
case 7:
m_autoWrap = enable;
break;
+ case 2004:
+ m_bracketedPaste = enable;
+ break;
case 25:
m_cursorVisible = enable;
break;
@@ -754,8 +880,8 @@ void TerminalSession::setPrivateMode(const QVector ¶ms, bool enable) {
switchAlternateScreen(enable, true);
break;
default:
- // Mouse reporting (1000/1002/1003/1006) and bracketed paste (2004)
- // are not implemented — safe to ignore rather than misbehave.
+ // Mouse reporting (1000/1002/1003/1006) is not implemented — safe
+ // to ignore rather than misbehave.
break;
}
}
@@ -829,14 +955,226 @@ void TerminalSession::handleSgr(const QVector ¶msIn) {
}
void TerminalSession::dispatchOsc() {
- const int semi = m_oscBuffer.indexOf(';');
- if (semi < 0) {
- m_oscBuffer.clear();
+ const QByteArray buffer = m_oscBuffer;
+ const bool overflow = m_oscOverflow;
+ m_oscBuffer.clear();
+ m_oscOverflow = false;
+ const int semi = buffer.indexOf(';');
+ if (semi < 0 || overflow)
return;
- }
- const QByteArray code = m_oscBuffer.left(semi);
- const QByteArray payload = m_oscBuffer.mid(semi + 1);
+ const QByteArray code = buffer.left(semi);
+ const QByteArray payload = buffer.mid(semi + 1);
if (code == "0" || code == "2")
emit titleChanged(QString::fromUtf8(payload));
- m_oscBuffer.clear();
+ else if (code == "52")
+ handleOsc52(payload);
+}
+
+// OSC 52 ; ; . Only writes: "?" asks for the clipboard's
+// contents, which would let anything running in the Box read what the user
+// copied on the host, so it is ignored (xterm's own default).
+void TerminalSession::handleOsc52(const QByteArray &payload) {
+ const int semi = payload.indexOf(';');
+ if (semi < 0)
+ return;
+ const QByteArray targets = payload.left(semi);
+ const QByteArray data = payload.mid(semi + 1);
+ // Empty targets mean the default "s 0"; c is the clipboard, p/s the
+ // primary selection. Anything else (cut buffers) isn't a clipboard here.
+ if (!targets.isEmpty() && !targets.contains('c') && !targets.contains('p') &&
+ !targets.contains('s'))
+ return;
+ if (data == "?")
+ return;
+ const auto decoded = QByteArray::fromBase64Encoding(
+ data, QByteArray::AbortOnBase64DecodingErrors);
+ if (!decoded)
+ return;
+ emit clipboardWriteRequested(QString::fromUtf8(*decoded));
+}
+
+int TerminalSession::bufferLineCount() const {
+ return m_scrollback.size() + grid().size();
+}
+
+QVector TerminalSession::bufferLine(int index) const {
+ if (index < 0 || index >= bufferLineCount())
+ return {};
+ if (index < m_scrollback.size())
+ return m_scrollback.at(index);
+ return grid().at(index - m_scrollback.size());
+}
+
+QString TerminalSession::text(int startLine, int startCol, int endLine,
+ int endCol) const {
+ if (startLine > endLine || (startLine == endLine && startCol > endCol)) {
+ qSwap(startLine, endLine);
+ qSwap(startCol, endCol);
+ }
+ QStringList lines;
+ for (int l = qMax(0, startLine); l <= endLine && l < bufferLineCount();
+ ++l) {
+ const QVector line = bufferLine(l);
+ int first = l == startLine ? qMax(0, startCol) : 0;
+ const int last = l == endLine ? qMin(endCol, int(line.size()) - 1)
+ : int(line.size()) - 1;
+ // Starting on the right half of a wide character copies all of it.
+ while (first > 0 && first < line.size() && line.at(first).ch.isEmpty())
+ --first;
+ QString out;
+ for (int c = first; c <= last; ++c)
+ out += line.at(c).ch;
+ while (out.endsWith(QLatin1Char(' ')))
+ out.chop(1);
+ lines << out;
+ }
+ return lines.join(QLatin1Char('\n'));
+}
+
+QPair TerminalSession::wordBounds(int line, int col) const {
+ const QVector cells = bufferLine(line);
+ if (col < 0 || col >= cells.size())
+ return {col, col};
+ // Paths, URLs and e-mail addresses select as one word, like in most
+ // terminals.
+ const auto isWord = [&cells](int c) {
+ const QString &ch = cells.at(c).ch;
+ if (ch.isEmpty()) // right half of a wide character
+ return true;
+ const QChar first = ch.at(0);
+ return first.isLetterOrNumber() || first.isMark() ||
+ QStringLiteral("-_./~:@%+#?=&").contains(first) ||
+ first.unicode() > 0x2e7f; // CJK and other wide scripts
+ };
+ while (col > 0 && cells.at(col).ch.isEmpty())
+ --col;
+ if (!isWord(col))
+ return {col, col};
+ int first = col;
+ int last = col;
+ while (first > 0 && isWord(first - 1))
+ --first;
+ while (first < cells.size() && cells.at(first).ch.isEmpty())
+ ++first;
+ while (last + 1 < cells.size() && isWord(last + 1))
+ ++last;
+ return {first, last};
+}
+
+bool TerminalSession::isCopyShortcut(int key,
+ Qt::KeyboardModifiers modifiers) {
+ const Qt::KeyboardModifiers relevant =
+ modifiers & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier);
+ return (key == Qt::Key_Insert && relevant == Qt::ControlModifier) ||
+ (key == Qt::Key_C &&
+ relevant == (Qt::ControlModifier | Qt::ShiftModifier));
+}
+
+QByteArray TerminalSession::keySequence(int key,
+ Qt::KeyboardModifiers modifiers,
+ const QString &text) const {
+ const bool shift = modifiers & Qt::ShiftModifier;
+ const bool alt = modifiers & Qt::AltModifier;
+ const bool ctrl = modifiers & Qt::ControlModifier;
+ // xterm's modifier parameter: 1 + Shift(1) + Alt(2) + Ctrl(4).
+ const int modifier = 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
+
+ // Cursor keys, Home/End and F1-F4: a final letter after CSI or SS3.
+ char final = 0;
+ bool cursorKey = false;
+ switch (key) {
+ case Qt::Key_Up: final = 'A'; cursorKey = true; break;
+ case Qt::Key_Down: final = 'B'; cursorKey = true; break;
+ case Qt::Key_Right: final = 'C'; cursorKey = true; break;
+ case Qt::Key_Left: final = 'D'; cursorKey = true; break;
+ case Qt::Key_Home: final = 'H'; cursorKey = true; break;
+ case Qt::Key_End: final = 'F'; cursorKey = true; break;
+ case Qt::Key_F1: final = 'P'; break;
+ case Qt::Key_F2: final = 'Q'; break;
+ case Qt::Key_F3: final = 'R'; break;
+ case Qt::Key_F4: final = 'S'; break;
+ default: break;
+ }
+ if (final) {
+ if (modifier > 1)
+ return QByteArray("\x1b[1;") + QByteArray::number(modifier) + final;
+ const bool ss3 = !cursorKey || m_applicationCursorKeys;
+ return QByteArray(ss3 ? "\x1bO" : "\x1b[") + final;
+ }
+
+ // Editing keys and F5-F12: CSI number ~.
+ int number = 0;
+ switch (key) {
+ case Qt::Key_Insert: number = 2; break;
+ case Qt::Key_Delete: number = 3; break;
+ case Qt::Key_PageUp: number = 5; break;
+ case Qt::Key_PageDown: number = 6; break;
+ default:
+ if (key >= Qt::Key_F5 && key <= Qt::Key_F12) {
+ static const int numbers[] = {15, 17, 18, 19, 20, 21, 23, 24};
+ number = numbers[key - Qt::Key_F5];
+ }
+ break;
+ }
+ if (number) {
+ QByteArray out = "\x1b[" + QByteArray::number(number);
+ if (modifier > 1)
+ out += ';' + QByteArray::number(modifier);
+ return out + '~';
+ }
+
+ QByteArray out;
+ switch (key) {
+ case Qt::Key_Return:
+ case Qt::Key_Enter:
+ out = "\r";
+ break;
+ case Qt::Key_Backspace:
+ out = ctrl ? "\x08" : "\x7f";
+ break;
+ case Qt::Key_Tab:
+ out = "\t";
+ break;
+ case Qt::Key_Backtab:
+ return QByteArrayLiteral("\x1b[Z");
+ case Qt::Key_Escape:
+ out = "\x1b";
+ break;
+ default:
+ if (ctrl && key >= Qt::Key_A && key <= Qt::Key_Z) {
+ out = QByteArray(1, char(key - Qt::Key_A + 1));
+ } else if (ctrl && (key == Qt::Key_Space || key == Qt::Key_At)) {
+ out = QByteArray(1, '\0');
+ } else if (ctrl && key >= Qt::Key_BracketLeft && key <= Qt::Key_Underscore) {
+ // Ctrl+[, Ctrl+\, Ctrl+], Ctrl+^ and Ctrl+_ are ESC, FS, GS, RS and US.
+ out = QByteArray(1, char(key - Qt::Key_BracketLeft + 0x1b));
+ } else if (!text.isEmpty()) {
+ out = text.toUtf8();
+ }
+ break;
+ }
+ if (!out.isEmpty() && alt && !out.startsWith('\x1b'))
+ out.prepend('\x1b');
+ return out;
+}
+
+bool TerminalSession::isPasteShortcut(int key,
+ Qt::KeyboardModifiers modifiers) {
+ const Qt::KeyboardModifiers relevant =
+ modifiers & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier);
+ return (key == Qt::Key_Insert && relevant == Qt::ShiftModifier) ||
+ (key == Qt::Key_V &&
+ relevant == (Qt::ControlModifier | Qt::ShiftModifier));
+}
+
+QByteArray TerminalSession::pasteSequence(const QString &text) const {
+ QString body = text;
+ body.replace(QStringLiteral("\r\n"), QStringLiteral("\r"));
+ body.replace(QLatin1Char('\n'), QLatin1Char('\r'));
+ if (!m_bracketedPaste)
+ return body.toUtf8();
+ // An end marker inside the text would close the bracket early and turn
+ // the rest of the paste into typed input.
+ body.remove(QStringLiteral("\x1b[201~"));
+ return "\x1b[200~" + body.toUtf8() + "\x1b[201~";
}
diff --git a/gui/terminal.h b/gui/terminal.h
index f925345..c274204 100644
--- a/gui/terminal.h
+++ b/gui/terminal.h
@@ -72,6 +72,40 @@ class TerminalSession : public QObject {
int cursorRow() const { return m_cursorRow; }
int cursorCol() const { return m_cursorCol; }
bool cursorVisible() const { return m_cursorVisible; }
+ bool running() const { return m_masterFd >= 0; }
+ // Bytes to send to the child for a key press, following the modes the
+ // program set (application cursor keys) and xterm's modifier encoding,
+ // which is what TERM=xterm-256color promises. Empty for keys that send
+ // nothing (a lone modifier).
+ QByteArray keySequence(int key, Qt::KeyboardModifiers modifiers,
+ const QString &text) const;
+ // Shift+Insert (what Omarchy's universal paste sends to terminals) or
+ // Ctrl+Shift+V.
+ static bool isPasteShortcut(int key, Qt::KeyboardModifiers modifiers);
+ // Bytes to send for pasted text: newlines as Enter, wrapped in bracketed
+ // paste markers when the program enabled them.
+ QByteArray pasteSequence(const QString &text) const;
+ // Ctrl+Shift+C, or Ctrl+Insert (what Omarchy's universal copy sends to
+ // terminals). Never forwarded to the program: Ctrl+Shift+C would
+ // otherwise reach it as Ctrl+C.
+ static bool isCopyShortcut(int key, Qt::KeyboardModifiers modifiers);
+
+ // The scrollback followed by the visible screen, as one list of lines.
+ int bufferLineCount() const;
+ QVector bufferLine(int index) const;
+ // Lines dropped from the front of the scrollback so far: an index plus
+ // this stays attached to the same line as more output arrives.
+ qint64 droppedLines() const { return m_droppedLines; }
+ // Text from (startLine, startCol) to (endLine, endCol), both inclusive,
+ // in buffer lines. Trailing blanks of each line are dropped, as every
+ // terminal does; a wide character is copied whole.
+ QString text(int startLine, int startCol, int endLine, int endCol) const;
+ // The columns [first, last] of the word under (line, col), for
+ // double-click selection. A blank cell selects just itself.
+ QPair wordBounds(int line, int col) const;
+ // Largest OSC 52 payload accepted (base64 text), about 1 MiB of text.
+ static constexpr int kMaxOscLength = 1400 * 1024;
+
bool alternateScreen() const { return m_altScreenActive; }
const QVector> &grid() const {
return m_altScreenActive ? m_altGrid : m_grid;
@@ -84,6 +118,9 @@ class TerminalSession : public QObject {
void updated();
void bell();
void titleChanged(const QString &title);
+ // A program asked to put text on the clipboard (OSC 52). Reading the
+ // clipboard that way is never answered.
+ void clipboardWriteRequested(const QString &text);
void finished(int exitCode);
void errorOccurred(const QString &message);
@@ -99,6 +136,7 @@ class TerminalSession : public QObject {
void putChar(const QString &ch);
void dispatchCsi(char final);
void dispatchOsc();
+ void handleOsc52(const QByteArray &payload);
void handleSgr(const QVector ¶ms);
void setPrivateMode(const QVector ¶ms, bool enable);
static QVector splitParams(const QByteArray &raw);
@@ -135,6 +173,11 @@ class TerminalSession : public QObject {
qint64 m_childPid = -1; // pid_t, kept as qint64 to avoid a
// dependency in this header — see terminal.cpp
QSocketNotifier *m_notifier = nullptr;
+ // Input the PTY hasn't taken yet (it is non-blocking, and a program
+ // that isn't reading fills it): written as soon as it takes more.
+ QByteArray m_pendingInput;
+ QSocketNotifier *m_writeNotifier = nullptr;
+ void flushInput();
int m_cols = 80;
int m_rows = 24;
@@ -143,6 +186,10 @@ class TerminalSession : public QObject {
bool m_cursorVisible = true;
bool m_wrapPending = false;
bool m_autoWrap = true;
+ // DECCKM (\e[?1h): cursor keys send SS3 (\eOA) instead of CSI (\e[A).
+ bool m_applicationCursorKeys = false;
+ // \e[?2004h: the program wants pastes wrapped in \e[200~ ... \e[201~.
+ bool m_bracketedPaste = false;
int m_scrollTop = 0;
int m_scrollBottom = 23;
@@ -176,6 +223,10 @@ class TerminalSession : public QObject {
QByteArray m_csiParams;
bool m_csiPrivate = false;
QByteArray m_oscBuffer;
+ // Set when an OSC outgrew kMaxOscLength: the rest is skipped and the
+ // sequence ignored, instead of growing without bound.
+ bool m_oscOverflow = false;
+ qint64 m_droppedLines = 0;
// Pending UTF-8 continuation bytes (a PTY read can split a multi-byte
// sequence across two feed() calls).
diff --git a/gui/terminalview.cpp b/gui/terminalview.cpp
index 19d8d51..7680877 100644
--- a/gui/terminalview.cpp
+++ b/gui/terminalview.cpp
@@ -1,9 +1,12 @@
#include "terminalview.h"
#include "colorstoml.h"
+#include
#include
#include
+#include
#include
+#include
#include
#include
#include
@@ -55,6 +58,12 @@ TerminalView::TerminalView(QQuickItem *parent) : QQuickPaintedItem(parent) {
[this] { /* visual bell TODO */ });
connect(&m_session, &TerminalSession::titleChanged, this,
&TerminalView::titleChanged);
+ connect(&m_session, &TerminalSession::clipboardWriteRequested, this,
+ [this](const QString &text) {
+ if (m_shareClipboard)
+ QGuiApplication::clipboard()->setText(text);
+ });
+ setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton);
connect(&m_session, &TerminalSession::finished, this,
&TerminalView::finished);
connect(&m_session, &TerminalSession::errorOccurred, this,
@@ -74,6 +83,8 @@ void TerminalView::loadPalette() {
m_defaultBg = get(QStringLiteral("background"), qRgb(0x10, 0x10, 0x10));
m_defaultFg = get(QStringLiteral("foreground"), qRgb(0xee, 0xee, 0xee));
+ m_selection = get(QStringLiteral("selection_background"),
+ get(QStringLiteral("selection"), qRgb(0x44, 0x44, 0x44)));
m_palette[0] = m_defaultBg;
m_palette[1] = get(QStringLiteral("red"), qRgb(0xcd, 0x00, 0x00));
@@ -94,6 +105,11 @@ void TerminalView::loadPalette() {
get(QStringLiteral("bright_foreground"), qRgb(0xff, 0xff, 0xff));
}
+void TerminalView::reloadPalette() {
+ loadPalette();
+ update();
+}
+
void TerminalView::setEnvName(const QString &name) {
if (m_envName == name)
return;
@@ -104,6 +120,14 @@ void TerminalView::setEnvName(const QString &name) {
m_session.start(m_envName, cols > 1 ? cols : 80, rows > 1 ? rows : 24);
}
+void TerminalView::restart() {
+ if (m_session.running() || m_envName.isEmpty())
+ return;
+ m_session.feed(QByteArrayLiteral("\r\n"));
+ m_session.start(m_envName, m_session.cols(), m_session.rows());
+ forceActiveFocus();
+}
+
void TerminalView::geometryChange(const QRectF &newGeometry,
const QRectF &oldGeometry) {
QQuickPaintedItem::geometryChange(newGeometry, oldGeometry);
@@ -130,17 +154,115 @@ QRgb TerminalView::resolveColor(const TerminalColor &color,
return foreground ? m_defaultFg : m_defaultBg;
}
+int TerminalView::visibleToBuffer(int visibleRow) const {
+ const int bottomIndex = m_session.bufferLineCount() - 1 - m_scrollOffset;
+ return bottomIndex - (m_session.rows() - 1 - visibleRow);
+}
+
QVector TerminalView::lineAt(int visibleRow) const {
- const auto &scrollback = m_session.scrollback();
- const auto &grid = m_session.grid();
- const int total = scrollback.size() + grid.size();
- const int bottomIndex = total - 1 - m_scrollOffset;
- const int sourceIndex = bottomIndex - (m_session.rows() - 1 - visibleRow);
- if (sourceIndex < 0 || sourceIndex >= total)
+ const int sourceIndex = visibleToBuffer(visibleRow);
+ if (sourceIndex < 0 || sourceIndex >= m_session.bufferLineCount())
return QVector(m_session.cols());
- if (sourceIndex < scrollback.size())
- return scrollback.at(sourceIndex);
- return grid.at(sourceIndex - scrollback.size());
+ return m_session.bufferLine(sourceIndex);
+}
+
+TerminalView::CellPos TerminalView::cellAt(const QPointF &pos) const {
+ const int row = qBound(0, int(pos.y() / m_cellHeight), m_session.rows() - 1);
+ const int col = qBound(0, int(pos.x() / m_cellWidth), m_session.cols() - 1);
+ return {visibleToBuffer(row) + m_session.droppedLines(), col};
+}
+
+bool TerminalView::isSelected(int bufferLine, int col) const {
+ CellPos start = m_selAnchor;
+ CellPos end = m_selEnd;
+ if (start.line > end.line || (start.line == end.line && start.col > end.col))
+ qSwap(start, end);
+ const qint64 line = bufferLine + m_session.droppedLines();
+ if (line < start.line || line > end.line)
+ return false;
+ if (line == start.line && col < start.col)
+ return false;
+ if (line == end.line && col > end.col)
+ return false;
+ return true;
+}
+
+QString TerminalView::selectedText() const {
+ const qint64 dropped = m_session.droppedLines();
+ return m_session.text(int(m_selAnchor.line - dropped), m_selAnchor.col,
+ int(m_selEnd.line - dropped), m_selEnd.col);
+}
+
+void TerminalView::clearSelection() {
+ if (!hasSelection())
+ return;
+ m_selecting = false;
+ m_selected = false;
+ update();
+}
+
+void TerminalView::copySelection(QClipboard::Mode mode) {
+ if (!m_selected)
+ return;
+ const QString text = selectedText();
+ if (!text.isEmpty())
+ QGuiApplication::clipboard()->setText(text, mode);
+}
+
+void TerminalView::mousePressEvent(QMouseEvent *event) {
+ forceActiveFocus();
+ if (event->button() == Qt::MiddleButton) {
+ // X11/Wayland convention: middle click pastes the primary selection.
+ const QString text =
+ QGuiApplication::clipboard()->text(QClipboard::Selection);
+ if (!text.isEmpty())
+ m_session.write(m_session.pasteSequence(text));
+ event->accept();
+ return;
+ }
+ m_selAnchor = cellAt(event->position());
+ m_selEnd = m_selAnchor;
+ m_selecting = true;
+ m_selected = false;
+ update();
+ event->accept();
+}
+
+void TerminalView::mouseMoveEvent(QMouseEvent *event) {
+ if (!m_selecting)
+ return;
+ m_selEnd = cellAt(event->position());
+ update();
+ event->accept();
+}
+
+void TerminalView::mouseReleaseEvent(QMouseEvent *event) {
+ if (!m_selecting)
+ return;
+ m_selecting = false;
+ // A click without a drag clears the selection instead of selecting a
+ // single cell.
+ m_selected = m_selAnchor.line != m_selEnd.line ||
+ m_selAnchor.col != m_selEnd.col;
+ if (m_selected)
+ copySelection(QClipboard::Selection);
+ update();
+ event->accept();
+}
+
+void TerminalView::mouseDoubleClickEvent(QMouseEvent *event) {
+ if (event->button() != Qt::LeftButton)
+ return;
+ const CellPos pos = cellAt(event->position());
+ const auto [first, last] = m_session.wordBounds(
+ int(pos.line - m_session.droppedLines()), pos.col);
+ m_selAnchor = {pos.line, first};
+ m_selEnd = {pos.line, last};
+ m_selecting = false;
+ m_selected = true;
+ copySelection(QClipboard::Selection);
+ update();
+ event->accept();
}
void TerminalView::paint(QPainter *painter) {
@@ -155,10 +277,19 @@ void TerminalView::paint(QPainter *painter) {
const QVector line = lineAt(r);
const qreal y = r * m_cellHeight;
int c = 0;
+ // A wide character (head cell + empty continuation cell) is drawn on
+ // its own across both cells: inside a run, its glyph's advance rarely
+ // matches two cells exactly and would shift the rest of the line.
+ const auto isWide = [&line](int col) {
+ return col + 1 < line.size() && !line.at(col).ch.isEmpty() &&
+ line.at(col + 1).ch.isEmpty();
+ };
while (c < cols && c < line.size()) {
const TerminalCell &first = line.at(c);
- int runEnd = c + 1;
- while (runEnd < cols && runEnd < line.size()) {
+ const bool wide = isWide(c);
+ int runEnd = c + (wide ? 2 : 1);
+ while (!wide && runEnd < cols && runEnd < line.size() &&
+ !isWide(runEnd) && !line.at(runEnd).ch.isEmpty()) {
const TerminalCell &next = line.at(runEnd);
if (next.fg == first.fg && next.bg == first.bg &&
next.bold == first.bold && next.underline == first.underline &&
@@ -196,6 +327,18 @@ void TerminalView::paint(QPainter *painter) {
c = runEnd;
}
+
+ if (hasSelection()) {
+ const int bufferLine = visibleToBuffer(r);
+ QColor overlay(m_selection);
+ overlay.setAlpha(150);
+ for (int col = 0; col < cols; ++col) {
+ if (isSelected(bufferLine, col))
+ painter->fillRect(QRectF(col * m_cellWidth, y, m_cellWidth,
+ m_cellHeight),
+ overlay);
+ }
+ }
}
// With m_scrollOffset == 0 (the only time the cursor is drawn), a
@@ -210,81 +353,26 @@ void TerminalView::paint(QPainter *painter) {
}
void TerminalView::keyPressEvent(QKeyEvent *event) {
- QByteArray out;
- const int key = event->key();
- const Qt::KeyboardModifiers mods = event->modifiers();
- const bool ctrl = mods & Qt::ControlModifier;
- const bool alt = mods & Qt::AltModifier;
-
- switch (key) {
- case Qt::Key_Return:
- case Qt::Key_Enter:
- out = "\r";
- break;
- case Qt::Key_Backspace:
- out = "\x7f";
- break;
- case Qt::Key_Tab:
- out = "\t";
- break;
- case Qt::Key_Escape:
- out = "\x1b";
- break;
- case Qt::Key_Up:
- out = "\x1b[A";
- break;
- case Qt::Key_Down:
- out = "\x1b[B";
- break;
- case Qt::Key_Right:
- out = "\x1b[C";
- break;
- case Qt::Key_Left:
- out = "\x1b[D";
- break;
- case Qt::Key_Home:
- out = "\x1b[H";
- break;
- case Qt::Key_End:
- out = "\x1b[F";
- break;
- case Qt::Key_Insert:
- out = "\x1b[2~";
- break;
- case Qt::Key_Delete:
- out = "\x1b[3~";
- break;
- case Qt::Key_PageUp:
- out = "\x1b[5~";
- break;
- case Qt::Key_PageDown:
- out = "\x1b[6~";
- break;
- default:
- if (key >= Qt::Key_F1 && key <= Qt::Key_F4) {
- static const char *codes[] = {"\x1bOP", "\x1bOQ", "\x1bOR", "\x1bOS"};
- out = codes[key - Qt::Key_F1];
- } else if (key >= Qt::Key_F5 && key <= Qt::Key_F12) {
- static const int nums[] = {15, 17, 18, 19, 20, 21, 23, 24};
- out = QByteArray("\x1b[") + QByteArray::number(nums[key - Qt::Key_F5]) +
- "~";
- } else if (ctrl && key >= Qt::Key_A && key <= Qt::Key_Z) {
- out = QByteArray(1, char(key - Qt::Key_A + 1));
- } else {
- const QString text = event->text();
- if (!text.isEmpty())
- out = text.toUtf8();
- }
- break;
+ if (TerminalSession::isCopyShortcut(event->key(), event->modifiers())) {
+ copySelection(QClipboard::Clipboard);
+ event->accept();
+ return;
}
-
+ if (TerminalSession::isPasteShortcut(event->key(), event->modifiers())) {
+ const QString text = QGuiApplication::clipboard()->text();
+ if (!text.isEmpty())
+ m_session.write(m_session.pasteSequence(text));
+ event->accept();
+ return;
+ }
+ const QByteArray out =
+ m_session.keySequence(event->key(), event->modifiers(), event->text());
if (out.isEmpty()) {
event->ignore();
return;
}
- if (alt && !out.startsWith('\x1b'))
- out.prepend('\x1b');
m_session.write(out);
+ clearSelection();
if (m_scrollOffset != 0) {
m_scrollOffset = 0;
update();
diff --git a/gui/terminalview.h b/gui/terminalview.h
index 440553e..64eee41 100644
--- a/gui/terminalview.h
+++ b/gui/terminalview.h
@@ -1,5 +1,6 @@
#pragma once
+#include
#include
#include
#include
@@ -7,12 +8,15 @@
#include "terminal.h"
// Renders a TerminalSession's grid and forwards keyboard/wheel input back
-// to it — the terminal-mode counterpart of VncView for a Machine's
+// to it — the terminal-mode counterpart of DisplayView for a Machine's
// display. See gui/terminal.h for what the parser does and doesn't cover.
class TerminalView : public QQuickPaintedItem {
Q_OBJECT
Q_PROPERTY(
QString envName READ envName WRITE setEnvName NOTIFY envNameChanged)
+ // Whether programs in the Box may set the clipboard (OSC 52). The Box's
+ // own setting, on by default.
+ Q_PROPERTY(bool shareClipboard MEMBER m_shareClipboard)
public:
explicit TerminalView(QQuickItem *parent = nullptr);
@@ -21,6 +25,10 @@ class TerminalView : public QQuickPaintedItem {
void setEnvName(const QString &name);
void paint(QPainter *painter) override;
+ // Runs `omavm open` again after the session ended, below what the last
+ // one printed (e.g. after starting the Box's container engine).
+ Q_INVOKABLE void restart();
+ Q_INVOKABLE void reloadPalette();
signals:
void envNameChanged();
@@ -33,12 +41,33 @@ class TerminalView : public QQuickPaintedItem {
const QRectF &oldGeometry) override;
void keyPressEvent(QKeyEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
+ void mousePressEvent(QMouseEvent *event) override;
+ void mouseMoveEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent *event) override;
+ void mouseDoubleClickEvent(QMouseEvent *event) override;
private:
+ // A cell in buffer coordinates that survive scrollback trimming: line
+ // counts from the first line ever written (see droppedLines()).
+ struct CellPos {
+ qint64 line = 0;
+ int col = 0;
+ };
+ CellPos cellAt(const QPointF &pos) const;
+ bool hasSelection() const {
+ return m_selected || (m_selecting && (m_selAnchor.line != m_selEnd.line ||
+ m_selAnchor.col != m_selEnd.col));
+ }
+ bool isSelected(int bufferLine, int col) const;
+ QString selectedText() const;
+ void clearSelection();
+ void copySelection(QClipboard::Mode mode);
+
void updateGridSize();
void loadPalette();
QRgb resolveColor(const TerminalColor &color, bool foreground) const;
QVector lineAt(int visibleRow) const;
+ int visibleToBuffer(int visibleRow) const;
QString m_envName;
TerminalSession m_session;
@@ -48,6 +77,13 @@ class TerminalView : public QQuickPaintedItem {
int m_scrollOffset = 0;
QTimer m_resizeTimer;
+ CellPos m_selAnchor;
+ CellPos m_selEnd;
+ bool m_selecting = false; // a drag is in progress
+ bool m_selected = false; // a finished selection is shown
+ bool m_shareClipboard = true;
+ QRgb m_selection;
+
QRgb m_palette[16];
QRgb m_defaultFg;
QRgb m_defaultBg;
diff --git a/gui/tests/backend_refresh_test.cpp b/gui/tests/backend_refresh_test.cpp
new file mode 100644
index 0000000..210edfe
--- /dev/null
+++ b/gui/tests/backend_refresh_test.cpp
@@ -0,0 +1,377 @@
+#include "../backend.h"
+#include "../colorstoml.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+class BackendRefreshTest : public QObject {
+ Q_OBJECT
+
+private slots:
+ void textColorsMeetEnhancedContrast();
+ void themeChangeKeepsReadableText();
+ void unchangedPollDoesNotFlash();
+ void failedPreviewIsNotRetriedEveryPoll();
+ void quitWaitsForRunningAction();
+ void pickedFilesBecomeLocalPaths();
+ void boxTerminalIsTaggedAsTerminal();
+ void onlyActiveViewerRulesCount();
+ void actionsOnDifferentEnvironmentsRunTogether();
+ void everyThemeTextMeetsAAA();
+};
+
+// Regression: status colors were used as text straight from the theme —
+// red errors, green "Running", accent labels — and most Omarchy themes
+// put them under WCAG 1.4.6's 7:1 (red under it in 20 of the 22 themes
+// shipped on 2026-09-29, 4 of them under even 3:1). Every theme
+// installed here is checked, plus a fixed set for machines without
+// Omarchy, the colors taken from its nord, catppuccin-latte and miasma.
+void BackendRefreshTest::everyThemeTextMeetsAAA() {
+ QStringList themes;
+ QDirIterator it(QStringLiteral("/usr/share/omarchy/themes"),
+ {QStringLiteral("colors.toml")}, QDir::Files,
+ QDirIterator::Subdirectories);
+ while (it.hasNext())
+ themes << QString::fromUtf8(
+ [&] {
+ QFile f(it.next());
+ return f.open(QIODevice::ReadOnly) ? f.readAll() : QByteArray();
+ }());
+ themes << QStringLiteral(
+ "mode = \"dark\"\naccent = \"#81a1c1\"\nmuted = \"#4c566a\"\n"
+ "background = \"#2e3440\"\nlighter_background = \"#3b4252\"\n"
+ "foreground = \"#d8dee9\"\nred = \"#bf616a\"\ngreen = \"#a3be8c\"\n")
+ << QStringLiteral(
+ "mode = \"light\"\naccent = \"#1e66f5\"\nmuted = \"#9ca0b0\"\n"
+ "background = \"#eff1f5\"\nlighter_background = \"#e6e9ef\"\n"
+ "foreground = \"#4c4f69\"\nred = \"#d20f39\"\ngreen = \"#40a02b\"\n")
+ << QStringLiteral(
+ "mode = \"dark\"\naccent = \"#78824b\"\nmuted = \"#666666\"\n"
+ "background = \"#222222\"\nlighter_background = \"#333333\"\n"
+ "foreground = \"#c2c2b0\"\nred = \"#685742\"\ngreen = \"#5f875f\"\n");
+
+ const QByteArray oldHome = qgetenv("HOME");
+ for (const QString &theme : std::as_const(themes)) {
+ QTemporaryDir home;
+ QVERIFY(home.isValid());
+ const QString dir =
+ home.filePath(QStringLiteral(".local/state/omarchy/current/theme"));
+ QVERIFY(QDir().mkpath(dir));
+ QFile colors(dir + QStringLiteral("/colors.toml"));
+ QVERIFY(colors.open(QIODevice::WriteOnly));
+ colors.write(theme.toUtf8());
+ colors.close();
+ qputenv("HOME", home.path().toUtf8());
+ Backend backend;
+ const QColor background(backend.themeBackground()),
+ surface(backend.themeSurface());
+ for (const QString &text :
+ {backend.themeForeground(), backend.themeMuted(),
+ backend.themeAccentText(), backend.themeGreen(),
+ backend.themeRed()}) {
+ const double ratio =
+ minimumContrastRatio(QColor(text), background, surface);
+ QVERIFY2(ratio >= 7.0, qPrintable(QStringLiteral("%1 at %2:1 in\n%3")
+ .arg(text)
+ .arg(ratio, 0, 'f', 2)
+ .arg(theme)));
+ }
+ }
+ qputenv("HOME", oldHome);
+}
+
+// Actions used to run one at a time across the whole window: a Box
+// pulling its image for minutes disabled every other card. Different
+// environments now run together; a second action on the same one is
+// refused with what is running, and quitting waits for all of them.
+void BackendRefreshTest::actionsOnDifferentEnvironmentsRunTogether() {
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ const QString log = dir.filePath(QStringLiteral("log"));
+ QFile cli(dir.filePath(QStringLiteral("omavm")));
+ QVERIFY(cli.open(QIODevice::WriteOnly));
+ cli.write("#!/bin/sh\n"
+ "case \"$1\" in\n"
+ " start) echo \"begin $2\" >> \"$OMAVM_TEST_LOG\"; sleep 0.4;\n"
+ " echo \"end $2\" >> \"$OMAVM_TEST_LOG\" ;;\n"
+ " list) printf '[]' ;;\n"
+ "esac\n");
+ cli.close();
+ QVERIFY(cli.setPermissions(QFile::ReadOwner | QFile::WriteOwner |
+ QFile::ExeOwner));
+ qputenv("OMAVM_TEST_LOG", log.toUtf8());
+ qputenv("PATH", dir.path().toUtf8() + ':' + qgetenv("PATH"));
+
+ Backend backend;
+ QSignalSpy finished(&backend, &Backend::actionFinished);
+ QSignalSpy ready(&backend, &Backend::readyToQuit);
+ backend.start(QStringLiteral("a"));
+ backend.start(QStringLiteral("b"));
+ QCOMPARE(finished.size(), 0); // neither refused
+ QVERIFY(backend.busyEnvironments().contains(QStringLiteral("a")));
+ QVERIFY(backend.busyEnvironments().contains(QStringLiteral("b")));
+
+ backend.start(QStringLiteral("a"));
+ QCOMPARE(finished.size(), 1);
+ QCOMPARE(finished.at(0).at(1).toBool(), false);
+ QVERIFY(finished.at(0).at(2).toString().contains(QStringLiteral("starting a")));
+
+ backend.requestQuit();
+ QTRY_COMPARE_WITH_TIMEOUT(ready.size(), 1, 5000);
+ QFile out(log);
+ QVERIFY(out.open(QIODevice::ReadOnly));
+ const QList lines = out.readAll().trimmed().split('\n');
+ QCOMPARE(lines.size(), 4);
+ // Both began before either ended.
+ QVERIFY(lines.at(0).startsWith("begin") && lines.at(1).startsWith("begin"));
+ QVERIFY(backend.busyEnvironments().isEmpty());
+}
+
+// Regression: Omarchy's Super+C reached a Box's terminal as Ctrl+C
+// (SIGINT) because the window lacked the "terminal" tag.
+void BackendRefreshTest::boxTerminalIsTaggedAsTerminal() {
+ const QString script = terminalTagScript(4242);
+ QVERIFY(script.contains(QStringLiteral("w.pid == 4242")));
+ QVERIFY(script.contains(QStringLiteral("w.class == 'dev.omavm.viewer'")));
+ QVERIFY(script.contains(QStringLiteral("tag = '+terminal'")));
+ QVERIFY(script.contains(QStringLiteral("window = 'address:' .. w.address")));
+}
+
+// A personal rule for the viewer takes over workspace placement, but a
+// commented-out one must not.
+void BackendRefreshTest::onlyActiveViewerRulesCount() {
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ QVERIFY(QDir().mkpath(dir.filePath(QStringLiteral("sub"))));
+ const auto write = [&dir](const QString &name, const QByteArray &text) {
+ QFile file(dir.filePath(name));
+ QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Truncate));
+ file.write(text);
+ };
+ write(QStringLiteral("windows.lua"),
+ "-- o.window(\"dev.omavm.viewer\", { fullscreen = true })\n"
+ "o.window(\"firefox\", {}) -- not dev.omavm.viewer\n");
+ write(QStringLiteral("sub/old.conf"),
+ "# windowrule = fullscreen, class:dev.omavm.viewer\n");
+ QVERIFY(!hasPersonalViewerRule(dir.path()));
+ write(QStringLiteral("sub/rules.lua"),
+ "o.window(\"dev.omavm.viewer\", { workspace = \"name:omavm\" })\n");
+ QVERIFY(hasPersonalViewerRule(dir.path()));
+ QVERIFY(!hasPersonalViewerRule(dir.filePath(QStringLiteral("missing"))));
+}
+
+void BackendRefreshTest::textColorsMeetEnhancedContrast() {
+ // A color with meaning keeps its hue: a red error stays red.
+ const QColor red = accessibleColor(QColor("#bf616a"), QColor("#2e3440"),
+ QColor("#3b4252"));
+ QVERIFY(minimumContrastRatio(red, QColor("#2e3440"), QColor("#3b4252")) >=
+ 7.0);
+ QVERIFY(red.red() > red.green() && red.red() > red.blue());
+
+ const auto ratio = [](QColor a, QColor b) {
+ const auto luminance = [](QColor c) {
+ const auto channel = [](int value) {
+ const double x = value / 255.0;
+ return x <= 0.04045 ? x / 12.92 : std::pow((x + 0.055) / 1.055, 2.4);
+ };
+ return 0.2126 * channel(c.red()) + 0.7152 * channel(c.green()) +
+ 0.0722 * channel(c.blue());
+ };
+ const double x = luminance(a), y = luminance(b);
+ return (qMax(x, y) + 0.05) / (qMin(x, y) + 0.05);
+ };
+ for (const auto &colors : {
+ std::array{"#717a86", "#08090a", "#16181b"},
+ {"#808080", "#f7f7f7", "#ffffff"},
+ {"#dddddd", "#101010", "#202020"},
+ }) {
+ const QColor wanted(colors[0]), background(colors[1]), surface(colors[2]);
+ const QColor actual = readableTextColor(wanted, background, surface);
+ QVERIFY2(ratio(actual, background) >= 7.0, colors[1]);
+ QVERIFY2(ratio(actual, surface) >= 7.0, colors[2]);
+ if (ratio(wanted, background) >= 7.0 && ratio(wanted, surface) >= 7.0)
+ QCOMPARE(actual, wanted);
+ }
+}
+
+void BackendRefreshTest::themeChangeKeepsReadableText() {
+ QTemporaryDir home;
+ QVERIFY(home.isValid());
+ const QString themeDir = home.filePath(
+ QStringLiteral(".local/state/omarchy/current/theme"));
+ QVERIFY(QDir().mkpath(themeDir));
+ QFile colors(themeDir + QStringLiteral("/colors.toml"));
+ const auto writeTheme = [&colors](const QByteArray &contents) {
+ if (!colors.open(QIODevice::WriteOnly | QIODevice::Truncate))
+ return false;
+ const bool ok = colors.write(contents) == contents.size();
+ colors.close();
+ return ok;
+ };
+ QVERIFY(writeTheme("mode = \"dark\"\nbackground = \"#08090a\"\n"
+ "lighter_background = \"#16181b\"\n"
+ "foreground = \"#717a86\"\nmuted = \"#717a86\"\n"));
+
+ const QByteArray oldHome = qgetenv("HOME");
+ qputenv("HOME", home.path().toUtf8());
+ struct RestoreHome {
+ QByteArray value;
+ ~RestoreHome() {
+ if (value.isNull())
+ qunsetenv("HOME");
+ else
+ qputenv("HOME", value);
+ }
+ } restore{oldHome};
+
+ Backend backend;
+ QCOMPARE(backend.themeMode(), QStringLiteral("dark"));
+ QCOMPARE(backend.themeForeground(), QStringLiteral("#ffffff"));
+ QCOMPARE(backend.themeMuted(), QStringLiteral("#ffffff"));
+
+ QVERIFY(writeTheme("mode = \"light\"\nbackground = \"#f7f7f7\"\n"
+ "lighter_background = \"#ffffff\"\n"
+ "foreground = \"#777777\"\nmuted = \"#777777\"\n"));
+ QTRY_COMPARE(backend.themeMode(), QStringLiteral("light"));
+ QCOMPARE(backend.themeForeground(), QStringLiteral("#000000"));
+ QCOMPARE(backend.themeMuted(), QStringLiteral("#000000"));
+}
+
+void BackendRefreshTest::unchangedPollDoesNotFlash() {
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ const QString marker = dir.filePath(QStringLiteral("polls"));
+ QFile cli(dir.filePath(QStringLiteral("omavm")));
+ QVERIFY(cli.open(QIODevice::WriteOnly));
+ cli.write(
+ "#!/bin/sh\n"
+ "if [ \"$1\" = list ]; then\n"
+ " printf 'x' >> \"$OMAVM_TEST_POLLS\"\n"
+ " printf '[{\"id\":\"one\",\"name\":\"demo\",\"kind\":\"box\","
+ "\"settings\":{},\"status\":{\"state\":\"stopped\"}}]'\n"
+ "fi\n");
+ cli.close();
+ QVERIFY(cli.setPermissions(QFile::ReadOwner | QFile::WriteOwner |
+ QFile::ExeOwner));
+ qputenv("OMAVM_TEST_POLLS", marker.toUtf8());
+ qputenv("PATH", dir.path().toUtf8() + ':' + qgetenv("PATH"));
+
+ Backend backend;
+ QSignalSpy busy(&backend, &Backend::busyChanged);
+ QSignalSpy changed(&backend, &Backend::environmentsChanged);
+ backend.poll();
+ QTRY_VERIFY(!backend.environments().isEmpty());
+ QTRY_COMPARE(
+ backend.environments().first().toMap().value("status").toString(),
+ QStringLiteral("stopped"));
+ QCOMPARE(busy.size(), 0);
+ const int firstChanges = changed.size();
+
+ backend.poll();
+ QTRY_VERIFY([&] {
+ QFile count(marker);
+ return count.open(QIODevice::ReadOnly) && count.readAll().size() == 2;
+ }());
+ QTest::qWait(100);
+ QCOMPARE(changed.size(), firstChanges);
+ QCOMPARE(busy.size(), 0);
+}
+
+void BackendRefreshTest::failedPreviewIsNotRetriedEveryPoll() {
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ const QString marker = dir.filePath(QStringLiteral("calls"));
+ QFile cli(dir.filePath(QStringLiteral("omavm")));
+ QVERIFY(cli.open(QIODevice::WriteOnly));
+ cli.write(
+ "#!/bin/sh\n"
+ "printf '%s\\n' \"$1\" >> \"$OMAVM_TEST_CALLS\"\n"
+ "case \"$1\" in\n"
+ " list) printf '[{\"id\":\"m\",\"name\":\"vm\",\"kind\":\"machine\","
+ "\"settings\":{},\"status\":{\"state\":\"running\"},"
+ "\"integration\":{\"guest_agent\":\"unavailable\"}}]' ;;\n"
+ " preview) echo 'no surface' >&2; exit 1 ;;\n"
+ "esac\n");
+ cli.close();
+ QVERIFY(cli.setPermissions(QFile::ReadOwner | QFile::WriteOwner |
+ QFile::ExeOwner));
+ qputenv("OMAVM_TEST_CALLS", marker.toUtf8());
+ qputenv("PATH", dir.path().toUtf8() + ':' + qgetenv("PATH"));
+
+ const auto count = [&](const QByteArray &command) {
+ QFile calls(marker);
+ if (!calls.open(QIODevice::ReadOnly))
+ return 0;
+ return int(calls.readAll().split('\n').count(command));
+ };
+ Backend backend;
+ backend.poll();
+ QTRY_COMPARE(count("preview"), 1);
+ QTRY_COMPARE(backend.environments().first().toMap().value("guestAgent"),
+ QVariant(QStringLiteral("unavailable")));
+ backend.poll();
+ QTRY_COMPARE(count("list"), 2);
+ QTest::qWait(100);
+ QCOMPARE(count("preview"), 1);
+ // One process per poll: status and guest tools come with the list.
+ QCOMPARE(count("status") + count("integration"), 0);
+}
+
+// Closing the Experience Center mid-action used to destroy the QProcess,
+// which SIGKILLs `omavm`: a Restart cut between its Stop and Start left
+// the Machine powered off.
+void BackendRefreshTest::quitWaitsForRunningAction() {
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+ const QString marker = dir.filePath(QStringLiteral("restarted"));
+ QFile cli(dir.filePath(QStringLiteral("omavm")));
+ QVERIFY(cli.open(QIODevice::WriteOnly));
+ cli.write("#!/bin/sh\n"
+ "if [ \"$1\" = restart ]; then sleep 0.5; : > \"$OMAVM_TEST_MARKER\"; fi\n"
+ "[ \"$1\" = list ] && printf '[]'\n"
+ "exit 0\n");
+ cli.close();
+ QVERIFY(cli.setPermissions(QFile::ReadOwner | QFile::WriteOwner |
+ QFile::ExeOwner));
+ qputenv("OMAVM_TEST_MARKER", marker.toUtf8());
+ qputenv("PATH", dir.path().toUtf8() + ':' + qgetenv("PATH"));
+
+ {
+ Backend backend;
+ QSignalSpy ready(&backend, &Backend::readyToQuit);
+ backend.restart(QStringLiteral("vm"));
+ QVERIFY(backend.busy());
+ backend.requestQuit();
+ QTest::qWait(50);
+ QCOMPARE(ready.size(), 0);
+ QTRY_COMPARE(ready.size(), 1);
+ QVERIFY(QFile::exists(marker));
+ }
+
+ Backend idle;
+ QSignalSpy ready(&idle, &Backend::readyToQuit);
+ idle.requestQuit();
+ QTRY_COMPARE(ready.size(), 1);
+}
+
+// File pickers hand QML a URL; stripping "file://" by hand left spaces and
+// accents percent-encoded ("Minhas%20ISOs"), a path QEMU cannot open.
+void BackendRefreshTest::pickedFilesBecomeLocalPaths() {
+ Backend backend;
+ const QString path = QStringLiteral("/home/user/Minhas ISOs/Fedora ção #1.iso");
+ QCOMPARE(backend.localPath(QUrl::fromLocalFile(path)), path);
+ QCOMPARE(backend.localPath(QUrl(QStringLiteral(
+ "file:///home/user/Minhas%20ISOs/a%25b.iso"))),
+ QStringLiteral("/home/user/Minhas ISOs/a%b.iso"));
+ QCOMPARE(backend.localPath(QUrl()), QString());
+}
+
+QTEST_GUILESS_MAIN(BackendRefreshTest)
+#include "backend_refresh_test.moc"
diff --git a/gui/tests/backend_refresh_test.pro b/gui/tests/backend_refresh_test.pro
new file mode 100644
index 0000000..ffa3098
--- /dev/null
+++ b/gui/tests/backend_refresh_test.pro
@@ -0,0 +1,5 @@
+QT += core gui network testlib
+CONFIG += c++17 testcase
+TARGET = backend_refresh_test
+SOURCES += backend_refresh_test.cpp ../backend.cpp ../colorstoml.cpp
+HEADERS += ../backend.h ../colorstoml.h
diff --git a/gui/tests/cest.h b/gui/tests/cest.h
new file mode 100644
index 0000000..dfe89af
--- /dev/null
+++ b/gui/tests/cest.h
@@ -0,0 +1,1197 @@
+#ifndef CEST_H_INCLUDED
+#define CEST_H_INCLUDED
+
+#define _POSIX_C_SOURCE 200809L
+#define _DEFAULT_SOURCE
+
+#include
+#include
+#include
+#include
+#include
+#ifndef _WIN32
+# include
+# include
+#endif
+#ifdef CEST_ENABLE_SIGNAL_HANDLER
+# include
+#endif
+
+#ifdef __OBJC__
+#import
+#endif
+
+#ifdef __cplusplus
+#include
+#include
+#include
+#endif
+
+// ============================================================================
+// Warning Suppression (enabled by default, can be disabled)
+// ============================================================================
+#ifndef CEST_SUPPRESS_WARNINGS
+# define CEST_SUPPRESS_WARNINGS 1
+#endif
+
+#if CEST_SUPPRESS_WARNINGS
+# ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wpedantic"
+# pragma GCC diagnostic ignored "-Wstrict-prototypes"
+# pragma GCC diagnostic ignored "-Wunused-function"
+# pragma GCC diagnostic ignored "-Wunused-parameter"
+# pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
+# pragma GCC diagnostic ignored "-Wcast-align"
+# endif
+# ifdef __clang__
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wpedantic"
+# pragma clang diagnostic ignored "-Wstrict-prototypes"
+# pragma clang diagnostic ignored "-Wunused-function"
+# pragma clang diagnostic ignored "-Wunused-parameter"
+# pragma clang diagnostic ignored "-Wimplicit-fallthrough"
+# pragma clang diagnostic ignored "-Wcast-align"
+# pragma clang diagnostic ignored "-Wcovered-switch-default"
+# endif
+# ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4100) // unreferenced formal parameter
+# pragma warning(disable: 4102) // unreferenced label
+# pragma warning(disable: 4189) // local variable is initialized
+# pragma warning(disable: 4201) // nameless struct/union
+# pragma warning(disable: 4214) // bitfield types other than int
+# pragma warning(disable: 4505) // unreferenced local function
+# endif
+#endif
+
+#define _CEST_C11 (__STDC_VERSION__ >= 201112L)
+
+// ============================================================================
+// CONFIGURATION MACROS (define before including cest.h)
+// ============================================================================
+// #define CEST_NO_COLORS // Disable colored output
+// #define CEST_THREAD_SAFE // Enable thread safety (requires pthreads)
+// #define CEST_NO_CLI // Disable CLI argument parsing
+// #define CEST_NO_HOOKS // Disable beforeEach/afterEach hooks
+// #define CEST_ENABLE_COVERAGE // Enable gcov coverage integration
+// #define CEST_ENABLE_LEAK_DETECTION // Enable memory leak detection (disabled if sanitizer active)
+// #define CEST_ENABLE_SIGNAL_HANDLER // Enable crash diagnostics (SIGSEGV, SIGABRT, etc.)
+// #define CEST_PREFIX // Use cest_ prefix on all public macros
+
+// NOTE (C++): cest.h defines short macros like `test` and `it`. Include any
+// standard library headers (, , etc.) BEFORE including
+// cest.h, or those macros can collide with unrelated identifiers such as
+// std::bitset::test(). If that's not possible, define CEST_PREFIX to use
+// cest_test/cest_it instead.
+
+// ============================================================================
+// Automatic Sanitizer Detection (before any configuration)
+// ============================================================================
+#ifndef CEST_SANITIZER_FLAGS
+# ifdef __has_feature
+# if __has_feature(address_sanitizer)
+# define CEST_ASAN_ACTIVE 1
+# endif
+# if __has_feature(thread_sanitizer)
+# define CEST_TSAN_ACTIVE 1
+# endif
+# if __has_feature(memory_sanitizer)
+# define CEST_MSAN_ACTIVE 1
+# endif
+# if __has_feature(undefined_sanitizer)
+# define CEST_UBSAN_ACTIVE 1
+# endif
+# endif
+# if defined(__SANITIZE_ADDRESS__) && !defined(CEST_ASAN_ACTIVE)
+# define CEST_ASAN_ACTIVE 1
+# endif
+# if defined(__SANITIZE_THREAD__) && !defined(CEST_TSAN_ACTIVE)
+# define CEST_TSAN_ACTIVE 1
+# endif
+# if defined(__SANITIZE_MEMORY__) && !defined(CEST_MSAN_ACTIVE)
+# define CEST_MSAN_ACTIVE 1
+# endif
+# if defined(__SANITIZE_UNDEFINED__) && !defined(CEST_UBSAN_ACTIVE)
+# define CEST_UBSAN_ACTIVE 1
+# endif
+
+// If any sanitizer is active, disable internal leak detection to avoid conflicts
+# if defined(CEST_ASAN_ACTIVE) || defined(CEST_TSAN_ACTIVE) || defined(CEST_MSAN_ACTIVE) || defined(CEST_UBSAN_ACTIVE)
+# ifdef CEST_ENABLE_LEAK_DETECTION
+# undef CEST_ENABLE_LEAK_DETECTION
+# pragma message("Cest: Leak detection disabled because a sanitizer is active.")
+# endif
+# endif
+#endif
+
+// ============================================================================
+// Sanitizer Suppression Macros (use before functions that intentionally trigger UB)
+// ============================================================================
+#if defined(__GNUC__) || defined(__clang__)
+# define CEST_NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address")))
+# define CEST_NO_SANITIZE_THREAD __attribute__((no_sanitize("thread")))
+# define CEST_NO_SANITIZE_MEMORY __attribute__((no_sanitize("memory")))
+# define CEST_NO_SANITIZE_UNDEFINED __attribute__((no_sanitize("undefined")))
+# define CEST_NO_SANITIZE_ALL __attribute__((no_sanitize("address", "thread", "memory", "undefined")))
+#elif defined(_MSC_VER)
+# define CEST_NO_SANITIZE_ADDRESS __declspec(no_sanitize_address)
+# define CEST_NO_SANITIZE_THREAD /* not supported */
+# define CEST_NO_SANITIZE_MEMORY /* not supported */
+# define CEST_NO_SANITIZE_UNDEFINED /* not supported */
+# define CEST_NO_SANITIZE_ALL /* not supported */
+#else
+# define CEST_NO_SANITIZE_ADDRESS
+# define CEST_NO_SANITIZE_THREAD
+# define CEST_NO_SANITIZE_MEMORY
+# define CEST_NO_SANITIZE_UNDEFINED
+# define CEST_NO_SANITIZE_ALL
+#endif
+
+// ============================================================================
+// Portability - MSVC and Cross-Platform Support
+// ============================================================================
+#ifndef CEST_WEAK
+# if defined(_MSC_VER)
+# if defined(__cplusplus)
+# define CEST_WEAK static
+# else
+# define CEST_WEAK __declspec(selectany) extern
+# endif
+# else
+# define CEST_WEAK __attribute__((weak))
+# endif
+#endif
+
+#ifndef CEST_UNUSED
+# if defined(_MSC_VER)
+# define CEST_UNUSED
+# elif defined(__GNUC__) || defined(__clang__)
+# define CEST_UNUSED __attribute__((unused))
+# else
+# define CEST_UNUSED
+# endif
+#endif
+
+// Thread safety support
+//
+// Serializes access to the shared stats counters (_cest_global_stats) and
+// makes the per-assertion context (_cest_ctx) thread-local, so worker
+// threads spawned from inside a test body can each run their own
+// expect()...toX() chains without clobbering one another. The test runner
+// itself (describe/test macros) is still sequential by design.
+#ifdef CEST_THREAD_SAFE
+# include
+CEST_WEAK pthread_mutex_t _cest_mutex = PTHREAD_MUTEX_INITIALIZER;
+# define CEST_LOCK() pthread_mutex_lock(&_cest_mutex)
+# define CEST_UNLOCK() pthread_mutex_unlock(&_cest_mutex)
+# if defined(__cplusplus) && __cplusplus >= 201103L
+# define CEST_THREAD_LOCAL thread_local
+# elif defined(_CEST_C11) && _CEST_C11 && !defined(__STDC_NO_THREADS__)
+# define CEST_THREAD_LOCAL _Thread_local
+# elif defined(_MSC_VER)
+# define CEST_THREAD_LOCAL __declspec(thread)
+# elif defined(__GNUC__) || defined(__clang__)
+# define CEST_THREAD_LOCAL __thread
+# else
+# define CEST_THREAD_LOCAL
+# endif
+#else
+# define CEST_LOCK()
+# define CEST_UNLOCK()
+# define CEST_THREAD_LOCAL
+#endif
+
+// Windows console color support
+#ifdef _WIN32
+# ifndef CEST_NO_COLORS
+# include
+# define _CEST_INIT_COLORS() do { \
+ DWORD mode; \
+ HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); \
+ if (GetConsoleMode(h, &mode)) SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING); \
+ } while(0)
+# endif
+#endif
+
+#ifndef _CEST_INIT_COLORS
+# define _CEST_INIT_COLORS()
+#endif
+
+// Internal Math Helpers (To avoid -lm dependency)
+// GNU/Clang: single evaluation via statement-expression + typeof.
+// Other compilers (MSVC): falls back to the classic double-evaluation macro —
+// safe today because every call site passes a side-effect-free expression,
+// but avoid passing an expression with side effects (e.g. a function call) to it.
+#if defined(__GNUC__) || defined(__clang__)
+# define _CEST_ABS(x) __extension__ ({ __typeof__(x) _cest_abs_v = (x); _cest_abs_v < 0 ? -_cest_abs_v : _cest_abs_v; })
+#else
+# define _CEST_ABS(x) ((x) < 0 ? -(x) : (x))
+#endif
+
+// Color codes
+#ifndef CEST_NO_COLORS
+# define CEST_CLR_RESET "\033[0m"
+# define CEST_CLR_RED "\033[31m"
+# define CEST_CLR_GREEN "\033[32m"
+# define CEST_CLR_YELLOW "\033[33m"
+# define CEST_CLR_BLUE "\033[34m"
+# define CEST_CLR_BOLD "\033[1m"
+# define CEST_CLR_DIM "\033[90m"
+#else
+# define CEST_CLR_RESET ""
+# define CEST_CLR_RED ""
+# define CEST_CLR_GREEN ""
+# define CEST_CLR_YELLOW ""
+# define CEST_CLR_BLUE ""
+# define CEST_CLR_BOLD ""
+# define CEST_CLR_DIM ""
+#endif
+
+// Types and Values
+typedef enum {
+ CEST_TYPE_INT,
+ CEST_TYPE_DOUBLE,
+ CEST_TYPE_STR,
+ CEST_TYPE_PTR,
+ CEST_TYPE_BOOL,
+ CEST_TYPE_OBJC_ID,
+ CEST_TYPE_REGEX,
+ CEST_TYPE_ARRAY,
+ CEST_TYPE_CHAR8,
+ CEST_TYPE_CHAR16,
+ CEST_TYPE_CHAR32,
+ CEST_TYPE_BYTE
+} cest_type_t;
+
+typedef struct {
+ cest_type_t type;
+ union {
+ long long i;
+ double d;
+ const char *s;
+ const void *p;
+ bool b;
+ unsigned char u8;
+#ifdef __OBJC__
+ id obj;
+#endif
+#ifdef __cplusplus
+ std::regex* re;
+#endif
+ } as;
+ int len;
+ size_t elem_size; // arrays only: sizeof one element
+} cest_value_t;
+
+typedef int (*cest_match_fn)(cest_value_t actual, cest_value_t expected, int* diff_pos);
+
+// ============================================================================
+// Leak Detection (optional - enable with CEST_ENABLE_LEAK_DETECTION)
+// ============================================================================
+#ifdef CEST_ENABLE_LEAK_DETECTION
+CEST_WEAK long long _cest_alloc_count = 0;
+CEST_WEAK long long _cest_free_count = 0;
+
+#define cest_malloc(size) _cest_malloc(size)
+#define cest_free(ptr) _cest_free(ptr)
+
+static inline void* _cest_malloc(size_t size) {
+ void* p = malloc(size);
+ if (p) _cest_alloc_count++;
+ return p;
+}
+
+static inline void _cest_free(void* ptr) {
+ if (ptr) _cest_free_count++;
+ free(ptr);
+}
+#else
+#define cest_malloc(size) malloc(size)
+#define cest_free(ptr) free(ptr)
+#endif
+
+// ============================================================================
+// Hook Identifiers
+// ============================================================================
+typedef enum {
+ CEST_HOOK_NONE = 0,
+ CEST_HOOK_BEFORE_EACH = 1,
+ CEST_HOOK_AFTER_EACH = 2,
+ CEST_HOOK_BEFORE_ALL = 3,
+ CEST_HOOK_AFTER_ALL = 4
+} cest_hook_id_t;
+
+// ============================================================================
+// Signal Handler (crash diagnostics without fork)
+// ============================================================================
+#ifdef CEST_ENABLE_SIGNAL_HANDLER
+static volatile const char* _cest_signal_test_name = NULL;
+static volatile int _cest_in_hook = CEST_HOOK_NONE;
+
+static const char* _cest_signal_name(int sig) {
+ switch(sig) {
+ case SIGSEGV: return "SIGSEGV (Segmentation Fault)";
+ case SIGABRT: return "SIGABRT (Abort)";
+ case SIGFPE: return "SIGFPE (Floating Point Exception)";
+ case SIGBUS: return "SIGBUS (Bus Error)";
+ case SIGILL: return "SIGILL (Illegal Instruction)";
+ default: return "Unknown Signal";
+ }
+}
+
+static const char* _cest_hook_name(int hook_id) {
+ switch(hook_id) {
+ case CEST_HOOK_BEFORE_EACH: return "beforeEach";
+ case CEST_HOOK_AFTER_EACH: return "afterEach";
+ case CEST_HOOK_BEFORE_ALL: return "beforeAll";
+ case CEST_HOOK_AFTER_ALL: return "afterAll";
+ default: return "unknown hook";
+ }
+}
+
+static void _cest_signal_handler(int sig) {
+ // Use write() instead of printf() — async-signal-safe
+ const char* msg_prefix = "\n \033[31m✕ CRASH: ";
+ const char* msg_signal = _cest_signal_name(sig);
+ const char* msg_reset = "\033[0m\n";
+ (void)!write(STDERR_FILENO, msg_prefix, strlen(msg_prefix));
+ (void)!write(STDERR_FILENO, msg_signal, strlen(msg_signal));
+ if (_cest_in_hook) {
+ const char* hook_msg = " in hook: ";
+ const char* hook_name = _cest_hook_name(_cest_in_hook);
+ (void)!write(STDERR_FILENO, hook_msg, strlen(hook_msg));
+ (void)!write(STDERR_FILENO, hook_name, strlen(hook_name));
+ }
+ if (_cest_signal_test_name) {
+ const char* test_msg = " during test: ";
+ (void)!write(STDERR_FILENO, test_msg, strlen(test_msg));
+ (void)!write(STDERR_FILENO, (const char*)_cest_signal_test_name, strlen((const char*)_cest_signal_test_name));
+ }
+ (void)!write(STDERR_FILENO, msg_reset, strlen(msg_reset));
+ _exit(128 + sig);
+}
+
+static inline void _cest_install_signal_handlers(void) {
+ struct sigaction sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = _cest_signal_handler;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_flags = SA_RESETHAND; // One-shot: restore default after first signal
+ sigaction(SIGSEGV, &sa, NULL);
+ sigaction(SIGABRT, &sa, NULL);
+ sigaction(SIGFPE, &sa, NULL);
+ sigaction(SIGBUS, &sa, NULL);
+ sigaction(SIGILL, &sa, NULL);
+}
+# define _CEST_SIGNAL_INIT() _cest_install_signal_handlers()
+# define _CEST_SIGNAL_SET_TEST(name) (_cest_signal_test_name = (name))
+# define _CEST_SIGNAL_SET_HOOK(id) (_cest_in_hook = (id))
+# define _CEST_SIGNAL_CLEAR_HOOK() (_cest_in_hook = CEST_HOOK_NONE)
+#else
+# define _CEST_SIGNAL_INIT()
+# define _CEST_SIGNAL_SET_TEST(name) ((void)(name))
+# define _CEST_SIGNAL_SET_HOOK(id) ((void)(id))
+# define _CEST_SIGNAL_CLEAR_HOOK()
+#endif
+
+// ============================================================================
+// Stats and Globals
+// ============================================================================
+typedef struct {
+ int passed;
+ int failed;
+ int skipped;
+ const char* filter_pattern;
+} cest_stats_t;
+
+CEST_WEAK cest_stats_t _cest_global_stats = {0, 0, 0, NULL};
+
+// Public, prefixed accessor for the shared stats counters. _cest_global_stats
+// was documented as the public way to read pass/fail/skip counts despite its
+// leading underscore (an internal-naming convention elsewhere in this file),
+// which is inconsistent and makes it look like an implementation detail
+// that should not be touched directly. Prefer cest_stats() in new code;
+// _cest_global_stats is kept, unchanged, for backward compatibility.
+static inline cest_stats_t cest_stats(void) { return _cest_global_stats; }
+
+CEST_WEAK const char* _cest_current_test_name = NULL;
+CEST_WEAK const char* _cest_junit_output = NULL;
+CEST_WEAK const char* _cest_json_output = NULL;
+CEST_WEAK double _cest_total_time = 0.0;
+CEST_WEAK clock_t _cest_suite_start_time = 0;
+
+// ============================================================================
+// Per-test recording (used by --junit / --json reports)
+// ============================================================================
+#ifndef CEST_MAX_TEST_RECORDS
+# define CEST_MAX_TEST_RECORDS 4096
+#endif
+
+typedef struct {
+ const char* name;
+ double time;
+ int failed; // 1 if at least one assertion failed during this test
+ int skipped; // 1 if this test was filtered out and never ran
+} cest_test_record_t;
+
+CEST_WEAK cest_test_record_t _cest_test_records[CEST_MAX_TEST_RECORDS] = { {NULL, 0, 0, 0} };
+CEST_WEAK int _cest_test_record_count = 0;
+
+static inline void _cest_record_test(const char* name, double time, int failed, int skipped) {
+ CEST_LOCK();
+ if (_cest_test_record_count < CEST_MAX_TEST_RECORDS) {
+ _cest_test_records[_cest_test_record_count].name = name;
+ _cest_test_records[_cest_test_record_count].time = time;
+ _cest_test_records[_cest_test_record_count].failed = failed;
+ _cest_test_records[_cest_test_record_count].skipped = skipped;
+ _cest_test_record_count++;
+ }
+ CEST_UNLOCK();
+}
+
+// Minimal escaping so test names never produce malformed reports.
+static inline void _cest_fputs_xml_escaped(const char* s, FILE* f) {
+ if (!s) return;
+ for (const char* p = s; *p; p++) {
+ switch (*p) {
+ case '&': fputs("&", f); break;
+ case '<': fputs("<", f); break;
+ case '>': fputs(">", f); break;
+ case '"': fputs(""", f); break;
+ case '\'': fputs("'", f); break;
+ default: fputc(*p, f);
+ }
+ }
+}
+
+static inline void _cest_fputs_json_escaped(const char* s, FILE* f) {
+ if (!s) return;
+ for (const char* p = s; *p; p++) {
+ switch (*p) {
+ case '"': fputs("\\\"", f); break;
+ case '\\': fputs("\\\\", f); break;
+ case '\n': fputs("\\n", f); break;
+ case '\t': fputs("\\t", f); break;
+ default:
+ if ((unsigned char)*p < 0x20) fprintf(f, "\\u%04x", *p);
+ else fputc(*p, f);
+ }
+ }
+}
+
+// ============================================================================
+// Coverage Support
+// ============================================================================
+#ifdef CEST_ENABLE_COVERAGE
+# define CEST_COVERAGE_INIT() \
+ do { \
+ extern void __gcov_flush(void); \
+ atexit(__gcov_flush); \
+ } while(0)
+# define _CEST_COVERAGE_BEFORE_EACH() \
+ do { \
+ extern void __gcov_reset(void); \
+ __gcov_reset(); \
+ } while(0)
+# define _CEST_COVERAGE_AFTER_EACH() \
+ do { \
+ extern void __gcov_dump(void); \
+ __gcov_dump(); \
+ } while(0)
+#else
+# define CEST_COVERAGE_INIT()
+# define _CEST_COVERAGE_BEFORE_EACH()
+# define _CEST_COVERAGE_AFTER_EACH()
+#endif
+
+// ============================================================================
+// Value Wrappers
+// ============================================================================
+static inline cest_value_t cest_int(long long v) { cest_value_t cv; cv.type = CEST_TYPE_INT; cv.as.i = v; cv.len = 0; return cv; }
+static inline cest_value_t cest_double(double v) { cest_value_t cv; cv.type = CEST_TYPE_DOUBLE; cv.as.d = v; cv.len = 0; return cv; }
+// Keeps a NULL char*/const char* as an actual NULL instead of the literal
+// string "NULL", so toBeNull() and the null-safe matchers below can tell a
+// missing string apart from the four-character text "NULL".
+static inline cest_value_t cest_str(const char* v) { cest_value_t cv; cv.type = CEST_TYPE_STR; cv.as.s = v; cv.len = 0; return cv; }
+static inline cest_value_t cest_ptr(const void* v) { cest_value_t cv; cv.type = CEST_TYPE_PTR; cv.as.p = v; cv.len = 0; return cv; }
+static inline cest_value_t cest_bool(bool v) { cest_value_t cv; cv.type = CEST_TYPE_BOOL; cv.as.b = v; cv.len = 0; return cv; }
+static inline cest_value_t _cest_array(const void* v, int len, size_t elem_size) { cest_value_t cv; cv.type = CEST_TYPE_ARRAY; cv.as.p = v; cv.len = len; cv.elem_size = elem_size; return cv; }
+#define cest_array(x, len) _cest_array((x), (len), sizeof(*(x)))
+#ifdef __OBJC__
+static inline cest_value_t cest_id(id v) { cest_value_t cv; cv.type = CEST_TYPE_OBJC_ID; cv.as.obj = v; cv.len = 0; return cv; }
+#endif
+
+#ifdef __cplusplus
+static inline cest_value_t cest_value(bool v) { return cest_bool(v); }
+static inline cest_value_t cest_value(int v) { return cest_int(v); }
+static inline cest_value_t cest_value(long v) { return cest_int(v); }
+static inline cest_value_t cest_value(long long v) { return cest_int(v); }
+static inline cest_value_t cest_value(float v) { return cest_double(v); }
+static inline cest_value_t cest_value(double v) { return cest_double(v); }
+static inline cest_value_t cest_value(char* v) { return cest_str(v); }
+static inline cest_value_t cest_value(const char* v) { return cest_str(v); }
+static inline cest_value_t cest_value(const std::string& v) { return cest_str(v.c_str()); }
+#ifdef __OBJC__
+static inline cest_value_t cest_value(id v) { return cest_id(v); }
+#endif
+template
+static inline cest_value_t cest_value(T* v) { return cest_ptr((const void*)v); }
+#else
+#define cest_value(x) \
+ _Generic((x), \
+ _Bool: cest_bool, \
+ int: cest_int, \
+ long: cest_int, \
+ long long: cest_int, \
+ float: cest_double, \
+ double: cest_double, \
+ char*: cest_str, \
+ const char*: cest_str, \
+ _CEST_OBJC_GENERIC(x) \
+ default: cest_ptr \
+ )(x)
+
+#ifdef __OBJC__
+# define _CEST_OBJC_GENERIC(x) id: cest_id,
+#else
+# define _CEST_OBJC_GENERIC(x)
+#endif
+#endif
+
+// ============================================================================
+// Core Assertion Implementation
+// ============================================================================
+static CEST_THREAD_LOCAL struct {
+ const char* file;
+ int line;
+ const char* actual_expr;
+ cest_value_t actual;
+ cest_value_t expected;
+ const char* expected_expr;
+} _cest_ctx;
+
+// Reset context to a clean state — prevents stale data leaking between asserts
+static inline void _cest_ctx_reset(void) {
+ _cest_ctx.file = NULL;
+ _cest_ctx.line = 0;
+ _cest_ctx.actual_expr = NULL;
+ memset(&_cest_ctx.actual, 0, sizeof(cest_value_t));
+ memset(&_cest_ctx.expected, 0, sizeof(cest_value_t));
+ _cest_ctx.expected_expr = NULL;
+}
+
+static inline void _cest_print_value(cest_value_t v) {
+ switch(v.type) {
+ case CEST_TYPE_INT: printf("(int: %lld)", v.as.i); break;
+ case CEST_TYPE_DOUBLE: printf("(double: %g)", v.as.d); break;
+ case CEST_TYPE_STR:
+ if (v.as.s) printf("(string: \"%s\")", v.as.s);
+ else printf("(string: null)");
+ break;
+ case CEST_TYPE_PTR: printf("(pointer: %p)", v.as.p); break;
+ case CEST_TYPE_BOOL: printf("(bool: %s)", v.as.b ? "true" : "false"); break;
+ case CEST_TYPE_ARRAY: printf("(array[%d]: %p)", v.len, v.as.p); break;
+#ifdef __OBJC__
+ case CEST_TYPE_OBJC_ID: printf("(id: %p)", (void*)v.as.obj); break;
+#else
+ case CEST_TYPE_OBJC_ID: printf("(id: %p)", v.as.p); break;
+#endif
+ case CEST_TYPE_REGEX: printf("(regex)"); break;
+ default: printf("(unknown)"); break;
+ }
+}
+
+static inline void _cest_assert_impl(cest_value_t expected, cest_match_fn match, const char* match_name, const char* expected_expr) {
+ int diff_pos = -1;
+ int passed = match(_cest_ctx.actual, expected, &diff_pos);
+ CEST_LOCK();
+ if (passed) {
+ printf(" " CEST_CLR_GREEN "✓" CEST_CLR_RESET " %s %s %s\n", _cest_ctx.actual_expr, match_name, expected_expr);
+ _cest_global_stats.passed++;
+ } else {
+ printf(" " CEST_CLR_RED "✕ %s failed" CEST_CLR_RESET "\n", _cest_ctx.actual_expr);
+ printf(" " CEST_CLR_GREEN "Expected %s: %s" CEST_CLR_RESET "\n", match_name, expected_expr);
+ printf(" " CEST_CLR_RED "Received "); _cest_print_value(_cest_ctx.actual); printf(CEST_CLR_RESET "\n");
+ if (_cest_ctx.actual.type == CEST_TYPE_STR && expected.type == CEST_TYPE_STR) {
+ if (diff_pos >= 0) {
+ printf(" " CEST_CLR_DIM "Diff at position %d: '%c' vs '%c'" CEST_CLR_RESET "\n",
+ diff_pos, _cest_ctx.actual.as.s[diff_pos], expected.as.s[diff_pos]);
+ }
+ }
+ if (_cest_ctx.actual.type == CEST_TYPE_DOUBLE && expected.type == CEST_TYPE_DOUBLE) {
+ double diff = _CEST_ABS(_cest_ctx.actual.as.d - expected.as.d);
+ printf(" " CEST_CLR_DIM "Diff: %g" CEST_CLR_RESET "\n", diff);
+ }
+ if (_cest_ctx.actual.type == CEST_TYPE_ARRAY && expected.type == CEST_TYPE_ARRAY) {
+ if (_cest_ctx.actual.len != expected.len) {
+ printf(" " CEST_CLR_DIM "Length mismatch: %d vs %d" CEST_CLR_RESET "\n", _cest_ctx.actual.len, expected.len);
+ } else {
+ printf(" " CEST_CLR_DIM "Arrays differ in content" CEST_CLR_RESET "\n");
+ }
+ }
+ printf(" " CEST_CLR_DIM "(%s:%d)" CEST_CLR_RESET "\n", _cest_ctx.file, _cest_ctx.line);
+ _cest_global_stats.failed++;
+ }
+ fflush(stdout); // Ensure output is visible even if test crashes after this assert
+ CEST_UNLOCK();
+}
+
+// ============================================================================
+// Matcher Logic
+// ============================================================================
+static inline int match_eq(cest_value_t a, cest_value_t b, int* diff_pos) {
+ if (diff_pos) *diff_pos = -1;
+ if (a.type != b.type) {
+ // toBeNull() builds its expectation as cest_ptr(NULL); a NULL
+ // char*/const char* actual represents the same "no value" and must
+ // be able to match it even though the stored types differ.
+ if ((a.type == CEST_TYPE_STR && a.as.s == NULL && b.type == CEST_TYPE_PTR && b.as.p == NULL) ||
+ (b.type == CEST_TYPE_STR && b.as.s == NULL && a.type == CEST_TYPE_PTR && a.as.p == NULL)) {
+ return 1;
+ }
+#ifdef __OBJC__
+ if ((a.type == CEST_TYPE_PTR && b.type == CEST_TYPE_OBJC_ID) ||
+ (a.type == CEST_TYPE_OBJC_ID && b.type == CEST_TYPE_PTR)) {
+ const void *p = a.type == CEST_TYPE_PTR ? a.as.p : b.as.p;
+ id obj = a.type == CEST_TYPE_OBJC_ID ? a.as.obj : b.as.obj;
+ return p == (const void*)obj;
+ }
+ if ((a.type == CEST_TYPE_PTR || a.type == CEST_TYPE_OBJC_ID) &&
+ (b.type == CEST_TYPE_PTR || b.type == CEST_TYPE_OBJC_ID)) {
+ const void *p1 = a.type == CEST_TYPE_PTR ? a.as.p : (const void*)a.as.obj;
+ const void *p2 = b.type == CEST_TYPE_PTR ? b.as.p : (const void*)b.as.obj;
+ return p1 == p2;
+ }
+#endif
+ return 0;
+ }
+ switch (a.type) {
+ case CEST_TYPE_INT: return a.as.i == b.as.i;
+ case CEST_TYPE_DOUBLE: return _CEST_ABS(a.as.d - b.as.d) < 0.000001;
+ case CEST_TYPE_STR: {
+ if (a.as.s == NULL || b.as.s == NULL) return a.as.s == b.as.s;
+ if (strcmp(a.as.s, b.as.s) == 0) return 1;
+ if (diff_pos) {
+ const char* p1 = a.as.s;
+ const char* p2 = b.as.s;
+ while (*p1 && *p2) {
+ if (*p1 != *p2) break;
+ p1++; p2++;
+ }
+ *diff_pos = (int)(p1 - a.as.s);
+ }
+ return 0;
+ }
+ case CEST_TYPE_PTR: return a.as.p == b.as.p;
+ case CEST_TYPE_BOOL: return a.as.b == b.as.b;
+ case CEST_TYPE_ARRAY: {
+ if (a.len != b.len || a.elem_size != b.elem_size) return 0;
+ if (a.len == 0) return 1;
+ return memcmp(a.as.p, b.as.p, (size_t)a.len * a.elem_size) == 0;
+ }
+#ifdef __OBJC__
+ case CEST_TYPE_OBJC_ID: return a.as.obj == b.as.obj;
+#endif
+ default: return 0;
+ }
+}
+
+static inline int match_gt(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_INT && b.type == CEST_TYPE_INT) return a.as.i > b.as.i;
+ if (a.type == CEST_TYPE_DOUBLE && b.type == CEST_TYPE_DOUBLE) return a.as.d > b.as.d;
+ return 0;
+}
+
+static inline int match_lt(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_INT && b.type == CEST_TYPE_INT) return a.as.i < b.as.i;
+ if (a.type == CEST_TYPE_DOUBLE && b.type == CEST_TYPE_DOUBLE) return a.as.d < b.as.d;
+ return 0;
+}
+
+static inline int match_in_range(cest_value_t a, cest_value_t min, cest_value_t max, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_INT && min.type == CEST_TYPE_INT && max.type == CEST_TYPE_INT) {
+ return a.as.i >= min.as.i && a.as.i <= max.as.i;
+ }
+ if (a.type == CEST_TYPE_DOUBLE && min.type == CEST_TYPE_DOUBLE && max.type == CEST_TYPE_DOUBLE) {
+ return a.as.d >= min.as.d && a.as.d <= max.as.d;
+ }
+ return 0;
+}
+
+static inline int match_start_with(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_STR && b.type == CEST_TYPE_STR) {
+ if (a.as.s == NULL || b.as.s == NULL) return 0;
+ return strncmp(a.as.s, b.as.s, strlen(b.as.s)) == 0;
+ }
+ return 0;
+}
+
+static inline int match_end_with(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_STR && b.type == CEST_TYPE_STR) {
+ if (a.as.s == NULL || b.as.s == NULL) return 0;
+ size_t len_a = strlen(a.as.s);
+ size_t len_b = strlen(b.as.s);
+ if (len_b > len_a) return 0;
+ return strcmp(a.as.s + len_a - len_b, b.as.s) == 0;
+ }
+ return 0;
+}
+
+static inline int match_contain(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_STR && b.type == CEST_TYPE_STR) {
+ if (a.as.s == NULL || b.as.s == NULL) return 0;
+ return strstr(a.as.s, b.as.s) != NULL;
+ }
+ return 0;
+}
+
+static inline int match_regex(cest_value_t a, cest_value_t b, int* diff_pos) {
+#ifdef __cplusplus
+ (void)diff_pos;
+ if (a.type == CEST_TYPE_STR && b.type == CEST_TYPE_REGEX) {
+ if (a.as.s == NULL) return 0;
+ return std::regex_match(a.as.s, *b.as.re);
+ }
+#else
+ (void)a; (void)b; (void)diff_pos;
+#endif
+ return 0;
+}
+
+static inline int match_truthy(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)b; (void)diff_pos;
+ switch (a.type) {
+ case CEST_TYPE_BOOL: return a.as.b;
+ case CEST_TYPE_INT: return a.as.i != 0;
+ case CEST_TYPE_DOUBLE: return a.as.d != 0.0;
+ case CEST_TYPE_STR: return a.as.s != NULL && strlen(a.as.s) > 0;
+ case CEST_TYPE_PTR: return a.as.p != NULL;
+#ifdef __OBJC__
+ case CEST_TYPE_OBJC_ID: return a.as.obj != nil;
+#endif
+ default: return 0;
+ }
+}
+
+static inline int match_falsy(cest_value_t a, cest_value_t b, int* diff_pos) {
+ return !match_truthy(a, b, diff_pos);
+}
+
+static inline int match_defined(cest_value_t a, cest_value_t b, int* diff_pos) {
+ (void)b; (void)diff_pos;
+ if (a.type == CEST_TYPE_PTR && a.as.p == NULL) return 0;
+#ifdef __OBJC__
+ if (a.type == CEST_TYPE_OBJC_ID && a.as.obj == nil) return 0;
+#endif
+ return 1;
+}
+
+static inline int match_undefined(cest_value_t a, cest_value_t b, int* diff_pos) {
+ return !match_defined(a, b, diff_pos);
+}
+
+// ============================================================================
+// Fluent API Bridge
+// ============================================================================
+typedef struct {
+ void (*_toEqual)(cest_value_t expected, const char* expected_expr);
+ void (*_toBe)(cest_value_t expected, const char* expected_expr);
+ void (*_toBeGreaterThan)(cest_value_t expected, const char* expected_expr);
+ void (*_toBeLessThan)(cest_value_t expected, const char* expected_expr);
+ void (*_toContain)(cest_value_t expected, const char* expected_expr);
+ void (*_toBeInRange)(cest_value_t min, cest_value_t max, const char* range_expr);
+ void (*_toStartWith)(cest_value_t expected, const char* expected_expr);
+ void (*_toEndWith)(cest_value_t expected, const char* expected_expr);
+ void (*_toBeNull)(void);
+ void (*_toBeTruthy)(void);
+ void (*_toBeFalsy)(void);
+ void (*_toBeCloseTo)(double val, double precision);
+ void (*_toEqualArray)(cest_value_t expected, const char* expected_expr);
+ void (*_toMatch)(cest_value_t expected, const char* expected_expr);
+ void (*_toBeDefined)(void);
+ void (*_toBeUndefined)(void);
+} _cest_bridge_t;
+
+static inline void b_toEqual(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_eq, "to equal", ee); }
+static inline void b_toEqualArray(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_eq, "to equal array", ee); }
+static inline void b_toBeGreaterThan(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_gt, "to be greater than", ee); }
+static inline void b_toBeLessThan(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_lt, "to be less than", ee); }
+static inline void b_toContain(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_contain, "to contain", ee); }
+static inline void b_toStartWith(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_start_with, "to start with", ee); }
+static inline void b_toEndWith(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_end_with, "to end with", ee); }
+static inline void b_toMatch(cest_value_t e, const char* ee) { _cest_assert_impl(e, match_regex, "to match", ee); }
+static inline void b_toBeNull(void) { _cest_assert_impl(cest_ptr(NULL), match_eq, "to be null", "NULL"); }
+static inline void b_toBeTruthy(void) { _cest_assert_impl(cest_bool(true), match_truthy, "to be", "truthy"); }
+static inline void b_toBeFalsy(void) { _cest_assert_impl(cest_bool(false), match_falsy, "to be", "falsy"); }
+static inline void b_toBeDefined(void) { _cest_assert_impl(cest_bool(true), match_defined, "to be", "defined"); }
+static inline void b_toBeUndefined(void) { _cest_assert_impl(cest_bool(true), match_undefined, "to be", "undefined"); }
+static inline void b_toBeCloseTo(double val, double precision) {
+ cest_value_t actual = _cest_ctx.actual;
+ int numeric = actual.type == CEST_TYPE_DOUBLE || actual.type == CEST_TYPE_INT;
+ double actual_d = actual.type == CEST_TYPE_INT ? (double)actual.as.i : actual.as.d;
+ double diff = numeric ? _CEST_ABS(actual_d - val) : 0.0;
+ CEST_LOCK();
+ if (numeric && diff < precision) {
+ printf(" " CEST_CLR_GREEN "✓" CEST_CLR_RESET " %s to be close to %g (precision %g)\n", _cest_ctx.actual_expr, val, precision);
+ _cest_global_stats.passed++;
+ } else {
+ printf(" " CEST_CLR_RED "✕ %s to be close to" CEST_CLR_RESET "\n", _cest_ctx.actual_expr);
+ printf(" " CEST_CLR_GREEN "Expected to be close to: %g (precision %g)" CEST_CLR_RESET "\n", val, precision);
+ printf(" " CEST_CLR_RED "Received "); _cest_print_value(actual);
+ if (numeric) printf(" (diff %g)", diff);
+ printf(CEST_CLR_RESET "\n");
+ printf(" " CEST_CLR_DIM "(%s:%d)" CEST_CLR_RESET "\n", _cest_ctx.file, _cest_ctx.line);
+ _cest_global_stats.failed++;
+ }
+ fflush(stdout);
+ CEST_UNLOCK();
+}
+static inline void b_toBeInRange(cest_value_t min, cest_value_t max, const char* re) {
+ int passed = match_in_range(_cest_ctx.actual, min, max, NULL);
+ CEST_LOCK();
+ if (passed) {
+ printf(" " CEST_CLR_GREEN "✓" CEST_CLR_RESET " %s to be in range %s\n", _cest_ctx.actual_expr, re);
+ _cest_global_stats.passed++;
+ } else {
+ printf(" " CEST_CLR_RED "✕ %s to be in range" CEST_CLR_RESET "\n", _cest_ctx.actual_expr);
+ printf(" " CEST_CLR_GREEN "Expected range: %s" CEST_CLR_RESET "\n", re);
+ printf(" " CEST_CLR_RED "Received "); _cest_print_value(_cest_ctx.actual); printf(CEST_CLR_RESET "\n");
+ printf(" " CEST_CLR_DIM "(%s:%d)" CEST_CLR_RESET "\n", _cest_ctx.file, _cest_ctx.line);
+ _cest_global_stats.failed++;
+ }
+ fflush(stdout);
+ CEST_UNLOCK();
+}
+
+// Positional (not designated) initialization: designated initializers
+// require C++20 on MSVC, but this struct is also used from C++11/14/17
+// translation units. Field order here must match _cest_bridge_t exactly.
+static _cest_bridge_t _cest_bridge CEST_UNUSED = {
+ b_toEqual,
+ b_toEqual,
+ b_toBeGreaterThan,
+ b_toBeLessThan,
+ b_toContain,
+ b_toBeInRange,
+ b_toStartWith,
+ b_toEndWith,
+ b_toBeNull,
+ b_toBeTruthy,
+ b_toBeFalsy,
+ b_toBeCloseTo,
+ b_toEqualArray,
+ b_toMatch,
+ b_toBeDefined,
+ b_toBeUndefined
+};
+
+#define expect(x) (_cest_ctx_reset(), _cest_ctx.file = __FILE__, _cest_ctx.line = __LINE__, _cest_ctx.actual_expr = #x, _cest_ctx.actual = cest_value(x), _cest_bridge)
+#define expect_array(x, len) (_cest_ctx_reset(), _cest_ctx.file = __FILE__, _cest_ctx.line = __LINE__, _cest_ctx.actual_expr = #x, _cest_ctx.actual = cest_array(x, len), _cest_bridge)
+
+#define toEqual(x) _toEqual(cest_value(x), #x)
+#define toBe(x) _toBe(cest_value(x), #x)
+#define toBeGreaterThan(x) _toBeGreaterThan(cest_value(x), #x)
+#define toBeLessThan(x) _toBeLessThan(cest_value(x), #x)
+#define toContain(x) _toContain(cest_value(x), #x)
+#define toBeInRange(min, max) _toBeInRange(cest_value(min), cest_value(max), #min " to " #max)
+#define toStartWith(x) _toStartWith(cest_value(x), #x)
+#define toEndWith(x) _toEndWith(cest_value(x), #x)
+#define toBeNull() _toBeNull()
+#define toBeTruthy() _toBeTruthy()
+#define toBeFalsy() _toBeFalsy()
+#define toBeCloseTo(v, p) _toBeCloseTo(v, p)
+#define toEqualArray(x, len) _toEqualArray(cest_array(x, len), #x ", " #len)
+#define toMatch(regex) _toMatch(cest_value(regex), #regex)
+#define toBeDefined() _toBeDefined()
+#define toBeUndefined() _toBeUndefined()
+
+// ============================================================================
+// Test Runner Macros with Timing
+// ============================================================================
+static clock_t _cest_test_start_time CEST_UNUSED = 0;
+
+#define describe(name, block) do { \
+ printf("\n" CEST_CLR_BOLD "● %s" CEST_CLR_RESET "\n", name); \
+ fflush(stdout); \
+ _CEST_RUN_BEFORE_ALL(); \
+ block \
+ _CEST_RUN_AFTER_ALL(); \
+} while (0)
+
+#define test(name, block) do { \
+ if (!_cest_should_run_test(name)) { \
+ printf(" " CEST_CLR_DIM "○ %s (filtered)" CEST_CLR_RESET "\n", name); \
+ CEST_LOCK(); _cest_global_stats.skipped++; CEST_UNLOCK(); \
+ _cest_record_test(name, 0.0, 0, 1); \
+ } else { \
+ _cest_current_test_name = name; \
+ _CEST_SIGNAL_SET_TEST(name); \
+ _cest_test_start_time = clock(); \
+ int _cest_failed_before = _cest_global_stats.failed; \
+ printf(" %s\n", name); \
+ fflush(stdout); \
+ _CEST_RUN_BEFORE_EACH(); \
+ block; \
+ _CEST_RUN_AFTER_EACH(); \
+ fflush(stdout); \
+ _cest_record_test(name, (double)(clock() - _cest_test_start_time) / CLOCKS_PER_SEC, _cest_global_stats.failed > _cest_failed_before, 0); \
+ } \
+} while (0)
+
+#define bench(name, block) do { \
+ clock_t _bench_start = clock(); \
+ for(int _i = 0; _i < 1000; _i++) { block } \
+ clock_t _bench_end = clock(); \
+ double _bench_time = (double)(_bench_end - _bench_start) / CLOCKS_PER_SEC; \
+ printf(" " CEST_CLR_BLUE "⚡ %s: %.6fs total, %.6fs avg" CEST_CLR_RESET "\n", name, _bench_time, _bench_time / 1000); \
+} while (0)
+
+#define it(name, block) test(name, block)
+
+// ============================================================================
+// Hooks
+// ============================================================================
+#ifndef CEST_NO_HOOKS
+typedef void (*cest_hook_fn)(void);
+static cest_hook_fn _cest_before_each_fn CEST_UNUSED = NULL;
+static cest_hook_fn _cest_after_each_fn CEST_UNUSED = NULL;
+static cest_hook_fn _cest_before_all_fn CEST_UNUSED = NULL;
+static cest_hook_fn _cest_after_all_fn CEST_UNUSED = NULL;
+
+#define beforeEach(fn) do { _cest_before_each_fn = fn; } while (0)
+#define afterEach(fn) do { _cest_after_each_fn = fn; } while (0)
+#define beforeAll(fn) do { _cest_before_all_fn = fn; } while (0)
+#define afterAll(fn) do { _cest_after_all_fn = fn; } while (0)
+
+#define _CEST_RUN_BEFORE_EACH() do { \
+ _CEST_SIGNAL_SET_HOOK(CEST_HOOK_BEFORE_EACH); \
+ if (_cest_before_each_fn) _cest_before_each_fn(); \
+ _CEST_SIGNAL_CLEAR_HOOK(); \
+ _CEST_COVERAGE_BEFORE_EACH(); \
+} while(0)
+#define _CEST_RUN_AFTER_EACH() do { \
+ _CEST_SIGNAL_SET_HOOK(CEST_HOOK_AFTER_EACH); \
+ if (_cest_after_each_fn) _cest_after_each_fn(); \
+ _CEST_SIGNAL_CLEAR_HOOK(); \
+ _CEST_COVERAGE_AFTER_EACH(); \
+} while(0)
+#define _CEST_RUN_BEFORE_ALL() do { \
+ _CEST_SIGNAL_SET_HOOK(CEST_HOOK_BEFORE_ALL); \
+ if (_cest_before_all_fn) _cest_before_all_fn(); \
+ _CEST_SIGNAL_CLEAR_HOOK(); \
+} while(0)
+#define _CEST_RUN_AFTER_ALL() do { \
+ _CEST_SIGNAL_SET_HOOK(CEST_HOOK_AFTER_ALL); \
+ if (_cest_after_all_fn) _cest_after_all_fn(); \
+ _CEST_SIGNAL_CLEAR_HOOK(); \
+} while(0)
+#else
+#define beforeEach(fn)
+#define afterEach(fn)
+#define beforeAll(fn)
+#define afterAll(fn)
+#define _CEST_RUN_BEFORE_EACH()
+#define _CEST_RUN_AFTER_EACH()
+#define _CEST_RUN_BEFORE_ALL()
+#define _CEST_RUN_AFTER_ALL()
+#endif
+
+// ============================================================================
+// CLI Arguments and Reports
+// ============================================================================
+#ifndef CEST_NO_CLI
+static inline void _cest_write_junit(void) {
+ if (!_cest_junit_output) return;
+ FILE* f = fopen(_cest_junit_output, "w");
+ if (!f) return;
+ // tests/failures must count testcase elements (one per it()/test(), plus
+ // one per filtered-out test), not assertions: a test can hold several
+ // expect() calls, and _cest_global_stats.passed/failed count those, not
+ // the tests that contain them.
+ int tests = _cest_test_record_count;
+ int failures = 0;
+ for (int i = 0; i < _cest_test_record_count; i++) {
+ if (_cest_test_records[i].failed) failures++;
+ }
+ fprintf(f, "\n");
+ fprintf(f, "\n",
+ tests, failures, _cest_global_stats.skipped, _cest_total_time);
+ fprintf(f, " \n",
+ tests, failures, _cest_global_stats.skipped, _cest_total_time);
+ for (int i = 0; i < _cest_test_record_count; i++) {
+ fprintf(f, " ", _cest_test_records[i].time);
+ if (_cest_test_records[i].skipped) {
+ fprintf(f, "");
+ } else if (_cest_test_records[i].failed) {
+ fprintf(f, "");
+ }
+ fprintf(f, "\n");
+ }
+ fprintf(f, " \n");
+ fprintf(f, "\n");
+ fclose(f);
+}
+
+static inline void _cest_write_json(void) {
+ if (!_cest_json_output) return;
+ FILE* f = fopen(_cest_json_output, "w");
+ if (!f) return;
+ fprintf(f, "{\n");
+ fprintf(f, " \"stats\": {\n");
+ fprintf(f, " \"passed\": %d,\n", _cest_global_stats.passed);
+ fprintf(f, " \"failed\": %d,\n", _cest_global_stats.failed);
+ fprintf(f, " \"skipped\": %d,\n", _cest_global_stats.skipped);
+ fprintf(f, " \"total_time\": %.3f\n", _cest_total_time);
+ fprintf(f, " },\n");
+ fprintf(f, " \"tests\": [\n");
+ for (int i = 0; i < _cest_test_record_count; i++) {
+ fprintf(f, " {\"name\": \"");
+ _cest_fputs_json_escaped(_cest_test_records[i].name, f);
+ fprintf(f, "\", \"time\": %.6f, \"status\": \"%s\"}%s\n",
+ _cest_test_records[i].time,
+ _cest_test_records[i].skipped ? "skipped" : (_cest_test_records[i].failed ? "failed" : "passed"),
+ (i + 1 < _cest_test_record_count) ? "," : "");
+ }
+ fprintf(f, " ]\n");
+ fprintf(f, "}\n");
+ fclose(f);
+}
+
+static inline void _cest_parse_cli_args(int argc, char* argv[]) {
+ _CEST_INIT_COLORS();
+
+ for (int i = 1; i < argc; i++) {
+ if (argv[i][0] == '-') {
+ if (strcmp(argv[i], "--junit") == 0 && i + 1 < argc) {
+ _cest_junit_output = argv[++i];
+ } else if (strcmp(argv[i], "--json") == 0 && i + 1 < argc) {
+ _cest_json_output = argv[++i];
+ }
+ } else {
+ _cest_global_stats.filter_pattern = argv[i];
+ }
+ }
+}
+
+static inline int _cest_should_run_test(const char* name) {
+ if (!_cest_global_stats.filter_pattern) return 1;
+ return strstr(name, _cest_global_stats.filter_pattern) != NULL;
+}
+
+#define cest_init(argc, argv) do { _cest_parse_cli_args(argc, argv); _CEST_SIGNAL_INIT(); } while(0)
+#else
+#define cest_init(argc, argv) do { _CEST_SIGNAL_INIT(); } while(0)
+#define _cest_should_run_test(name) (1)
+// --junit/--json are CLI flags; with CEST_NO_CLI there's no way to set the
+// output path, so these are no-ops (cest_result() still calls them unconditionally).
+static inline void _cest_write_junit(void) {}
+static inline void _cest_write_json(void) {}
+#endif
+
+// ============================================================================
+// Enhanced Results
+// ============================================================================
+static inline int cest_result(void) {
+ _cest_total_time = (double)(clock() - _cest_suite_start_time) / CLOCKS_PER_SEC;
+
+ printf("\n" CEST_CLR_BOLD "Test Suites Summary:" CEST_CLR_RESET "\n");
+ if (_cest_global_stats.failed == 0) {
+ printf(" " CEST_CLR_GREEN "All %d tests passed!" CEST_CLR_RESET, _cest_global_stats.passed);
+ if (_cest_global_stats.skipped > 0) printf(" (" CEST_CLR_YELLOW "%d skipped" CEST_CLR_RESET ")", _cest_global_stats.skipped);
+ printf("\n");
+ } else {
+ printf(" " CEST_CLR_GREEN "Passed: %d" CEST_CLR_RESET, _cest_global_stats.passed);
+ printf("\n " CEST_CLR_RED "Failed: %d" CEST_CLR_RESET, _cest_global_stats.failed);
+ if (_cest_global_stats.skipped > 0) printf("\n " CEST_CLR_YELLOW "Skipped: %d" CEST_CLR_RESET, _cest_global_stats.skipped);
+ printf("\n");
+ }
+
+#ifdef CEST_ENABLE_LEAK_DETECTION
+ printf("\n" CEST_CLR_BOLD "Memory:" CEST_CLR_RESET "\n");
+ if (_cest_alloc_count == _cest_free_count) {
+ printf(" " CEST_CLR_GREEN "All %lld allocations freed!" CEST_CLR_RESET "\n", _cest_alloc_count);
+ } else {
+ long long leaked = _cest_alloc_count - _cest_free_count;
+ printf(" " CEST_CLR_RED "Memory leak: %lld allocations not freed" CEST_CLR_RESET "\n", leaked);
+ }
+#endif
+
+ // Write reports
+ _cest_write_junit();
+ _cest_write_json();
+
+ // Post-run command hook.
+ // SECURITY: this runs CEST_POST_RUN through the system shell verbatim. Only set
+ // this env var to a command you trust — never forward untrusted/external input
+ // into it (e.g. from a PR description, webhook payload, etc.).
+ const char* post_run = getenv("CEST_POST_RUN");
+ if (post_run != NULL) {
+ printf("\n" CEST_CLR_BOLD "Running post-test command:" CEST_CLR_RESET " %s\n", post_run);
+ int ret = system(post_run);
+ if (ret == -1) {
+ printf(CEST_CLR_RED "Failed to execute post-run command." CEST_CLR_RESET "\n");
+ } else {
+#ifdef _WIN32
+ printf(CEST_CLR_GREEN "Post-run command executed with exit code %d." CEST_CLR_RESET "\n", ret);
+#else
+ printf(CEST_CLR_GREEN "Post-run command executed with exit code %d." CEST_CLR_RESET "\n", WEXITSTATUS(ret));
+#endif
+ }
+ }
+
+ printf("\n");
+ return _cest_global_stats.failed > 0 ? 1 : 0;
+}
+
+// ============================================================================
+// Optional Namespaced Macros (define CEST_PREFIX before including cest.h)
+// ============================================================================
+#ifdef CEST_PREFIX
+# define cest_describe(name, block) describe(name, block)
+# define cest_test(name, block) test(name, block)
+# define cest_it(name, block) it(name, block)
+# define cest_expect(x) expect(x)
+# define cest_expect_array(x, len) expect_array(x, len)
+# define cest_bench(name, block) bench(name, block)
+# define cest_beforeEach(fn) beforeEach(fn)
+# define cest_afterEach(fn) afterEach(fn)
+# define cest_beforeAll(fn) beforeAll(fn)
+# define cest_afterAll(fn) afterAll(fn)
+#endif
+
+// ============================================================================
+// File-based Test Grouping (describe with automatic filename)
+// ============================================================================
+#define describe_file(block) \
+ describe(_cest_basename(__FILE__), block)
+
+static inline const char* _cest_basename(const char* path) {
+ const char* sep = path ? strrchr(path, '/') : NULL;
+ return sep ? sep + 1 : (path ? path : "unknown");
+}
+
+// ============================================================================
+// End Warning Suppression
+// ============================================================================
+#if CEST_SUPPRESS_WARNINGS
+# ifdef __GNUC__
+# pragma GCC diagnostic pop
+# endif
+# ifdef __clang__
+# pragma clang diagnostic pop
+# endif
+# ifdef _MSC_VER
+# pragma warning(pop)
+# endif
+#endif
+
+#endif // CEST_H_INCLUDED
diff --git a/gui/tests/displayclient_test.cpp b/gui/tests/displayclient_test.cpp
new file mode 100644
index 0000000..d8dd320
--- /dev/null
+++ b/gui/tests/displayclient_test.cpp
@@ -0,0 +1,217 @@
+#include "../displayclient.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+namespace {
+// Reads QMP replies until one that answers a command (skipping events).
+QJsonObject qmpReply(int fd) {
+ QByteArray line;
+ char c;
+ while (read(fd, &c, 1) == 1) {
+ if (c != '\n') {
+ line.append(c);
+ continue;
+ }
+ const QJsonObject reply = QJsonDocument::fromJson(line).object();
+ line.clear();
+ if (reply.contains(QStringLiteral("return")) ||
+ reply.contains(QStringLiteral("error")) ||
+ reply.contains(QStringLiteral("QMP")))
+ return reply;
+ }
+ return {};
+}
+
+bool qmpSend(int fd, const QByteArray &command, int passFd = -1) {
+ QByteArray data = command + '\n';
+ iovec io{data.data(), size_t(data.size())};
+ msghdr msg{};
+ msg.msg_iov = &io;
+ msg.msg_iovlen = 1;
+ char control[CMSG_SPACE(sizeof(int))] = {};
+ if (passFd >= 0) {
+ msg.msg_control = control;
+ msg.msg_controllen = sizeof(control);
+ cmsghdr *header = CMSG_FIRSTHDR(&msg);
+ header->cmsg_level = SOL_SOCKET;
+ header->cmsg_type = SCM_RIGHTS;
+ header->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(header), &passFd, sizeof(int));
+ }
+ return sendmsg(fd, &msg, 0) == qsizetype(data.size()) &&
+ !qmpReply(fd).contains(QStringLiteral("error"));
+}
+
+// What qemu.Backend.attachDisplay does in Go: hand QEMU one end of a
+// socket pair over QMP and return the other.
+int attachDisplay(const QString &qmpPath) {
+ const int qmp = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ const QByteArray path = QFile::encodeName(qmpPath);
+ memcpy(address.sun_path, path.constData(), size_t(path.size()));
+ if (::connect(qmp, reinterpret_cast(&address),
+ sizeof(address)) != 0) {
+ close(qmp);
+ return -1;
+ }
+ int pair[2];
+ socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair);
+ const bool ok =
+ !qmpReply(qmp).isEmpty() &&
+ qmpSend(qmp, R"({"execute":"qmp_capabilities"})") &&
+ qmpSend(qmp, R"({"execute":"getfd","arguments":{"fdname":"t"}})",
+ pair[1]) &&
+ qmpSend(qmp, R"({"execute":"add_client","arguments":)"
+ R"({"protocol":"@dbus-display","fdname":"t"}})");
+ close(qmp);
+ close(pair[1]);
+ if (!ok) {
+ close(pair[0]);
+ return -1;
+ }
+ return pair[0];
+}
+
+bool renderNodeAvailable() {
+ for (const QString &node :
+ QDir(QStringLiteral("/dev/dri"))
+ .entryList({QStringLiteral("renderD*")}, QDir::System)) {
+ QFile file(QStringLiteral("/dev/dri/") + node);
+ if (file.open(QIODevice::ReadWrite))
+ return true;
+ }
+ return false;
+}
+} // namespace
+
+// Exercises DisplayClient against a real QEMU (no guest disk: the
+// firmware's text screen is enough to produce frames).
+class DisplayClientTest : public QObject {
+ Q_OBJECT
+
+private slots:
+ void sharedMemoryFrames();
+ void dmabufFramesArePacedByFrameRendered();
+
+private:
+ bool startQemu(const QStringList &display);
+ QTemporaryDir m_dir{QStringLiteral("/tmp/omavm-display-XXXXXX")};
+ QProcess m_qemu;
+ QString m_qmp;
+
+ void cleanup() {
+ m_qemu.kill();
+ m_qemu.waitForFinished(3000);
+ }
+};
+
+bool DisplayClientTest::startQemu(const QStringList &display) {
+ if (QStandardPaths::findExecutable(QStringLiteral("qemu-system-x86_64"))
+ .isEmpty() ||
+ !QFile::exists(QStringLiteral("/dev/kvm")))
+ return false;
+ m_qmp = m_dir.filePath(QStringLiteral("qmp.sock"));
+ QFile::remove(m_qmp);
+ m_qemu.start(QStringLiteral("qemu-system-x86_64"),
+ QStringList{QStringLiteral("-m"), QStringLiteral("128"),
+ QStringLiteral("-enable-kvm"),
+ QStringLiteral("-monitor"), QStringLiteral("none"),
+ QStringLiteral("-serial"), QStringLiteral("none"),
+ QStringLiteral("-qmp"),
+ QStringLiteral("unix:%1,server,nowait").arg(m_qmp)} +
+ display);
+ if (!m_qemu.waitForStarted(3000))
+ return false;
+ for (int i = 0; i < 50 && !QFile::exists(m_qmp); ++i)
+ QTest::qWait(100);
+ return QFile::exists(m_qmp);
+}
+
+void DisplayClientTest::sharedMemoryFrames() {
+ if (!startQemu({QStringLiteral("-display"), QStringLiteral("dbus,p2p=yes")}))
+ QSKIP("needs qemu-system-x86_64 with KVM");
+ const int fd = attachDisplay(m_qmp);
+ QVERIFY(fd >= 0);
+
+ DisplayClient client;
+ QSignalSpy scanouts(&client, &DisplayClient::imageScanout);
+ QSignalSpy updates(&client, &DisplayClient::frameUpdated);
+ QSignalSpy errors(&client, &DisplayClient::errorOccurred);
+ client.connectToFd(fd);
+
+ QTRY_VERIFY_WITH_TIMEOUT(!scanouts.isEmpty(), 10000);
+ QVERIFY(!client.frame().isNull());
+ QVERIFY(client.frame().width() >= 640);
+ QTRY_VERIFY_WITH_TIMEOUT(!updates.isEmpty(), 10000);
+ // The firmware screen is not all one color once text is drawn.
+ const QImage frame = client.frame();
+ bool varied = false;
+ for (int y = 0; y < frame.height() && !varied; y += 4)
+ for (int x = 0; x < frame.width() && !varied; x += 4)
+ varied = frame.pixel(x, y) != frame.pixel(0, 0);
+ QVERIFY(varied);
+
+ // Input on a console without an absolute pointer must not fail the
+ // connection.
+ client.pressKey(0x1e);
+ client.releaseKey(0x1e);
+ client.movePointerBy(5, 5);
+ QTest::qWait(300);
+ QVERIFY2(errors.isEmpty(), qPrintable(errors.value(0).value(0).toString()));
+ cleanup();
+ QTRY_VERIFY_WITH_TIMEOUT(!errors.isEmpty(), 5000);
+}
+
+void DisplayClientTest::dmabufFramesArePacedByFrameRendered() {
+ if (!renderNodeAvailable())
+ QSKIP("needs a GPU render node");
+ if (!startQemu({QStringLiteral("-device"), QStringLiteral("virtio-vga-gl"),
+ QStringLiteral("-display"),
+ QStringLiteral("dbus,p2p=yes,gl=on")}))
+ QSKIP("needs qemu-system-x86_64 with KVM and virtio-vga-gl");
+ const int fd = attachDisplay(m_qmp);
+ QVERIFY(fd >= 0);
+
+ DisplayClient client;
+ QList buffers;
+ connect(&client, &DisplayClient::dmabufScanout, this,
+ [&](DisplayClient::Dmabuf buffer) { buffers.append(buffer); });
+ QSignalSpy updates(&client, &DisplayClient::frameUpdated);
+ client.connectToFd(fd);
+
+ QTRY_VERIFY_WITH_TIMEOUT(!buffers.isEmpty(), 10000);
+ const DisplayClient::Dmabuf buffer = buffers.last();
+ QVERIFY(buffer.fd >= 0);
+ QVERIFY(buffer.width >= 640 && buffer.stride >= buffer.width * 4);
+ QVERIFY(client.frame().isNull());
+
+ // QEMU holds the guest's GPU until each UpdateDMABUF is answered; the
+ // client answers on frameRendered() (or its timeout), so updates keep
+ // flowing either way.
+ QTRY_VERIFY_WITH_TIMEOUT(updates.size() >= 1, 10000);
+ const qsizetype before = updates.size();
+ client.frameRendered();
+ QTRY_VERIFY_WITH_TIMEOUT(updates.size() > before, 10000);
+
+ client.resizeDisplay(1024, 768, 270, 203);
+ QTest::qWait(200);
+ for (const DisplayClient::Dmabuf &b : std::as_const(buffers))
+ close(b.fd);
+ cleanup();
+}
+
+QTEST_GUILESS_MAIN(DisplayClientTest)
+#include "displayclient_test.moc"
diff --git a/gui/tests/displayclient_test.pro b/gui/tests/displayclient_test.pro
new file mode 100644
index 0000000..f11e698
--- /dev/null
+++ b/gui/tests/displayclient_test.pro
@@ -0,0 +1,7 @@
+QT += core gui testlib
+CONFIG += console testcase c++17 link_pkgconfig
+PKGCONFIG += gio-2.0 gio-unix-2.0
+TEMPLATE = app
+TARGET = displayclient_test
+SOURCES += displayclient_test.cpp ../displayclient.cpp
+HEADERS += ../displayclient.h
diff --git a/gui/tests/displayview_test.cpp b/gui/tests/displayview_test.cpp
new file mode 100644
index 0000000..d1fbec7
--- /dev/null
+++ b/gui/tests/displayview_test.cpp
@@ -0,0 +1,216 @@
+#include "../displayview.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+namespace {
+QJsonObject qmpReply(int fd) {
+ QByteArray line;
+ char c;
+ while (read(fd, &c, 1) == 1) {
+ if (c != '\n') {
+ line.append(c);
+ continue;
+ }
+ const QJsonObject reply = QJsonDocument::fromJson(line).object();
+ line.clear();
+ if (reply.contains(QStringLiteral("return")) ||
+ reply.contains(QStringLiteral("error")) ||
+ reply.contains(QStringLiteral("QMP")))
+ return reply;
+ }
+ return {};
+}
+
+bool qmpSend(int fd, const QByteArray &command, int passFd = -1) {
+ QByteArray data = command + '\n';
+ iovec io{data.data(), size_t(data.size())};
+ msghdr msg{};
+ msg.msg_iov = &io;
+ msg.msg_iovlen = 1;
+ char control[CMSG_SPACE(sizeof(int))] = {};
+ if (passFd >= 0) {
+ msg.msg_control = control;
+ msg.msg_controllen = sizeof(control);
+ cmsghdr *header = CMSG_FIRSTHDR(&msg);
+ header->cmsg_level = SOL_SOCKET;
+ header->cmsg_type = SCM_RIGHTS;
+ header->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(header), &passFd, sizeof(int));
+ }
+ return sendmsg(fd, &msg, 0) == qsizetype(data.size()) &&
+ !qmpReply(fd).contains(QStringLiteral("error"));
+}
+
+int attachDisplay(const QString &qmpPath) {
+ const int qmp = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ sockaddr_un address{};
+ address.sun_family = AF_UNIX;
+ const QByteArray path = QFile::encodeName(qmpPath);
+ memcpy(address.sun_path, path.constData(), size_t(path.size()));
+ if (::connect(qmp, reinterpret_cast(&address),
+ sizeof(address)) != 0) {
+ close(qmp);
+ return -1;
+ }
+ int pair[2];
+ socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair);
+ const bool ok =
+ !qmpReply(qmp).isEmpty() &&
+ qmpSend(qmp, R"({"execute":"qmp_capabilities"})") &&
+ qmpSend(qmp, R"({"execute":"getfd","arguments":{"fdname":"t"}})",
+ pair[1]) &&
+ qmpSend(qmp, R"({"execute":"add_client","arguments":)"
+ R"({"protocol":"@dbus-display","fdname":"t"}})");
+ close(qmp);
+ close(pair[1]);
+ if (!ok) {
+ close(pair[0]);
+ return -1;
+ }
+ return pair[0];
+}
+
+// Fraction of rows in [from, to) that contain anything but the most
+// common (background) color.
+double inkedRows(const QImage &image, int from, int to) {
+ const QRgb background = image.pixel(image.width() - 1, image.height() / 2);
+ int inked = 0;
+ for (int y = from; y < to; ++y) {
+ for (int x = 0; x < image.width(); x += 2) {
+ if (image.pixel(x, y) != background) {
+ ++inked;
+ break;
+ }
+ }
+ }
+ return to > from ? double(inked) / (to - from) : 0;
+}
+} // namespace
+
+// Renders DisplayView offscreen (no window is shown) against a real QEMU
+// checking both frame paths end to end: the firmware's text must land at
+// the top of the view, not mirrored.
+class DisplayViewTest : public QObject {
+ Q_OBJECT
+
+private slots:
+ void rendersFramesUpright_data();
+ void rendersFramesUpright();
+};
+
+void DisplayViewTest::rendersFramesUpright_data() {
+ QTest::addColumn("display");
+ QTest::newRow("dma-buf (host GPU)")
+ << QStringList{QStringLiteral("-device"), QStringLiteral("virtio-vga-gl"),
+ QStringLiteral("-display"),
+ QStringLiteral("dbus,p2p=yes,gl=on")};
+ QTest::newRow("shared memory (no host GPU)")
+ << QStringList{QStringLiteral("-display"), QStringLiteral("dbus,p2p=yes")};
+}
+
+void DisplayViewTest::rendersFramesUpright() {
+ QFETCH(QStringList, display);
+ if (QGuiApplication::platformName() != QStringLiteral("wayland"))
+ QSKIP("needs a Wayland session (EGL dma-buf import)");
+ if (QStandardPaths::findExecutable(QStringLiteral("qemu-system-x86_64"))
+ .isEmpty() ||
+ !QFile::exists(QStringLiteral("/dev/kvm")))
+ QSKIP("needs qemu-system-x86_64 with KVM");
+
+ QTemporaryDir dir(QStringLiteral("/tmp/omavm-view-XXXXXX"));
+ const QString qmp = dir.filePath(QStringLiteral("qmp.sock"));
+ QProcess qemu;
+ qemu.start(QStringLiteral("qemu-system-x86_64"),
+ QStringList{QStringLiteral("-m"), QStringLiteral("128"),
+ QStringLiteral("-enable-kvm"), QStringLiteral("-monitor"),
+ QStringLiteral("none"), QStringLiteral("-serial"),
+ QStringLiteral("none"), QStringLiteral("-qmp"),
+ QStringLiteral("unix:%1,server,nowait").arg(qmp)} +
+ display);
+ QVERIFY(qemu.waitForStarted(3000));
+ auto stopQemu = qScopeGuard([&] {
+ qemu.kill();
+ qemu.waitForFinished(3000);
+ });
+ QTRY_VERIFY_WITH_TIMEOUT(QFile::exists(qmp), 5000);
+ const int fd = attachDisplay(qmp);
+ QVERIFY(fd >= 0);
+
+ QOpenGLContext context;
+ QVERIFY(context.create());
+ QOffscreenSurface surface;
+ surface.setFormat(context.format());
+ surface.create();
+ QVERIFY(context.makeCurrent(&surface));
+
+ const QSize size(720, 400);
+ QOpenGLFramebufferObject fbo(size);
+ QQuickRenderControl control;
+ QQuickWindow window(&control);
+ window.setGraphicsDevice(
+ QQuickGraphicsDevice::fromOpenGLContext(&context));
+ QVERIFY(control.initialize());
+ window.setRenderTarget(
+ QQuickRenderTarget::fromOpenGLTexture(fbo.texture(), size));
+ window.resize(size);
+ window.contentItem()->setSize(size);
+
+ DisplayView view(window.contentItem());
+ view.setSize(size);
+ QString failure;
+ connect(&view, &DisplayView::connectionFailed, this,
+ [&](const QString &message) { failure = message; });
+ view.setConnectionFd(fd);
+
+ QImage frame;
+ for (int attempt = 0; attempt < 100 && failure.isEmpty(); ++attempt) {
+ QTest::qWait(100);
+ control.polishItems();
+ control.beginFrame();
+ control.sync();
+ control.render();
+ control.endFrame();
+ frame = fbo.toImage();
+ // Wait for the firmware to have printed something.
+ if (inkedRows(frame, 0, frame.height()) > 0.05)
+ break;
+ }
+ QVERIFY2(failure.isEmpty(), qPrintable(failure));
+ QVERIFY2(inkedRows(frame, 0, frame.height()) > 0.05,
+ "no guest content was rendered");
+ // Firmware text starts at the top of the screen.
+ const double top = inkedRows(frame, 0, frame.height() / 4);
+ const double bottom = inkedRows(frame, frame.height() * 3 / 4, frame.height());
+ QVERIFY2(top > bottom, qPrintable(QStringLiteral("text not at the top: "
+ "top %1, bottom %2")
+ .arg(top)
+ .arg(bottom)));
+}
+
+int main(int argc, char **argv) {
+ // Without a Wayland session there is nothing to render with; fall back
+ // to the offscreen platform so the test reports a skip, not a crash.
+ if (qEnvironmentVariableIsEmpty("WAYLAND_DISPLAY"))
+ qputenv("QT_QPA_PLATFORM", "offscreen");
+ QGuiApplication app(argc, argv);
+ DisplayViewTest test;
+ return QTest::qExec(&test, argc, argv);
+}
+#include "displayview_test.moc"
diff --git a/gui/tests/displayview_test.pro b/gui/tests/displayview_test.pro
new file mode 100644
index 0000000..97d05d7
--- /dev/null
+++ b/gui/tests/displayview_test.pro
@@ -0,0 +1,7 @@
+QT += core gui quick opengl testlib
+CONFIG += console testcase c++17 link_pkgconfig
+PKGCONFIG += gio-2.0 gio-unix-2.0 egl
+TEMPLATE = app
+TARGET = displayview_test
+SOURCES += displayview_test.cpp ../displayview.cpp ../displayclient.cpp
+HEADERS += ../displayview.h ../displayclient.h ../keymap.h
diff --git a/gui/tests/qml/tst_accessibility.qml b/gui/tests/qml/tst_accessibility.qml
new file mode 100644
index 0000000..488ffda
--- /dev/null
+++ b/gui/tests/qml/tst_accessibility.qml
@@ -0,0 +1,103 @@
+import QtQuick
+import QtTest
+
+// Every control a person can act on has a name a screen reader reads and
+// can be reached with the keyboard (WCAG 4.1.2 and 2.1.1), checked on the
+// accessibility tree Qt gives assistive technologies.
+Item {
+ id: root
+ width: 900
+ height: 800
+
+ TestCase {
+ name: "Accessibility"
+ when: windowShown
+
+ function audit(item) {
+ const problems = backend.accessibilityProblems(item)
+ compare(problems.join("\n"), "", "accessibility problems")
+ }
+
+ function test_cards_data() {
+ return [
+ { tag: "stopped box", kind: "box", status: "stopped" },
+ { tag: "running machine", kind: "machine", status: "running" },
+ { tag: "paused machine", kind: "machine", status: "paused" },
+ { tag: "failed machine", kind: "machine", status: "error" },
+ { tag: "narrow card", kind: "machine", status: "running", width: 320 }
+ ]
+ }
+ function test_cards(data) {
+ const component = Qt.createComponent("qrc:/EnvironmentCard.qml")
+ compare(component.status, Component.Ready, component.errorString())
+ const card = component.createObject(root, {
+ width: data.width || 680,
+ environment: { name: "demo", kind: data.kind, status: data.status, settings: {} }
+ })
+ audit(card)
+ const menu = findChild(card, "actionsMenu")
+ menu.open()
+ tryVerify(() => menu.opened)
+ audit(menu.contentItem)
+ menu.close()
+ card.destroy()
+ }
+
+ function dialog(url, properties) {
+ const component = Qt.createComponent(url)
+ compare(component.status, Component.Ready, component.errorString())
+ const d = component.createObject(root, properties || {})
+ d.open()
+ tryVerify(() => d.opened)
+ return d
+ }
+
+ function test_settings_data() {
+ return [{ tag: "machine", kind: "machine" }, { tag: "box", kind: "box" }]
+ }
+ function test_settings(data) {
+ const d = dialog("qrc:/SettingsDialog.qml", { environment: { name: "demo", kind: data.kind, settings: {} } })
+ audit(d.contentItem.parent)
+ d.destroy()
+ }
+
+ function test_create_data() {
+ return [
+ { tag: "kind", step: 0, machine: true },
+ { tag: "iso", step: 1, machine: true },
+ { tag: "image", step: 1, machine: false },
+ { tag: "name", step: 2, machine: true },
+ { tag: "summary", step: 3, machine: true }
+ ]
+ }
+ function test_create(data) {
+ const d = dialog("qrc:/CreateDialog.qml")
+ d.machine = data.machine
+ d.step = data.step
+ wait(300) // the step transition
+ audit(d.contentItem.parent)
+ d.destroy()
+ }
+
+ function test_apps() {
+ backend.appsEnvironment = "dev"
+ backend.appsError = ""
+ backend.appsLoading = false
+ backend.apps = [{ id: "/usr/share/applications/a.desktop", name: "Gimp", exported: true },
+ { id: "/usr/share/applications/b.desktop", name: "Inkscape", exported: false }]
+ const d = dialog("qrc:/AppsDialog.qml", { environment: { name: "dev", kind: "box", settings: {} } })
+ audit(d.contentItem.parent)
+ d.destroy()
+ backend.apps = []
+ }
+
+ function test_snapshots() {
+ const d = dialog("qrc:/SnapshotsDialog.qml", {
+ environment: { name: "demo", kind: "machine", status: "stopped", settings: {},
+ snapshots: [{ id: "a-1", label: "Clean installation", created_at: "2026-09-29T12:00:00Z" }] }
+ })
+ audit(d.contentItem.parent)
+ d.destroy()
+ }
+ }
+}
diff --git a/gui/tests/qml/tst_createdialog.qml b/gui/tests/qml/tst_createdialog.qml
new file mode 100644
index 0000000..e6fb0ad
--- /dev/null
+++ b/gui/tests/qml/tst_createdialog.qml
@@ -0,0 +1,31 @@
+import QtQuick
+import QtTest
+
+Item {
+ id: root
+ width: 800
+ height: 700
+
+ TestCase {
+ name: "CreateDialog"
+
+ // The field repeats the Core's name rules (internal/core's
+ // validateEnvironmentName) so a bad name is caught before the CLI.
+ function test_nameRulesMatchTheCore() {
+ const component = Qt.createComponent("qrc:/CreateDialog.qml")
+ compare(component.status, Component.Ready, component.errorString())
+ const dialog = component.createObject(root)
+ verify(dialog.validateName("") !== "")
+ verify(dialog.validateName("..") !== "")
+ verify(dialog.validateName("a/b") !== "")
+ // Regression: a leading dash made the name read as an option.
+ verify(dialog.validateName("--json") !== "")
+ verify(dialog.validateName("-x") !== "")
+ verify(dialog.validateName("a\u0085b") !== "", "C1 control")
+ compare(dialog.validateName("a-b"), "")
+ compare(dialog.validateName("Fedora de Teste"), "")
+ compare(dialog.validateName("Ação"), "")
+ dialog.destroy()
+ }
+ }
+}
diff --git a/gui/tests/qml/tst_environmentcard.qml b/gui/tests/qml/tst_environmentcard.qml
new file mode 100644
index 0000000..821f3c8
--- /dev/null
+++ b/gui/tests/qml/tst_environmentcard.qml
@@ -0,0 +1,118 @@
+import QtQuick
+import QtTest
+
+Item {
+ id: root
+ width: 700
+ height: 200
+
+ Loader { id: loader }
+
+ TestCase {
+ name: "EnvironmentCard"
+ when: windowShown
+
+ function menuFor(kind, status) {
+ loader.setSource("qrc:/EnvironmentCard.qml", {
+ width: 680,
+ environment: { name: "demo", kind: kind, status: status || "stopped", settings: {} }
+ })
+ tryVerify(() => loader.status === Loader.Ready)
+ const menu = findChild(loader.item, "actionsMenu")
+ verify(menu)
+ menu.open()
+ tryVerify(() => menu.opened)
+ return menu
+ }
+
+ // A Machine paused because the host's disk filled up says so, and
+ // offers Resume; a running one doesn't show its routine detail.
+ function test_pausedMachineShowsWhy() {
+ const why = "paused: this computer's disk is full (12 MiB free); free up space, then Resume"
+ loader.setSource("qrc:/EnvironmentCard.qml", {
+ width: 680,
+ environment: { name: "vm", kind: "machine", status: "paused", statusDetail: why, settings: {} }
+ })
+ tryVerify(() => loader.status === Loader.Ready)
+ const detail = findChild(loader.item, "statusDetailLabel")
+ verify(detail.visible)
+ compare(detail.text, why)
+ loader.setSource("qrc:/EnvironmentCard.qml", {
+ width: 680,
+ environment: { name: "vm", kind: "machine", status: "running", statusDetail: "display available", settings: {} }
+ })
+ tryVerify(() => loader.status === Loader.Ready)
+ verify(!findChild(loader.item, "statusDetailLabel").visible)
+ }
+
+ // A hidden MenuItem still takes its full height in a Qt Quick Menu,
+ // leaving blank rows (a Box's menu had four).
+ function test_hiddenActionsLeaveNoGap_data() {
+ return [{ tag: "box", kind: "box" }, { tag: "machine", kind: "machine" }]
+ }
+ function test_hiddenActionsLeaveNoGap(data) {
+ const menu = menuFor(data.kind)
+ let hidden = 0
+ let shownHeight = 0
+ for (let i = 0; i < menu.count; ++i) {
+ const item = menu.itemAt(i)
+ if (item.visible)
+ shownHeight += item.height
+ else {
+ ++hidden
+ compare(item.height, 0, item.text + " is hidden but still takes space")
+ }
+ }
+ verify(hidden > 0)
+ compare(menu.contentItem.contentHeight, shownHeight)
+ menu.close()
+ }
+
+ function menuItem(menu, text) {
+ for (let i = 0; i < menu.count; ++i)
+ if (menu.itemAt(i).text === text)
+ return menu.itemAt(i)
+ return null
+ }
+
+ // QEMU alive but its monitor silent reports "unknown": that must not
+ // read as the initial "Checking…" nor leave the Machine impossible to
+ // stop from the GUI.
+ function test_unresponsiveMachineCanBeForceStopped() {
+ const menu = menuFor("machine", "unknown")
+ compare(findChild(loader.item, "statusLabel").text, "Not responding")
+ verify(menuItem(menu, "Force Stop…").enabled, "Force Stop must be available")
+ verify(menuItem(menu, "Shut Down").enabled, "Shut Down must be available")
+ // Its process exists, so "Start" would silently do nothing.
+ verify(menuItem(menu, "Open"), "the first action must be Open, not Start")
+ menu.close()
+ }
+
+ function test_keyboardActionsHaveNamesAndVisibleStatus() {
+ loader.setSource("qrc:/EnvironmentCard.qml", {
+ width: 680,
+ environment: { name: "demo", kind: "box", status: "running", settings: {} }
+ })
+ tryVerify(() => loader.status === Loader.Ready)
+ const primary = findChild(loader.item, "primaryAction")
+ const actions = findChild(loader.item, "actionsButton")
+ const status = findChild(loader.item, "statusLabel")
+ verify(primary && actions && status)
+ verify(primary.Accessible.name.length > 0)
+ verify(actions.Accessible.name.indexOf("demo") >= 0)
+ compare(status.text, "Running")
+ verify(primary.width >= 44 && primary.height >= 44,
+ "primary action needs a 44×44 pointer target")
+ verify(actions.width >= 44 && actions.height >= 44,
+ "actions menu needs a 44×44 pointer target")
+ primary.forceActiveFocus(Qt.TabFocusReason)
+ verify(primary.activeFocus)
+ keyClick(Qt.Key_Tab)
+ tryVerify(() => actions.activeFocus)
+ keyClick(Qt.Key_Space)
+ const menu = findChild(loader.item, "actionsMenu")
+ tryVerify(() => menu.opened)
+ menu.close()
+ }
+ }
+}
diff --git a/gui/tests/qml/tst_environmentlistmodel.qml b/gui/tests/qml/tst_environmentlistmodel.qml
new file mode 100644
index 0000000..a259c35
--- /dev/null
+++ b/gui/tests/qml/tst_environmentlistmodel.qml
@@ -0,0 +1,61 @@
+import QtQuick
+import QtTest
+
+Item {
+ id: root
+ width: 400
+ height: 600
+
+ Loader { id: loader }
+
+ ListView {
+ id: view
+ anchors.fill: parent
+ model: loader.item
+ delegate: Item {
+ required property var environment
+ width: view.width
+ height: 40
+ }
+ }
+
+ TestCase {
+ name: "EnvironmentListModel"
+ when: windowShown
+
+ function env(name, status) {
+ return { name: name, kind: "box", status: status, settings: {} }
+ }
+
+ function init() {
+ loader.source = ""
+ loader.source = "qrc:/EnvironmentListModel.qml"
+ tryVerify(() => loader.status === Loader.Ready)
+ }
+
+ // A poll that only changes a status used to reset the whole list:
+ // every card was destroyed and faded in again (the Experience
+ // Center flickered), and an open card menu vanished.
+ function test_statusChangeKeepsTheSameCard() {
+ const model = loader.item
+ model.sync([env("a", "stopped"), env("b", "stopped")])
+ tryVerify(() => view.itemAtIndex(1) !== null)
+ const card = view.itemAtIndex(0)
+ model.sync([env("a", "running"), env("b", "stopped")])
+ compare(view.itemAtIndex(0), card, "the card must be updated in place, not recreated")
+ compare(card.environment.status, "running")
+ }
+
+ function test_insertRemoveAndOrder() {
+ const model = loader.item
+ model.sync([env("a", "stopped"), env("b", "stopped")])
+ model.sync([env("c", "stopped"), env("a", "running")])
+ compare(model.count, 2)
+ compare(model.get(0).environment.name, "c")
+ compare(model.get(1).environment.name, "a")
+ compare(model.get(1).environment.status, "running")
+ model.sync([])
+ compare(model.count, 0)
+ }
+ }
+}
diff --git a/gui/tests/qml/tst_settingsdialog.qml b/gui/tests/qml/tst_settingsdialog.qml
new file mode 100644
index 0000000..d67b6e4
--- /dev/null
+++ b/gui/tests/qml/tst_settingsdialog.qml
@@ -0,0 +1,109 @@
+import QtQuick
+import QtTest
+
+Item {
+ id: root
+ width: 800
+ height: 700
+
+ TestCase {
+ name: "SettingsDialog"
+ when: windowShown
+
+ function saveUntouched(settings) {
+ backend.lastCall = []
+ const component = Qt.createComponent("qrc:/SettingsDialog.qml")
+ compare(component.status, Component.Ready, component.errorString())
+ const dialog = component.createObject(root, {
+ environment: { name: "desktop", kind: "machine", settings: settings }
+ })
+ dialog.open()
+ tryVerify(() => dialog.opened)
+ findChild(dialog, "saveButton").clicked()
+ dialog.destroy()
+ const call = backend.lastCall
+ compare(call[0], "configure")
+ return {
+ cpusTouched: call[4], memoryTouched: call[6],
+ shareClipboard: call[12], travelMode: call[13], vulkan: call[14],
+ launcher: call[16], ssh: call[17], fullscreen: call[18]
+ }
+ }
+
+ // Saving without touching CPU/memory must not pin them: a pinned
+ // CPU count turns Travel Mode's battery reduction off for good.
+ function test_saveDoesNotPinHardware() {
+ const saved = saveUntouched({ description: "x" })
+ compare(saved.cpusTouched, false)
+ compare(saved.memoryTouched, false)
+ }
+
+ // Opt-out settings: absent from the JSON means on.
+ function test_optOutDefaultsAreOn() {
+ const saved = saveUntouched({})
+ compare(saved.shareClipboard, true)
+ compare(saved.travelMode, true)
+ compare(saved.vulkan, true)
+ compare(saved.launcher, true)
+ compare(saved.ssh, true)
+ compare(saved.fullscreen, true)
+ }
+
+ // Repeater delegates live in the visual tree, not among QObject
+ // children, so findChild() can't see them.
+ function findItem(item, name) {
+ if (!item)
+ return null
+ if (item.objectName === name)
+ return item
+ const kids = [].concat(item.children ? Array.from(item.children) : [],
+ item.contentItem ? [item.contentItem] : [])
+ for (const kid of kids) {
+ const found = findItem(kid, name)
+ if (found)
+ return found
+ }
+ return null
+ }
+
+ // The selected color is only a thicker border: a screen reader has
+ // to be told which swatch is the current one.
+ function test_selectedColorIsAnnouncedToScreenReaders() {
+ const component = Qt.createComponent("qrc:/SettingsDialog.qml")
+ const dialog = component.createObject(root, {
+ environment: { name: "desktop", kind: "machine", settings: { color: "blue" } }
+ })
+ dialog.open()
+ tryVerify(() => dialog.opened)
+ const blue = findItem(dialog.contentItem, "colorSwatch-blue")
+ const red = findItem(dialog.contentItem, "colorSwatch-red")
+ const none = findItem(dialog.contentItem, "colorSwatch-none")
+ verify(none, "none swatch found")
+ verify(blue, "blue swatch found")
+ verify(red, "red swatch found")
+ for (const swatch of [none, blue, red])
+ verify(swatch.width >= 44 && swatch.height >= 44,
+ swatch.objectName + " needs a 44×44 pointer target")
+ // As a screen reader gets it, not the QML attached property:
+ // with accessibility active Qt announces the control's own
+ // state, which older Qt (6.4) and newer disagree on otherwise.
+ const state = swatch => backend.accessibleState(swatch)
+ verify(state(blue).checkable)
+ verify(state(blue).checked, "blue is the selected color")
+ verify(!state(red).checked)
+ verify(!state(none).checked)
+ compare(state(blue).name, "blue")
+ dialog.destroy()
+ }
+
+ function test_optOutsRoundTrip() {
+ const saved = saveUntouched({ clipboard_disabled: true, travel_mode_disabled: true, vulkan_disabled: true, launcher_disabled: true, ssh_disabled: true, fullscreen_disabled: true })
+ compare(saved.shareClipboard, false)
+ compare(saved.travelMode, false)
+ compare(saved.vulkan, false)
+ compare(saved.launcher, false)
+ compare(saved.ssh, false)
+ compare(saved.fullscreen, false)
+ }
+ }
+}
diff --git a/gui/tests/qml/tst_snapshotsdialog.qml b/gui/tests/qml/tst_snapshotsdialog.qml
new file mode 100644
index 0000000..434e921
--- /dev/null
+++ b/gui/tests/qml/tst_snapshotsdialog.qml
@@ -0,0 +1,56 @@
+import QtQuick
+import QtTest
+
+Item {
+ id: root
+ width: 800
+ height: 700
+
+ TestCase {
+ name: "SnapshotsDialog"
+ when: windowShown
+
+ function findItem(item, name) {
+ if (!item)
+ return null
+ if (item.objectName === name)
+ return item
+ const kids = [].concat(item.children ? Array.from(item.children) : [],
+ item.contentItem ? [item.contentItem] : [])
+ for (const kid of kids) {
+ const found = findItem(kid, name)
+ if (found)
+ return found
+ }
+ return null
+ }
+
+ function openWith(status) {
+ const component = Qt.createComponent("qrc:/SnapshotsDialog.qml")
+ compare(component.status, Component.Ready, component.errorString())
+ const dialog = component.createObject(root, {
+ environment: { name: "desktop", kind: "machine", status: status,
+ snapshots: [{ id: "a-1", label: "Clean", created_at: "2026-09-29T10:00:00Z" }] }
+ })
+ dialog.open()
+ tryVerify(() => dialog.opened)
+ return dialog
+ }
+
+ // Regression: Go To was offered on a running Machine and failed
+ // halfway (QEMU only reverts a disk-only snapshot offline).
+ function test_goToNeedsAStoppedMachine() {
+ let dialog = openWith("running")
+ tryVerify(() => findItem(dialog.contentItem, "goToButton") !== null)
+ verify(!findItem(dialog.contentItem, "goToButton").enabled)
+ verify(findItem(dialog.contentItem, "runningHint").visible)
+ dialog.destroy()
+
+ dialog = openWith("stopped")
+ tryVerify(() => findItem(dialog.contentItem, "goToButton") !== null)
+ verify(findItem(dialog.contentItem, "goToButton").enabled)
+ verify(!findItem(dialog.contentItem, "runningHint").visible)
+ dialog.destroy()
+ }
+ }
+}
diff --git a/gui/tests/qml_test.cpp b/gui/tests/qml_test.cpp
new file mode 100644
index 0000000..da5d288
--- /dev/null
+++ b/gui/tests/qml_test.cpp
@@ -0,0 +1,146 @@
+#include
+#include
+#include
+#include