|
| 1 | +"""Resolve which application is registered to open a given file type. |
| 2 | +
|
| 3 | +:func:`shell_open` opens a file with whatever app is registered for it; |
| 4 | +``file_assoc`` answers the inverse, read-only question — *which* app is that? |
| 5 | +Given ``report.pdf`` (or a bare ``.pdf`` / ``pdf``) it returns the registered |
| 6 | +executable, the friendly app name, the open command line and the MIME content |
| 7 | +type, via the Windows ``AssocQueryStringW`` shell API. |
| 8 | +
|
| 9 | +:func:`normalize_ext` is a pure helper (path / bare-extension -> ``.ext``), |
| 10 | +fully unit-testable. :func:`file_association` runs the lookup through an |
| 11 | +injectable ``resolver`` seam (the real shell API by default), so the assembly |
| 12 | +logic is testable without Windows. Imports no ``PySide6``. |
| 13 | +""" |
| 14 | +import ctypes |
| 15 | +import os |
| 16 | +import sys |
| 17 | +from typing import Any, Callable, Dict, Optional |
| 18 | + |
| 19 | +# ASSOCSTR query ids (shlwapi AssocQueryStringW) -> result-dict keys. |
| 20 | +_ASSOC_FIELDS = { |
| 21 | + "command": 1, # ASSOCSTR_COMMAND |
| 22 | + "exe": 2, # ASSOCSTR_EXECUTABLE |
| 23 | + "friendly": 4, # ASSOCSTR_FRIENDLYAPPNAME |
| 24 | + "content_type": 12, # ASSOCSTR_CONTENTTYPE |
| 25 | +} |
| 26 | + |
| 27 | +# A resolver: ext (".pdf") -> {command, exe, friendly, content_type}. |
| 28 | +AssocResolver = Callable[[str], Dict[str, Any]] |
| 29 | + |
| 30 | + |
| 31 | +def normalize_ext(target: str) -> str: |
| 32 | + """Return the lowercased extension (with leading dot) of a path or ext. |
| 33 | +
|
| 34 | + Accepts ``report.pdf``, ``C:\\x\\y.PDF``, ``.pdf`` or bare ``pdf``. Raises |
| 35 | + ``ValueError`` for an empty target or one with no resolvable extension. |
| 36 | + """ |
| 37 | + text = str(target).strip() |
| 38 | + if not text: |
| 39 | + raise ValueError("target is empty") |
| 40 | + _, ext = os.path.splitext(os.path.basename(text)) |
| 41 | + if not ext: |
| 42 | + ext = text if text.startswith(".") else "." + text |
| 43 | + ext = ext.lower() |
| 44 | + if len(ext) < 2 or any(char in ext for char in "/\\ \t"): |
| 45 | + raise ValueError(f"no file extension in target: {target!r}") |
| 46 | + return ext |
| 47 | + |
| 48 | + |
| 49 | +def _assoc_query(ext: str, assoc_str: int) -> Optional[str]: |
| 50 | + """Run one AssocQueryStringW lookup; return the string or None.""" |
| 51 | + shlwapi = ctypes.windll.shlwapi |
| 52 | + size = ctypes.c_ulong(0) |
| 53 | + shlwapi.AssocQueryStringW(0, assoc_str, ext, None, None, ctypes.byref(size)) |
| 54 | + if size.value == 0: |
| 55 | + return None |
| 56 | + buf = ctypes.create_unicode_buffer(size.value) |
| 57 | + result = shlwapi.AssocQueryStringW(0, assoc_str, ext, None, buf, |
| 58 | + ctypes.byref(size)) |
| 59 | + return buf.value if result == 0 else None |
| 60 | + |
| 61 | + |
| 62 | +def _default_resolver(ext: str) -> Dict[str, Any]: |
| 63 | + """Resolve ``ext``'s registered app via the Windows shell API.""" |
| 64 | + if not sys.platform.startswith("win"): |
| 65 | + raise RuntimeError( |
| 66 | + "file association lookup is Windows-only; pass resolver=") |
| 67 | + return {key: _assoc_query(ext, assoc_str) |
| 68 | + for key, assoc_str in _ASSOC_FIELDS.items()} |
| 69 | + |
| 70 | + |
| 71 | +def file_association(target: str, *, |
| 72 | + resolver: Optional[AssocResolver] = None) -> Dict[str, Any]: |
| 73 | + """Return the app registered to open ``target``'s file type. |
| 74 | +
|
| 75 | + Returns ``{ext, command, exe, friendly, content_type}`` (the app fields are |
| 76 | + None when nothing is registered). Pass ``resolver`` (``ext -> dict``) to |
| 77 | + intercept the lookup in tests; the default uses the Windows shell API. |
| 78 | + """ |
| 79 | + ext = normalize_ext(target) |
| 80 | + resolve = resolver if resolver is not None else _default_resolver |
| 81 | + info = resolve(ext) |
| 82 | + return {"ext": ext, |
| 83 | + "command": info.get("command"), |
| 84 | + "exe": info.get("exe"), |
| 85 | + "friendly": info.get("friendly"), |
| 86 | + "content_type": info.get("content_type")} |
0 commit comments