Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ releases and the AppStream metadata.
focus is removed, so ZapZap no longer writes to the clipboard when it gains
focus (#498, #523, #969). Its tests are replaced with tests for the new
selection rules and for the paste script in a real WebEngine page.
- Make images dragged out of ZapZap reach other applications in the Flatpak
(#522). The sandbox has a private `/tmp`, where Qt WebEngine saved the
dragged file, so the drop target received a path that does not exist outside
the sandbox: an empty attachment, or a "file not found" error in a file
manager. ZapZap now uses `$XDG_RUNTIME_DIR/app/$FLATPAK_ID`, which Flatpak
already shares with the host under the same path, as its temporary
directory, so no new filesystem permission is needed. An explicit `TMPDIR`
is respected. The single-instance socket also lives in the temporary
directory, so while an instance started before this change is still running
the private `/tmp` keeps being used and the new launch still finds it. Add
tests for the selection rules and the bootstrap order.

## [7.5.1] - 2026-10-15

Expand Down
12 changes: 12 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ O caminho principal está em `zapzap/app/application.py`:
9. no encerramento, remove notificações, para D-Bus e tema e libera páginas
WebEngine explicitamente.

No Flatpak, logo depois de `SetupManager.apply()` e antes de criar
`SingleApplication`, `SetupManager.apply_flatpak_temp_dir()` define `TMPDIR`
como `$XDG_RUNTIME_DIR/app/$FLATPAK_ID`. O `/tmp` do sandbox é privado, e o Qt
WebEngine grava em um `QTemporaryDir` a imagem arrastada para fora da página;
com o `/tmp` privado, o destino do arraste recebia um caminho que não existe no
host. Essa pasta já é compartilhada pelo Flatpak com o host no mesmo caminho,
sem permissão adicional de filesystem. Um `TMPDIR` explícito é respeitado. O
`QLocalServer` de instância única também fica no diretório temporário: enquanto
existir no `/tmp` privado o socket de uma instância iniciada antes dessa
mudança, o `/tmp` continua em uso, para que o novo lançamento encontre essa
instância em vez de abrir uma segunda sobre o mesmo perfil.

Em sistemas POSIX, `app.unix_signal_bridge` converte `SIGTERM` em uma
solicitação normal de saída. O handler Python não chama Qt: o wakeup fd escreve
em um `socketpair` não bloqueante, um `QSocketNotifier` recebe o evento dentro
Expand Down
2 changes: 2 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ documente o que ele protege.
| `test_documentation_structure.py` | camadas de UI, ciclo numérico versionado do changelog e sincronização entre árvore, inventários técnicos, convenção de commits e guia para agentes |
| `test_donations_page.py` | URLs HTTPS oficiais, fallback externo, cartões responsivos/acessíveis, troca imediata de idioma e rota única pela sidebar, Configurações e Sobre |
| `test_external_link_lifecycle.py` | classificação interna/externa de pop-ups, profile compartilhado, entrega única ao navegador e cleanup no fechamento/shutdown |
| `test_flatpak_temp_dir.py` | diretório temporário visível ao host no Flatpak (`TMPDIR` em `$XDG_RUNTIME_DIR/app/$FLATPAK_ID`), precedência do `TMPDIR` explícito, socket legado de instância única no `/tmp` privado e ordem do bootstrap |
| `test_freedesktop_notification_backend.py` | avisos nas saídas antecipadas da inicialização D-Bus, falhas de `Notify`/`CloseNotification`, aviso único na transição para indisponível e fachada sem backend |
| `test_global_mute.py` | estado persistente de mute global, sincronização dos controles, fan-out para todas as contas e roteamento do atalho de colagem para a conta ativa |
| `test_gpu_environment.py` | detecção multi-GPU, conectores e seleção de render node |
Expand Down Expand Up @@ -203,6 +204,7 @@ documente o que ele protege.
- `test_donations_page.py`
- `test_download_settings.py`
- `test_external_link_lifecycle.py`
- `test_flatpak_temp_dir.py`
- `test_freedesktop_notification_backend.py`
- `test_global_mute.py`
- `test_gpu_environment.py`
Expand Down
149 changes: 149 additions & 0 deletions tests/test_flatpak_temp_dir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Tests for the host-visible temporary directory used inside Flatpak."""

import ast
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

from zapzap.core.environment import setup_manager
from zapzap.core.environment.setup_manager import (
SetupManager,
flatpak_shared_temp_dir,
)


SERVER_NAME = "zapzap-application"
SHARED_DIR = "/run/user/1000/app/com.rtosta.zapzap"


def flatpak_environment(**extra):
return {
"FLATPAK_ID": "com.rtosta.zapzap",
"XDG_RUNTIME_DIR": "/run/user/1000",
**extra,
}


class FlatpakSharedTempDirTests(unittest.TestCase):

def resolve(self, environment, *, legacy_socket=False, writable=True):
return flatpak_shared_temp_dir(
SERVER_NAME,
environment,
path_exists=lambda path: (
legacy_socket and path == f"/tmp/{SERVER_NAME}"
),
is_writable_dir=lambda path: writable and path == SHARED_DIR,
)

def test_uses_the_app_directory_flatpak_shares_with_the_host(self):
self.assertEqual(self.resolve(flatpak_environment()), SHARED_DIR)

def test_keeps_the_default_outside_flatpak(self):
self.assertIsNone(self.resolve({"XDG_RUNTIME_DIR": "/run/user/1000"}))

def test_keeps_the_default_without_a_runtime_directory(self):
self.assertIsNone(self.resolve({"FLATPAK_ID": "com.rtosta.zapzap"}))

def test_keeps_an_explicit_tmpdir(self):
self.assertIsNone(
self.resolve(flatpak_environment(TMPDIR="/var/tmp/custom"))
)

def test_keeps_the_private_tmp_while_an_older_instance_listens_there(self):
self.assertIsNone(
self.resolve(flatpak_environment(), legacy_socket=True)
)

def test_keeps_the_default_when_the_directory_is_not_writable(self):
self.assertIsNone(self.resolve(flatpak_environment(), writable=False))

def test_checks_the_real_directory_by_default(self):
server_name = "zapzap-test-socket-that-does-not-exist"
with tempfile.TemporaryDirectory() as runtime_dir:
environment = {
"FLATPAK_ID": "com.rtosta.zapzap",
"XDG_RUNTIME_DIR": runtime_dir,
}
shared_dir = os.path.join(runtime_dir, "app", "com.rtosta.zapzap")

self.assertIsNone(flatpak_shared_temp_dir(server_name, environment))

os.makedirs(shared_dir)
self.assertEqual(
flatpak_shared_temp_dir(server_name, environment),
shared_dir,
)


class ApplyFlatpakTempDirTests(unittest.TestCase):

def test_sets_tmpdir_when_a_shared_directory_applies(self):
with (
patch.dict(os.environ, {}, clear=False),
patch.object(
setup_manager,
"flatpak_shared_temp_dir",
return_value=SHARED_DIR,
) as resolve,
):
os.environ.pop("TMPDIR", None)
SetupManager.apply_flatpak_temp_dir(SERVER_NAME)

resolve.assert_called_once_with(SERVER_NAME)
self.assertEqual(os.environ["TMPDIR"], SHARED_DIR)

def test_leaves_the_environment_alone_otherwise(self):
with (
patch.dict(os.environ, {}, clear=False),
patch.object(
setup_manager,
"flatpak_shared_temp_dir",
return_value=None,
),
):
os.environ.pop("TMPDIR", None)
SetupManager.apply_flatpak_temp_dir(SERVER_NAME)

self.assertNotIn("TMPDIR", os.environ)


class TempDirBootstrapOrderTests(unittest.TestCase):

def test_temp_dir_is_chosen_before_the_single_instance_socket(self):
application_path = (
Path(setup_manager.__file__).resolve().parents[2]
/ "app"
/ "application.py"
)
tree = ast.parse(application_path.read_text(encoding="utf-8"))
main = next(
node
for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name == "main"
)
calls = [
node for node in ast.walk(main) if isinstance(node, ast.Call)
]
temp_dir_call = next(
node
for node in calls
if isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "SetupManager"
and node.func.attr == "apply_flatpak_temp_dir"
)
application_call = next(
node
for node in calls
if isinstance(node.func, ast.Name)
and node.func.id == "SingleApplication"
)

self.assertLess(temp_dir_call.lineno, application_call.lineno)


if __name__ == "__main__":
unittest.main()
3 changes: 3 additions & 0 deletions zapzap/app/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ def main():
QCoreApplication.setOrganizationDomain(zapzap.__domain__)

SetupManager.apply()
# The single-instance socket and the files Qt WebEngine writes for a
# drag out of the page both live in the temporary directory.
SetupManager.apply_flatpak_temp_dir(zapzap.__appid__)
TranslationManager.apply()

# Qt requires QWebEngineView to be imported (or the corresponding
Expand Down
53 changes: 52 additions & 1 deletion zapzap/core/environment/setup_manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from collections.abc import MutableMapping
import os
from collections.abc import Callable, Mapping, MutableMapping
from os import environ

from PyQt6.QtCore import QFileInfo
Expand Down Expand Up @@ -60,6 +61,45 @@ def update_chromium_flag(
environment["QTWEBENGINE_CHROMIUM_FLAGS"] = " ".join(flags)


LEGACY_TEMP_DIR = "/tmp"


def _is_writable_dir(path: str) -> bool:
return os.path.isdir(path) and os.access(path, os.W_OK | os.X_OK)


def flatpak_shared_temp_dir(
server_name: str,
environment: Mapping[str, str] = environ,
*,
path_exists: Callable[[str], bool] = os.path.exists,
is_writable_dir: Callable[[str], bool] = _is_writable_dir,
) -> str | None:
"""Return the Flatpak directory to use as TMPDIR, or None to keep it.

The sandbox has a private /tmp. Qt WebEngine saves an image dragged out of
the page in a QTemporaryDir and offers that local path to the drop target,
which then gets a file that does not exist outside the sandbox (#522).
Flatpak shares $XDG_RUNTIME_DIR/app/$FLATPAK_ID with the host under the
same path, so using it as the temporary directory makes the dragged file
reachable without any extra filesystem permission.
"""
app_id = environment.get("FLATPAK_ID")
runtime_dir = environment.get("XDG_RUNTIME_DIR")
if not app_id or not runtime_dir or environment.get("TMPDIR"):
return None

# QLocalServer keeps the single-instance socket in the temporary
# directory. An instance started before this change still listens in the
# private /tmp: keep that location until it exits, so this launch finds
# it instead of starting a second instance on the same profile.
if path_exists(os.path.join(LEGACY_TEMP_DIR, server_name)):
return None

candidate = os.path.join(runtime_dir, "app", app_id)
return candidate if is_writable_dir(candidate) else None


class SetupManager:
"""Gerencia as configurações de ambiente para o aplicativo."""

Expand Down Expand Up @@ -234,6 +274,17 @@ def add_flag(flag: str):
ProxyManager.strict_isolation_active(),
)

@staticmethod
def apply_flatpak_temp_dir(server_name: str) -> None:
"""Choose a temporary directory the host can also read in Flatpak.

Call it before SingleApplication and Qt WebEngine exist: both resolve
the temporary directory when they first need it.
"""
shared_temp_dir = flatpak_shared_temp_dir(server_name)
if shared_temp_dir:
environ["TMPDIR"] = shared_temp_dir

@staticmethod
def apply_qt_scale_factor_rounding_policy():
"""Deve ser aplicado após a criação da instância do app"""
Expand Down