Migra server desktop a PySide6, auto-update Gitea e CI multi-piattaforma
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Failing after 39s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Successful in 3m42s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Successful in 1m5s

This commit is contained in:
brontomark committed 2026-11-11 17:32:19 +01:00
1 parent 5a8b0916f5
commit 8aa5694d9f
17 files changed
+2131 -741

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
name: Build and Release Barcode Reader Server (Multi-Platform)
on:
push:
tags:
- 'v*'
jobs:
# -----------------------------------------------------------------
# JOB 1: WINDOWS INSTALLER (.exe)
# -----------------------------------------------------------------
build-windows:
runs-on: windows-native
steps:
- name: Checkout del codice
uses: actions/checkout@v3
- name: Rileva Python e compila binario PySide6
run: |
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
$PyCmd = $null
if (Get-Command py -ErrorAction SilentlyContinue) {
$PyCmd = @("py", "-3")
} elseif (Get-Command python -ErrorAction SilentlyContinue) {
$PyCmd = @("python")
} elseif (Get-Command python3 -ErrorAction SilentlyContinue) {
$PyCmd = @("python3")
} else {
throw "Python 3 non trovato sul runner Windows."
}
if ($PyCmd.Count -gt 1) {
& $PyCmd[0] $PyCmd[1] server/build_binary.py --onedir --windowed --version "$TagVersion"
} else {
& $PyCmd[0] server/build_binary.py --onedir --windowed --version "$TagVersion"
}
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Firma opzionale eseguibile Windows
run: |
$PfxPath = "C:\flux_privato.pfx"
$PfxPass = "${{ secrets.PFX_PASSWORD }}"
if ((Test-Path $PfxPath) -and (-not [string]::IsNullOrWhiteSpace($PfxPass))) {
$Signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1).FullName
if ($Signtool) {
& $Signtool sign /f $PfxPath /p $PfxPass /fd SHA256 "server\dist\BarcodeServer\BarcodeServer.exe"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} else {
Write-Host "[i] signtool.exe non trovato: firma saltata."
}
} else {
Write-Host "[i] Certificato o PFX_PASSWORD non configurati: salto firma eseguibile."
}
- name: Build Installer Inno Setup
run: |
$TagVersion = "${{ github.ref_name }}".TrimStart('v')
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" "/DMyAppVersion=$TagVersion" "server\win_installer.iss"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Firma opzionale Installer Windows
run: |
$PfxPath = "C:\flux_privato.pfx"
$PfxPass = "${{ secrets.PFX_PASSWORD }}"
if ((Test-Path $PfxPath) -and (-not [string]::IsNullOrWhiteSpace($PfxPass))) {
$Signtool = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1).FullName
if ($Signtool) {
& $Signtool sign /f $PfxPath /p $PfxPass /fd SHA256 "server\dist\installer\BarcodeServerSetup.exe"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
}
- name: Upload Windows Installer Asset
uses: https://gitea.com/actions/release-action@main
with:
files: "server/dist/installer/BarcodeServerSetup.exe"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
# -----------------------------------------------------------------
# JOB 2: LINUX APPIMAGE (.AppImage)
# -----------------------------------------------------------------
build-linux:
runs-on: linux-runner
steps:
- name: Checkout del codice
uses: actions/checkout@v3
- name: Compila binario e AppDir PySide6
run: |
TagVersion="${GITHUB_REF_NAME#v}"
python3 server/build_binary.py --onedir --windowed --appdir --version "$TagVersion"
- name: Scarica appimagetool se non presente
run: |
if [ ! -f ./appimagetool-x86_64.AppImage ]; then
curl -L -o appimagetool-x86_64.AppImage https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 APPIMAGE_EXTRACT_AND_RUN=1 ./appimagetool-x86_64.AppImage server/dist/BarcodeServer.AppDir BarcodeServer-x86_64.AppImage
chmod +x BarcodeServer-x86_64.AppImage
APPIMAGE_EXTRACT_AND_RUN=1 ./BarcodeServer-x86_64.AppImage --version
- name: Upload Linux AppImage Asset
uses: https://gitea.com/actions/release-action@main
with:
files: "BarcodeServer-x86_64.AppImage"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
# -----------------------------------------------------------------
# JOB 3: MACOS (.dmg e .zip per auto-update)
# -----------------------------------------------------------------
build-macos:
runs-on: macos-runner
steps:
- name: Checkout del codice
uses: actions/checkout@v3
- name: Compila bundle .app PySide6
run: |
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
TagVersion="${GITHUB_REF_NAME#v}"
python3 server/build_binary.py --onedir --windowed --version "$TagVersion"
- name: Genera DMG e ZIP macOS
run: |
hdiutil create -volname "Barcode Reader Server" -srcfolder "server/dist/BarcodeServer.app" -ov -format UDZO "BarcodeServer-macOS.dmg"
ditto -c -k --sequesterRsrc --keepParent "server/dist/BarcodeServer.app" "BarcodeServer-macOS.zip"
- name: Upload macOS Assets
uses: https://gitea.com/actions/release-action@main
with:
files: |
BarcodeServer-macOS.dmg
BarcodeServer-macOS.zip
api_key: ${{ secrets.MYRELEASE_TOKEN }}
+4
View File
@@ -15,6 +15,10 @@ server/venv_unix/
server/__pycache__/ server/__pycache__/
server/build/ server/build/
server/dist/ server/dist/
server/*.spec
*.spec
*.AppImage
*.dmg
server/*.log server/*.log
# OS # OS
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

+4
View File
@@ -9,6 +9,10 @@ PLIST_LABEL = "com.catellisrl.barcodereader"
def get_launch_command() -> list[str]: def get_launch_command() -> list[str]:
"""Ottiene il comando eseguibile appropriato per l'avvio automatico.""" """Ottiene il comando eseguibile appropriato per l'avvio automatico."""
if getattr(sys, "frozen", False): if getattr(sys, "frozen", False):
# Su Linux AppImage usa il percorso del file .AppImage invece del mount /tmp/.mount_*
appimage_path = os.environ.get("APPIMAGE")
if sys.platform.startswith("linux") and appimage_path:
return [appimage_path, "--minimized"]
# Se compilato con PyInstaller # Se compilato con PyInstaller
return [sys.executable, "--minimized"] return [sys.executable, "--minimized"]
+187 -33
View File
@@ -1,27 +1,49 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Script per creare un eseguibile standalone (Windows .exe, Linux binary, macOS binary) Script multi-piattaforma per compilare Barcode Reader Server con PyInstaller (PySide6)
con PyInstaller in un singolo file, usando automaticamente un ambiente virtuale locale. e preparare l'AppDir per AppImage su Linux o bundle .app su macOS.
""" """
from __future__ import annotations
import argparse import argparse
import os import os
from pathlib import Path
import platform import platform
import re
import shutil
import subprocess import subprocess
import sys import sys
from pathlib import Path
from version import APP_BINARY_NAME, APP_ID, APP_NAME
SERVER_DIR = Path(__file__).resolve().parent SERVER_DIR = Path(__file__).resolve().parent
VERSION_FILE = SERVER_DIR / "version.py"
HIDDEN_IMPORTS = [ HIDDEN_IMPORTS = [
"pystray", "PySide6.QtCore",
"PySide6.QtGui",
"PySide6.QtWidgets",
"PIL", "PIL",
"PIL.ImageTk", "PIL.Image",
"PIL._tkinter_finder",
"qrcode", "qrcode",
"aiohttp", "aiohttp",
"pynput", "pynput",
"pyperclip",
]
EXCLUDED_MODULES = [
"tkinter",
"_tkinter",
"PyQt5",
"PyQt6",
"PySide6.QtQml",
"PySide6.QtQuick",
"PySide6.QtQuickWidgets",
"PySide6.QtWebEngineCore",
"PySide6.QtWebEngineWidgets",
"PySide6.Qt3DCore",
"PySide6.QtMultimedia",
] ]
@@ -69,7 +91,6 @@ def _can_import(python_exe: Path, module_name: str) -> bool:
def _ensure_venv_python(base_dir: Path) -> Path: def _ensure_venv_python(base_dir: Path) -> Path:
# Se gia' dentro un virtualenv attivo, usa quell'interprete senza annidare venv.
if sys.prefix != getattr(sys, "base_prefix", sys.prefix): if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return Path(sys.executable) return Path(sys.executable)
@@ -82,74 +103,207 @@ def _ensure_venv_python(base_dir: Path) -> Path:
def _ensure_build_dependencies(venv_python: Path) -> None: def _ensure_build_dependencies(venv_python: Path) -> None:
print("[+] Verifica dipendenze in requirements.txt...") print("[+] Verifica/installazione dipendenze da requirements.txt...")
subprocess.check_call( subprocess.check_call(
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r", "requirements.txt"] [str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r", "requirements.txt"]
) )
if not _can_import(venv_python, "PyInstaller"): if not _can_import(venv_python, "PyInstaller"):
print("[!] PyInstaller non installato nel venv. Installazione in corso...") print("[+] Installazione PyInstaller nel venv...")
subprocess.check_call( subprocess.check_call(
[str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "pyinstaller"] [str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "pyinstaller"]
) )
def _warn_if_tkinter_missing(venv_python: Path) -> None: def _stamp_version(version_override: str | None) -> str | None:
if _can_import(venv_python, "tkinter"): """Sostituisce temporaneamente APP_VERSION in version.py, restituendo il contenuto originale."""
return if not version_override:
return None
cleaned = version_override.strip().lstrip("vV")
if not cleaned:
return None
print("[!] ATTENZIONE: Tkinter non trovato in questo Python.") original = VERSION_FILE.read_text(encoding="utf-8")
print(" L'eseguibile compilato funzionera' solo in modalita' CLI (--cli).") updated, count = re.subn(
if platform.system() == "Linux": r'^APP_VERSION\s*=\s*["\'][^"\']*["\']',
print(" Per includere anche la GUI, installa tk (es. sudo pacman -S tk / sudo apt install python3-tk).") f'APP_VERSION = "{cleaned}"',
elif platform.system() == "Windows": original,
print(" Reinstalla Python assicurandoti di includere 'tcl/tk and IDLE'.") count=1,
flags=re.MULTILINE,
)
if count != 1:
raise RuntimeError("Impossibile aggiornare APP_VERSION in version.py")
VERSION_FILE.write_text(updated, encoding="utf-8")
print(f"[+] Versione di build impostata a: {cleaned}")
return original
def build(windowed: bool = False) -> None: def _build_linux_appdir(dist_bundle_dir: Path, appdir_path: Path) -> None:
"""Impacchetta la cartella --onedir di PyInstaller in una AppDir valida per AppImage."""
if appdir_path.exists():
shutil.rmtree(appdir_path)
usr_bin = appdir_path / "usr" / "bin"
shutil.copytree(dist_bundle_dir, usr_bin, symlinks=True)
icon_src = SERVER_DIR / "assets" / "icon.png"
if icon_src.exists():
shutil.copy2(icon_src, appdir_path / f"{APP_BINARY_NAME}.png")
shutil.copy2(icon_src, appdir_path / ".DirIcon")
hicolor = appdir_path / "usr" / "share" / "icons" / "hicolor" / "512x512" / "apps"
hicolor.mkdir(parents=True, exist_ok=True)
shutil.copy2(icon_src, hicolor / f"{APP_BINARY_NAME}.png")
apprun = appdir_path / "AppRun"
apprun.write_text(
"#!/bin/sh\n"
'HERE="$(dirname "$(readlink -f "${0}")")"\n'
f'exec "${{HERE}}/usr/bin/{APP_BINARY_NAME}" "$@"\n',
encoding="utf-8",
)
apprun.chmod(0o755)
desktop_file = appdir_path / f"{APP_BINARY_NAME}.desktop"
desktop_file.write_text(
"[Desktop Entry]\n"
"Version=1.0\n"
"Type=Application\n"
f"Name={APP_NAME}\n"
f"Exec={APP_BINARY_NAME} %u\n"
f"Icon={APP_BINARY_NAME}\n"
"Terminal=false\n"
"Categories=Utility;\n"
f"StartupWMClass={APP_ID}\n",
encoding="utf-8",
)
print(f"[OK] AppDir pronta per AppImage: {appdir_path}")
def build(
onefile: bool = False,
windowed: bool = True,
create_appdir: bool = False,
version_override: str | None = None,
) -> None:
_configure_console_encoding() _configure_console_encoding()
os.chdir(SERVER_DIR) os.chdir(SERVER_DIR)
print(f"[+] Compilazione eseguibile per {platform.system()}...") if create_appdir and onefile:
print("[i] --appdir richiede --onedir: disabilito --onefile per creare l'AppDir.")
onefile = False
system = platform.system()
print(f"[+] Compilazione {APP_BINARY_NAME} per {system}...")
venv_python = _ensure_venv_python(SERVER_DIR) venv_python = _ensure_venv_python(SERVER_DIR)
_ensure_build_dependencies(venv_python) _ensure_build_dependencies(venv_python)
_warn_if_tkinter_missing(venv_python)
original_version_text = _stamp_version(version_override)
try:
data_sep = ";" if system == "Windows" else ":"
cmd = [ cmd = [
str(venv_python), str(venv_python),
"-m", "-m",
"PyInstaller", "PyInstaller",
"--name=barcode_server", f"--name={APP_BINARY_NAME}",
"--onefile", "--onefile" if onefile else "--onedir",
"--clean", "--clean",
"--noconfirm", "--noconfirm",
"--collect-submodules=pynput",
] ]
if system == "Linux":
cmd.append("--collect-submodules=Xlib")
if windowed: if windowed:
cmd.append("--windowed") cmd.append("--windowed")
if system == "Darwin":
cmd.append(f"--osx-bundle-identifier={APP_ID}")
assets_dir = SERVER_DIR / "assets"
if assets_dir.exists():
cmd.append(f"--add-data={assets_dir}{data_sep}assets")
if system == "Windows" and (assets_dir / "icon.ico").exists():
cmd.append(f"--icon={assets_dir / 'icon.ico'}")
elif (assets_dir / "icon.png").exists():
cmd.append(f"--icon={assets_dir / 'icon.png'}")
for hidden_import in HIDDEN_IMPORTS: for hidden_import in HIDDEN_IMPORTS:
cmd.append(f"--hidden-import={hidden_import}") cmd.append(f"--hidden-import={hidden_import}")
for excluded in EXCLUDED_MODULES:
cmd.append(f"--exclude-module={excluded}")
cmd.append("main.py") cmd.append("main.py")
print(f"[+] Comando: {' '.join(cmd)}") print(f"[+] Comando: {' '.join(cmd)}")
subprocess.check_call(cmd) subprocess.check_call(cmd)
finally:
if original_version_text is not None:
VERSION_FILE.write_text(original_version_text, encoding="utf-8")
ext = ".exe" if platform.system() == "Windows" else "" dist_dir = SERVER_DIR / "dist"
output_bin = SERVER_DIR / "dist" / f"barcode_server{ext}" if system == "Darwin" and windowed and not onefile:
print("\n[OK] Compilazione completata con successo!") output_path = dist_dir / f"{APP_BINARY_NAME}.app"
print(f"[OK] Eseguibile creato: {output_bin}") elif onefile:
if platform.system() == "Windows" and not windowed: ext = ".exe" if system == "Windows" else ""
print("[i] Suggerimento: per un .exe Windows senza finestra CMD, usa: build_binary.py --windowed") output_path = dist_dir / f"{APP_BINARY_NAME}{ext}"
else:
output_path = dist_dir / APP_BINARY_NAME
print(f"\n[OK] Compilazione completata: {output_path}")
if create_appdir:
if system != "Linux":
print("[!] --appdir è supportato solo su Linux; passaggio saltato.")
else:
appdir_path = dist_dir / f"{APP_BINARY_NAME}.AppDir"
_build_linux_appdir(output_path, appdir_path)
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser(description="Compila barcode_server in un eseguibile standalone") parser = argparse.ArgumentParser(description="Compila Barcode Reader Server con PyInstaller")
parser.add_argument(
"--onefile",
action="store_true",
help="Genera un singolo eseguibile compresso invece della cartella --onedir",
)
parser.add_argument(
"--onedir",
action="store_true",
help="Genera la cartella standalone --onedir (default)",
)
parser.add_argument(
"--console",
action="store_true",
help="Mantieni la console di sistema aperta (disattiva --windowed)",
)
parser.add_argument( parser.add_argument(
"--windowed", "--windowed",
action="store_true", action="store_true",
help="Compila senza finestra terminale (GUI/Tray only; su --cli non mostrera' output su Windows)", help="Compila senza finestra terminale (default)",
) )
parser.add_argument(
"--appdir",
action="store_true",
help="Crea dist/BarcodeServer.AppDir pronta per appimagetool su Linux",
)
parser.add_argument(
"--version",
type=str,
default=None,
help="Sovrascrive APP_VERSION durante il build (es. 1.0.1)",
)
args = parser.parse_args() args = parser.parse_args()
build(windowed=args.windowed) windowed = False if args.console else True
onefile = bool(args.onefile and not args.onedir)
build(
onefile=onefile,
windowed=windowed,
create_appdir=args.appdir,
version_override=args.version,
)
if __name__ == "__main__": if __name__ == "__main__":
+13 -2
View File
@@ -8,17 +8,26 @@ from pathlib import Path
def _resolve_config_file() -> Path: def _resolve_config_file() -> Path:
"""Restituisce un percorso persistente e scrivibile per config.json (anche in binary PyInstaller).""" """Restituisce un percorso persistente e scrivibile per config.json (anche in binary PyInstaller)."""
if getattr(sys, "frozen", False): if getattr(sys, "frozen", False):
exe_dir = Path(sys.executable).resolve().parent exe_path = Path(sys.executable).resolve()
exe_dir = exe_path.parent
candidate = exe_dir / "config.json" candidate = exe_dir / "config.json"
is_appimage = sys.platform.startswith("linux") and bool(os.environ.get("APPIMAGE"))
is_mac_bundle = sys.platform == "darwin" and ".app/" in str(exe_path)
is_win_installer = sys.platform == "win32" and (exe_dir / "unins000.exe").exists()
# Mantieni portable solo per binari standalone non gestiti da AppImage/bundle/installer
if not is_appimage and not is_mac_bundle and not is_win_installer:
if candidate.exists(): if candidate.exists():
if os.access(candidate, os.W_OK): if os.access(candidate, os.W_OK):
return candidate return candidate
elif os.access(exe_dir, os.W_OK): elif os.access(exe_dir, os.W_OK):
return candidate return candidate
# Fallback nella directory configurazione utente se la cartella dell'eseguibile è read-only # Directory configurazione utente persistente tra gli aggiornamenti
if sys.platform == "win32": if sys.platform == "win32":
base_dir = Path(os.environ.get("APPDATA", Path.home())) / "BarcodeReaderServer" base_dir = Path(os.environ.get("APPDATA", Path.home())) / "BarcodeReaderServer"
elif sys.platform == "darwin":
base_dir = Path.home() / "Library" / "Application Support" / "BarcodeReaderServer"
else: else:
base_dir = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "barcode_reader_server" base_dir = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "barcode_reader_server"
return base_dir / "config.json" return base_dir / "config.json"
@@ -41,6 +50,8 @@ DEFAULT_CONFIG = {
"listening": True, # Whether the server actively processes and types barcodes "listening": True, # Whether the server actively processes and types barcodes
"minimize_to_tray": True, # Close/minimize button hides to system tray "minimize_to_tray": True, # Close/minimize button hides to system tray
"log_history": True, "log_history": True,
"check_updates": True, # Check for app updates on startup
"update_url": "", # Optional custom release metadata URL
} }
+833 -483
View File
File diff suppressed because it is too large. Load diff
+27 -18
View File
@@ -18,6 +18,7 @@ from datetime import datetime
from config import load_config from config import load_config
from server_core import BarcodeServerCore from server_core import BarcodeServerCore
from version import APP_ID, APP_NAME, APP_VERSION
def _configure_stdio() -> bool: def _configure_stdio() -> bool:
@@ -62,13 +63,10 @@ def _configure_stdio() -> bool:
def _show_fatal_gui_error(message: str) -> None: def _show_fatal_gui_error(message: str) -> None:
"""Mostra un avviso grafico se l'avvio windowless fallisce senza terminale visibile.""" """Mostra un avviso grafico se l'avvio windowless fallisce senza terminale visibile."""
try: try:
import tkinter as tk from PySide6.QtWidgets import QApplication, QMessageBox
from tkinter import messagebox
root = tk.Tk() app = QApplication.instance() or QApplication(sys.argv)
root.withdraw() QMessageBox.critical(None, APP_NAME, message)
messagebox.showerror("Barcode Reader PC Server", message)
root.destroy()
return return
except Exception: except Exception:
pass pass
@@ -77,7 +75,7 @@ def _show_fatal_gui_error(message: str) -> None:
try: try:
import ctypes import ctypes
ctypes.windll.user32.MessageBoxW(0, message, "Barcode Reader PC Server", 0x10) ctypes.windll.user32.MessageBoxW(0, message, APP_NAME, 0x10)
except Exception: except Exception:
pass pass
@@ -141,18 +139,33 @@ def run_cli_mode(server: BarcodeServerCore):
def run_gui_mode(server: BarcodeServerCore, start_minimized: bool): def run_gui_mode(server: BarcodeServerCore, start_minimized: bool):
"""Avvio con interfaccia grafica moderna e System Tray.""" """Avvio con interfaccia grafica moderna PySide6 (Qt6) e System Tray."""
import tkinter as tk from PySide6.QtWidgets import QApplication
from gui import ServerAppGUI from gui import ServerAppGUI
root = tk.Tk() app = QApplication.instance() or QApplication(sys.argv)
app = ServerAppGUI(root=root, server=server, start_minimized=start_minimized) app.setApplicationName(APP_NAME)
root.mainloop() app.setApplicationVersion(APP_VERSION)
app.setOrganizationName("Catelli Srl")
app.setDesktopFileName(APP_ID)
app.setQuitOnLastWindowClosed(False)
window = ServerAppGUI(server=server, start_minimized=start_minimized)
server.start_background()
exit_code = app.exec()
window.quit_app()
if exit_code:
sys.exit(exit_code)
def main(): def main():
is_windowless = _configure_stdio() is_windowless = _configure_stdio()
parser = argparse.ArgumentParser(description="Barcode Reader PC Server - Catelli Srl") parser = argparse.ArgumentParser(description="Barcode Reader PC Server - Catelli Srl")
parser.add_argument(
"--version",
action="version",
version=f"{APP_NAME} {APP_VERSION}",
)
parser.add_argument( parser.add_argument(
"--cli", "--headless", "--no-gui", "--cli", "--headless", "--no-gui",
action="store_true", action="store_true",
@@ -190,12 +203,8 @@ def main():
sys.exit(1) sys.exit(1)
print(f"\n[!] Avviso: Impossibile avviare interfaccia grafica ({e}). Fallback su modalità terminale.") print(f"\n[!] Avviso: Impossibile avviare interfaccia grafica ({e}). Fallback su modalità terminale.")
if "tkinter" in str(e).lower() or "libtk" in str(e).lower() or isinstance(e, ImportError): if isinstance(e, ImportError) or "PySide6" in str(e) or "Qt" in str(e):
print("\n[i] NOTA PER LINUX:") print(" Suggerimento: verifica l'installazione di PySide6-Essentials e delle librerie grafiche di sistema.")
print(" Per abilitare l'interfaccia grafica (GUI), installa Tkinter per la tua distribuzione:")
print(" • Arch / CachyOS / Manjaro: sudo pacman -S tk")
print(" • Ubuntu / Debian / Mint: sudo apt install python3-tk")
print(" • Fedora: sudo dnf install python3-tkinter\n")
run_cli_mode(server) run_cli_mode(server)
+1 -1
View File
@@ -2,5 +2,5 @@ aiohttp>=3.9.0
pynput>=1.7.6 pynput>=1.7.6
pyperclip>=1.8.2 pyperclip>=1.8.2
qrcode>=7.4.2 qrcode>=7.4.2
pystray>=0.19.5 PySide6-Essentials>=6.8.0
pillow>=10.0.0 pillow>=10.0.0
+4 -5
View File
@@ -50,7 +50,7 @@ if not exist "%VENV_PY%" (
) )
) )
"%VENV_PY%" -c "import aiohttp, pynput, pyperclip, qrcode, pystray, PIL" >nul 2>&1 "%VENV_PY%" -c "import aiohttp, pynput, pyperclip, qrcode, PySide6.QtWidgets, PIL" >nul 2>&1
if errorlevel 1 ( if errorlevel 1 (
echo [+] Installazione dipendenze da requirements.txt... echo [+] Installazione dipendenze da requirements.txt...
"%VENV_PY%" -m pip install --disable-pip-version-check -q -r requirements.txt "%VENV_PY%" -m pip install --disable-pip-version-check -q -r requirements.txt
@@ -72,13 +72,12 @@ for %%A in (%*) do (
) )
if "%FORCE_CONSOLE%"=="0" ( if "%FORCE_CONSOLE%"=="0" (
"%VENV_PY%" -c "import tkinter" >nul 2>&1 "%VENV_PY%" -c "from PySide6.QtWidgets import QApplication" >nul 2>&1
if errorlevel 1 ( if errorlevel 1 (
echo ------------------------------------------------------------------ echo ------------------------------------------------------------------
echo [!] ATTENZIONE: Tkinter non risulta installato in questo Python. echo [!] ATTENZIONE: PySide6 non risulta caricabile in questo ambiente.
echo L'applicazione fara' fallback sulla modalita' terminale ^(CLI^). echo L'applicazione fara' fallback sulla modalita' terminale ^(CLI^).
echo Per avere la GUI e la Tray Icon, reinstalla Python includendo echo Verifica l'installazione delle dipendenze da requirements.txt.
echo l'opzione "tcl/tk and IDLE".
echo ------------------------------------------------------------------ echo ------------------------------------------------------------------
set "FORCE_CONSOLE=1" set "FORCE_CONSOLE=1"
) )
+4 -11
View File
@@ -17,20 +17,13 @@ fi
source "$VENV_DIR/bin/activate" source "$VENV_DIR/bin/activate"
pip install --disable-pip-version-check -q -r requirements.txt pip install --disable-pip-version-check -q -r requirements.txt
# Verifica presenza di Tkinter se non è richiesta la modalità CLI esplicita # Verifica presenza di PySide6 (Qt6) se non è richiesta la modalità CLI esplicita
if [[ ! " $* " =~ " --cli " && ! " $* " =~ " --headless " && ! " $* " =~ " --no-gui " ]]; then if [[ ! " $* " =~ " --cli " && ! " $* " =~ " --headless " && ! " $* " =~ " --no-gui " ]]; then
if ! python3 -c "import tkinter" &>/dev/null; then if ! python3 -c "from PySide6.QtWidgets import QApplication" &>/dev/null; then
echo "------------------------------------------------------------------" echo "------------------------------------------------------------------"
echo " [!] ATTENZIONE: La libreria grafica Tkinter non risulta installata." echo " [!] ATTENZIONE: PySide6 (Qt6) non è utilizzabile su questo sistema."
echo " L'applicazione farà fallback sulla modalità terminale (CLI)." echo " L'applicazione farà fallback sulla modalità terminale (CLI)."
echo " Per avere la finestra grafica (GUI) e la Tray Icon, installala con:" echo " Su distribuzioni minimali verifica le librerie grafiche (es. libgl, libxkbcommon, libxcb)."
if command -v pacman &>/dev/null; then
echo " sudo pacman -S tk"
elif command -v apt-get &>/dev/null; then
echo " sudo apt install python3-tk"
elif command -v dnf &>/dev/null; then
echo " sudo dnf install python3-tkinter"
fi
echo "------------------------------------------------------------------" echo "------------------------------------------------------------------"
fi fi
fi fi
+235
View File
@@ -0,0 +1,235 @@
"""Test unitari e smoke test GUI/Tray Qt6 per Barcode Reader Server."""
from __future__ import annotations
import json
import os
import sys
import tempfile
import types
import unittest
import urllib.error
from pathlib import Path
from unittest.mock import patch
SERVER_DIR = Path(__file__).resolve().parent.parent
if str(SERVER_DIR) not in sys.path:
sys.path.insert(0, str(SERVER_DIR))
import autostart
import config
import updater
import version
from server_core import generate_qr_image
class _DummyServer:
"""Stub minimale compatibile con ServerAppGUI per test isolati senza socket di rete."""
def __init__(self):
self.local_ip = "192.168.1.50"
self.port = 8765
self.server_name = "TEST-PC"
self.is_listening = True
self.config = dict(config.DEFAULT_CONFIG)
self.config["check_updates"] = False
self.on_scan = None
self.on_devices_change = None
self.on_status_change = None
self.stopped = False
@property
def pairing_payload(self) -> str:
return json.dumps(
{"ip": self.local_ip, "port": self.port, "pin": self.config.get("pin", ""), "name": self.server_name}
)
@property
def web_url(self) -> str:
return f"http://{self.local_ip}:{self.port}"
def set_listening(self, listening: bool) -> None:
self.is_listening = listening
if self.on_status_change:
self.on_status_change(listening)
def update_settings(self, new_config: dict) -> None:
self.config.update(new_config)
self.server_name = self.config.get("server_name", self.server_name)
def stop(self) -> None:
self.stopped = True
class VersionAndResourceTests(unittest.TestCase):
def test_assets_exist_and_resolve(self):
self.assertTrue(version.get_resource_path("assets/icon.png").exists())
self.assertTrue(version.get_resource_path("assets/icon.ico").exists())
def test_frozen_meipass_resolution(self):
with tempfile.TemporaryDirectory() as tmp:
with patch.object(sys, "frozen", True, create=True), patch.object(
sys, "_MEIPASS", tmp, create=True
):
resolved = version.get_resource_path("assets/icon.png")
self.assertEqual(resolved, Path(tmp) / "assets/icon.png")
class ConfigAndAutostartTests(unittest.TestCase):
def test_resolve_config_for_appimage_uses_xdg_dir(self):
with tempfile.TemporaryDirectory() as tmp:
with patch.object(sys, "frozen", True, create=True), patch.object(
sys, "platform", "linux"
), patch.dict(
os.environ,
{"APPIMAGE": "/opt/BarcodeServer.AppImage", "XDG_CONFIG_HOME": tmp},
clear=False,
):
path = config._resolve_config_file()
self.assertEqual(path, Path(tmp) / "barcode_reader_server" / "config.json")
def test_autostart_prefers_appimage_env(self):
with patch.object(sys, "frozen", True, create=True), patch.object(
sys, "platform", "linux"
), patch.dict(os.environ, {"APPIMAGE": "/home/user/BarcodeServer.AppImage"}, clear=False):
self.assertEqual(
autostart.get_launch_command(),
["/home/user/BarcodeServer.AppImage", "--minimized"],
)
class UpdaterTests(unittest.TestCase):
def test_version_comparisons(self):
self.assertTrue(updater.is_newer_version("v1.0.1", "1.0.0"))
self.assertTrue(updater.is_newer_version("1.10.0", "1.2.0"))
self.assertFalse(updater.is_newer_version("v1.0.0", "1.0.0"))
self.assertFalse(updater.is_newer_version("0.9.9", "1.0.0"))
def test_parse_gitea_release_and_select_assets(self):
payload = {
"tag_name": "v1.2.0",
"name": "Release 1.2.0",
"body": "Migliorata UI Qt6",
"html_url": "https://gitea.catelli.it/brontomark/barcode_reader_pc/releases/tag/v1.2.0",
"assets": [
{"name": "BarcodeServerSetup.exe", "browser_download_url": "https://ex/win.exe", "size": 100},
{"name": "BarcodeServer-x86_64.AppImage", "browser_download_url": "https://ex/lin.AppImage", "size": 200},
{"name": "BarcodeServer-macOS.dmg", "browser_download_url": "https://ex/mac.dmg", "size": 300},
{"name": "BarcodeServer-macOS.zip", "browser_download_url": "https://ex/mac.zip", "size": 250},
],
}
release = updater.parse_release_payload(payload)
self.assertIsNotNone(release)
assert release is not None
self.assertEqual(release.version, "1.2.0")
self.assertEqual(updater.select_asset_for_platform(release.assets, "win32").name, "BarcodeServerSetup.exe")
self.assertEqual(
updater.select_asset_for_platform(release.assets, "linux").name, "BarcodeServer-x86_64.AppImage"
)
self.assertEqual(updater.select_asset_for_platform(release.assets, "darwin").name, "BarcodeServer-macOS.zip")
def test_parse_custom_flat_json_list(self):
payload = [
{
"version": "1.3.0",
"release_notes": "Aggiornamento DB",
"linux_url": "https://example.com/BarcodeServer-x86_64.AppImage",
}
]
release = updater.parse_release_payload(payload)
self.assertIsNotNone(release)
assert release is not None
self.assertEqual(release.version, "1.3.0")
self.assertEqual(release.assets[0].name, "BarcodeServer-x86_64.AppImage")
def test_check_for_updates_handles_200_and_404(self):
class _FakeResp:
def __init__(self, body: bytes):
self._body = body
def __enter__(self):
return self
def __exit__(self, *args):
return False
def read(self):
return self._body
mock_body = json.dumps({"tag_name": "v2.0.0", "assets": []}).encode("utf-8")
with patch("urllib.request.urlopen", return_value=_FakeResp(mock_body)):
res = updater.check_for_updates(current_version="1.0.0")
self.assertEqual(res.status, "update_available")
self.assertEqual(res.release.version, "2.0.0")
err_404 = urllib.error.HTTPError("https://example.com", 404, "Not Found", {}, None)
with patch("urllib.request.urlopen", side_effect=err_404):
res = updater.check_for_updates(current_version="1.0.0")
self.assertEqual(res.status, "unavailable")
class QtGuiAndTrayTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
cls.app = QApplication.instance() or QApplication([])
def test_qr_generation_and_gui_lifecycle(self):
from gui import ServerAppGUI, UpdateDialog
from tray import ServerTrayIcon, create_status_pixmap
qr_bytes = generate_qr_image('{"ip":"127.0.0.1"}').getvalue()
self.assertTrue(qr_bytes.startswith(b"\x89PNG"))
pix_on = create_status_pixmap(True, 64)
pix_off = create_status_pixmap(False, 64)
self.assertEqual(pix_on.width(), 64)
self.assertEqual(pix_off.width(), 64)
dummy = _DummyServer()
with patch("gui.load_config", return_value=dict(dummy.config)), patch(
"gui.is_autostart_enabled", return_value=False
):
gui = ServerAppGUI(server=dummy, start_minimized=False)
self.assertIn(version.APP_VERSION, gui.windowTitle())
# Simula callback ricezione scansione, cambio dispositivi e toggle pausa
gui._on_scan_received("8001234567890", "Pixel 8", True)
gui._on_devices_changed(["Pixel 8"])
gui.toggle_listening()
self.assertEqual(gui.table.rowCount(), 1)
self.assertIn("Pixel 8", gui.lbl_devices.text())
self.assertFalse(dummy.is_listening)
self.assertIn("IN PAUSA", gui.status_badge.text())
# Smoke test UpdateDialog
rel = updater.ReleaseInfo(
version="9.9.9",
tag_name="v9.9.9",
title="Test Release",
notes="Note test",
assets=[updater.ReleaseAsset("BarcodeServer-x86_64.AppImage", "https://ex/a.AppImage", 1024)],
)
dlg = UpdateDialog(rel, rel.assets[0], lambda: None, parent=gui)
self.assertIn("9.9.9", dlg.windowTitle())
dlg.close()
gui.quit_app()
self.assertTrue(dummy.stopped)
# Verifica anche creazione diretta tray icon helper
tray = ServerTrayIcon(
on_show_window=lambda: None,
on_toggle_listening=lambda: None,
on_open_web=lambda: None,
on_check_updates=lambda: None,
on_quit=lambda: None,
)
tray.stop()
if __name__ == "__main__":
unittest.main()
+153 -188
View File
@@ -1,226 +1,191 @@
import sys """System Tray nativa basata su PySide6 (Wayland/X11 StatusNotifierItem, Windows, macOS)."""
import threading
from __future__ import annotations
from typing import Callable, Optional from typing import Callable, Optional
# Su Windows e Linux usiamo pystray from PySide6.QtCore import QObject, Qt
# Su macOS usiamo direttamente Cocoa NSStatusBar per compatibilità perfetta con il main thread di Tkinter from PySide6.QtGui import QAction, QColor, QFont, QIcon, QPainter, QPainterPath, QPen, QPixmap
IS_MAC = sys.platform == "darwin" from PySide6.QtWidgets import QMenu, QSystemTrayIcon
if IS_MAC: from version import APP_NAME, APP_VERSION, get_resource_path
try:
from AppKit import NSApplication, NSStatusBar, NSVariableStatusItemLength, NSMenu, NSMenuItem
from Foundation import NSObject
class MacMenuHandler(NSObject):
on_show = None
on_toggle = None
on_web = None
on_quit = None
def onShow_(self, sender):
if MacMenuHandler.on_show:
MacMenuHandler.on_show()
def onToggle_(self, sender):
if MacMenuHandler.on_toggle:
MacMenuHandler.on_toggle()
def onWeb_(self, sender):
if MacMenuHandler.on_web:
MacMenuHandler.on_web()
def onQuit_(self, sender):
if MacMenuHandler.on_quit:
MacMenuHandler.on_quit()
except Exception as e:
print(f"Avviso: PyObjC non disponibile per macOS menu bar: {e}")
IS_MAC = False
class ServerTrayIcon: def create_status_pixmap(is_listening: bool, size: int = 64) -> QPixmap:
"""Genera un'icona nitida per la System Tray con indicatore stato attivo/pausa."""
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
accent = QColor("#10B981") if is_listening else QColor("#F59E0B")
margin = max(2, round(size * 0.06))
rect_size = size - 2 * margin
radius = max(4, round(size * 0.22))
path = QPainterPath()
path.addRoundedRect(margin, margin, rect_size, rect_size, radius, radius)
painter.fillPath(path, QColor("#0F172A"))
painter.setPen(QPen(accent, max(2, round(size * 0.06))))
painter.drawPath(path)
# Barre barcode verticali ad alto contrasto
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#F8FAFC"))
top = round(size * 0.27)
height = round(size * 0.46)
bars = [
(0.20, 0.07),
(0.32, 0.05),
(0.42, 0.09),
(0.56, 0.05),
(0.66, 0.09),
]
for x_ratio, w_ratio in bars:
bx = round(size * x_ratio)
bw = max(2, round(size * w_ratio))
painter.drawRoundedRect(bx, top, bw, height, 1.5, 1.5)
# Linea laser di scansione / stato
painter.setBrush(accent)
laser_y = round(size * 0.48)
laser_h = max(3, round(size * 0.07))
painter.drawRoundedRect(round(size * 0.14), laser_y, round(size * 0.72), laser_h, 2, 2)
painter.end()
return pixmap
def load_app_icon() -> QIcon:
"""Carica l'icona principale dell'app da assets/icon.png (con fallback dinamico)."""
icon_file = get_resource_path("assets/icon.png")
if icon_file.exists():
icon = QIcon(str(icon_file))
if not icon.isNull():
return icon
return QIcon(create_status_pixmap(True, 128))
class ServerTrayIcon(QObject):
"""Gestisce l'icona e il menu contestuale nella System Tray tramite Qt6."""
def __init__( def __init__(
self, self,
on_show_window: Callable[[], None], on_show_window: Callable[[], None],
on_toggle_listening: Callable[[], None], on_toggle_listening: Callable[[], None],
on_open_web: Callable[[], None], on_open_web: Callable[[], None],
on_check_updates: Callable[[], None],
on_quit: Callable[[], None], on_quit: Callable[[], None],
is_listening: bool = True, is_listening: bool = True,
parent: Optional[QObject] = None,
): ):
super().__init__(parent)
self.on_show_window = on_show_window self.on_show_window = on_show_window
self.on_toggle_listening = on_toggle_listening self.on_toggle_listening = on_toggle_listening
self.on_open_web = on_open_web self.on_open_web = on_open_web
self.on_check_updates = on_check_updates
self.on_quit = on_quit self.on_quit = on_quit
self.is_listening = is_listening self.is_listening = is_listening
# macOS specific self._tray: Optional[QSystemTrayIcon] = None
self._mac_status_item = None self._menu: Optional[QMenu] = None
self._mac_handler = None self._action_status: Optional[QAction] = None
self._mac_status_menu_item = None self._action_show: Optional[QAction] = None
self._mac_toggle_menu_item = None self._action_toggle: Optional[QAction] = None
self._action_web: Optional[QAction] = None
self._action_updates: Optional[QAction] = None
self._action_quit: Optional[QAction] = None
# Windows / Linux specific @staticmethod
self._pystray_icon = None def is_available() -> bool:
self._thread: Optional[threading.Thread] = None """Verifica se il desktop corrente espone una System Tray attiva."""
return QSystemTrayIcon.isSystemTrayAvailable()
def start(self): def start(self) -> bool:
"""Avvia la System Tray Icon in base alla piattaforma.""" """Inizializza e mostra l'icona nella System Tray. Restituisce False se assente."""
if IS_MAC: if not self.is_available():
self._start_mac() return False
else:
self._start_pystray()
def _start_mac(self): if self._tray is None:
try: self._tray = QSystemTrayIcon(self)
status_bar = NSStatusBar.systemStatusBar() self._build_menu()
self._mac_status_item = status_bar.statusItemWithLength_(NSVariableStatusItemLength) self._tray.setContextMenu(self._menu)
self._tray.activated.connect(self._on_activated)
MacMenuHandler.on_show = self.on_show_window self.update_status(self.is_listening)
MacMenuHandler.on_toggle = self.on_toggle_listening self._tray.show()
MacMenuHandler.on_web = self.on_open_web return self._tray.isVisible()
MacMenuHandler.on_quit = self.on_quit
self._mac_handler = MacMenuHandler.alloc().init()
menu = NSMenu.alloc().init() def _build_menu(self) -> None:
self._menu = QMenu()
item_show = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( self._action_status = QAction(self._menu)
"Mostra Server Barcode", "onShow:", "" self._action_status.setEnabled(False)
) self._menu.addAction(self._action_status)
item_show.setTarget_(self._mac_handler)
menu.addItem_(item_show)
menu.addItem_(NSMenuItem.separatorItem()) self._action_show = QAction("Mostra Finestra", self._menu)
show_font = QFont(self._action_show.font())
show_font.setBold(True)
self._action_show.setFont(show_font)
self._action_show.triggered.connect(self.on_show_window)
self._menu.addAction(self._action_show)
status_text = "● Stato: IN ASCOLTO" if self.is_listening else "○ Stato: IN PAUSA" self._menu.addSeparator()
self._mac_status_menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
status_text, "", ""
)
self._mac_status_menu_item.setEnabled_(False)
menu.addItem_(self._mac_status_menu_item)
toggle_text = "Metti in Pausa Ricezione" if self.is_listening else "Riprendi Ricezione Codici" self._action_toggle = QAction(self._menu)
self._mac_toggle_menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( self._action_toggle.triggered.connect(self.on_toggle_listening)
toggle_text, "onToggle:", "" self._menu.addAction(self._action_toggle)
)
self._mac_toggle_menu_item.setTarget_(self._mac_handler)
menu.addItem_(self._mac_toggle_menu_item)
item_web = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( self._action_web = QAction("Apri Dashboard Web", self._menu)
"Apri Dashboard Web", "onWeb:", "" self._action_web.triggered.connect(self.on_open_web)
) self._menu.addAction(self._action_web)
item_web.setTarget_(self._mac_handler)
menu.addItem_(item_web)
menu.addItem_(NSMenuItem.separatorItem()) self._action_updates = QAction("Controlla Aggiornamenti...", self._menu)
self._action_updates.triggered.connect(self.on_check_updates)
self._menu.addAction(self._action_updates)
item_quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( self._menu.addSeparator()
"Esci Definitivamente", "onQuit:", ""
)
item_quit.setTarget_(self._mac_handler)
menu.addItem_(item_quit)
self._mac_status_item.setMenu_(menu) self._action_quit = QAction("Esci", self._menu)
self._update_mac_title() self._action_quit.triggered.connect(self.on_quit)
self._menu.addAction(self._action_quit)
except Exception as e: def _on_activated(self, reason: QSystemTrayIcon.ActivationReason) -> None:
print(f"Avviso: Impossibile creare status item su macOS: {e}") if reason in (
QSystemTrayIcon.ActivationReason.Trigger,
QSystemTrayIcon.ActivationReason.DoubleClick,
):
self.on_show_window()
def _update_mac_title(self): def update_status(self, is_listening: bool) -> None:
if self._mac_status_item: """Aggiorna icona, tooltip e testi menu in base allo stato di ascolto."""
title = "● 📦 Barcode" if self.is_listening else "○ 📦 Barcode"
self._mac_status_item.button().setTitle_(title)
def _start_pystray(self):
try:
from PIL import Image, ImageDraw
import pystray
from pystray import MenuItem as item, Menu
def create_image(listening: bool):
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.rounded_rectangle((4, 4, 60, 60), radius=12, fill="#0F172A", outline="#334155", width=2)
bar_color = "#38BDF8"
for x, w in [(14, 2), (19, 4), (26, 2), (31, 5), (39, 2), (44, 4)]:
draw.rectangle((x, 18, x + w - 1, 46), fill=bar_color)
dot_color = "#10B981" if listening else "#F59E0B"
draw.ellipse((42, 42, 58, 58), fill=dot_color, outline="#0F172A", width=2)
return img
def build_menu():
status_label = "● Stato: IN ASCOLTO" if self.is_listening else "○ Stato: IN PAUSA"
toggle_label = "Metti in Pausa Ricezione" if self.is_listening else "Riprendi Ricezione Codici"
return Menu(
item("Mostra Server Barcode", lambda icon, item: self.on_show_window(), default=True),
Menu.SEPARATOR,
item(status_label, lambda icon, item: None, enabled=False),
item(toggle_label, lambda icon, item: self.on_toggle_listening()),
item("Apri Dashboard Web", lambda icon, item: self.on_open_web()),
Menu.SEPARATOR,
item("Esci Definitivamente", lambda icon, item: self.on_quit()),
)
image = create_image(self.is_listening)
self._pystray_icon = pystray.Icon(
name="barcode_reader_server",
icon=image,
title="Barcode Reader Server",
menu=build_menu(),
)
def run():
try:
self._pystray_icon.run()
except Exception as e:
print(f"Avviso pystray: {e}")
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
except Exception as e:
print(f"Avviso: Impossibile avviare pystray: {e}")
def update_status(self, is_listening: bool):
"""Aggiorna lo stato visivo della tray icon."""
self.is_listening = is_listening self.is_listening = is_listening
if self._tray is None:
return
if IS_MAC and self._mac_status_item: icon = QIcon()
try: icon.addPixmap(create_status_pixmap(is_listening, 32))
self._update_mac_title() icon.addPixmap(create_status_pixmap(is_listening, 64))
if self._mac_status_menu_item: self._tray.setIcon(icon)
status_text = "● Stato: IN ASCOLTO" if is_listening else "○ Stato: IN PAUSA"
self._mac_status_menu_item.setTitle_(status_text)
if self._mac_toggle_menu_item:
toggle_text = "Metti in Pausa Ricezione" if is_listening else "Riprendi Ricezione Codici"
self._mac_toggle_menu_item.setTitle_(toggle_text)
except Exception:
pass
elif self._pystray_icon:
try:
from PIL import Image, ImageDraw
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.rounded_rectangle((4, 4, 60, 60), radius=12, fill="#0F172A", outline="#334155", width=2)
for x, w in [(14, 2), (19, 4), (26, 2), (31, 5), (39, 2), (44, 4)]:
draw.rectangle((x, 18, x + w - 1, 46), fill="#38BDF8")
dot_color = "#10B981" if is_listening else "#F59E0B"
draw.ellipse((42, 42, 58, 58), fill=dot_color, outline="#0F172A", width=2)
self._pystray_icon.icon = img status_text = "IN ASCOLTO" if is_listening else "IN PAUSA"
self._pystray_icon.title = f"Barcode Reader Server ({'In ascolto' if is_listening else 'In pausa'})" self._tray.setToolTip(f"{APP_NAME} v{APP_VERSION} — {status_text}")
except Exception:
pass
def stop(self): if self._action_status is not None:
"""Rimuove l'icona della tray.""" marker = "●" if is_listening else "○"
if IS_MAC and self._mac_status_item: self._action_status.setText(f"{marker} {status_text} (v{APP_VERSION})")
try: if self._action_toggle is not None:
NSStatusBar.systemStatusBar().removeStatusItem_(self._mac_status_item) self._action_toggle.setText("Metti in Pausa" if is_listening else "Riprendi Ascolto")
self._mac_status_item = None
except Exception: def show_message(self, title: str, message: str, duration_ms: int = 5000) -> None:
pass """Mostra una notifica desktop nativa tramite la System Tray."""
elif self._pystray_icon: if self._tray and self._tray.isVisible():
try: self._tray.showMessage(title, message, QSystemTrayIcon.MessageIcon.Information, duration_ms)
self._pystray_icon.stop()
self._pystray_icon = None def stop(self) -> None:
except Exception: """Nasconde e rimuove l'icona della tray."""
pass if self._tray is not None:
self._tray.hide()
self._tray.deleteLater()
self._tray = None
+455
View File
@@ -0,0 +1,455 @@
"""Controllo versioni e auto-aggiornamento cross-platform via Gitea Releases (o JSON custom)."""
from __future__ import annotations
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
from version import APP_NAME, APP_VERSION, RELEASES_PAGE_URL, UPDATE_RELEASES_API
@dataclass
class ReleaseAsset:
"""Singolo file eseguibile o installer allegato a una release."""
name: str
download_url: str
size: int = 0
@dataclass
class ReleaseInfo:
"""Metadati di una release disponibile."""
version: str
tag_name: str
title: str
notes: str = ""
html_url: str = RELEASES_PAGE_URL
assets: list[ReleaseAsset] = field(default_factory=list)
@dataclass
class UpdateCheckResult:
"""Esito della verifica aggiornamenti."""
status: str # "up_to_date", "update_available", "unavailable", "error"
current_version: str
message: str = ""
release: Optional[ReleaseInfo] = None
selected_asset: Optional[ReleaseAsset] = None
def normalize_version_string(version: str) -> str:
"""Rimuove prefisso 'v' ed eventuali spazi dalla stringa versione."""
return (version or "").strip().lstrip("vV")
def parse_version_tuple(version: str) -> tuple[int, ...]:
"""Converte una stringa semver (es. 'v1.2.3-rc1') in tupla numerica confrontabile."""
cleaned = normalize_version_string(version)
if not cleaned:
return (0,)
core = re.split(r"[-+]", cleaned, maxsplit=1)[0]
parts: list[int] = []
for segment in core.split("."):
match = re.match(r"(\d+)", segment.strip())
parts.append(int(match.group(1)) if match else 0)
return tuple(parts) or (0,)
def is_newer_version(remote_version: str, current_version: str) -> bool:
"""Restituisce True se remote_version è strettamente maggiore di current_version."""
remote = list(parse_version_tuple(remote_version))
current = list(parse_version_tuple(current_version))
max_len = max(len(remote), len(current))
remote.extend([0] * (max_len - len(remote)))
current.extend([0] * (max_len - len(current)))
return tuple(remote) > tuple(current)
def _extract_assets_from_payload(data: dict) -> list[ReleaseAsset]:
"""Estrae la lista degli asset sia da schema Gitea/GitHub sia da JSON custom."""
assets: list[ReleaseAsset] = []
raw_assets = data.get("assets")
if isinstance(raw_assets, list):
for item in raw_assets:
if not isinstance(item, dict):
continue
url = item.get("browser_download_url") or item.get("download_url") or item.get("url") or ""
name = item.get("name") or (url.rsplit("/", 1)[-1] if url else "")
size = int(item.get("size") or 0)
if name and url:
assets.append(ReleaseAsset(name=str(name), download_url=str(url), size=size))
return assets
# Supporto opzionale a campi flat (es. endpoint DB stile Flux app_config)
for key, fallback_name in (
("windows_url", "BarcodeServerSetup.exe"),
("linux_url", "BarcodeServer-x86_64.AppImage"),
("macos_url", "BarcodeServer-macOS.zip"),
("mac_url", "BarcodeServer-macOS.zip"),
("download_url", "update-package"),
):
url = data.get(key)
if isinstance(url, str) and url.strip():
inferred_name = url.rstrip("/").rsplit("/", 1)[-1] or fallback_name
assets.append(ReleaseAsset(name=inferred_name, download_url=url.strip()))
return assets
def parse_release_payload(payload: object) -> Optional[ReleaseInfo]:
"""Interpreta il JSON restituito dall'endpoint aggiornamenti."""
if isinstance(payload, list):
payload = payload[0] if payload else None
if not isinstance(payload, dict):
return None
tag_or_version = (
payload.get("tag_name")
or payload.get("version")
or payload.get("latest_version")
or ""
)
version = normalize_version_string(str(tag_or_version))
if not version:
return None
title = str(payload.get("name") or payload.get("title") or f"{APP_NAME} v{version}")
notes = str(payload.get("body") or payload.get("release_notes") or payload.get("notes") or "")
html_url = str(payload.get("html_url") or payload.get("release_url") or RELEASES_PAGE_URL)
assets = _extract_assets_from_payload(payload)
return ReleaseInfo(
version=version,
tag_name=str(tag_or_version),
title=title,
notes=notes,
html_url=html_url,
assets=assets,
)
def select_asset_for_platform(
assets: list[ReleaseAsset], platform_name: Optional[str] = None
) -> Optional[ReleaseAsset]:
"""Seleziona l'installer o pacchetto più adatto per il sistema operativo corrente."""
if not assets:
return None
plat = platform_name or sys.platform
lower_pairs = [(asset.name.lower(), asset) for asset in assets]
if plat == "win32":
for priority in (
lambda n: n.endswith(".exe") and "setup" in n,
lambda n: n.endswith(".exe"),
lambda n: n.endswith(".msi"),
lambda n: n.endswith(".zip") and "win" in n,
):
for name, asset in lower_pairs:
if priority(name):
return asset
elif plat.startswith("linux"):
for priority in (
lambda n: n.endswith(".appimage"),
lambda n: "linux" in n and (n.endswith(".tar.gz") or n.endswith(".zip")),
):
for name, asset in lower_pairs:
if priority(name):
return asset
elif plat == "darwin":
for priority in (
lambda n: n.endswith(".zip") and ("mac" in n or "darwin" in n or ".app" in n),
lambda n: n.endswith(".dmg"),
lambda n: n.endswith(".zip"),
):
for name, asset in lower_pairs:
if priority(name):
return asset
return None
def can_self_update() -> tuple[bool, str]:
"""Indica se l'app può auto-aggiornarsi direttamente sul sistema corrente."""
if not getattr(sys, "frozen", False):
return False, "Avviata da sorgente Python: aggiornamento automatico disponibile solo nei pacchetti rilasciati."
if sys.platform == "win32":
return True, ""
if sys.platform.startswith("linux"):
appimage_path = os.environ.get("APPIMAGE")
if not appimage_path:
return False, "Eseguibile Linux non avviato tramite AppImage: scarica manualmente la nuova release."
target = Path(appimage_path)
if target.exists() and not os.access(target, os.W_OK):
return False, f"Permessi insufficienti per sostituire {target}."
if not target.exists() and not os.access(target.parent, os.W_OK):
return False, f"Cartella {target.parent} non scrivibile."
return True, ""
if sys.platform == "darwin":
bundle = _find_macos_app_bundle()
if not bundle:
return False, "Bundle .app non rilevato: scarica il pacchetto .dmg dalla pagina release."
if not os.access(bundle.parent, os.W_OK):
return False, f"Cartella {bundle.parent} non scrivibile: sostituisci manualmente l'app."
return True, ""
return False, "Piattaforma non supportata per l'auto-aggiornamento."
def _find_macos_app_bundle() -> Optional[Path]:
"""Risale dal percorso sys.executable al bundle '.app' su macOS."""
exe_path = Path(sys.executable).resolve()
for parent in exe_path.parents:
if parent.suffix == ".app":
return parent
return None
def check_for_updates(
current_version: str = APP_VERSION,
update_url: str = "",
timeout: float = 8.0,
) -> UpdateCheckResult:
"""Interroga l'API delle release e confronta la versione remota con quella locale."""
target_url = (update_url or "").strip() or UPDATE_RELEASES_API
req = urllib.request.Request(
target_url,
headers={
"Accept": "application/json",
"User-Agent": f"BarcodeReaderServer/{current_version}",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", errors="replace")
payload = json.loads(raw)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return UpdateCheckResult(
status="unavailable",
current_version=current_version,
message="Nessuna release pubblica trovata sul server (HTTP 404).",
)
return UpdateCheckResult(
status="error",
current_version=current_version,
message=f"Errore HTTP {exc.code} durante il controllo aggiornamenti.",
)
except Exception as exc:
return UpdateCheckResult(
status="error",
current_version=current_version,
message=f"Impossibile contattare il server aggiornamenti: {exc}",
)
release = parse_release_payload(payload)
if not release:
return UpdateCheckResult(
status="unavailable",
current_version=current_version,
message="Risposta release non valida o nessuna versione pubblicata.",
)
if not is_newer_version(release.version, current_version):
return UpdateCheckResult(
status="up_to_date",
current_version=current_version,
message=f"L'applicazione è già aggiornata (v{current_version}).",
release=release,
)
asset = select_asset_for_platform(release.assets)
return UpdateCheckResult(
status="update_available",
current_version=current_version,
message=f"Disponibile la nuova versione v{release.version} (attuale v{current_version}).",
release=release,
selected_asset=asset,
)
def download_asset(
asset: ReleaseAsset,
progress_callback: Optional[Callable[[int, int], None]] = None,
timeout: float = 30.0,
) -> Path:
"""Scarica l'asset della release in una directory temporanea e ne restituisce il Path."""
download_dir = Path(tempfile.mkdtemp(prefix="barcode_server_update_"))
safe_name = Path(asset.name).name or "update_package"
dest_path = download_dir / safe_name
req = urllib.request.Request(
asset.download_url,
headers={"User-Agent": f"BarcodeReaderServer/{APP_VERSION}"},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
total = int(resp.headers.get("Content-Length") or asset.size or 0)
downloaded = 0
with open(dest_path, "wb") as out:
while True:
chunk = resp.read(65536)
if not chunk:
break
out.write(chunk)
downloaded += len(chunk)
if progress_callback:
progress_callback(downloaded, total)
return dest_path
def apply_downloaded_update(downloaded_path: Path) -> None:
"""Avvia il processo di sostituzione e riavvio dell'applicazione."""
if sys.platform == "win32":
_apply_windows_update(downloaded_path)
elif sys.platform.startswith("linux"):
_apply_linux_appimage_update(downloaded_path)
elif sys.platform == "darwin":
_apply_macos_update(downloaded_path)
else:
raise RuntimeError(f"Auto-aggiornamento non supportato su {sys.platform}")
def _apply_windows_update(installer_path: Path) -> None:
"""Avvia un batch nascosto che attende l'uscita, installa silently e riavvia l'app."""
pid = os.getpid()
current_exe = str(Path(sys.executable).resolve())
helper_bat = installer_path.parent / "apply_update.bat"
if installer_path.suffix.lower() == ".exe":
install_cmd = f'"{installer_path}" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS'
elif installer_path.suffix.lower() == ".msi":
install_cmd = f'msiexec /i "{installer_path}" /passive /norestart'
else:
os.startfile(str(installer_path)) # type: ignore[attr-defined]
return
script_content = (
"@echo off\r\n"
":wait_pid\r\n"
f'tasklist /FI "PID eq {pid}" 2>nul | find "{pid}" >nul\r\n'
"if not errorlevel 1 (\r\n"
" ping 127.0.0.1 -n 2 >nul\r\n"
" goto wait_pid\r\n"
")\r\n"
f"{install_cmd}\r\n"
"if %ERRORLEVEL% EQU 0 (\r\n"
f' start "" "{current_exe}"\r\n'
")\r\n"
)
helper_bat.write_text(script_content, encoding="utf-8")
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) | getattr(
subprocess, "DETACHED_PROCESS", 0
)
subprocess.Popen(
["cmd.exe", "/c", str(helper_bat)],
close_fds=True,
creationflags=creationflags,
)
def _apply_linux_appimage_update(new_appimage: Path) -> None:
"""Sostituisce l'AppImage corrente dopo la chiusura e riavvia il processo."""
appimage_env = os.environ.get("APPIMAGE")
if not appimage_env:
raise RuntimeError("Variabile APPIMAGE non presente.")
target_appimage = Path(appimage_env).resolve()
new_appimage.chmod(0o755)
staged = target_appimage.with_suffix(".AppImage.new")
shutil.copy2(new_appimage, staged)
staged.chmod(0o755)
pid = os.getpid()
helper_sh = new_appimage.parent / "apply_update.sh"
target_q = shlex.quote(str(target_appimage))
staged_q = shlex.quote(str(staged))
script_content = (
"#!/bin/sh\n"
f"while kill -0 {pid} 2>/dev/null; do sleep 0.2; done\n"
f"mv -f {staged_q} {target_q}\n"
f"chmod +x {target_q}\n"
f"exec {target_q} >/dev/null 2>&1 &\n"
)
helper_sh.write_text(script_content, encoding="utf-8")
helper_sh.chmod(0o755)
clean_env = os.environ.copy()
for var in ("LD_LIBRARY_PATH", "QT_PLUGIN_PATH", "QML2_IMPORT_PATH", "APPIMAGE", "APPDIR", "OWD"):
clean_env.pop(var, None)
subprocess.Popen(
["/bin/sh", str(helper_sh)],
start_new_session=True,
close_fds=True,
env=clean_env,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _apply_macos_update(package_path: Path) -> None:
"""Aggiorna il bundle .app da archivio .zip (o apre il .dmg se necessario)."""
bundle = _find_macos_app_bundle()
if not bundle:
subprocess.Popen(["open", str(package_path)], start_new_session=True)
return
suffix = package_path.suffix.lower()
if suffix == ".dmg":
subprocess.Popen(["open", str(package_path)], start_new_session=True)
return
if suffix != ".zip":
subprocess.Popen(["open", str(package_path)], start_new_session=True)
return
pid = os.getpid()
extract_dir = package_path.parent / "extracted"
extract_dir.mkdir(exist_ok=True)
helper_sh = package_path.parent / "apply_update.sh"
script_content = (
"#!/bin/sh\n"
f"while kill -0 {pid} 2>/dev/null; do sleep 0.2; done\n"
f"ditto -xk {shlex.quote(str(package_path))} {shlex.quote(str(extract_dir))}\n"
f'NEW_APP=$(find {shlex.quote(str(extract_dir))} -maxdepth 3 -name "*.app" | head -n 1)\n'
'if [ -n "$NEW_APP" ]; then\n'
f" rm -rf {shlex.quote(str(bundle))}\n"
f' mv "$NEW_APP" {shlex.quote(str(bundle))}\n'
f" open -n {shlex.quote(str(bundle))}\n"
"fi\n"
)
helper_sh.write_text(script_content, encoding="utf-8")
helper_sh.chmod(0o755)
subprocess.Popen(
["/bin/sh", str(helper_sh)],
start_new_session=True,
close_fds=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
+25
View File
@@ -0,0 +1,25 @@
"""Metadati versione, URL rilasci e risoluzione risorse dell'applicazione."""
import sys
from pathlib import Path
APP_NAME = "Barcode Reader Server"
APP_BINARY_NAME = "BarcodeServer"
APP_ID = "com.catellisrl.barcodereader"
APP_PUBLISHER = "Catelli Srl"
APP_VERSION = "1.0.0"
GITEA_BASE_URL = "https://gitea.catelli.it"
GITEA_REPO = "brontomark/barcode_reader_pc"
UPDATE_RELEASES_API = f"{GITEA_BASE_URL}/api/v1/repos/{GITEA_REPO}/releases/latest"
RELEASES_PAGE_URL = f"{GITEA_BASE_URL}/{GITEA_REPO}/releases"
def get_resource_path(relative_path: str) -> Path:
"""Risolve il percorso di una risorsa sia da sorgente che dentro bundle PyInstaller."""
if getattr(sys, "frozen", False):
base_dir = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))
else:
base_dir = Path(__file__).resolve().parent
return base_dir / relative_path
+48
View File
@@ -0,0 +1,48 @@
#ifndef MyAppVersion
#define MyAppVersion "1.0.0"
#endif
#define MyAppName "Barcode Reader Server"
#define MyAppPublisher "Catelli Srl"
#define MyAppURL "https://catellisrl.com"
#define MyAppExeName "BarcodeServer.exe"
[Setup]
AppId={{7D5F24B1-8A4C-4F6D-9B3C-2E8A901C4D11}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={autopf}\{#MyAppName}
DisableProgramGroupPage=yes
OutputDir=dist\installer
OutputBaseFilename=BarcodeServerSetup
SetupIconFile=assets\icon.ico
UninstallDisplayIcon={app}\{#MyAppExeName}
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
CloseApplications=yes
RestartApplications=no
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
[Languages]
Name: "italian"; MessagesFile: "compiler:Languages\Italian.isl"
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
[Files]
Source: "dist\BarcodeServer\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent