Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Adiciona o suporte para GNOME com Wayland
yanscholze4b4729c25027
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 6ae31e67..0eab0176 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -53,6 +53,8 @@ machine that built it. Check a package withOn KDE Plasma 6 the drag gesture can also run there, experimentally and only with `FILEE_WAYLAND_GESTURES=1`. It needsthe user in the `input` group (libuiohook's libinput back end) and the KWin script in `installer/linux/kwin`, whichmoves the donut window (titled "Filee Donut") to the cursor. See `installer/linux/INSTALL.txt`.+ On GNOME Wayland, the bundled Shell extension supplies pointer state through a private Unix socket; no input+ group is required. See [docs/GNOME-WAYLAND.md](docs/GNOME-WAYLAND.md) for setup, scope, limitations and tests.- **macOS:** grant Filee Accessibility permission for gestures and Finder Automation permission for selection.Keep the development `.app` at a stable path while testing these permissions. Finder integration is a QuickAction under Services; auto-start uses a per-user LaunchAgent.diff --git a/README.md b/README.mdindex 07518443..4dfd9e8c 100644--- a/README.md+++ b/README.md@@ -85,8 +85,9 @@ Download from [Releases](https://github.com/KnifeLemon/Filee/releases/latest).- Or open the `.dmg` and drag Filee to Applications (the `filee` command comes with `install.sh`).- The build isn't notarized yet, so allow the first start in System Settings → Privacy & Security → **Open Anyway**.- **Linux x64/ARM64** (Ubuntu 22.04+): unpack the package and run `./install.sh` (no root, needs Python 3).- - Drag gestures need X11.- On Wayland, use the drop zone and the file manager's right-click menu.+ - Drag gestures work on X11. GNOME Wayland has experimental support through the bundled+ “Filee donut at the cursor” extension, without input-device permissions. See [GNOME Wayland setup](docs/GNOME-WAYLAND.md).+ The drop zone and file manager's right-click menu also work on Wayland.Filee shows new releases in its menu and updates itself, keeping your settings and engines.After an update, a few slides show what's new.diff --git a/README.pt-BR.md b/README.pt-BR.mdindex 4ec6584f..e89ed6b0 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -85,8 +85,9 @@ Baixe em [Releases](https://github.com/KnifeLemon/Filee/releases/latest).- Ou abra o `.dmg` e arraste o Filee para Aplicativos (o comando `filee` só vem com o `install.sh`).- A build ainda não é notarizada, então permita a primeira abertura em Ajustes do Sistema → Privacidade e Segurança → **Abrir Mesmo Assim**.- **Linux x64/ARM64** (Ubuntu 22.04+): descompacte o pacote e execute `./install.sh` (sem root, precisa do Python 3).- - Gestos de arrastar precisam do X11.- No Wayland, use a área de soltar e o menu do botão direito do gerenciador de arquivos.+ - Gestos de arrastar funcionam no X11. No GNOME Wayland, há suporte experimental pela extensão+ “Filee donut at the cursor”, sem permissão para dispositivos de entrada. Veja o [guia do GNOME Wayland](docs/GNOME-WAYLAND.md).+ A área de soltar e o menu do botão direito do gerenciador também funcionam no Wayland.O Filee mostra versões novas no menu e se atualiza sozinho, mantendo suas configurações e motores.Depois de uma atualização, alguns slides mostram o que há de novo.diff --git a/build/build-portable.ps1 b/build/build-portable.ps1index edf5979b..a6f9613a 100644--- a/build/build-portable.ps1+++ b/build/build-portable.ps1@@ -140,6 +140,8 @@ else {Copy-Item -LiteralPath (Join-Path $root 'installer/linux/uninstall.sh') -Destination $packageCopy-Item -LiteralPath (Join-Path $root 'installer/linux/INSTALL.txt') -Destination $packageCopy-Item -LiteralPath (Join-Path $root 'installer/linux/kwin') -Destination $package -Recurse+ Copy-Item -LiteralPath (Join-Path $root 'installer/linux/gnome') -Destination $package -Recurse+ Copy-Item -LiteralPath (Join-Path $root 'docs/GNOME-WAYLAND.md') -Destination $package}Invoke-Checked 'Installer permissions' { chmod +x (Join-Path $package 'install.sh') (Join-Path $package 'uninstall.sh') }$temporaryArchive = "$archive.$([Guid]::NewGuid().ToString('N')).partial"diff --git a/docs/GNOME-WAYLAND.md b/docs/GNOME-WAYLAND.mdnew file mode 100644index 00000000..7f18c97b--- /dev/null+++ b/docs/GNOME-WAYLAND.md@@ -0,0 +1,120 @@+# Filee no GNOME Wayland++Registro de implementação e guia de teste — 23/10/2026.++## Como usar++1. Instale esta versão do Filee com `./install.sh`. No GNOME, o pacote inclui a extensão **Filee donut at the cursor**.+2. Abra **Extensões** e ative essa extensão. Se ela não aparecer ou ainda carregar uma versão anterior, **encerre a sessão e entre novamente**. Reiniciar apenas o Filee não recarrega o código da extensão no GNOME Shell.+3. Abra o Filee. Em **Atalhos**, a detecção deve aparecer em execução. Se aparecer “Aguardando a extensão do Filee para GNOME”, consulte as verificações abaixo.+4. Em **Arquivos / Nautilus**, segure **Ctrl**, clique em um arquivo e arraste. Quando a roda aparecer, mova o arquivo até o formato desejado e solte.+5. Para interromper os gestos, use **Pausar** no Filee ou desative a extensão. Os modificadores personalizados e os aplicativos excluídos continuam sendo considerados.++**Não é necessário executar o Filee como administrador, usar sudo ou entrar no grupo `input`.** A extensão fornece somente o estado do ponteiro e das teclas modificadoras; não lê texto digitado nem o conteúdo dos arquivos.++A integração depende do GNOME Shell e funciona com o aplicativo do Filee em XWayland, como a versão atual do Avalonia. Não adiciona um backend gráfico nativo Wayland ao Avalonia. O caminho do KDE continua independente.++## Por que Ctrl + arrastar fazia uma cópia++A versão anterior habilitava o GNOME no mesmo caminho do KDE, que usa libinput para ler `/dev/input`. A sessão examinada não tinha permissão para essa leitura. A extensão estava ativa, mas só tentava posicionar uma janela: ela não fornecia eventos para o detector de gestos. Assim, a roda nunca abria e o Nautilus executava sua ação normal de copiar com Ctrl.++Também havia um problema de posicionamento: a extensão recentralizava continuamente a roda no ponteiro. Isso impediria alcançar uma fatia para escolher o formato. Agora ela posiciona a roda **uma vez por abertura**, mantendo-a parada até o próximo gesto.++Esta implementação não desativa a função de cópia do Nautilus. O Filee oferece um destino para a soltura quando detecta o gesto e recebe um arraste de arquivos. Com a extensão desativada, o Filee pausado, gesto desabilitado, aplicativo excluído ou soltura fora da roda, o gerenciador mantém seu comportamento normal. Uma seleção sem arquivos não deve exibir formatos.++## O que mudou++- **Extensão GNOME:** detecta estado global do ponteiro com `Shell.Global.get_pointer`, identifica o aplicativo sob ele e fornece snapshots pelo socket privado `$XDG_RUNTIME_DIR/filee-gnome/pointer-v1.sock`.+- **Permissões:** diretório privado do usuário, socket `0600` e validação das credenciais do cliente. Nenhum acesso a `/dev/input` nem registro de teclas digitadas.+- **Comunicação:** escritas assíncronas, sem fila ilimitada; um consumidor lento não bloqueia o desktop. O aplicativo reconecta quando a extensão volta e encerra um gesto se a comunicação cai. Bloqueio de tela, visão geral e diálogos modais suspendem os snapshots de entrada.+- **Detecção no Filee:** um adaptador transforma snapshots em eventos para o `GestureDetector` existente. Pausa, botões, limiar de movimento, modificadores, escopo e exclusões passam pelo mesmo detector. Não carrega SharpHook no caminho GNOME.+- **Posicionamento:** limita a janela ao monitor do ponteiro e não rouba o foco. Exige título e identidade de aplicativo do Filee antes de mover uma janela.+- **Interface:** informa que está aguardando a extensão e explica a ativação em português e inglês. Os demais idiomas recebem os novos textos em inglês, preservando as traduções já existentes.+- **Pacote:** inclui a extensão e este guia; o instalador preserva a lista de outras extensões e o desinstalador remove apenas a extensão marcada como gerenciada pelo Filee.++O GNOME tenta conectar à extensão por padrão; ativá-la é a opção de participação. `FILEE_WAYLAND_GESTURES=0` permite desativar explicitamente a ponte no processo. O modo experimental KDE mantém sua opção `FILEE_WAYLAND_GESTURES=1`, libinput e script KWin. Não foram alterados conversores, motores, formatos, configurações de conversão, implementações Windows/macOS ou o detector compartilhado de gestos.++## Se a roda não abrir++- Confira se **Pausar** está desligado e se o gesto **Ctrl + botão esquerdo + arrastar** está habilitado em **Atalhos**.+- Confira a extensão no aplicativo **Extensões**. Uma versão antiga pode aparecer ativa sem fornecer a nova ponte. Saia da sessão e entre novamente após atualizá-la.+- O **Arquivos / Nautilus** não deve estar na lista de aplicativos excluídos.+- Confira se o processo não foi iniciado com `FILEE_WAYLAND_GESTURES=0`.+- Não execute o aplicativo com `sudo`: a ponte pertence ao usuário da sessão gráfica.+- A área de soltar e o menu do gerenciador permanecem utilizáveis enquanto a extensão não está disponível.++Verificações opcionais no Terminal:++```sh+gnome-extensions info [email protected]+ls -l "$XDG_RUNTIME_DIR/filee-gnome/pointer-v1.sock"+```++Com a nova extensão ativa, o segundo comando deve mostrar um socket acessível somente ao usuário. O log do Filee registra `GNOME pointer extension connected` quando a conexão funciona. A ausência desse registro não comprova que o gesto tenha sido detectado: confira também o estado da extensão e o socket.++## Limites explícitos++- Integração experimental; metadados permitem GNOME Shell 45–50. Testes com bibliotecas reais foram executados no Fedora 44 / GNOME 50; não se afirma validação de todas essas versões.+- Não implementa atalhos globais para consultar seleção nem gestos de segurar. O caminho Linux já não oferecia esses recursos de seleção global.+- A ponte não fornece Tab ou roda do mouse globalmente para alternar faces durante um arraste. Não se afirma funcionamento dessa alternância em outros clientes durante drag-and-drop.+- O estado do ponteiro é amostrado a cada 16 ms enquanto o Filee está conectado; cliques muito curtos entre amostras podem não ser observados.+- O escopo usa a geometria e ordem de janelas visíveis; não interpreta regiões internas como barra de tarefas/painéis de outros clientes. Processos que desapareçam antes da consulta podem ficar sem identificação.+- Captura visual, posicionamento com escalas diferentes e entrega de drag-and-drop entre Nautilus nativo Wayland e Filee em XWayland exigem teste real na sessão. Testes automatizados não substituem essa confirmação.++## Testes de regressão e reprodução++```sh+dotnet test tests/Filee.App.Tests/Filee.App.Tests.csproj -c Release --filter FullyQualifiedName~GnomePointerBridgeTests+dotnet test Filee.slnx -c Release+node --check installer/linux/gnome/[email protected]/extension.js+sh -n installer/linux/install.sh installer/linux/uninstall.sh+```++O teste GJS exercita o **socket Gio real** com janelas e ponteiro simulados, sem alterar o desktop em uso. Em Fedora/GNOME 50 (ajuste os caminhos para a versão do Mutter instalada):++```sh+filee_runtime_test=$(mktemp -d /tmp/filee-gjs-XXXXXX)+XDG_RUNTIME_DIR="$filee_runtime_test" \+GI_TYPELIB_PATH=/usr/lib64/mutter-18 \+LD_LIBRARY_PATH=/usr/lib64/mutter-18 \+gjs tests/gnome/extension-smoke.js "$PWD/installer/linux/gnome/[email protected]/extension.js"+```++Cobertura nova: Ctrl + arrastar com limiar, soltura única, arraste sem Ctrl, escopo rejeitado, reconexão durante um arraste, bloqueio/desbloqueio, pausa, gesto desabilitado, modificadores personalizados e tardios, validação do protocolo, comunicação Unix real e reconexão após fechamento. No lado GJS: permissões privadas, máscaras de botões/modificadores, bloqueio de tela, posição fixa por abertura, bordas do monitor e limpeza ao desativar.++### Roteiro manual obrigatório++Use um arquivo descartável em uma pasta temporária:++- [ ] Ctrl + arrastar no Nautilus abre a roda; soltar sobre um formato inicia a conversão e não cria uma cópia do arquivo de origem no local da soltura.+- [ ] Mover o ponteiro alcança as fatias; a roda não foge do cursor.+- [ ] Soltar/cancelar sem escolher um formato fecha a roda e preserva o arquivo original.+- [ ] Arrastar sem Ctrl mantém a operação normal do Nautilus.+- [ ] Pausar ou desabilitar o gesto impede a abertura.+- [ ] Modificador personalizado funciona; aplicativo excluído não abre a roda.+- [ ] Desativar/reativar a extensão desconecta/reconecta sem reiniciar o Filee.+- [ ] Bloquear/desbloquear a tela não deixa um gesto preso.+- [ ] Testar monitor secundário, escala fracionária e bordas de tela.+- [ ] Conferir área de soltar, menu de contexto e uma conversão existente.+- [ ] Em X11/KDE, repetir o gesto existente no ambiente correspondente.++### Resultado nesta execução++- **11 testes novos da ponte:** aprovados.+- **110 testes direcionados do aplicativo:** aprovados, incluindo ponte GNOME, ciclo de vida do hook, detector, controlador da roda e traduções. A primeira execução geral encontrou ausência das duas novas chaves em outros idiomas; as chaves foram adicionadas e essa verificação passou na repetição direcionada.+- **Núcleo:** 513 aprovados. **CLI:** 28 aprovados. **Plataformas:** 52 aprovados e 5 ignorados por plataforma indisponível.+- **GJS com Gio real:** aprovado, incluindo permissões, comunicação, posicionamento fixo, bordas e limpeza.+- **GNOME Shell 50 real, em sessão headless isolada:** extensão carregada; Filee conectado sem grupo `input`; entrada virtual Ctrl + arrastar em um cliente GTK4 Wayland nativo abriu a roda do Filee em XWayland. Soltar sobre uma fatia executou `to-pdf` e produziu `sample.pdf`, preservando `sample.png` byte a byte e sem arquivo de cópia adicional. O cliente GTK4 de teste identificou seu processo como `nautilus` para exercitar o escopo padrão; **não foi um teste manual dentro do Nautilus**.+- **Compatibilidade X11:** inicialização contra o XWayland da sessão isolada, com ambiente X11, carregou o hook existente (`Global input hook started`), sem selecionar a ponte GNOME. Não substitui teste em uma sessão Xorg/KDE real.+- **Publicação Linux x64:** aplicativo e CLI compilados como `2.0.0-gnome.2`; CLI confirmou a versão; aplicativo instalado e iniciado. Fontes mantêm a versão original do projeto, sem alteração de versionamento para o PR.+- **Instalação anterior:** preservada em `artifacts/gnome.2/previous-installed-gnome.1`, incluindo a extensão anterior. Configurações e motores do usuário foram preservados. A extensão nova está no disco; a sessão GNOME atual ainda mantém o módulo anterior em memória, portanto é necessário sair e entrar novamente.+- **Suíte geral:** não ficou totalmente verde neste ambiente. Setup teve 36 falhas; quatro falhas representativas de caminhos/recursos Windows também foram reproduzidas no código original `098b02a`, sem o patch. Engines teve 70 falhas, incluindo FFmpeg sem `libx264`, conversões LibreOffice e expectativa de seleção de engine. Esse código foi mantido intacto. A longa bateria de renderização do aplicativo foi interrompida após aproximadamente 15 minutos, ainda produzindo capturas; não se declara aprovação integral dessa bateria nem da suíte geral. Os 110 testes direcionados foram concluídos separadamente após o ajuste das traduções.+- **Validação restante:** Nautilus na sessão do usuário, múltiplos monitores/escala fracionária e outras versões GNOME/KDE/Xorg. Os itens manuais acima permanecem desmarcados.++Os registros desta execução e o par PNG/PDF de teste ficam localmente em `artifacts/gnome.2/validation` (pasta ignorada pelo Git).++## Referências técnicas++- [GNOME Shell: `Global.get_pointer`](https://gnome.pages.gitlab.gnome.org/gnome-shell/shell/method.Global.get_pointer.html).+- [Mutter: `Window.move_frame`](https://mutter.gnome.org/meta/method.Window.move_frame.html).+- [Gio: `SocketService::incoming`](https://gnome.pages.gitlab.gnome.org/gtk/gio/signal.SocketService.incoming.html).diff --git a/installer/linux/INSTALL.txt b/installer/linux/INSTALL.txtindex 68d5c4a5..c077247e 100644--- a/installer/linux/INSTALL.txt+++ b/installer/linux/INSTALL.txt@@ -24,6 +24,21 @@ X11 supports the global gesture toolbar; it needs libXtst and libXt (libxtst6,libxt6). A native Wayland session has additional input restrictions; use thedrop window and file-manager actions, or the experimental setup below.+GNOME Wayland gestures (experimental, GNOME Shell 45–50): the Linux package+includes the “Filee donut at the cursor” Shell extension. install.sh installs+it for the current user on GNOME and requests activation. Open Extensions and+enable it. If it is missing or still running an older version, sign out and+sign in again, then start Filee and hold Ctrl while dragging a file in Files.+No input group, sudo, or FILEE_WAYLAND_GESTURES setting is required on GNOME.+The Triggers page says when Filee is waiting for the extension. The extension+provides pointer state over a private local socket and places the menu once+per opening; Filee respects its configured gestures, Pause and excluded apps.+It does not collect typed keys. Global selection/hold gestures and Tab/wheel+flipping during a drag are not supplied by this integration. Disabling the+extension stops detection; FILEE_WAYLAND_GESTURES=0 opts out on GNOME too.+Read GNOME-WAYLAND.md in the package (docs/GNOME-WAYLAND.md in the source) for+troubleshooting, manual checks and the implementation record.+Wayland gesture (experimental, KDE Plasma 6 only, off by default): Filee readsthe mouse and keyboard from /dev/input through libinput, and a KWin script movesthe donut to the cursor because Wayland apps cannot place windows. It needsdiff --git a/installer/linux/gnome/[email protected]/extension.js b/installer/linux/gnome/[email protected]/extension.jsnew file mode 100644index 00000000..3efbfc7d--- /dev/null+++ b/installer/linux/gnome/[email protected]/extension.js@@ -0,0 +1,189 @@+import Clutter from 'gi://Clutter';+import Gio from 'gi://Gio';+import GLib from 'gi://GLib';+import Meta from 'gi://Meta';+import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';+import * as Main from 'resource:///org/gnome/shell/ui/main.js';++const DONUT_TITLE = 'Filee Donut';+const encoder = new TextEncoder();++// This bridge reads only pointer coordinates, buttons, modifier state and the app under the pointer.+// It never grabs input, changes Nautilus's copy action, reads typed keys, or accesses /dev/input.+export default class FileeDonutExtension extends Extension {+ enable() {+ this._enabled = true;+ this._processes = new WeakMap();+ this._pendingActor = null;+ this._connection = null;+ this._writing = false;+ this._lastState = '';+ const directory = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'filee-gnome']);+ GLib.mkdir_with_parents(directory, 0o700);+ this._socketFile = Gio.File.new_for_path(`${directory}/pointer-v1.sock`);+ if (this._socketFile.query_exists(null))+ this._socketFile.delete(null); // a stale socket from a previous Shell session+ this._service = new Gio.SocketService();+ this._service.add_address(new Gio.UnixSocketAddress({path: this._socketFile.get_path()}),+ Gio.SocketType.STREAM, Gio.SocketProtocol.DEFAULT, null);+ this._socketFile.set_attribute_uint32('unix::mode', 0o600, Gio.FileQueryInfoFlags.NONE, null);+ this._service.connect('incoming', (_service, connection) => {+ // Filesystem permissions and peer credentials restrict the bridge to the signed-in user.+ if (connection.get_socket().get_credentials().get_unix_user() !== new Gio.Credentials().get_unix_user()) {+ connection.close(null);+ return true;+ }+ this._closeConnection();+ this._connection = connection;+ this._lastState = '';+ this._lastSent = 0;+ return true;+ });+ this._service.start();+ this._mapSignal = global.window_manager.connect('map', (_wm, actor) => {+ if (this._isDonut(actor.meta_window)) {+ this._pendingActor = actor;+ this._placeAttempts = 0;+ }+ });+ this._tickSource = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 16, () => {+ if (this._pendingActor) {+ if (this._placeDonut(this._pendingActor) || ++this._placeAttempts >= 20)+ this._pendingActor = null;+ }+ if (this._connection)+ this._sendPointer();+ return GLib.SOURCE_CONTINUE;+ });+ }++ disable() {+ this._enabled = false;+ if (this._tickSource)+ GLib.Source.remove(this._tickSource);+ this._tickSource = 0;+ if (this._mapSignal)+ global.window_manager.disconnect(this._mapSignal);+ this._mapSignal = 0;+ this._pendingActor = null;+ this._closeConnection();+ this._service?.stop();+ this._service?.close();+ this._service = null;+ if (this._socketFile?.query_exists(null))+ this._socketFile.delete(null);+ this._socketFile = null;+ this._processes = null;+ }++ _closeConnection() {+ const connection = this._connection;+ this._connection = null;+ this._writing = false;+ if (connection) {+ try { connection.close(null); } catch (_error) { /* already disconnected */ }+ }+ }++ _isDonut(window) {+ return window?.get_title() === DONUT_TITLE &&+ [window.get_wm_class(), window.get_wm_class_instance(), window.get_gtk_application_id()]+ .some(value => /^(filee|com\.filee\.app)$/i.test(value ?? ''));+ }++ _pointerWindow(x, y) {+ const windows = global.get_window_actors().filter(actor => actor.is_visible())+ .map(actor => actor.meta_window).filter(window => window?.showing_on_its_workspace());+ return global.display.sort_windows_by_stacking(windows).reverse().find(window => {+ const rect = window.get_frame_rect();+ return x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height;+ });+ }++ _processName(window) {+ if (!window)+ return null;+ if (!this._processes.has(window)) {+ let process = null;+ try {+ const [ok, bytes] = GLib.file_get_contents(`/proc/${window.get_pid()}/comm`);+ if (ok)+ process = new TextDecoder().decode(bytes).trim();+ } catch (_error) { /* a window can disappear between snapshots */ }+ this._processes.set(window, process);+ }+ return this._processes.get(window);+ }++ _sendPointer() {+ // One async write at a time: a slow/dead Filee must never block the desktop or build an unbounded queue.+ if (this._writing)+ return;+ const [x, y, mask] = global.get_pointer();+ const blocked = Main.sessionMode.isLocked || !Main.sessionMode.hasWindows || Main.overview.visible || Main.modalCount > 0;+ const now = GLib.get_monotonic_time();+ const pointerKey = `${x}:${y}:${mask}:${blocked}`;+ // Idle desktops need only a heartbeat. Look up window geometry when input changes or at most four times/s.+ if (pointerKey === this._lastPointerKey && now - this._lastSent < 250000)+ return;+ const window = blocked ? null : this._pointerWindow(x, y);+ const modifiers = (mask & Clutter.ModifierType.CONTROL_MASK ? 1 : 0) |+ (mask & Clutter.ModifierType.MOD1_MASK ? 2 : 0) |+ (mask & Clutter.ModifierType.SHIFT_MASK ? 4 : 0) |+ (mask & Clutter.ModifierType.SUPER_MASK ? 8 : 0);+ // Clutter numbers middle before right; Filee numbers right before middle.+ const buttons = (mask & Clutter.ModifierType.BUTTON1_MASK ? 1 : 0) |+ (mask & Clutter.ModifierType.BUTTON3_MASK ? 2 : 0) |+ (mask & Clutter.ModifierType.BUTTON2_MASK ? 4 : 0) |+ (mask & Clutter.ModifierType.BUTTON4_MASK ? 8 : 0) |+ (mask & Clutter.ModifierType.BUTTON5_MASK ? 16 : 0);+ const state = JSON.stringify({Version: 1, X: x, Y: y, Modifiers: blocked ? 0 : modifiers,+ Buttons: blocked ? 0 : buttons, Process: this._processName(window),+ Desktop: window?.get_window_type() === Meta.WindowType.DESKTOP, Blocked: blocked});+ if (state === this._lastState && now - this._lastSent < 250000)+ return;+ this._writing = true;+ const connection = this._connection;+ connection.get_output_stream().write_all_async(encoder.encode(`${state}\n`), GLib.PRIORITY_DEFAULT, null,+ (stream, result) => {+ try {+ stream.write_all_finish(result);+ if (this._enabled && this._connection === connection) {+ this._lastState = state;+ this._lastSent = now;+ this._lastPointerKey = pointerKey;+ }+ } catch (_error) {+ if (this._connection === connection)+ this._closeConnection();+ } finally {+ if (this._connection === connection)+ this._writing = false;+ }+ });+ }++ _placeDonut(actor) {+ const window = actor.meta_window;+ if (!this._isDonut(window))+ return true;+ const rect = window.get_frame_rect();+ if (rect.width <= 0 || rect.height <= 0 || !actor.is_visible())+ return false;+ const [pointerX, pointerY] = global.get_pointer();+ let x = Math.round(pointerX - rect.width / 2);+ let y = Math.round(pointerY - rect.height / 2);+ const monitor = Main.layoutManager.monitors.find(area =>+ pointerX >= area.x && pointerX < area.x + area.width &&+ pointerY >= area.y && pointerY < area.y + area.height);+ if (monitor) {+ x = Math.max(monitor.x, Math.min(x, monitor.x + monitor.width - rect.width));+ y = Math.max(monitor.y, Math.min(y, monitor.y + monitor.height - rect.height));+ }+ window.make_above();+ window.move_frame(true, x, y);+ window.raise();+ // Keep it here so moving outward can reach a format; recenter only on the next map/open.+ return true;+ }+}diff --git a/installer/linux/gnome/[email protected]/metadata.json b/installer/linux/gnome/[email protected]/metadata.jsonnew file mode 100644index 00000000..078b24d5--- /dev/null+++ b/installer/linux/gnome/[email protected]/metadata.json@@ -0,0 +1,14 @@+{+ "uuid": "[email protected]",+ "name": "Filee donut at the cursor",+ "description": "Enables Filee drag gestures on GNOME Wayland without input-device permissions, and places its conversion menu at the pointer.",+ "version": 2,+ "shell-version": [+ "45",+ "46",+ "47",+ "48",+ "49",+ "50"+ ]+}diff --git a/installer/linux/install.sh b/installer/linux/install.shindex 2a3cec01..0d3cef7e 100644--- a/installer/linux/install.sh+++ b/installer/linux/install.sh@@ -6,6 +6,9 @@ data_dir=${XDG_DATA_HOME:-"$HOME/.local/share"}install_dir="$data_dir/filee/application"bin_dir="$HOME/.local/bin"desktop_file="$data_dir/applications/com.filee.app.desktop"+gnome_extension_id="[email protected]"+gnome_extension_source="$source_dir/gnome/$gnome_extension_id"+gnome_extension_dir="$data_dir/gnome-shell/extensions/$gnome_extension_id"if [ -e "$install_dir" ] || [ -L "$install_dir" ]; thenprintf '%s\n' "An installation already exists at $install_dir. Run its uninstall.sh first."exit 1@@ -18,6 +21,14 @@ if [ -e "$desktop_file" ] || [ -L "$desktop_file" ]; thenprintf '%s\n' "$desktop_file already exists. Remove or rename it before installing Filee."exit 1fi+is_gnome=false+if printf '%s' "${XDG_CURRENT_DESKTOP:-}" | tr ':' '\n' | grep -qi '^GNOME$'; then+ is_gnome=true+fi+if [ "$is_gnome" = true ] && [ -d "$gnome_extension_source" ] && { [ -e "$gnome_extension_dir" ] || [ -L "$gnome_extension_dir" ]; }; then+ printf '%s\n' "A GNOME extension already exists at $gnome_extension_dir. Remove or rename it before installing Filee."+ exit 1+ficommand -v python3 >/dev/nulltest -x "$source_dir/Filee"test -x "$source_dir/filee-cli"@@ -25,6 +36,34 @@ mkdir -p "$data_dir/filee" "$bin_dir" "$data_dir/applications"cp -R "$source_dir" "$install_dir"printf '%s\n' 'com.filee.app' > "$install_dir/.filee-package"ln -s "$install_dir/filee-cli" "$bin_dir/filee"+if [ "$is_gnome" = true ] && [ -d "$gnome_extension_source" ]; then+ mkdir -p "$(dirname "$gnome_extension_dir")"+ cp -R "$install_dir/gnome/$gnome_extension_id" "$gnome_extension_dir"+ printf '%s\n' 'com.filee.app' > "$gnome_extension_dir/.filee-package"+ if command -v gsettings >/dev/null 2>&1; then+ enabled=$(gsettings get org.gnome.shell enabled-extensions 2>/dev/null || true)+ if [ -n "$enabled" ]; then+ updated=$(python3 - "$enabled" "$gnome_extension_id" <<'PY'+import ast+import sys++try:+ extensions = ast.literal_eval(sys.argv[1].removeprefix("@as "))+except (SyntaxError, ValueError):+ raise SystemExit(0)+if not isinstance(extensions, list) or not all(isinstance(item, str) for item in extensions):+ raise SystemExit(0)+if sys.argv[2] not in extensions:+ extensions.append(sys.argv[2])+print("[" + ", ".join("'" + item.replace("'", "\\'") + "'" for item in extensions) + "]")+PY+ )+ if [ -n "$updated" ]; then+ gsettings set org.gnome.shell enabled-extensions "$updated" >/dev/null 2>&1 || true+ fi+ fi+ fi+fipython3 - "$install_dir" "$desktop_file" <<'PY'import pathlibimport sys@@ -50,3 +89,7 @@ if command -v update-desktop-database >/dev/null 2>&1; thenupdate-desktop-database "$data_dir/applications"fiprintf '%s\n' "Installed Filee at $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."++if [ "$is_gnome" = true ] && [ -d "$gnome_extension_source" ]; then+ printf '%s\n' 'GNOME Wayland: enable "Filee donut at the cursor" in Extensions.' 'Sign out and sign in if the extension is not listed yet. Then hold Ctrl and drag a file in Files.' 'No administrator access or input group is required. See GNOME-WAYLAND.md.'+fidiff --git a/installer/linux/uninstall.sh b/installer/linux/uninstall.shindex bccb5593..00dedfd7 100644--- a/installer/linux/uninstall.sh+++ b/installer/linux/uninstall.sh@@ -4,6 +4,8 @@ set -eudata_dir=${XDG_DATA_HOME:-"$HOME/.local/share"}install_dir="$data_dir/filee/application"desktop_file="$data_dir/applications/com.filee.app.desktop"+gnome_extension_id="[email protected]"+gnome_extension_dir="$data_dir/gnome-shell/extensions/$gnome_extension_id"python3 - "$data_dir" "$install_dir" <<'PY'import pathlibimport sys@@ -16,6 +18,12 @@ if (target / '.filee-package').read_text(encoding='utf-8').strip() != 'com.fileeraise SystemExit('The directory is not an installation created by Filee.')PY"$install_dir/Filee" --uninstall-cleanup+if [ -f "$gnome_extension_dir/.filee-package" ] && [ "$(cat "$gnome_extension_dir/.filee-package")" = 'com.filee.app' ]; then+ if command -v gnome-extensions >/dev/null 2>&1; then+ gnome-extensions disable "$gnome_extension_id" >/dev/null 2>&1 || true+ fi+ rm -rf -- "$gnome_extension_dir"+fiif [ -L "$HOME/.local/bin/filee" ] && [ "$(readlink "$HOME/.local/bin/filee")" = "$install_dir/filee-cli" ]; thenrm -- "$HOME/.local/bin/filee"fidiff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.jsonindex d5f34485..932f4a15 100644--- a/src/Filee.App/Assets/i18n/ar.json+++ b/src/Filee.App/Assets/i18n/ar.json@@ -333,6 +333,8 @@"triggers.description": "اختر طريقة فتح شريط الأدوات الدائري. يمكنك إضافة ما تشاء من الإيماءات.","triggers.macos_permissions": "اسمح لـ Filee من إعدادات النظام > الخصوصية والأمن > تسهيلات الاستخدام.\nإذا كان Filee مفعّلًا بالفعل ولم تبدأ الإيماءات، فأزله بالزر − ثم أضفه مجددًا بالزر +.\nيطلب Finder أيضًا إذن الأتمتة عند استخدام اختصار الملفات المحددة للمرة الأولى.","triggers.linux_x11": "تعمل إيماءات السحب على X11.\nعند تفعيل التكامل مع مدير الملفات، يشغّل أول اختصار لوحة مفاتيح إجراء Filee في Thunar (أعد فتح Thunar بعد تغييره).\nإيماءات الضغط المستمر والاختصارات في مديري الملفات الآخرين غير متاحة. استخدم قائمة Filee أو منطقة الإفلات.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "الإيماءات التي تتبع المؤشر غير متاحة على Wayland.\nاستخدم جلسة X11، أو حوّل من قائمة مدير الملفات ومنطقة الإفلات.\nيمكن لـ Thunar استخدام أول اختصار لوحة مفاتيح بعد إعادة تشغيله.","triggers.linux_wayland_experimental": "الإيماءات على Wayland تجريبية وتعمل على KDE Plasma فقط.\nيقرأ Filee الماوس من /dev/input ويضع نص KWin برمجي الشريط الدائري عند المؤشر (راجع INSTALL.txt). قد يتأثر Ctrl مع السحب في التطبيقات الأخرى؛ استخدم مفتاح تعديل آخر مثل Ctrl+Shift إذا تعارض ذلك مع عملك.","triggers.open_accessibility": "فتح إعدادات تسهيلات الاستخدام",diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 08c33f55..e26668f1 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -346,6 +346,8 @@"triggers.description": "Choose how the donut toolbar opens. You can add as many gestures as you like.","triggers.macos_permissions": "Allow Filee in System Settings > Privacy & Security > Accessibility.\nIf Filee is already switched on but gestures don't start, remove it with − and add it again with +.\nFinder also asks for Automation permission the first time you use a selection shortcut.","triggers.linux_x11": "Drag gestures work on X11.\nWith file manager integration on, the first keyboard shortcut runs Thunar's Filee action (reopen Thunar after changing it).\nHold gestures and shortcuts in other file managers aren't available. Use the Filee menu or the drop zone.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Gestures that follow the cursor aren't available on Wayland.\nUse an X11 session, or convert with the file manager menu and the drop zone.\nThunar can use the first keyboard shortcut after it restarts.","triggers.linux_wayland_experimental": "Gestures on Wayland are experimental and only work on KDE Plasma.\nFilee reads the mouse from /dev/input and a KWin script places the donut at the cursor (see INSTALL.txt). Ctrl+drag in other apps can be interrupted; use another modifier such as Ctrl+Shift if it gets in the way.","triggers.open_accessibility": "Open Accessibility settings",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex fbc629f4..b0c4aa8c 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -333,6 +333,8 @@"triggers.description": "Elige cómo se abre el menú circular. Puedes añadir tantos gestos como quieras.","triggers.macos_permissions": "Permite Filee en Ajustes del Sistema > Privacidad y seguridad > Accesibilidad.\nSi Filee ya está activado pero los gestos no se inician, quítalo con − y vuelve a añadirlo con +.\nFinder también pide permiso de Automatización la primera vez que uses un atajo de selección.","triggers.linux_x11": "Los gestos de arrastre funcionan en X11.\nCon la integración con el gestor de archivos activada, el primer atajo de teclado ejecuta la acción de Filee en Thunar (vuelve a abrir Thunar después de cambiarlo).\nLos gestos de pulsación mantenida y los atajos en otros gestores de archivos no están disponibles. Usa el menú de Filee o la zona de suelta.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Los gestos que siguen el cursor no están disponibles en Wayland.\nUsa una sesión X11 o convierte con el menú del gestor de archivos y la zona de suelta.\nThunar puede usar el primer atajo de teclado cuando se reinicie.","triggers.linux_wayland_experimental": "Los gestos en Wayland son experimentales y solo funcionan en KDE Plasma.\nFilee lee el ratón desde /dev/input y un script de KWin coloca el menú circular en el cursor (consulta INSTALL.txt). Arrastrar con Ctrl en otras aplicaciones puede verse interrumpido; si te estorba, usa otro modificador, como Ctrl+Shift.","triggers.open_accessibility": "Abrir los ajustes de Accesibilidad",diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.jsonindex fbc0a30b..9a2b79e1 100644--- a/src/Filee.App/Assets/i18n/fr.json+++ b/src/Filee.App/Assets/i18n/fr.json@@ -346,6 +346,8 @@"triggers.description": "Choisissez comment s'ouvre le menu circulaire. Vous pouvez ajouter autant de gestes que vous voulez.","triggers.macos_permissions": "Autorisez Filee dans Réglages Système > Confidentialité et sécurité > Accessibilité.\nSi Filee est déjà activé mais que les gestes ne démarrent pas, supprimez-le avec − puis ajoutez-le à nouveau avec +.\nLe Finder demande aussi l'autorisation d'automatisation la première fois que vous utilisez un raccourci sur la sélection.","triggers.linux_x11": "Les gestes de glissement fonctionnent sous X11.\nAvec l'intégration au gestionnaire de fichiers activée, le premier raccourci clavier lance l'action Filee de Thunar (rouvrez Thunar après l'avoir modifié).\nLes gestes de maintien et les raccourcis dans les autres gestionnaires de fichiers ne sont pas disponibles. Utilisez le menu Filee ou la zone de dépôt.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Les gestes qui suivent le curseur ne sont pas disponibles sous Wayland.\nUtilisez une session X11, ou convertissez avec le menu du gestionnaire de fichiers et la zone de dépôt.\nThunar peut utiliser le premier raccourci clavier après son redémarrage.","triggers.linux_wayland_experimental": "Les gestes sous Wayland sont expérimentaux et ne fonctionnent que sous KDE Plasma.\nFilee lit la souris depuis /dev/input et un script KWin place le menu circulaire au curseur (voir INSTALL.txt). Ctrl+glisser dans d'autres applications peut être interrompu ; utilisez un autre modificateur comme Ctrl+Shift s'il vous gêne.","triggers.open_accessibility": "Ouvrir les réglages d'accessibilité",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex aa2b97dd..5ff49f5d 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -333,6 +333,8 @@"triggers.description": "चुनें कि डोनट टूलबार कैसे खुले। आप जितने चाहें उतने जेस्चर जोड़ सकते हैं।","triggers.macos_permissions": "सिस्टम सेटिंग्स > Privacy & Security > Accessibility में Filee को अनुमति दें।\nअगर Filee पहले से चालू है फिर भी जेस्चर शुरू नहीं होते, तो उसे − से हटाएँ और + से फिर जोड़ें।\nचयन वाले शॉर्टकट पहली बार इस्तेमाल करने पर Finder Automation की अनुमति भी माँगता है।","triggers.linux_x11": "ड्रैग जेस्चर X11 पर काम करते हैं।\nफ़ाइल मैनेजर इंटीग्रेशन चालू होने पर, पहला कीबोर्ड शॉर्टकट Thunar का Filee एक्शन चलाता है (बदलने के बाद Thunar दोबारा खोलें)।\nअन्य फ़ाइल मैनेजर में होल्ड जेस्चर और शॉर्टकट उपलब्ध नहीं हैं। Filee मेनू या ड्रॉप ज़ोन इस्तेमाल करें।",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "कर्सर का पीछा करने वाले जेस्चर Wayland पर उपलब्ध नहीं हैं।\nX11 सेशन इस्तेमाल करें, या फ़ाइल मैनेजर मेनू और ड्रॉप ज़ोन से कन्वर्ट करें।\nThunar रीस्टार्ट होने के बाद पहला कीबोर्ड शॉर्टकट इस्तेमाल कर सकता है।","triggers.linux_wayland_experimental": "Wayland पर जेस्चर प्रायोगिक हैं और सिर्फ़ KDE Plasma पर काम करते हैं।\nFilee माउस को /dev/input से पढ़ता है और एक KWin स्क्रिप्ट डोनट को कर्सर पर दिखाती है (INSTALL.txt देखें)। दूसरे ऐप्स में Ctrl+ड्रैग बीच में रुक सकता है; अगर इससे परेशानी हो, तो Ctrl+Shift जैसा कोई दूसरा मॉडिफ़ायर इस्तेमाल करें।","triggers.open_accessibility": "Accessibility सेटिंग्स खोलें",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex ede66293..36453d08 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -333,6 +333,8 @@"triggers.description": "ドーナツメニューを開く操作を選びます。ジェスチャーはいくつでも追加できます。","triggers.macos_permissions": "「システム設定」→「プライバシーとセキュリティ」→「アクセシビリティ」でFileeを許可してください。\nすでにオンなのにジェスチャーが始まらない場合は、−でFileeを削除してから+でもう一度追加してください。\n選択したファイルに対してショートカットを初めて使うと、Finderのオートメーションの許可も求められます。","triggers.linux_x11": "X11ではドラッグジェスチャーを使えます。\nファイルマネージャー連携が有効な場合、最初のキーボードショートカットでThunarのFileeアクションを実行します(設定を変更した後はThunarを再起動してください)。\n長押しジェスチャーは使えません。ショートカットを使えるのはThunarのみです。\nほかのファイルマネージャーでは、Fileeのメニューかドロップ領域を使ってください。",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Waylandではカーソルに追従するジェスチャーを使えません。\nX11セッションを使うか、ファイルマネージャーのメニューまたはドロップ領域から変換してください。\nThunarでは再起動後に最初のキーボードショートカットを使えます。","triggers.linux_wayland_experimental": "Waylandでのジェスチャー機能は実験的で、KDE Plasmaでのみ動作します。\nFileeは/dev/inputからマウス入力を読み取り、KWinスクリプトでカーソル位置にドーナツメニューを表示します(INSTALL.txtを参照)。ほかのアプリのCtrl+ドラッグ操作が妨げられることがあります。支障がある場合は、Ctrl+Shiftなど別の修飾キーを使ってください。","triggers.open_accessibility": "アクセシビリティ設定を開く",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 91d11c7e..614a2b07 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -346,6 +346,8 @@"triggers.description": "원형 툴바를 여는 방법을 정하세요. 제스처는 원하는 만큼 추가할 수 있어요.","triggers.macos_permissions": "시스템 설정 > 개인정보 보호 및 보안 > 손쉬운 사용에서 Filee를 허용해 주세요.\n이미 켜져 있는데도 제스처가 시작되지 않으면 − 버튼으로 Filee를 지운 뒤 + 버튼으로 다시 추가해 주세요.\n선택 파일 단축키를 처음 쓸 때 Finder 자동화 권한도 요청해요.","triggers.linux_x11": "드래그 제스처는 X11에서 작동해요.\n파일 관리자 연동을 켜면 첫 번째 키보드 단축키가 Thunar의 Filee 동작에 연결돼요(바꾼 뒤 Thunar를 다시 열어 주세요).\n길게 누르기와 다른 파일 관리자의 단축키는 지원하지 않아요. Filee 메뉴나 드롭 영역을 써 주세요.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Wayland에서는 커서를 따라가는 제스처를 쓸 수 없어요.\nX11 세션을 쓰거나, 파일 관리자 메뉴와 드롭 영역으로 변환해 주세요.\nThunar는 다시 시작하면 첫 번째 키보드 단축키를 쓸 수 있어요.","triggers.linux_wayland_experimental": "Wayland에서 제스처는 실험 기능이고 KDE Plasma에서만 동작해요.\nFilee가 /dev/input에서 마우스 입력을 읽고, KWin 스크립트가 원형 툴바를 커서 위치로 옮겨요(INSTALL.txt 참고). 다른 앱에서 Ctrl+드래그가 방해받을 수 있으니, 불편하면 Ctrl+Shift 같은 다른 보조 키를 쓰세요.","triggers.open_accessibility": "손쉬운 사용 설정 열기",diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.jsonindex 17e5fd99..15147a25 100644--- a/src/Filee.App/Assets/i18n/ne.json+++ b/src/Filee.App/Assets/i18n/ne.json@@ -333,6 +333,8 @@"triggers.description": "डोनट टुलबार कसरी खुल्छ रोज्नुहोस्। तपाईंले चाहे जति जेस्चरहरू थप्न सक्नुहुन्छ।","triggers.macos_permissions": "Filee लाई प्रणाली सेटिङहरू > गोपनीयता र सुरक्षा > पहुँच (Accessibility) मा अनुमति दिनुहोस्।\nFilee पहिले नै अन छ तर जेस्चरहरू सुरु हुँदैनन् भने, यसलाई − ले हटाउनुहोस् र + ले फेरि थप्नुहोस्।\nतपाईंले पहिलो पटक छनोट सर्टकट प्रयोग गर्दा Finder ले Automation अनुमतिका लागि पनि सोध्नेछ।","triggers.linux_x11": "तान्ने जेस्चरहरू X11 मा काम गर्छन्।\nफाइल प्रबन्धक एकीकरण सक्रिय हुँदा, पहिलो किबोर्ड सर्टकटले Thunar को Filee कार्य चलाउँछ (यसलाई परिवर्तन गरेपछि Thunar पुन: खोल्नुहोस्)।\nअन्य फाइल प्रबन्धकहरूमा होल्ड जेस्चर र सर्टकटहरू उपलब्ध छैनन्। Filee मेनु वा ड्रप क्षेत्र प्रयोग गर्नुहोस्।",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "कर्सर पछ्याउने जेस्चरहरू Wayland मा उपलब्ध छैनन्।\nX11 सत्र प्रयोग गर्नुहोस्, वा फाइल प्रबन्धक मेनु र ड्रप क्षेत्रबाट रूपान्तरण गर्नुहोस्।\nThunar पुन: सुरु भएपछि पहिलो किबोर्ड सर्टकट प्रयोग गर्न सक्छ।","triggers.linux_wayland_experimental": "Wayland मा जेस्चरहरू प्रायोगिक हुन् र केवल KDE Plasma मा मात्र काम गर्छन्।\nFilee ले /dev/input बाट माउस पढ्छ र KWin लिपिले डोनटलाई कर्सरमा राख्छ (INSTALL.txt हेर्नुहोस्)। अन्य एपहरूमा Ctrl+drag अवरुद्ध हुन सक्छ; यदि समस्या भएमा Ctrl+Shift जस्तो अर्को परिमार्जक प्रयोग गर्नुहोस्।","triggers.open_accessibility": "पहुँच सेटिङहरू खोल्नुहोस्",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 9f88452c..8ff4f2e2 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -346,6 +346,8 @@"triggers.description": "Wybierz, jak otwiera się pasek-pierścień. Możesz dodać dowolnie wiele gestów.","triggers.macos_permissions": "Zezwól Filee w Ustawienia systemowe > Prywatność i ochrona > Dostępność.\nJeśli Filee jest już włączony, a gesty się nie uruchamiają, usuń go przyciskiem − i dodaj ponownie przyciskiem +.\nFinder poprosi też o uprawnienie Automatyzacji przy pierwszym użyciu skrótu zaznaczenia.","triggers.linux_x11": "Gesty przeciągania działają w X11.\nPrzy włączonej integracji z menedżerem plików pierwszy skrót klawiszowy uruchamia akcję Filee w Thunarze (po zmianie otwórz Thunara ponownie).\nGesty przytrzymania i skróty w innych menedżerach plików są niedostępne. Użyj menu Filee lub strefy upuszczania.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Gesty podążające za kursorem są niedostępne w Waylandzie.\nUżyj sesji X11 albo konwertuj przez menu menedżera plików i strefę upuszczania.\nThunar może używać pierwszego skrótu klawiszowego po ponownym uruchomieniu.","triggers.linux_wayland_experimental": "Gesty w Waylandzie są eksperymentalne i działają tylko w KDE Plasma.\nFilee odczytuje mysz z /dev/input, a skrypt KWin umieszcza pasek-pierścień przy kursorze (zobacz INSTALL.txt). Przeciąganie z Ctrl w innych aplikacjach może zostać przerwane; jeśli to przeszkadza, użyj innego modyfikatora, np. Ctrl+Shift.","triggers.open_accessibility": "Otwórz ustawienia Dostępności",diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.jsonindex ab9da6f1..533fdbcb 100644--- a/src/Filee.App/Assets/i18n/pt-BR.json+++ b/src/Filee.App/Assets/i18n/pt-BR.json@@ -346,6 +346,8 @@"triggers.description": "Escolha como o menu circular abre. Você pode adicionar quantos gestos quiser.","triggers.macos_permissions": "Permita o Filee em Ajustes do Sistema > Privacidade e Segurança > Acessibilidade.\nSe o Filee já estiver ativado, mas os gestos não iniciarem, remova-o com − e adicione-o de novo com +.\nO Finder também pede permissão de Automação na primeira vez que você usa um atalho de seleção.","triggers.linux_x11": "Gestos de arrastar funcionam no X11.\nCom a integração do gerenciador de arquivos ligada, o primeiro atalho de teclado executa a ação do Filee no Thunar (reabra o Thunar depois de mudar).\nGestos de segurar e atalhos em outros gerenciadores não estão disponíveis. Use o menu do Filee ou a área de soltar.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: ative “Filee donut at the cursor” no aplicativo Extensões; depois segure Ctrl e arraste um arquivo no aplicativo Arquivos.\nDepois de instalar ou atualizar a extensão, encerre a sessão e entre novamente se ela ainda não tiver carregado. Não é necessário acesso de administrador nem entrar no grupo input.\nGestos de arrastar, modificadores personalizados, Pausar e aplicativos excluídos são respeitados. Esta integração não oferece atalhos globais de seleção, gestos de segurar ou alternância por Tab e roda do mouse durante o arraste.",+ "triggers.gnome_waiting": "Aguardando a extensão do Filee para GNOME.\nAtive “Filee donut at the cursor” no aplicativo Extensões. Depois de instalar ou atualizar, encerre a sessão e entre novamente se necessário. A área de soltar e as ações do gerenciador de arquivos continuam disponíveis.","triggers.linux_wayland": "Gestos que seguem o cursor não estão disponíveis no Wayland.\nUse uma sessão X11, ou converta pelo menu do gerenciador de arquivos e pela área de soltar.\nO Thunar pode usar o primeiro atalho de teclado depois de reiniciar.","triggers.linux_wayland_experimental": "Gestos no Wayland são experimentais e só funcionam no KDE Plasma.\nO Filee lê o mouse em /dev/input e um script do KWin coloca o menu no cursor (veja INSTALL.txt). Ctrl+arrastar em outros apps pode ser interrompido; use outro modificador, como Ctrl+Shift, se atrapalhar.","triggers.open_accessibility": "Abrir ajustes de Acessibilidade",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex 8aacb6aa..ad97f88e 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -346,6 +346,8 @@"triggers.description": "Выберите, как открывается круговое меню. Жестов можно добавить сколько угодно.","triggers.macos_permissions": "Разрешите Filee в разделе «Системные настройки > Конфиденциальность и безопасность > Универсальный доступ».\nЕсли Filee уже включён, но жесты не запускаются, удалите его кнопкой − и добавьте снова кнопкой +.\nFinder также спросит разрешение на автоматизацию, когда вы впервые воспользуетесь сочетанием для выделенных файлов.","triggers.linux_x11": "Жесты перетаскивания работают в X11.\nЕсли встраивание в файловый менеджер включено, первое сочетание клавиш запускает действие Filee в Thunar (после изменения перезапустите Thunar).\nЖесты удержания и сочетания в других файловых менеджерах недоступны. Пользуйтесь меню Filee или зоной перетаскивания.",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Жесты, которые следуют за курсором, в Wayland недоступны.\nИспользуйте сессию X11 или конвертируйте через меню файлового менеджера и зону перетаскивания.\nThunar сможет использовать первое сочетание клавиш после перезапуска.","triggers.linux_wayland_experimental": "Жесты в Wayland экспериментальные и работают только в KDE Plasma.\nFilee читает мышь из /dev/input, а скрипт KWin ставит круговое меню у курсора (см. INSTALL.txt). Ctrl+перетаскивание в других программах может прерываться; если мешает, возьмите другой модификатор, например Ctrl+Shift.","triggers.open_accessibility": "Открыть настройки универсального доступа",diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.jsonindex 013e31ff..488d4ae7 100644--- a/src/Filee.App/Assets/i18n/th.json+++ b/src/Filee.App/Assets/i18n/th.json@@ -333,6 +333,8 @@"triggers.description": "เลือกวิธีเปิดแถบโดนัท คุณสามารถเพิ่มท่าทางและปุ่มลัดได้ตามต้องการ","triggers.macos_permissions": "อนุญาต Filee ใน การตั้งค่าระบบ > ความเป็นส่วนตัวและความปลอดภัย > การช่วยการเข้าถึง\nหาก Filee เปิดอยู่แล้วแต่ท่าทางไม่เริ่มทำงาน ให้ลบออกด้วยปุ่ม − แล้วเพิ่มกลับเข้าไปใหม่ด้วยปุ่ม +\nFinder จะขอสิทธิ์การควบคุมอัตโนมัติ (Automation) ในครั้งแรกที่คุณใช้ปุ่มลัดกับไฟล์ที่เลือก","triggers.linux_x11": "ท่าทางการลากทำงานบน X11\nเมื่อเปิดการทำงานร่วมกับโปรแกรมจัดการไฟล์ ปุ่มลัดแป้นพิมพ์แรกจะเรียกใช้คำสั่ง Filee ของ Thunar (เปิด Thunar ใหม่หลังเปลี่ยนค่า)\nท่าทางการกดค้างและปุ่มลัดในโปรแกรมจัดการไฟล์อื่นยังไม่รองรับ ให้ใช้เมนู Filee หรือพื้นที่วางไฟล์แทน",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "ท่าทางที่ติดตามเคอร์เซอร์ยังไม่พร้อมใช้งานบน Wayland\nโปรดใช้เซสชัน X11 หรือแปลงไฟล์ด้วยเมนูของโปรแกรมจัดการไฟล์และพื้นที่วางไฟล์\nThunar สามารถใช้ปุ่มลัดแรกได้หลังจากรีสตาร์ท","triggers.linux_wayland_experimental": "ท่าทางบน Wayland อยู่ในขั้นทดลองและทำงานได้บน KDE Plasma เท่านั้น\nFilee อ่านค่าเมาส์จาก /dev/input และสคริปต์ KWin จะวางโดนัทตรงเคอร์เซอร์ (ดู INSTALL.txt) การกด Ctrl+ลาก ในแอปอื่นอาจถูกรบกวน ให้ใช้ปุ่มปรับแต่งอื่น เช่น Ctrl+Shift แทนหากมีปัญหา","triggers.open_accessibility": "เปิดการตั้งค่าการช่วยการเข้าถึง",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex a880dc4c..4ca80537 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -346,6 +346,8 @@"triggers.description": "选择打开环形工具栏的方式。可以添加任意多个手势。","triggers.macos_permissions": "请在系统设置 > 隐私与安全性 > 辅助功能中允许 Filee。\n如果 Filee 已打开但手势仍未启动,请用 − 将其移除,再用 + 重新添加。\n首次使用选择文件的快捷键时,Finder 还会请求自动化权限。","triggers.linux_x11": "拖动手势需要 X11。\n启用文件管理器集成后,第一个键盘快捷键会运行 Thunar 的 Filee 操作(修改后请重新打开 Thunar)。\n不支持长按手势和其他文件管理器的快捷键,请使用 Filee 菜单或拖放区域。",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Wayland 下无法使用跟随光标的手势。\n请使用 X11 会话,或通过文件管理器菜单和拖放区域转换。\nThunar 重启后可以使用第一个键盘快捷键。","triggers.linux_wayland_experimental": "Wayland 下的手势为实验性功能,仅在 KDE Plasma 中可用。\nFilee 从 /dev/input 读取鼠标输入,并由 KWin 脚本将环形工具栏移到光标处(参见 INSTALL.txt)。在其他应用中按住 Ctrl 拖动可能会被打断,如有影响,请改用其他修饰键,例如 Ctrl+Shift。","triggers.open_accessibility": "打开辅助功能设置",diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.jsonindex 2e36d0d1..5095c3b8 100644--- a/src/Filee.App/Assets/i18n/zh-TW.json+++ b/src/Filee.App/Assets/i18n/zh-TW.json@@ -346,6 +346,8 @@"triggers.description": "選擇開啟環形工具列的方式。可以新增任意多個手勢。","triggers.macos_permissions": "請在「系統設定 > 隱私權與安全性 > 輔助使用」中允許 Filee。\n如果 Filee 已開啟但手勢仍未啟動,請用 − 將其移除,再用 + 重新加入。\n首次使用「選取檔案」的快速鍵時,Finder 還會要求自動化權限。","triggers.linux_x11": "拖曳手勢需要 X11。\n啟用檔案管理員整合後,第一個鍵盤快速鍵會執行 Thunar 的 Filee 操作(修改後請重新開啟 Thunar)。\n不支援長按手勢和其他檔案管理員的快速鍵,請使用 Filee 選單或拖放區域。",+ "triggers.linux_gnome_wayland": "GNOME Wayland: enable “Filee donut at the cursor” in the Extensions app, then hold Ctrl and drag a file in Files.\nAfter first installing or updating the extension, sign out and sign in again if it has not loaded. No administrator access or input group is needed.\nDrag gestures, custom modifiers, Pause and excluded apps are supported. Global selection shortcuts, hold gestures, Tab and wheel flipping during a drag are not provided by this integration.",+ "triggers.gnome_waiting": "Waiting for the Filee GNOME extension.\nEnable “Filee donut at the cursor” in Extensions. After installation or update, sign out and sign in if needed. The drop zone and file manager actions remain available.","triggers.linux_wayland": "Wayland 下無法使用跟隨游標的手勢。\n請使用 X11 工作階段,或透過檔案管理員選單和拖放區域轉換。\nThunar 重啟後可以使用第一個鍵盤快速鍵。","triggers.linux_wayland_experimental": "Wayland 下的手勢為實驗性功能,僅在 KDE Plasma 中可用。\nFilee 從 /dev/input 讀取滑鼠輸入,並由 KWin 指令碼將環形工具列移到游標處(參見 INSTALL.txt)。在其他應用程式中按住 Ctrl 拖曳可能會被打斷,如有影響,請改用其他修飾鍵,例如 Ctrl+Shift。","triggers.open_accessibility": "開啟輔助使用設定",diff --git a/src/Filee.App/Services/Triggers/GnomePointerBridge.cs b/src/Filee.App/Services/Triggers/GnomePointerBridge.csnew file mode 100644index 00000000..00263e22--- /dev/null+++ b/src/Filee.App/Services/Triggers/GnomePointerBridge.cs@@ -0,0 +1,131 @@+using System.Net.Sockets;+using System.Text.Json;+using Filee.Core.Settings;++namespace Filee.App.Services.Triggers;++/// <summary>+/// Connects to the per-user GNOME Shell extension. It sends pointer state only, never typed keys or file contents.+/// No native global hook is loaded on this path. Reconnection also covers enabling the extension after Filee starts.+/// </summary>+internal sealed class GnomePointerBridge(Action<GnomePointerState> received, Action<bool> status) : IDisposable+{+ private readonly CancellationTokenSource _stop = new();+ private readonly Task _reader = Task.CompletedTask;++ public GnomePointerBridge(string socketPath, Action<GnomePointerState> received, Action<bool> status)+ : this(received, status) => _reader = ReadAsync(socketPath);++ public static string? SocketPath => Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR") is { } directory+ && Path.IsPathFullyQualified(directory) ? Path.Combine(directory, "filee-gnome", "pointer-v1.sock") : null;++ private async Task ReadAsync(string path)+ {+ var cancel = _stop.Token;+ while (!cancel.IsCancellationRequested)+ {+ try+ {+ using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);+ await socket.ConnectAsync(new UnixDomainSocketEndPoint(path), cancel);+ using var stream = new NetworkStream(socket, ownsSocket: false);+ using var reader = new StreamReader(stream);+ var connected = false;+ while (!cancel.IsCancellationRequested)+ {+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancel);+ timeout.CancelAfter(TimeSpan.FromSeconds(3)); // also detects a stalled Shell connection+ var line = await reader.ReadLineAsync(timeout.Token);+ if (line is null)+ break;+ if (!GnomePointerState.TryParse(line, out var state))+ throw new IOException("Invalid GNOME pointer protocol.");+ if (!connected)+ {+ status(true);+ connected = true;+ }+ received(state!);+ }+ }+ catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException)+ {+ // Disabled extension, sign-out, or update. Keep the drop zone and the rest of Filee usable.+ }+ finally+ {+ status(false);+ }+ try { await Task.Delay(TimeSpan.FromSeconds(1), cancel); }+ catch (OperationCanceledException) { break; }+ }+ }++ public void Dispose()+ {+ _stop.Cancel();+ // The reader owns its socket; cancellation closes it after pending I/O unwinds, without blocking the UI.+ _ = _reader.ContinueWith(_ => _stop.Dispose(), TaskScheduler.Default);+ }+}++internal sealed record GnomePointerState(int Version, int X, int Y, int Modifiers, int Buttons,+ string? Process, bool Desktop, bool Blocked)+{+ public static bool TryParse(string json, out GnomePointerState? state)+ {+ state = null;+ if (json.Length > 2048)+ return false;+ try+ {+ // Deserialize only the fixed protocol fields; a missing version never turns into input.+ state = JsonSerializer.Deserialize<GnomePointerState>(json);+ return state is { Version: 1, Modifiers: >= 0 and <= 15, Buttons: >= 0 and <= 31 }+ && Math.Abs((long)state.X) <= 1_000_000 && Math.Abs((long)state.Y) <= 1_000_000+ && (state.Process?.Length ?? 0) <= 256;+ }+ catch (JsonException) { return false; }+ }+}++/// <summary>Turns Shell snapshots into the same detector events as the existing hooks.</summary>+internal sealed class GnomePointerInput(GestureDetector detector)+{+ private int _buttons;+ private bool _ready;++ public void Reset(int x, int y)+ {+ detector.MouseUp(TriggerMouseButton.None, x, y);+ _buttons = 0;+ _ready = false;+ }++ public void Apply(GnomePointerState state)+ {+ if (state.Blocked)+ {+ Reset(state.X, state.Y);+ return;+ }+ // Never capture a drag already held when connecting, unlocking, or reconnecting.+ if (!_ready)+ {+ _ready = state.Buttons == 0;+ return;+ }+ var modifiers = (ModifierKeys)state.Modifiers;+ for (var bit = 0; bit < 5; bit++)+ {+ var mask = 1 << bit;+ if ((_buttons & mask) != 0 && (state.Buttons & mask) == 0)+ detector.MouseUp((TriggerMouseButton)(bit + 1), state.X, state.Y);+ if ((_buttons & mask) == 0 && (state.Buttons & mask) != 0)+ detector.MouseDown((TriggerMouseButton)(bit + 1), state.X, state.Y, modifiers);+ }+ _buttons = state.Buttons;+ var held = Enumerable.Range(0, 5).FirstOrDefault(bit => (_buttons & (1 << bit)) != 0, -1);+ detector.MouseMove(state.X, state.Y, modifiers, held < 0 ? TriggerMouseButton.None : (TriggerMouseButton)(held + 1));+ }+}diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.csindex 177c2c34..4130503d 100644--- a/src/Filee.App/Services/Triggers/TriggerService.cs+++ b/src/Filee.App/Services/Triggers/TriggerService.cs@@ -23,6 +23,9 @@ public sealed class TriggerService : IDisposableprivate EventLoopGlobalHook? _hook;private Thread? _hookThread;private readonly Func<EventLoopGlobalHook> _createHook;+ private GnomePointerBridge? _gnomeBridge;+ private GnomePointerInput? _gnomeInput;+ private bool _gnomeConnected;private HashSet<string> _excluded = new(StringComparer.OrdinalIgnoreCase);/// <summary>FILEE_TRACE_GESTURES=1 logs each mouse press and scope decision, to find why a gesture doesn't fire.</summary>@@ -108,7 +111,7 @@ public sealed class TriggerService : IDisposable/// <summary>Last known cursor position (physical pixels).</summary>public (int X, int Y) LastCursor { get; private set; }- public bool IsRunning => _hook?.IsRunning == true;+ public bool IsRunning => _gnomeConnected || _hook?.IsRunning == true;public string? Error { get; private set; }/// <summary>@@ -148,6 +151,12 @@ public sealed class TriggerService : IDisposablepublic void Start(){+ if (OperatingSystem.IsLinux() && _platform is Filee.Platform.Linux.LinuxPlatformServices+ && Filee.Platform.Linux.LinuxPlatformServices.UsesGnomePointerBridge)+ {+ StartGnomeBridge();+ return;+ }if (_hook is not null)return;if (!_platform.SupportsGlobalPointerGestures)@@ -224,6 +233,46 @@ public sealed class TriggerService : IDisposable}}+ private void StartGnomeBridge()+ {+ if (_gnomeBridge is not null)+ return;+ if (GnomePointerBridge.SocketPath is not { } path)+ {+ Error = "GNOME pointer integration requires XDG_RUNTIME_DIR.";+ NotifyStatus();+ return;+ }+ Error = null;+ LinuxBackendMissing = false;+ _gnomeInput = new GnomePointerInput(_detector);+ GnomePointerBridge? bridge = null;+ bridge = new GnomePointerBridge(path, state => Post(() =>+ {+ if (!ReferenceEquals(_gnomeBridge, bridge))+ return;+ LastCursor = (state.X, state.Y);+ if (OperatingSystem.IsLinux() && _platform is Filee.Platform.Linux.LinuxPlatformServices linux)+ {+ linux.GnomePointerProcess = state.Process;+ linux.GnomePointerIsDesktop = state.Desktop;+ }+ _gnomeInput?.Apply(state);+ }), connected => Post(() =>+ {+ if (!ReferenceEquals(_gnomeBridge, bridge) || connected == _gnomeConnected)+ return;+ _gnomeConnected = connected;+ if (!connected)+ _gnomeInput?.Reset(LastCursor.X, LastCursor.Y);+ _log.LogInformation("GNOME pointer extension {State}", connected ? "connected" : "disconnected; waiting to reconnect");+ NotifyStatus();+ }));+ _gnomeBridge = bridge;+ _log.LogInformation("Waiting for the Filee GNOME pointer extension (no input-device permission required)");+ NotifyStatus();+ }+private void ReportFailure(Exception exception, string message){// The raw libuiohook result goes to the log either way (the packaged-app smoke test looks for it).@@ -340,6 +389,11 @@ public sealed class TriggerService : IDisposablepublic void Dispose(){+ _gnomeBridge?.Dispose();+ _gnomeBridge = null;+ _gnomeConnected = false;+ _gnomeInput?.Reset(LastCursor.X, LastCursor.Y);+ _gnomeInput = null;_permissionWatch?.Dispose();_permissionWatch = null;trydiff --git a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.csindex 472e1771..b311fd1b 100644--- a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs@@ -267,12 +267,16 @@ public sealed partial class TriggersPageViewModel : ObservableObject, IDisposablpublic string? PlatformNotice => _platform switch{MacOSPlatformServices => _loc["triggers.macos_permissions"],+ LinuxPlatformServices when OperatingSystem.IsLinux() && LinuxPlatformServices.IsGnomeWaylandSession =>+ _loc["triggers.linux_gnome_wayland"],LinuxPlatformServices linux when OperatingSystem.IsLinux() && LinuxPlatformServices.IsWaylandSession =>_loc[linux.SupportsGlobalPointerGestures ? "triggers.linux_wayland_experimental" : "triggers.linux_wayland"],LinuxPlatformServices => _loc["triggers.linux_x11"],_ => null,};public string? HookStatus => _triggers?.Error is { } error ? HookFailure(_loc, error, _triggers.LinuxBackendMissing)+ : OperatingSystem.IsLinux() && _platform is LinuxPlatformServices && LinuxPlatformServices.UsesGnomePointerBridge+ && _triggers is { IsRunning: false } ? _loc["triggers.gnome_waiting"]: _triggers is null ? null : _loc[_triggers.IsRunning ? "triggers.hook_running" : "triggers.hook_stopped"];/// <summary>diff --git a/src/Filee.Platform.Linux/LinuxPlatformServices.cs b/src/Filee.Platform.Linux/LinuxPlatformServices.csindex 15ae1143..4c2dc179 100644--- a/src/Filee.Platform.Linux/LinuxPlatformServices.cs+++ b/src/Filee.Platform.Linux/LinuxPlatformServices.cs@@ -21,6 +21,18 @@ public sealed class LinuxPlatformServices : IPlatformServicesstring.Equals(Environment.GetEnvironmentVariable("XDG_SESSION_TYPE"), "wayland", StringComparison.OrdinalIgnoreCase)|| !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY"));+ public static bool IsGnomeWaylandSession => IsWaylandSession+ && (Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP") ?? "").Split(':')+ .Contains("GNOME", StringComparer.OrdinalIgnoreCase);++ // Enabling the Shell extension opts in; no /dev/input permission or environment setup is needed on GNOME.+ // Keep KDE's existing libinput opt-in independent. A value of 0 explicitly disables the GNOME bridge too.+ public static bool UsesGnomePointerBridge => IsGnomeWaylandSession+ && Environment.GetEnvironmentVariable("FILEE_WAYLAND_GESTURES") != "0";++ public string? GnomePointerProcess { get; set; }+ public bool GnomePointerIsDesktop { get; set; }+// Wayland gestures (experimental) are opt-in: FILEE_WAYLAND_GESTURES=1 on KDE Plasma. libuiohook's libinput backend// reads /dev/input, so /dev/input is only probed once the switch is set, and it works once the user is in the// `input` group. Presses carry no position and a mouse only moves relatively there; a KWin script places the donut.@@ -43,7 +55,7 @@ public sealed class LinuxPlatformServices : IPlatformServicesreturn false;}- public bool SupportsGlobalPointerGestures => X11WindowSystem.IsAvailable || WaylandGestures;+ public bool SupportsGlobalPointerGestures => X11WindowSystem.IsAvailable || WaylandGestures || UsesGnomePointerBridge;public bool PressCarriesPosition => !WaylandGestures;public bool SupportsSelectionShortcut => false;public string SelectionShortcutUnavailableReason =>@@ -57,8 +69,10 @@ public sealed class LinuxPlatformServices : IPlatformServices// Wayland can't say which window is under the cursor, so any Ctrl+drag may open the (invisible) donut window;// it only shows when files are dragged in, and excluded apps can't be told apart there either.public bool IsFileManagerAt(int x, int y) =>- WaylandGestures || ProcessNameAt(x, y) is { } name && FileManagers.Contains(name);- public string? ProcessNameAt(int x, int y) => X11WindowSystem.ProcessNameAt(x, y);+ UsesGnomePointerBridge && GnomePointerIsDesktop+ || WaylandGestures || ProcessNameAt(x, y) is { } name && FileManagers.Contains(name);+ public string? ProcessNameAt(int x, int y) => UsesGnomePointerBridge+ ? GnomePointerProcess : X11WindowSystem.ProcessNameAt(x, y);public IReadOnlyList<string> RunningAppNames() => IPlatformServices.AppNames(X11WindowSystem.ClientProcessNames());public IReadOnlyList<string> GetFileManagerSelection() => throw new NotSupportedException(SelectionShortcutUnavailableReason);diff --git a/tests/Filee.App.Tests/GnomePointerBridgeTests.cs b/tests/Filee.App.Tests/GnomePointerBridgeTests.csnew file mode 100644index 00000000..aa0b7514--- /dev/null+++ b/tests/Filee.App.Tests/GnomePointerBridgeTests.cs@@ -0,0 +1,159 @@+using System.Net.Sockets;+using System.Text;+using Filee.App.Services.Triggers;+using Filee.Core.Settings;++namespace Filee.App.Tests;++public sealed class GnomePointerBridgeTests+{+ private static GnomePointerState State(int x = 100, int buttons = 0, int modifiers = 1, bool blocked = false) =>+ new(1, x, 100, modifiers, buttons, "nautilus", false, blocked);++ [Fact]+ public void Ctrl_drag_requires_movement_and_release_ends_it_once()+ {+ var detector = new GestureDetector();+ detector.Configure([new TriggerGesture { DragThreshold = 8 }]);+ var input = new GnomePointerInput(detector);+ var started = 0;+ var ended = 0;+ detector.DragStarted += (_, _, _) => started++;+ detector.DragEnded += (_, _) => ended++;+ input.Apply(State());+ input.Apply(State(buttons: 1));+ input.Apply(State(x: 105, buttons: 1));+ Assert.Equal(0, started);+ input.Apply(State(x: 120, buttons: 1));+ input.Apply(State(x: 140, buttons: 1));+ Assert.Equal(1, started);+ input.Apply(State(x: 140));+ input.Apply(State(x: 140));+ Assert.Equal(1, ended);+ }++ [Fact]+ public void Plain_drag_and_rejected_app_never_open_the_donut()+ {+ var detector = new GestureDetector();+ detector.Configure([new TriggerGesture()]);+ var input = new GnomePointerInput(detector);+ var started = 0;+ detector.DragStarted += (_, _, _) => started++;+ input.Apply(State());+ input.Apply(State(buttons: 1, modifiers: 0));+ input.Apply(State(x: 140, buttons: 1, modifiers: 0));+ input.Apply(State(x: 140));+ detector.ScopeFilter = (_, _, _) => false;+ input.Apply(State(buttons: 1));+ input.Apply(State(x: 180, buttons: 1));+ Assert.Equal(0, started);+ }++ [Fact]+ public void Connecting_mid_drag_and_unlocking_do_not_capture_an_existing_drag()+ {+ var detector = new GestureDetector();+ detector.Configure([new TriggerGesture()]);+ var input = new GnomePointerInput(detector);+ var started = 0;+ var ended = 0;+ detector.DragStarted += (_, _, _) => started++;+ detector.DragEnded += (_, _) => ended++;+ input.Apply(State(buttons: 1));+ input.Apply(State(x: 150, buttons: 1));+ Assert.Equal(0, started);+ input.Apply(State());+ input.Apply(State(buttons: 1));+ input.Apply(State(x: 150, buttons: 1));+ Assert.Equal(1, started);+ input.Apply(State(blocked: true));+ Assert.Equal(1, ended);+ input.Apply(State(x: 160, buttons: 1));+ input.Apply(State(x: 200, buttons: 1));+ Assert.Equal(1, started);+ }++ [Fact]+ public void Pause_disabled_gestures_and_custom_modifiers_are_respected()+ {+ var detector = new GestureDetector();+ detector.Configure([new TriggerGesture { Modifiers = ModifierKeys.Ctrl | ModifierKeys.Shift }]);+ var input = new GnomePointerInput(detector);+ var started = 0;+ detector.DragStarted += (_, _, _) => started++;+ input.Apply(State());+ input.Apply(State(buttons: 1));+ input.Apply(State(x: 150, buttons: 1));+ Assert.Equal(0, started);+ input.Apply(State(x: 150, buttons: 1, modifiers: 5)); // modifier added after starting the drag+ Assert.Equal(1, started);+ input.Apply(State());+ detector.Paused = true;+ input.Apply(State(buttons: 1, modifiers: 5));+ input.Apply(State(x: 200, buttons: 1, modifiers: 5));+ Assert.Equal(1, started);+ detector.Configure([]);+ detector.Paused = false;+ input.Apply(State());+ input.Apply(State(buttons: 1, modifiers: 5));+ input.Apply(State(x: 200, buttons: 1, modifiers: 5));+ Assert.Equal(1, started);+ }++ [Theory]+ [InlineData("{}")]+ [InlineData("{\"Version\":2}")]+ [InlineData("{\"Version\":1,\"Buttons\":32}")]+ [InlineData("{\"Version\":1,\"Modifiers\":16}")]+ [InlineData("{\"Version\":1,\"X\":2147483647}")]+ [InlineData("bad JSON")]+ public void Invalid_protocol_never_becomes_input(string json) => Assert.False(GnomePointerState.TryParse(json, out _));++ [Fact]+ public async Task Real_unix_socket_delivers_pointer_frames_and_reconnects_after_extension_restart()+ {+ if (!OperatingSystem.IsLinux())+ return;+ var directory = Path.Combine(Path.GetTempPath(), "filee-gnome-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var path = Path.Combine(directory, "pointer.sock");+ using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));+ using var listener = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);+ try+ {+ listener.Bind(new UnixDomainSocketEndPoint(path));+ listener.Listen(1);+ var first = new TaskCompletionSource<GnomePointerState>(TaskCreationOptions.RunContinuationsAsynchronously);+ var second = new TaskCompletionSource<GnomePointerState>(TaskCreationOptions.RunContinuationsAsynchronously);+ var disconnected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ var seen = false;+ using var bridge = new GnomePointerBridge(path, state =>+ {+ if (!first.TrySetResult(state)) second.TrySetResult(state);+ }, connected =>+ {+ if (connected) seen = true;+ else if (seen) disconnected.TrySetResult();+ });+ using (var socket = await listener.AcceptAsync(deadline.Token))+ {+ await socket.SendAsync(Encoding.UTF8.GetBytes("{\"Version\":1,\"X\":120,\"Y\":300,\"Process\":\"nautilus\"}\n"), deadline.Token);+ var state = await first.Task.WaitAsync(deadline.Token);+ Assert.Equal(120, state.X);+ Assert.Equal("nautilus", state.Process);+ }+ await disconnected.Task.WaitAsync(deadline.Token);+ using (var socket = await listener.AcceptAsync(deadline.Token))+ {+ await socket.SendAsync(Encoding.UTF8.GetBytes("{\"Version\":1,\"X\":200}\n"), deadline.Token);+ Assert.Equal(200, (await second.Task.WaitAsync(deadline.Token)).X);+ }+ }+ finally+ {+ listener.Close();+ Directory.Delete(directory, recursive: true);+ }+ }+}diff --git a/tests/gnome/extension-smoke.js b/tests/gnome/extension-smoke.jsnew file mode 100644index 00000000..6064b1bd--- /dev/null+++ b/tests/gnome/extension-smoke.js@@ -0,0 +1,76 @@+// Run with GJS and Mutter's typelib/library paths. Real Gio Unix sockets, mocked Shell windows and pointer.+// No interaction with the running desktop, settings, extensions or user files.+const {Gio, GLib, Clutter, Meta} = imports.gi;+const assert = (condition, message) => { if (!condition) throw new Error(message); };+const Main = {sessionMode: {isLocked: false, hasWindows: true}, overview: {visible: false}, modalCount: 0,+ layoutManager: {monitors: [{x: 0, y: 0, width: 1920, height: 1080}]}};+let pointer = [500, 400, 0];+let map;+let moves = [];+const window = {+ get_title: () => 'Filee Donut', get_wm_class: () => 'Filee', get_wm_class_instance: () => 'Filee',+ get_gtk_application_id: () => null, get_frame_rect: () => ({x: 0, y: 0, width: 400, height: 400}),+ get_pid: () => new Gio.Credentials().get_unix_pid(), get_window_type: () => Meta.WindowType.NORMAL,+ showing_on_its_workspace: () => true, make_above() {}, raise() {}, move_frame: (_user, x, y) => moves.push([x, y]),+};+const actor = {meta_window: window, is_visible: () => true};+const shell = {+ get_pointer: () => pointer, get_window_actors: () => [actor],+ window_manager: {connect: (_event, callback) => { map = callback; return 1; }, disconnect: () => { map = null; }},+ display: {sort_windows_by_stacking: windows => windows},+};+const path = ARGV[0];+const [ok, bytes] = GLib.file_get_contents(path);+assert(ok, 'read extension');+const source = new TextDecoder().decode(bytes).replace(/^import .*;\n/gm, '').replace('export default class', 'class');+const ExtensionClass = new Function('Clutter', 'Gio', 'GLib', 'Meta', 'Extension', 'Main', 'global',+ `${source}\nreturn FileeDonutExtension;`)(Clutter, Gio, GLib, Meta, class {}, Main, shell);+const loop = new GLib.MainLoop(null, false);+const extension = new ExtensionClass();+const socketPath = `${GLib.get_user_runtime_dir()}/filee-gnome/pointer-v1.sock`;+let connection;+function read(stream) {+ return new Promise((resolve, reject) => stream.read_line_async(GLib.PRIORITY_DEFAULT, null, (input, result) => {+ try { const [line] = input.read_line_finish_utf8(result); resolve(JSON.parse(line)); } catch (error) { reject(error); }+ }));+}+async function run() {+ extension.enable();+ const info = Gio.File.new_for_path(socketPath).query_info('unix::mode', Gio.FileQueryInfoFlags.NONE, null);+ assert((info.get_attribute_uint32('unix::mode') & 0o777) === 0o600, 'socket is private');+ const client = new Gio.SocketClient();+ connection = await new Promise((resolve, reject) => client.connect_async(new Gio.UnixSocketAddress({path: socketPath}), null,+ (object, result) => { try { resolve(object.connect_finish(result)); } catch (error) { reject(error); } }));+ const input = new Gio.DataInputStream({base_stream: connection.get_input_stream()});+ const first = await read(input);+ assert(first.Version === 1 && first.X === 500 && first.Buttons === 0, 'first pointer frame');+ pointer = [550, 450, Clutter.ModifierType.CONTROL_MASK | Clutter.ModifierType.BUTTON1_MASK];+ const pressed = await read(input);+ assert(pressed.Modifiers === 1 && pressed.Buttons === 1, 'Ctrl + left button mapping');+ pointer = [550, 450, Clutter.ModifierType.BUTTON3_MASK];+ assert((await read(input)).Buttons === 2, 'right button mapping');+ Main.sessionMode.isLocked = true;+ const locked = await read(input);+ assert(locked.Blocked && locked.Modifiers === 0 && locked.Buttons === 0 && locked.Process === null, 'lock screen suppresses state');+ Main.sessionMode.isLocked = false;+ map(null, actor);+ await read(input);+ assert(moves.length === 1, 'position exactly once when mapped');+ pointer = [800, 600, 0];+ await read(input);+ assert(moves.length === 1, 'moving to a format does not recenter the ring');+ pointer = [1910, 1070, 0];+ map(null, actor);+ await read(input);+ assert(moves.length === 2 && moves[1][0] === 1520 && moves[1][1] === 680, 'clamp at monitor edge on next opening');+ print('PASS: real Gio socket, private permissions, modifiers/buttons, lock screen, fixed placement, screen edges');+}+const timeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 8000, () => { printerr('FAIL: timed out'); imports.system.exit(1); return GLib.SOURCE_REMOVE; });+run().then(() => {+ GLib.Source.remove(timeout);+ extension.disable();+ assert(!map && !Gio.File.new_for_path(socketPath).query_exists(null), 'disable disconnects signals and removes socket');+ connection?.close(null);+ loop.quit();+}).catch(error => { printerr(error.stack); extension.disable(); imports.system.exit(1); });+loop.run();