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
21 changes: 21 additions & 0 deletions manatools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# vim: set fileencoding=utf-8 :
# vim: set et ts=4 sw=4:

import os
import sys

# gettext picks the message language from LANGUAGE/LC_ALL/LC_MESSAGES/LANG,
# which Windows never sets, so every translation would fall back to English.
# Seed LANGUAGE from the user's UI language (e.g. "it_IT"), unless the user
# already chose one.
if sys.platform == 'win32' and not any(
os.environ.get(v) for v in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG')):
try:
import ctypes
import locale
_lang = locale.windows_locale.get(
ctypes.windll.kernel32.GetUserDefaultUILanguage())
if _lang:
os.environ['LANGUAGE'] = _lang
except Exception:
pass
5 changes: 5 additions & 0 deletions manatools/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import argparse
import gettext
import os
import sys

class AppArgs :
'''
Expand All @@ -19,6 +20,10 @@ class AppArgs :
'''
def __init__(self, command, localedir='/usr/share/locale', strings_domain='python-manatools') :

# Windows has no /usr/share/locale; None selects gettext's default,
# <sys.base_prefix>/share/locale
if sys.platform == 'win32' and localedir == '/usr/share/locale':
localedir = None
translator = gettext.translation(strings_domain, localedir=localedir, fallback=True)
tr = translator.gettext

Expand Down
16 changes: 16 additions & 0 deletions manatools/aui/backends/curses/dialogcurses.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
_mod_logger.addHandler(_h)
_mod_logger.setLevel(logging.INFO)

# Enter arrives as '\r' or KEY_ENTER on some terminals and as PADENTER from
# the numeric keypad under PDCurses (windows-curses); widgets only handle '\n'.
_ENTER_KEYS = {ord('\r'), curses.KEY_ENTER}
if hasattr(curses, 'PADENTER'):
_ENTER_KEYS.add(curses.PADENTER)

class YDialogCurses(YSingleChildContainerWidget):
"""Ncurses dialog container with focus, help, and default button support."""
_open_dialogs = []
Expand Down Expand Up @@ -633,6 +639,9 @@ def waitForEvent(self, timeout_millisec=0):
break
time.sleep(0.01)
continue

if key in _ENTER_KEYS:
key = ord('\n')

#any key received, clear help overlay if active
self._help_overlay_text = None
Expand Down Expand Up @@ -663,6 +672,13 @@ def waitForEvent(self, timeout_millisec=0):
self._post_event(YCancelEvent())
break
elif key == curses.KEY_RESIZE:
# PDCurses (Windows) only picks up the new console size
# after resize_term(0, 0)
if sys.platform == 'win32':
try:
curses.resize_term(0, 0)
except Exception:
pass
# Debounce resize; do not redraw immediately to avoid flicker
try:
new_h, new_w = ui._stdscr.getmaxyx()
Expand Down
20 changes: 19 additions & 1 deletion manatools/aui/backends/qt/commonqt.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,29 @@
'''
from PySide6 import QtWidgets, QtGui, QtCore
import os
import sys
import logging
from ...yui_common import *


__all__ = ["_resolve_icon", "_install_context_menu_filter", "_open_context_menu"]
__all__ = ["_resolve_icon", "_setup_icon_theme", "_install_context_menu_filter", "_open_context_menu"]

def _setup_icon_theme():
"""Make the icon themes under icon_theme_dirs() visible to QIcon.fromTheme.

Windows has no system icon theme, so there the first of breeze, Adwaita
and hicolor found in the search paths is selected.
"""
paths = list(QtGui.QIcon.themeSearchPaths())
extra = [d for d in icon_theme_dirs() if d not in paths]
if extra:
paths += extra
QtGui.QIcon.setThemeSearchPaths(paths)
if sys.platform == 'win32':
for theme in ('breeze', 'Adwaita', 'hicolor'):
if any(os.path.isfile(os.path.join(d, theme, 'index.theme')) for d in paths):
QtGui.QIcon.setThemeName(theme)
break

def _resolve_icon(icon_name):
"""Resolve an icon name to a QtGui.QIcon or None.
Expand Down
30 changes: 14 additions & 16 deletions manatools/aui/backends/qt/dialogqt.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import os
import logging
import signal
import fcntl
import socket

class YDialogQt(YSingleChildContainerWidget):
"""Qt6 main window wrapper that manages dialog state and default buttons."""
Expand Down Expand Up @@ -568,22 +568,19 @@ def on_timeout():
def _setup_sigint_notifier(self, loop):
"""Install a wakeup fd and QSocketNotifier to gracefully quit on Ctrl-C."""
try:
# create non-blocking pipe
rfd, wfd = os.pipe()
for fd in (rfd, wfd):
try:
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
except Exception:
pass
# non-blocking socket pair rather than a pipe: on Windows both
# signal.set_wakeup_fd and QSocketNotifier only accept sockets
rsock, wsock = socket.socketpair()
rsock.setblocking(False)
wsock.setblocking(False)
prev = None
try:
# store previous wakeup fd to restore later
prev = signal.set_wakeup_fd(wfd)
prev = signal.set_wakeup_fd(wsock.fileno())
except Exception:
prev = None
self._sigint_r = rfd
self._sigint_w = wfd
self._sigint_r = rsock
self._sigint_w = wsock
self._prev_wakeup_fd = prev
# install a noop SIGINT handler to prevent KeyboardInterrupt
try:
Expand All @@ -598,13 +595,14 @@ def _noop_sigint(_sig, _frm):
except Exception:
pass
# notifier to watch read end
notifier = QtCore.QSocketNotifier(self._sigint_r, QtCore.QSocketNotifier.Read)
notifier = QtCore.QSocketNotifier(self._sigint_r.fileno(), QtCore.QSocketNotifier.Read)
def _on_readable():
try:
# drain bytes written by signal module
while True:
try:
os.read(self._sigint_r, 1024)
if not self._sigint_r.recv(1024):
break
except BlockingIOError:
break
except KeyboardInterrupt:
Expand Down Expand Up @@ -657,13 +655,13 @@ def _teardown_sigint_notifier(self):
try:
if self._sigint_r is not None:
try:
os.close(self._sigint_r)
self._sigint_r.close()
except Exception:
pass
self._sigint_r = None
if self._sigint_w is not None:
try:
os.close(self._sigint_w)
self._sigint_w.close()
except Exception:
pass
self._sigint_w = None
Expand Down
38 changes: 23 additions & 15 deletions manatools/aui/backends/web/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
from urllib.parse import urlparse, parse_qs
from importlib.resources import files

from ...yui_common import icon_theme_dirs

if TYPE_CHECKING:
from .dialogweb import YDialogWeb

Expand Down Expand Up @@ -356,13 +358,7 @@ def build(cls, *, title: str, app_name: str, dialog_html: str) -> str:

_ICON_NAME_RE = re.compile(r'^[a-zA-Z0-9_\-]+$')

_ICON_SEARCH_DIRS = [
"/usr/share/icons/hicolor",
"/usr/share/icons/breeze",
"/usr/share/icons/Adwaita",
"/usr/share/icons/breeze-dark",
"/usr/local/share/icons/hicolor",
]
_ICON_THEMES = ["hicolor", "breeze", "Adwaita", "breeze-dark"]

_ICON_SIZES = ["22x22", "24x24", "22", "24", "scalable", "16x16", "32x32", "48x48"]
_ICON_CATEGORIES = ["actions", "apps", "emblems", "status", "places", "mimetypes"]
Expand All @@ -372,12 +368,15 @@ def build(cls, *, title: str, app_name: str, dialog_html: str) -> str:
def _find_icon_file(icon_name: str) -> Optional[tuple]:
"""Return (filepath, mimetype) for a named XDG icon, or None if not found.

Searches standard system icon theme directories for the given icon name.
Searches the icon theme roots from :func:`icon_theme_dirs` for the given
icon name.
The icon_name must contain only [a-zA-Z0-9_-] characters (validated by caller).
Prefers SVG (scalable) over PNG; prefers 22px over other sizes.
"""
# Structured search: known roots × sizes × categories
for root in _ICON_SEARCH_DIRS:
roots = icon_theme_dirs()

# Structured search: known themes × sizes × categories
for root in (os.path.join(base, theme) for base in roots for theme in _ICON_THEMES):
if not os.path.isdir(root):
continue
for size in _ICON_SIZES:
Expand All @@ -386,17 +385,18 @@ def _find_icon_file(icon_name: str) -> Optional[tuple]:
path = os.path.join(root, size, category, icon_name + ext)
if os.path.isfile(path):
return path, mime
# Breeze nests the other way round: actions/22/
path = os.path.join(root, category, size, icon_name + ext)
if os.path.isfile(path):
return path, mime
# Also try "scalable" subfolder under size (some themes)
for ext, mime in _ICON_EXTENSIONS:
path = os.path.join(root, "scalable", category, icon_name + ext)
if os.path.isfile(path):
return path, mime

# Broader glob over all installed icon themes
for root in ["/usr/share/icons", "/usr/local/share/icons",
os.path.expanduser("~/.local/share/icons")]:
if not os.path.isdir(root):
continue
for root in roots:
for ext, mime in _ICON_EXTENSIONS:
matches = _glob.glob(
os.path.join(root, "**", icon_name + ext), recursive=True
Expand Down Expand Up @@ -827,9 +827,17 @@ def _serve_sse(self):

class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
"""HTTP server that handles each request in a dedicated thread."""
allow_reuse_address = True
# On Windows SO_REUSEADDR lets a second process bind a port that is in
# use, so a taken MUI_WEB_PORT would be shared instead of falling back
# to a free one; the port is claimed with SO_EXCLUSIVEADDRUSE there.
allow_reuse_address = not hasattr(socket, "SO_EXCLUSIVEADDRUSE")
daemon_threads = True

def server_bind(self):
if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
super().server_bind()


def _env_port() -> int:
"""Return the port requested via ``MUI_WEB_PORT`` (0 = any free port)."""
Expand Down
19 changes: 19 additions & 0 deletions manatools/aui/yui.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ def _detect_backend(cls):

Priority:
1. MUI_BACKEND environment variable (user override).
1b. Windows: there is no XDG/X11/Wayland environment to inspect and a
desktop is always present, so try Qt, then GTK4, then NCurses
(windows-curses).
2. XDG_CURRENT_DESKTOP present → desktop session:
- Known GTK desktops → try GTK4, warn + try Qt if unavailable.
- Everything else → try Qt, warn + try GTK4 if unavailable.
Expand Down Expand Up @@ -80,6 +83,22 @@ def _try_ncurses():
if backend_env == 'web':
return Backend.WEB

# ── 1b. Windows — none of the Linux session probes below apply ─────
if sys.platform == 'win32':
if _try_qt():
return Backend.QT
if _try_gtk():
return Backend.GTK
_log.warning(
"Neither PySide6 (Qt) nor GTK4 is available — falling back to NCurses."
)
if _try_ncurses():
return Backend.NCURSES
raise RuntimeError(
"No UI backend available: Qt and GTK4 are both missing, "
"and curses is not installed (pip install windows-curses)."
)

# ── 2. Desktop session present ─────────────────────────────────────
xdg = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg:
Expand Down
39 changes: 37 additions & 2 deletions manatools/aui/yui_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import re
import shutil
import subprocess
import sys
import uuid
from typing import Optional

Expand Down Expand Up @@ -39,9 +40,22 @@ def documents_dir() -> str:
The name is locale-dependent (Documents, Documenti, Dokumente, …), so it
must be resolved at runtime rather than hardcoded. ``xdg-user-dir`` is
tried first; if the binary is missing, ~/.config/user-dirs.dirs is parsed
directly. Home is returned whenever the lookup fails or names a directory
that does not exist.
directly. On Windows the shell is asked instead, which also follows a
Documents folder redirected to OneDrive. Home is returned whenever the
lookup fails or names a directory that does not exist.
"""
if sys.platform == "win32":
try:
import ctypes
buf = ctypes.create_unicode_buffer(260)
# CSIDL_PERSONAL (5) is the Documents folder
if ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, buf) == 0 \
and os.path.isdir(buf.value):
return buf.value
except Exception:
pass
return os.path.expanduser("~")

try:
xdg = shutil.which("xdg-user-dir")
if xdg:
Expand Down Expand Up @@ -75,6 +89,27 @@ def documents_dir() -> str:
return os.path.expanduser("~")


def icon_theme_dirs():
"""Return the existing icon theme roots (directories holding hicolor/, …).

``MANATOOLS_ICON_PATH`` (``os.pathsep``-separated) comes first, so users
can point at an icon theme of their choice. Windows has no system icon
themes; there ``<prefix>/share/icons`` is searched, which is where MSYS2
and conda install them. Elsewhere the XDG system and user roots are used.
"""
dirs = [d for d in os.environ.get("MANATOOLS_ICON_PATH", "").split(os.pathsep) if d]
if sys.platform == "win32":
dirs += [os.path.join(p, "share", "icons") for p in (sys.prefix, sys.base_prefix)]
else:
dirs += ["/usr/share/icons", "/usr/local/share/icons",
os.path.expanduser("~/.local/share/icons")]
found = []
for d in dirs:
if d not in found and os.path.isdir(d):
found.append(d)
return found


def list_entries(current_dir: str, select_file: bool, patterns):
"""List *current_dir* for a file chooser.

Expand Down
8 changes: 8 additions & 0 deletions manatools/aui/yui_curses.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,14 @@ def applicationIcon(self):
def setApplicationTitle(self, title):
"""Set the application title."""
self._application_title = title
if sys.platform == 'win32':
# The legacy Windows console prints OSC sequences verbatim
try:
import ctypes
ctypes.windll.kernel32.SetConsoleTitleW(str(title))
except Exception:
pass
return
# Update terminal/window title for xterm-like terminals when stdout is a TTY
escape_sequences = [
f"\033]0;{title}\007", # Standard
Expand Down
12 changes: 12 additions & 0 deletions manatools/aui/yui_gtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ def __init__(self):
self._logger = logging.getLogger(f"manatools.aui.gtk.{self.__class__.__name__}")
except Exception:
self._logger = logging.getLogger("manatools.aui.gtk.YUIGtk")
# GTK already searches its own prefix; add MANATOOLS_ICON_PATH and, on
# Windows, the Python prefix when GTK is installed elsewhere.
try:
display = Gdk.Display.get_default()
if display is not None:
theme = Gtk.IconTheme.get_for_display(display)
current = theme.get_search_path() or []
for d in icon_theme_dirs():
if d not in current:
theme.add_search_path(d)
except Exception:
self._logger.debug("icon theme search path setup failed", exc_info=True)

def widgetFactory(self):
return self._widget_factory
Expand Down
Loading