native-file-dialog 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of native-file-dialog might be problematic. Click here for more details.
- native_file_dialog-1.0.0/.gitignore +35 -0
- native_file_dialog-1.0.0/PKG-INFO +28 -0
- native_file_dialog-1.0.0/README.md +18 -0
- native_file_dialog-1.0.0/VERSION +1 -0
- native_file_dialog-1.0.0/pyproject.toml +23 -0
- native_file_dialog-1.0.0/src/native_file_dialog/__init__.py +190 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/__init__.py +0 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/gtk.py +73 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/gtk3.py +59 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/pyobjc.py +101 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/qt.py +43 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/tk.py +46 -0
- native_file_dialog-1.0.0/src/native_file_dialog/backends/win32.py +194 -0
- native_file_dialog-1.0.0/src/native_file_dialog/py.typed +0 -0
- native_file_dialog-1.0.0/src/native_file_dialog/tkinter.py +167 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Byte-compiled / cached
|
|
2
|
+
__pycache__/
|
|
3
|
+
|
|
4
|
+
# Distribution / build
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
/local-pypi
|
|
8
|
+
|
|
9
|
+
# Virtual environments
|
|
10
|
+
.venv/
|
|
11
|
+
|
|
12
|
+
# CMake
|
|
13
|
+
CMakeCache.txt
|
|
14
|
+
CMakeFiles/
|
|
15
|
+
cmake_install.cmake
|
|
16
|
+
*.cmake
|
|
17
|
+
!CMakeLists.txt
|
|
18
|
+
|
|
19
|
+
# IDE / editor
|
|
20
|
+
.idea/
|
|
21
|
+
.vscode/
|
|
22
|
+
*.swp
|
|
23
|
+
*.swo
|
|
24
|
+
*~
|
|
25
|
+
|
|
26
|
+
# OS
|
|
27
|
+
.DS_Store
|
|
28
|
+
Thumbs.db
|
|
29
|
+
|
|
30
|
+
# Testing / coverage
|
|
31
|
+
.coverage
|
|
32
|
+
htmlcov/
|
|
33
|
+
.pytest_cache/
|
|
34
|
+
.tox/
|
|
35
|
+
.nox/
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: native-file-dialog
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Cross-platform native file dialogs for Python
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Requires-Dist: native-file-dialog-gtk3; sys_platform == 'linux'
|
|
7
|
+
Requires-Dist: native-file-dialog-gtk; sys_platform == 'linux'
|
|
8
|
+
Requires-Dist: native-file-dialog-qt; sys_platform == 'linux'
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# native-file-dialog
|
|
12
|
+
|
|
13
|
+
Synchronous open, save and directory dialogs for Python 3.11+, with native
|
|
14
|
+
Windows, macOS and Linux backends and a Tkinter fallback. Includes a Tkinter /
|
|
15
|
+
CustomTkinter adapter that keeps the Tk event loop responsive on Linux.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from native_file_dialog import tkinter as dialogs
|
|
19
|
+
|
|
20
|
+
paths = dialogs.open_file(master=root, filters=[("PDF files", "*.pdf")])
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Pass an existing Tk window as `root`. On Linux, the core depends on the GTK4,
|
|
24
|
+
GTK3 and Qt backend packages; each is used only when its corresponding system toolkit can be loaded.
|
|
25
|
+
The backend wheels do not install or bundle GTK/Qt. Missing toolkits are skipped,
|
|
26
|
+
with Tkinter as the final fallback.
|
|
27
|
+
|
|
28
|
+
[Documentation and source](https://github.com/sherpya/native-file-dialog)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# native-file-dialog
|
|
2
|
+
|
|
3
|
+
Synchronous open, save and directory dialogs for Python 3.11+, with native
|
|
4
|
+
Windows, macOS and Linux backends and a Tkinter fallback. Includes a Tkinter /
|
|
5
|
+
CustomTkinter adapter that keeps the Tk event loop responsive on Linux.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from native_file_dialog import tkinter as dialogs
|
|
9
|
+
|
|
10
|
+
paths = dialogs.open_file(master=root, filters=[("PDF files", "*.pdf")])
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Pass an existing Tk window as `root`. On Linux, the core depends on the GTK4,
|
|
14
|
+
GTK3 and Qt backend packages; each is used only when its corresponding system toolkit can be loaded.
|
|
15
|
+
The backend wheels do not install or bundle GTK/Qt. Missing toolkits are skipped,
|
|
16
|
+
with Tkinter as the final fallback.
|
|
17
|
+
|
|
18
|
+
[Documentation and source](https://github.com/sherpya/native-file-dialog)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
1.0.0
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "native-file-dialog"
|
|
3
|
+
description = "Cross-platform native file dialogs for Python"
|
|
4
|
+
readme = "README.md"
|
|
5
|
+
dynamic = ["version"]
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"native-file-dialog-gtk; sys_platform == 'linux'",
|
|
9
|
+
"native-file-dialog-gtk3; sys_platform == 'linux'",
|
|
10
|
+
"native-file-dialog-qt; sys_platform == 'linux'",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[tool.hatch.version]
|
|
14
|
+
source = "regex"
|
|
15
|
+
path = "VERSION"
|
|
16
|
+
pattern = "^(?P<version>.+)$"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/native_file_dialog"]
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["hatchling"]
|
|
23
|
+
build-backend = "hatchling.build"
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""
|
|
2
|
+
native_file_dialog: native open/save file dialogs (single and multiple selection).
|
|
3
|
+
|
|
4
|
+
Uses Qt or GTK on Linux (via XDG_CURRENT_DESKTOP), ctypes on Windows,
|
|
5
|
+
PyObjC on macOS, with tkinter fallback.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import builtins
|
|
14
|
+
import threading
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from functools import cache
|
|
17
|
+
from typing import List, Literal, Tuple, TypeAlias
|
|
18
|
+
|
|
19
|
+
PathLike: TypeAlias = str | os.PathLike[str]
|
|
20
|
+
FilterSpec: TypeAlias = List[Tuple[str, str]]
|
|
21
|
+
Backend: TypeAlias = Literal['tk', 'qt', 'gtk', 'gtk3', 'pyobjc']
|
|
22
|
+
EventPump: TypeAlias = Callable[[], bool | None]
|
|
23
|
+
|
|
24
|
+
__all__ = ['open_file', 'save_file', 'open_directory', 'FilterSpec', 'Backend', 'EventPump']
|
|
25
|
+
|
|
26
|
+
package = 'native_file_dialog.backends'
|
|
27
|
+
_dialog_active = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _call_backend(backend_module, operation: str, *, event_pump: EventPump | None = None, **kwargs):
|
|
31
|
+
"""Keep native toolkit calls on the GUI thread and reject nested dialogs."""
|
|
32
|
+
global _dialog_active
|
|
33
|
+
if event_pump is not None and not callable(event_pump):
|
|
34
|
+
raise TypeError('event_pump must be callable or None')
|
|
35
|
+
if sys.platform != 'linux':
|
|
36
|
+
return getattr(backend_module, operation)(**kwargs)
|
|
37
|
+
if threading.current_thread() is not threading.main_thread():
|
|
38
|
+
raise RuntimeError('Linux file dialogs must run on the main thread')
|
|
39
|
+
if _dialog_active:
|
|
40
|
+
raise RuntimeError('A native file dialog is already active')
|
|
41
|
+
_dialog_active = True
|
|
42
|
+
try:
|
|
43
|
+
if event_pump is not None and backend_module.__name__.rsplit('.', 1)[-1] != 'tk':
|
|
44
|
+
kwargs['event_pump'] = event_pump
|
|
45
|
+
return getattr(backend_module, operation)(**kwargs)
|
|
46
|
+
finally:
|
|
47
|
+
_dialog_active = False
|
|
48
|
+
|
|
49
|
+
_GTK_MARKER = '_native_file_dialog_gtk_major'
|
|
50
|
+
_GTK_MIX_ERROR = (
|
|
51
|
+
'Cannot use GTK{requested} after GTK{active} in the same Python process; '
|
|
52
|
+
'choose one GTK backend per process or run the other backend in a subprocess.'
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _active_gtk_major() -> int | None:
|
|
57
|
+
active = getattr(builtins, _GTK_MARKER, None)
|
|
58
|
+
return active if active in (3, 4) else None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _ensure_gtk_major(requested: int) -> None:
|
|
62
|
+
active = _active_gtk_major()
|
|
63
|
+
if active is not None and active != requested:
|
|
64
|
+
raise RuntimeError(_GTK_MIX_ERROR.format(requested=requested, active=active))
|
|
65
|
+
setattr(builtins, _GTK_MARKER, requested)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _import_gtk3_backend():
|
|
69
|
+
_ensure_gtk_major(3)
|
|
70
|
+
return importlib.import_module('.gtk3', package=package)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@cache
|
|
74
|
+
def get_backend():
|
|
75
|
+
"""Resolve and cache the backend for the current platform."""
|
|
76
|
+
if sys.platform == 'win32':
|
|
77
|
+
return importlib.import_module('.win32', package=package)
|
|
78
|
+
|
|
79
|
+
if sys.platform == 'darwin':
|
|
80
|
+
try:
|
|
81
|
+
return importlib.import_module('.pyobjc', package=package)
|
|
82
|
+
except ImportError:
|
|
83
|
+
return importlib.import_module('.tk', package=package)
|
|
84
|
+
|
|
85
|
+
# Linux: choose order by XDG_CURRENT_DESKTOP
|
|
86
|
+
xdg = os.environ.get('XDG_CURRENT_DESKTOP', '').upper()
|
|
87
|
+
if 'KDE' in xdg:
|
|
88
|
+
order = ('.qt', '.gtk')
|
|
89
|
+
elif 'GNOME' in xdg or 'XFCE' in xdg or 'MATE' in xdg:
|
|
90
|
+
order = ('.gtk', '.qt')
|
|
91
|
+
else:
|
|
92
|
+
order = ('.qt', '.gtk')
|
|
93
|
+
|
|
94
|
+
if _active_gtk_major() == 3:
|
|
95
|
+
order = tuple('.gtk3' if name == '.gtk' else name for name in order)
|
|
96
|
+
|
|
97
|
+
for name in order:
|
|
98
|
+
try:
|
|
99
|
+
return importlib.import_module(name, package=package)
|
|
100
|
+
except ImportError:
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
return importlib.import_module('.tk', package=package)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def resolve_backend(override: Backend | None = None):
|
|
107
|
+
"""
|
|
108
|
+
Resolve backend: if override is 'gtk', 'gtk3', 'qt', 'pyobjc', 'tk',
|
|
109
|
+
use that backend. Otherwise, autodetect.
|
|
110
|
+
"""
|
|
111
|
+
if not override:
|
|
112
|
+
return get_backend()
|
|
113
|
+
|
|
114
|
+
if override == 'tk':
|
|
115
|
+
return importlib.import_module('.tk', package=package)
|
|
116
|
+
|
|
117
|
+
if sys.platform == 'linux':
|
|
118
|
+
if override == 'gtk':
|
|
119
|
+
_ensure_gtk_major(4)
|
|
120
|
+
return importlib.import_module('.gtk', package=package)
|
|
121
|
+
elif override == 'gtk3':
|
|
122
|
+
return _import_gtk3_backend()
|
|
123
|
+
elif override == 'qt':
|
|
124
|
+
return importlib.import_module('.qt', package=package)
|
|
125
|
+
|
|
126
|
+
if sys.platform == 'darwin':
|
|
127
|
+
if override == 'pyobjc':
|
|
128
|
+
return importlib.import_module('.pyobjc', package=package)
|
|
129
|
+
|
|
130
|
+
raise Exception(f'Invalid Backend {override} for platform {sys.platform}')
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def open_file(title: str | None = None, initialdir: PathLike | None = None, filters: FilterSpec | None = None,
|
|
134
|
+
multiple: bool = False, backend: Backend | None = None, *,
|
|
135
|
+
event_pump: EventPump | None = None) -> List[str] | None:
|
|
136
|
+
"""
|
|
137
|
+
Open a file selection dialog.
|
|
138
|
+
|
|
139
|
+
:param title: Dialog title (default backend-specific).
|
|
140
|
+
:param initialdir: Initial directory.
|
|
141
|
+
:param filters: List of (description, pattern) tuples, e.g. [('Python', '*.py')].
|
|
142
|
+
:param multiple: If True, allow selecting multiple files.
|
|
143
|
+
:param backend: Force backend: 'gtk', 'gtk3', 'qt' (Linux), 'pyobjc' (macOS), or 'tk' (any platform).
|
|
144
|
+
:param event_pump: Linux GTK/Qt: nonblocking callback every 20 ms; False cancels.
|
|
145
|
+
:return: List of selected paths, or None if cancelled. Single selection returns [path].
|
|
146
|
+
"""
|
|
147
|
+
backend_module = resolve_backend(backend)
|
|
148
|
+
if initialdir is not None:
|
|
149
|
+
initialdir = os.fspath(initialdir)
|
|
150
|
+
return _call_backend(backend_module, 'open_file', event_pump=event_pump,
|
|
151
|
+
title=title or '', initialdir=initialdir or '.', filters=filters, multiple=multiple)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def save_file(title: str | None = None, initialdir: PathLike | None = None, filters: FilterSpec | None = None,
|
|
155
|
+
default_name: str | None = None, backend: Backend | None = None, *,
|
|
156
|
+
event_pump: EventPump | None = None) -> str | None:
|
|
157
|
+
"""
|
|
158
|
+
Open a save file dialog.
|
|
159
|
+
|
|
160
|
+
:param title: Dialog title.
|
|
161
|
+
:param initialdir: Initial directory.
|
|
162
|
+
:param filters: List of (description, pattern) tuples, e.g. [('PDF files', '*.pdf')].
|
|
163
|
+
:param default_name: Pre-filled file name suggestion.
|
|
164
|
+
:param backend: Force backend: 'gtk', 'gtk3', 'qt' (Linux), 'pyobjc' (macOS), or 'tk' (any platform).
|
|
165
|
+
:param event_pump: Linux GTK/Qt: nonblocking callback every 20 ms; False cancels.
|
|
166
|
+
:return: Selected path or None if cancelled.
|
|
167
|
+
"""
|
|
168
|
+
backend_module = resolve_backend(backend)
|
|
169
|
+
if initialdir is not None:
|
|
170
|
+
initialdir = os.fspath(initialdir)
|
|
171
|
+
return _call_backend(backend_module, 'save_file', event_pump=event_pump,
|
|
172
|
+
title=title or '', initialdir=initialdir or '.', filters=filters, default_name=default_name)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def open_directory(title: str | None = None, initialdir: PathLike | None = None,
|
|
176
|
+
backend: Backend | None = None, *, event_pump: EventPump | None = None) -> str | None:
|
|
177
|
+
"""
|
|
178
|
+
Open a directory selection dialog.
|
|
179
|
+
|
|
180
|
+
:param title: Dialog title.
|
|
181
|
+
:param initialdir: Initial directory.
|
|
182
|
+
:param backend: Force backend: 'gtk', 'gtk3', 'qt' (Linux), 'pyobjc' (macOS), or 'tk' (any platform).
|
|
183
|
+
:param event_pump: Linux GTK/Qt: nonblocking callback every 20 ms; False cancels.
|
|
184
|
+
:return: Selected directory path or None if cancelled.
|
|
185
|
+
"""
|
|
186
|
+
backend_module = resolve_backend(backend)
|
|
187
|
+
if initialdir is not None:
|
|
188
|
+
initialdir = os.fspath(initialdir)
|
|
189
|
+
return _call_backend(backend_module, 'open_directory', event_pump=event_pump,
|
|
190
|
+
title=title or '', initialdir=initialdir or '.')
|
|
File without changes
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import builtins
|
|
4
|
+
from typing import TYPE_CHECKING, List
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .. import EventPump, FilterSpec
|
|
8
|
+
|
|
9
|
+
_GTK_MARKER = '_native_file_dialog_gtk_major'
|
|
10
|
+
_GTK_MIX_ERROR = (
|
|
11
|
+
'Cannot use GTK{requested} after GTK{active} in the same Python process; '
|
|
12
|
+
'choose one GTK backend per process or run the other backend in a subprocess.'
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _active_gtk_major() -> int | None:
|
|
17
|
+
active = getattr(builtins, _GTK_MARKER, None)
|
|
18
|
+
return active if active in (3, 4) else None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _ensure_gtk_major(requested: int) -> None:
|
|
22
|
+
active = _active_gtk_major()
|
|
23
|
+
if active is not None and active != requested:
|
|
24
|
+
raise RuntimeError(_GTK_MIX_ERROR.format(requested=requested, active=active))
|
|
25
|
+
setattr(builtins, _GTK_MARKER, requested)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Try GTK4 first, fall back to GTK3 only if GTK4 cannot be imported.
|
|
29
|
+
try:
|
|
30
|
+
from native_file_dialog_gtk import (
|
|
31
|
+
open_file as _open_file,
|
|
32
|
+
open_multiple as _open_multiple,
|
|
33
|
+
save_file as _save_file,
|
|
34
|
+
open_directory as _open_directory,
|
|
35
|
+
)
|
|
36
|
+
_ensure_gtk_major(4)
|
|
37
|
+
except ImportError:
|
|
38
|
+
_ensure_gtk_major(3)
|
|
39
|
+
from native_file_dialog_gtk3 import (
|
|
40
|
+
open_file as _open_file,
|
|
41
|
+
open_multiple as _open_multiple,
|
|
42
|
+
save_file as _save_file,
|
|
43
|
+
open_directory as _open_directory,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def filter_to_gtk_string(filters: FilterSpec | None = None) -> List[str]:
|
|
48
|
+
"""GTK format: list of 'Description | pattern1 pattern2'."""
|
|
49
|
+
if not filters:
|
|
50
|
+
return []
|
|
51
|
+
# GTK uses spaces to separate multiple patterns; normalize semicolons
|
|
52
|
+
return [f'{desc} | {pattern.replace(";", " ")}' for desc, pattern in filters]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
56
|
+
filters: FilterSpec | None = None, multiple: bool = False, *, event_pump: EventPump | None = None) -> List[str] | None:
|
|
57
|
+
if multiple:
|
|
58
|
+
result = _open_multiple(title or '', initialdir or '', filter_to_gtk_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
59
|
+
return result if result else None
|
|
60
|
+
path = _open_file(title or '', initialdir or '', filter_to_gtk_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
61
|
+
return [path] if path is not None else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
65
|
+
filters: FilterSpec | None = None, default_name: str | None = None, *, event_pump: EventPump | None = None) -> str | None:
|
|
66
|
+
result = _save_file(title or '', initialdir or '', filter_to_gtk_string(filters), default_name or '', *(() if event_pump is None else (event_pump,)))
|
|
67
|
+
return result if result is not None else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def open_directory(title: str | None = None, initialdir: str | None = None, *,
|
|
71
|
+
event_pump: EventPump | None = None) -> str | None:
|
|
72
|
+
result = _open_directory(title or '', initialdir or '', *(() if event_pump is None else (event_pump,)))
|
|
73
|
+
return result if result is not None else None
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import builtins
|
|
4
|
+
from typing import TYPE_CHECKING, List
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .. import EventPump, FilterSpec
|
|
8
|
+
|
|
9
|
+
_GTK_MARKER = '_native_file_dialog_gtk_major'
|
|
10
|
+
_GTK_MIX_ERROR = (
|
|
11
|
+
'Cannot use GTK{requested} after GTK{active} in the same Python process; '
|
|
12
|
+
'choose one GTK backend per process or run the other backend in a subprocess.'
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _ensure_gtk_major(requested: int) -> None:
|
|
17
|
+
active = getattr(builtins, _GTK_MARKER, None)
|
|
18
|
+
if active in (3, 4) and active != requested:
|
|
19
|
+
raise RuntimeError(_GTK_MIX_ERROR.format(requested=requested, active=active))
|
|
20
|
+
setattr(builtins, _GTK_MARKER, requested)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_ensure_gtk_major(3)
|
|
24
|
+
|
|
25
|
+
from native_file_dialog_gtk3 import (
|
|
26
|
+
open_file as _open_file,
|
|
27
|
+
open_multiple as _open_multiple,
|
|
28
|
+
save_file as _save_file,
|
|
29
|
+
open_directory as _open_directory,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def filter_to_gtk_string(filters: FilterSpec | None = None) -> List[str]:
|
|
34
|
+
"""GTK format: list of 'Description | pattern1 pattern2'."""
|
|
35
|
+
if not filters:
|
|
36
|
+
return []
|
|
37
|
+
# GTK uses spaces to separate multiple patterns; normalize semicolons
|
|
38
|
+
return [f'{desc} | {pattern.replace(";", " ")}' for desc, pattern in filters]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
42
|
+
filters: FilterSpec | None = None, multiple: bool = False, *, event_pump: EventPump | None = None) -> List[str] | None:
|
|
43
|
+
if multiple:
|
|
44
|
+
result = _open_multiple(title or '', initialdir or '', filter_to_gtk_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
45
|
+
return result if result else None
|
|
46
|
+
path = _open_file(title or '', initialdir or '', filter_to_gtk_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
47
|
+
return [path] if path is not None else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
51
|
+
filters: FilterSpec | None = None, default_name: str | None = None, *, event_pump: EventPump | None = None) -> str | None:
|
|
52
|
+
result = _save_file(title or '', initialdir or '', filter_to_gtk_string(filters), default_name or '', *(() if event_pump is None else (event_pump,)))
|
|
53
|
+
return result if result is not None else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def open_directory(title: str | None = None, initialdir: str | None = None, *,
|
|
57
|
+
event_pump: EventPump | None = None) -> str | None:
|
|
58
|
+
result = _open_directory(title or '', initialdir or '', *(() if event_pump is None else (event_pump,)))
|
|
59
|
+
return result if result is not None else None
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
macOS native file dialog backend via PyObjC (NSOpenPanel / NSSavePanel).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import TYPE_CHECKING, List
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .. import FilterSpec
|
|
11
|
+
|
|
12
|
+
from AppKit import NSOpenPanel, NSSavePanel # type: ignore
|
|
13
|
+
from Foundation import NSURL # type: ignore
|
|
14
|
+
from UniformTypeIdentifiers import UTType # type: ignore[import-not-found]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def filter_to_ut_types(filter_spec: FilterSpec) -> List[UTType]:
|
|
18
|
+
"""Extract UTTypes from glob patterns like '*.py', '*.md'"""
|
|
19
|
+
ut_types = []
|
|
20
|
+
for _, pattern in filter_spec:
|
|
21
|
+
# Split on spaces and semicolons to handle multiple patterns
|
|
22
|
+
for single in pattern.replace(';', ' ').split():
|
|
23
|
+
if single.startswith('*.'):
|
|
24
|
+
ext = single[2:]
|
|
25
|
+
if ut_type := UTType.typeWithFilenameExtension_(ext):
|
|
26
|
+
ut_types.append(ut_type)
|
|
27
|
+
return ut_types
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
31
|
+
filters: FilterSpec | None = None, multiple: bool = False) -> List[str] | None:
|
|
32
|
+
panel = NSOpenPanel.openPanel()
|
|
33
|
+
panel.setCanChooseFiles_(True)
|
|
34
|
+
panel.setCanChooseDirectories_(False)
|
|
35
|
+
panel.setAllowsMultipleSelection_(multiple)
|
|
36
|
+
|
|
37
|
+
if title:
|
|
38
|
+
panel.setTitle_(title)
|
|
39
|
+
|
|
40
|
+
if initialdir:
|
|
41
|
+
panel.setDirectoryURL_(NSURL.fileURLWithPath_(initialdir))
|
|
42
|
+
|
|
43
|
+
if filters:
|
|
44
|
+
types = filter_to_ut_types(filters)
|
|
45
|
+
panel.setAllowedContentTypes_(types)
|
|
46
|
+
|
|
47
|
+
if panel.runModal() != 1:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
urls = panel.URLs()
|
|
51
|
+
if not urls or urls.count() == 0:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
if multiple:
|
|
55
|
+
return [url.path() for url in urls]
|
|
56
|
+
return [urls[0].path()]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
60
|
+
filters: FilterSpec | None = None, default_name: str | None = None) -> str | None:
|
|
61
|
+
panel = NSSavePanel.savePanel()
|
|
62
|
+
|
|
63
|
+
if title:
|
|
64
|
+
panel.setTitle_(title)
|
|
65
|
+
|
|
66
|
+
if initialdir:
|
|
67
|
+
panel.setDirectoryURL_(NSURL.fileURLWithPath_(initialdir))
|
|
68
|
+
|
|
69
|
+
if default_name:
|
|
70
|
+
panel.setNameFieldStringValue_(default_name)
|
|
71
|
+
|
|
72
|
+
if filters:
|
|
73
|
+
types = filter_to_ut_types(filters)
|
|
74
|
+
panel.setAllowedContentTypes_(types)
|
|
75
|
+
|
|
76
|
+
if panel.runModal() != 1:
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
url = panel.URL()
|
|
80
|
+
return url.path() if url else None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def open_directory(title: str | None = None, initialdir: str | None = None) -> str | None:
|
|
84
|
+
panel = NSOpenPanel.openPanel()
|
|
85
|
+
panel.setCanChooseFiles_(False)
|
|
86
|
+
panel.setCanChooseDirectories_(True)
|
|
87
|
+
panel.setAllowsMultipleSelection_(False)
|
|
88
|
+
|
|
89
|
+
if title:
|
|
90
|
+
panel.setTitle_(title)
|
|
91
|
+
|
|
92
|
+
if initialdir:
|
|
93
|
+
panel.setDirectoryURL_(NSURL.fileURLWithPath_(initialdir))
|
|
94
|
+
|
|
95
|
+
if panel.runModal() != 1:
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
urls = panel.URLs()
|
|
99
|
+
if not urls or urls.count() == 0:
|
|
100
|
+
return None
|
|
101
|
+
return urls[0].path()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import TYPE_CHECKING, List
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .. import EventPump, FilterSpec
|
|
8
|
+
|
|
9
|
+
from native_file_dialog_qt import (
|
|
10
|
+
open_file as _open_file,
|
|
11
|
+
open_multiple as _open_multiple,
|
|
12
|
+
save_file as _save_file,
|
|
13
|
+
open_directory as _open_directory,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def filter_to_qt_string(filters: FilterSpec | None = None) -> str:
|
|
18
|
+
"""Qt format: 'Description (*.a *.b);;Other (*.c)' (;; between entries, space between patterns)."""
|
|
19
|
+
if not filters:
|
|
20
|
+
return ''
|
|
21
|
+
# Qt uses spaces to separate multiple patterns; normalize semicolons
|
|
22
|
+
return ';;'.join((f'{desc} ({pattern.replace(";", " ")})' for desc, pattern in filters))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
26
|
+
filters: FilterSpec | None = None, multiple: bool = False, *, event_pump: EventPump | None = None) -> List[str] | None:
|
|
27
|
+
if multiple:
|
|
28
|
+
result = _open_multiple(title or '', initialdir or '', filter_to_qt_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
29
|
+
return result if result else None
|
|
30
|
+
path = _open_file(title or '', initialdir or '', filter_to_qt_string(filters), *(() if event_pump is None else (event_pump,)))
|
|
31
|
+
return [path] if path is not None else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
35
|
+
filters: FilterSpec | None = None, default_name: str | None = None, *, event_pump: EventPump | None = None) -> str | None:
|
|
36
|
+
result = _save_file(title or '', os.fspath(initialdir) if initialdir else '', filter_to_qt_string(filters), default_name or '', *(() if event_pump is None else (event_pump,)))
|
|
37
|
+
return result if result is not None else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def open_directory(title: str | None = None, initialdir: str | None = None, *,
|
|
41
|
+
event_pump: EventPump | None = None) -> str | None:
|
|
42
|
+
result = _open_directory(title or '', os.fspath(initialdir) if initialdir else '', *(() if event_pump is None else (event_pump,)))
|
|
43
|
+
return result if result is not None else None
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import tkinter as tk
|
|
4
|
+
from functools import cache
|
|
5
|
+
from tkinter import filedialog
|
|
6
|
+
from typing import TYPE_CHECKING, List
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .. import FilterSpec
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@cache
|
|
13
|
+
def get_root() -> tk.Tk:
|
|
14
|
+
root = tk.Tk()
|
|
15
|
+
root.withdraw()
|
|
16
|
+
return root
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _normalize_filters(filters: FilterSpec | None) -> list:
|
|
20
|
+
"""Tk uses spaces to separate multiple patterns; normalize semicolons."""
|
|
21
|
+
if not filters:
|
|
22
|
+
return []
|
|
23
|
+
return [(desc, pattern.replace(';', ' ')) for desc, pattern in filters]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
27
|
+
filters: FilterSpec | None = None, multiple: bool = False, *, parent: tk.Misc | None = None) -> List[str] | None:
|
|
28
|
+
parent = parent if parent is not None else get_root()
|
|
29
|
+
ft = _normalize_filters(filters)
|
|
30
|
+
if multiple:
|
|
31
|
+
paths = filedialog.askopenfilenames(parent=parent, title=title, initialdir=initialdir, filetypes=ft)
|
|
32
|
+
return list(paths) if paths else None
|
|
33
|
+
path = filedialog.askopenfilename(parent=parent, title=title, initialdir=initialdir, filetypes=ft)
|
|
34
|
+
return [path] if path else None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
38
|
+
filters: FilterSpec | None = None, default_name: str | None = None, *, parent: tk.Misc | None = None) -> str | None:
|
|
39
|
+
parent = parent if parent is not None else get_root()
|
|
40
|
+
return filedialog.asksaveasfilename(parent=parent, title=title, initialdir=initialdir, filetypes=_normalize_filters(filters),
|
|
41
|
+
initialfile=default_name or '') or None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def open_directory(title: str | None = None, initialdir: str | None = None, *, parent: tk.Misc | None = None) -> str | None:
|
|
45
|
+
parent = parent if parent is not None else get_root()
|
|
46
|
+
return filedialog.askdirectory(parent=parent, title=title, initialdir=initialdir) or None
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Windows file dialog backend using ctypes (no external dependencies).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import ctypes
|
|
8
|
+
import ctypes.wintypes as wt
|
|
9
|
+
import os
|
|
10
|
+
from ctypes import (
|
|
11
|
+
POINTER, Structure, byref, c_void_p, c_wchar_p, create_unicode_buffer, sizeof,
|
|
12
|
+
)
|
|
13
|
+
from typing import TYPE_CHECKING, List
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .. import FilterSpec
|
|
17
|
+
|
|
18
|
+
# comdlg32: GetOpenFileNameW / GetSaveFileNameW
|
|
19
|
+
|
|
20
|
+
OFN_EXPLORER = 0x00080000
|
|
21
|
+
OFN_PATHMUSTEXIST = 0x00001000
|
|
22
|
+
OFN_FILEMUSTEXIST = 0x00002000
|
|
23
|
+
OFN_ALLOWMULTISELECT = 0x00000200
|
|
24
|
+
OFN_OVERWRITEPROMPT = 0x00000002
|
|
25
|
+
OFN_NOCHANGEDIR = 0x00000008
|
|
26
|
+
|
|
27
|
+
MAX_PATH_BUF = 32768
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class OPENFILENAMEW(Structure):
|
|
31
|
+
_fields_ = [
|
|
32
|
+
('lStructSize', wt.DWORD),
|
|
33
|
+
('hwndOwner', wt.HWND),
|
|
34
|
+
('hInstance', wt.HINSTANCE),
|
|
35
|
+
('lpstrFilter', c_wchar_p),
|
|
36
|
+
('lpstrCustomFilter', c_wchar_p),
|
|
37
|
+
('nMaxCustFilter', wt.DWORD),
|
|
38
|
+
('nFilterIndex', wt.DWORD),
|
|
39
|
+
('lpstrFile', ctypes.POINTER(wt.WCHAR)),
|
|
40
|
+
('nMaxFile', wt.DWORD),
|
|
41
|
+
('lpstrFileTitle', c_wchar_p),
|
|
42
|
+
('nMaxFileTitle', wt.DWORD),
|
|
43
|
+
('lpstrInitialDir', c_wchar_p),
|
|
44
|
+
('lpstrTitle', c_wchar_p),
|
|
45
|
+
('Flags', wt.DWORD),
|
|
46
|
+
('nFileOffset', wt.WORD),
|
|
47
|
+
('nFileExtension', wt.WORD),
|
|
48
|
+
('lpstrDefExt', c_wchar_p),
|
|
49
|
+
('lCustData', c_void_p),
|
|
50
|
+
('lpfnHook', c_void_p),
|
|
51
|
+
('lpTemplateName', c_wchar_p),
|
|
52
|
+
('pvReserved', c_void_p),
|
|
53
|
+
('dwReserved', wt.DWORD),
|
|
54
|
+
('FlagsEx', wt.DWORD),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_comdlg32 = ctypes.windll.comdlg32 # type: ignore[attr-defined]
|
|
59
|
+
_comdlg32.GetOpenFileNameW.argtypes = [POINTER(OPENFILENAMEW)]
|
|
60
|
+
_comdlg32.GetOpenFileNameW.restype = wt.BOOL
|
|
61
|
+
_comdlg32.GetSaveFileNameW.argtypes = [POINTER(OPENFILENAMEW)]
|
|
62
|
+
_comdlg32.GetSaveFileNameW.restype = wt.BOOL
|
|
63
|
+
|
|
64
|
+
# shell32: SHBrowseForFolderW / SHGetPathFromIDListW
|
|
65
|
+
|
|
66
|
+
BIF_RETURNONLYFSDIRS = 0x00000001
|
|
67
|
+
BIF_NEWDIALOGSTYLE = 0x00000040
|
|
68
|
+
BIF_EDITBOX = 0x00000010
|
|
69
|
+
|
|
70
|
+
BFFCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, wt.HWND, ctypes.c_uint, c_void_p, c_void_p) # type: ignore[attr-defined]
|
|
71
|
+
BFFM_INITIALIZED = 1
|
|
72
|
+
BFFM_SETSELECTION = 0x0467 # WM_USER + 103, Unicode variant
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class BROWSEINFOW(Structure):
|
|
76
|
+
_fields_ = [
|
|
77
|
+
('hwndOwner', wt.HWND),
|
|
78
|
+
('pidlRoot', c_void_p),
|
|
79
|
+
('pszDisplayName', ctypes.POINTER(wt.WCHAR)),
|
|
80
|
+
('lpszTitle', c_wchar_p),
|
|
81
|
+
('ulFlags', ctypes.c_uint),
|
|
82
|
+
('lpfn', BFFCALLBACK),
|
|
83
|
+
('lParam', c_void_p),
|
|
84
|
+
('iImage', ctypes.c_int),
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_shell32 = ctypes.windll.shell32 # type: ignore[attr-defined]
|
|
89
|
+
_shell32.SHBrowseForFolderW.argtypes = [POINTER(BROWSEINFOW)]
|
|
90
|
+
_shell32.SHBrowseForFolderW.restype = c_void_p
|
|
91
|
+
_shell32.SHGetPathFromIDListW.argtypes = [c_void_p, ctypes.POINTER(wt.WCHAR)]
|
|
92
|
+
_shell32.SHGetPathFromIDListW.restype = wt.BOOL
|
|
93
|
+
|
|
94
|
+
_ole32 = ctypes.windll.ole32 # type: ignore[attr-defined]
|
|
95
|
+
_ole32.CoTaskMemFree.argtypes = [c_void_p]
|
|
96
|
+
_ole32.CoTaskMemFree.restype = None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _filter_string(filters: FilterSpec | None) -> str:
|
|
100
|
+
"""Build Win32 filter string: 'Desc\\0pattern\\0Desc2\\0pattern2\\0\\0'."""
|
|
101
|
+
if not filters:
|
|
102
|
+
return 'All files\x00*.*\x00\x00'
|
|
103
|
+
parts = []
|
|
104
|
+
for desc, pattern in filters:
|
|
105
|
+
parts.append(desc)
|
|
106
|
+
# Win32 uses ';' to separate multiple patterns; normalize spaces
|
|
107
|
+
parts.append(';'.join(pattern.replace(';', ' ').split()))
|
|
108
|
+
return '\x00'.join(parts) + '\x00\x00'
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _resolve_dir(initialdir: str | None) -> str:
|
|
112
|
+
d = os.path.abspath(initialdir or '.')
|
|
113
|
+
return d if os.path.isdir(d) else (os.path.expanduser('~') or '.')
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _make_ofn(title: str | None, initialdir: str | None, filters: FilterSpec | None,
|
|
117
|
+
file_buf: ctypes.Array, flags: int) -> OPENFILENAMEW:
|
|
118
|
+
ofn = OPENFILENAMEW()
|
|
119
|
+
ofn.lStructSize = sizeof(OPENFILENAMEW)
|
|
120
|
+
ofn.lpstrFilter = _filter_string(filters)
|
|
121
|
+
ofn.nFilterIndex = 1
|
|
122
|
+
ofn.lpstrFile = ctypes.cast(file_buf, POINTER(wt.WCHAR))
|
|
123
|
+
ofn.nMaxFile = MAX_PATH_BUF
|
|
124
|
+
ofn.lpstrInitialDir = _resolve_dir(initialdir)
|
|
125
|
+
ofn.lpstrTitle = title or None
|
|
126
|
+
ofn.Flags = flags
|
|
127
|
+
return ofn
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def open_file(title: str | None = None, initialdir: str | None = None,
|
|
131
|
+
filters: FilterSpec | None = None, multiple: bool = False) -> List[str] | None:
|
|
132
|
+
buf = create_unicode_buffer(MAX_PATH_BUF)
|
|
133
|
+
flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR
|
|
134
|
+
if multiple:
|
|
135
|
+
flags |= OFN_ALLOWMULTISELECT
|
|
136
|
+
default_title = 'Choose one or more files' if multiple else 'Choose a file'
|
|
137
|
+
ofn = _make_ofn(title or default_title, initialdir, filters, buf, flags)
|
|
138
|
+
|
|
139
|
+
if not _comdlg32.GetOpenFileNameW(byref(ofn)):
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
if multiple:
|
|
143
|
+
raw = ctypes.wstring_at(buf, MAX_PATH_BUF)
|
|
144
|
+
parts = [p for p in raw.split('\x00') if p]
|
|
145
|
+
if not parts:
|
|
146
|
+
return None
|
|
147
|
+
if len(parts) == 1:
|
|
148
|
+
return [parts[0]]
|
|
149
|
+
directory = parts[0]
|
|
150
|
+
return [os.path.join(directory, f) for f in parts[1:]]
|
|
151
|
+
|
|
152
|
+
return [buf.value] if buf.value else None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def save_file(title: str | None = None, initialdir: str | None = None,
|
|
156
|
+
filters: FilterSpec | None = None, default_name: str | None = None) -> str | None:
|
|
157
|
+
buf = create_unicode_buffer(MAX_PATH_BUF)
|
|
158
|
+
if default_name:
|
|
159
|
+
for i, ch in enumerate(default_name[:MAX_PATH_BUF - 1]):
|
|
160
|
+
buf[i] = ch
|
|
161
|
+
ofn = _make_ofn(title or 'Save file', initialdir, filters, buf,
|
|
162
|
+
OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR)
|
|
163
|
+
if not _comdlg32.GetSaveFileNameW(byref(ofn)):
|
|
164
|
+
return None
|
|
165
|
+
return buf.value or None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def open_directory(title: str | None = None, initialdir: str | None = None) -> str | None:
|
|
169
|
+
resolved_dir = _resolve_dir(initialdir)
|
|
170
|
+
|
|
171
|
+
@BFFCALLBACK
|
|
172
|
+
def _browse_callback(hwnd, msg, _lp, _data):
|
|
173
|
+
if msg == BFFM_INITIALIZED:
|
|
174
|
+
ctypes.windll.user32.SendMessageW(hwnd, BFFM_SETSELECTION, 1, c_wchar_p(resolved_dir))
|
|
175
|
+
return 0
|
|
176
|
+
|
|
177
|
+
display_buf = create_unicode_buffer(MAX_PATH_BUF)
|
|
178
|
+
bi = BROWSEINFOW()
|
|
179
|
+
bi.pszDisplayName = ctypes.cast(display_buf, POINTER(wt.WCHAR))
|
|
180
|
+
bi.lpszTitle = title or 'Select Folder'
|
|
181
|
+
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_EDITBOX
|
|
182
|
+
bi.lpfn = _browse_callback
|
|
183
|
+
|
|
184
|
+
if not (pidl := _shell32.SHBrowseForFolderW(byref(bi))):
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
path_buf = create_unicode_buffer(MAX_PATH_BUF)
|
|
188
|
+
ok = _shell32.SHGetPathFromIDListW(pidl, ctypes.cast(path_buf, POINTER(wt.WCHAR)))
|
|
189
|
+
_ole32.CoTaskMemFree(pidl)
|
|
190
|
+
|
|
191
|
+
if not ok:
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
return path_buf.value or None
|
|
File without changes
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Synchronous native dialogs integrated with a Tk/CustomTkinter application.
|
|
2
|
+
|
|
3
|
+
Pass an explicit ``master`` owned by the main thread. On Linux, native GTK/Qt
|
|
4
|
+
dialogs service Tk events while temporarily shielding the application's input.
|
|
5
|
+
``master`` identifies the Tk interpreter and lifetime; it is not a foreign GTK
|
|
6
|
+
or Qt window handle and does not force native window placement.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import _tkinter
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import tkinter as tk
|
|
16
|
+
|
|
17
|
+
from . import Backend, FilterSpec, PathLike, _call_backend, resolve_backend
|
|
18
|
+
|
|
19
|
+
__all__ = ['open_file', 'save_file', 'open_directory']
|
|
20
|
+
|
|
21
|
+
_active_interpreters: set[int] = set()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _TkModal:
|
|
25
|
+
"""Own only the temporary grabs, busy windows and bindtags we install."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, master: tk.Misc):
|
|
28
|
+
self.master = master
|
|
29
|
+
self.tk = master.tk
|
|
30
|
+
self.tag = f'nfd_modal_{id(self)}'
|
|
31
|
+
self.tagged: set[str] = set()
|
|
32
|
+
self.busy: set[str] = set()
|
|
33
|
+
self.focus = ''
|
|
34
|
+
self.grab: tuple[str, str] | None = None
|
|
35
|
+
|
|
36
|
+
def _exists(self, window: str) -> bool:
|
|
37
|
+
try:
|
|
38
|
+
return bool(self.tk.getboolean(self.tk.call('winfo', 'exists', window)))
|
|
39
|
+
except tk.TclError:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def alive(self) -> bool:
|
|
44
|
+
return self._exists(str(self.master))
|
|
45
|
+
|
|
46
|
+
def _release_grab(self) -> None:
|
|
47
|
+
current = str(self.tk.call('grab', 'current', str(self.master)))
|
|
48
|
+
if current:
|
|
49
|
+
self.grab = current, str(self.tk.call('grab', 'status', current))
|
|
50
|
+
self.tk.call('grab', 'release', current)
|
|
51
|
+
|
|
52
|
+
def _protect_windows(self) -> None:
|
|
53
|
+
# Include new windows created by timer/background-result callbacks.
|
|
54
|
+
pending = ['.']
|
|
55
|
+
while pending:
|
|
56
|
+
window = pending.pop()
|
|
57
|
+
if not self._exists(window):
|
|
58
|
+
continue
|
|
59
|
+
tags = self.tk.splitlist(self.tk.call('bindtags', window))
|
|
60
|
+
if self.tag not in tags:
|
|
61
|
+
self.tk.call('bindtags', window, (self.tag, *tags))
|
|
62
|
+
self.tagged.add(window)
|
|
63
|
+
if str(self.tk.call('winfo', 'toplevel', window)) == window:
|
|
64
|
+
if not self.tk.getboolean(self.tk.call('tk', 'busy', 'status', window)):
|
|
65
|
+
self.tk.call('tk', 'busy', 'hold', window)
|
|
66
|
+
self.busy.add(window)
|
|
67
|
+
pending.extend(self.tk.splitlist(self.tk.call('winfo', 'children', window)))
|
|
68
|
+
self._release_grab()
|
|
69
|
+
|
|
70
|
+
def __enter__(self):
|
|
71
|
+
if threading.current_thread() is not threading.main_thread():
|
|
72
|
+
raise RuntimeError('Tk file dialogs must run on the main thread')
|
|
73
|
+
key = id(self.tk)
|
|
74
|
+
if key in _active_interpreters:
|
|
75
|
+
raise RuntimeError('A native file dialog is already active for this Tk application')
|
|
76
|
+
_active_interpreters.add(key)
|
|
77
|
+
try:
|
|
78
|
+
if self.alive:
|
|
79
|
+
self.focus = str(self.tk.call('focus'))
|
|
80
|
+
# Prepend the tag so widget, class and bind_all shortcuts cannot run.
|
|
81
|
+
for sequence in ('<KeyPress>', '<KeyRelease>', '<ButtonPress>',
|
|
82
|
+
'<ButtonRelease>', '<MouseWheel>', '<<Drop>>', '<<Drop:DND_Files>>'):
|
|
83
|
+
self.tk.call('bind', self.tag, sequence, 'break')
|
|
84
|
+
self._protect_windows()
|
|
85
|
+
self.master.update_idletasks()
|
|
86
|
+
return self
|
|
87
|
+
except BaseException:
|
|
88
|
+
self.__exit__(*sys.exc_info())
|
|
89
|
+
raise
|
|
90
|
+
|
|
91
|
+
def pump(self) -> bool | None:
|
|
92
|
+
if not self.alive:
|
|
93
|
+
return False
|
|
94
|
+
try:
|
|
95
|
+
self._protect_windows()
|
|
96
|
+
deadline = time.monotonic() + .005
|
|
97
|
+
for _ in range(64):
|
|
98
|
+
if not self.tk.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
|
|
99
|
+
break
|
|
100
|
+
if not self.alive:
|
|
101
|
+
return False
|
|
102
|
+
if time.monotonic() >= deadline:
|
|
103
|
+
break
|
|
104
|
+
self._protect_windows()
|
|
105
|
+
except tk.TclError:
|
|
106
|
+
if not self.alive:
|
|
107
|
+
return False
|
|
108
|
+
raise
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
def __exit__(self, *_):
|
|
112
|
+
try:
|
|
113
|
+
for window in self.busy:
|
|
114
|
+
if self._exists(window) and self.tk.getboolean(self.tk.call('tk', 'busy', 'status', window)):
|
|
115
|
+
self.tk.call('tk', 'busy', 'forget', window)
|
|
116
|
+
for window in self.tagged:
|
|
117
|
+
if self._exists(window):
|
|
118
|
+
tags = self.tk.splitlist(self.tk.call('bindtags', window))
|
|
119
|
+
self.tk.call('bindtags', window, tuple(tag for tag in tags if tag != self.tag))
|
|
120
|
+
# The interpreter survives destruction of its root, but Tk commands may not.
|
|
121
|
+
for sequence in self.tk.splitlist(self.tk.call('bind', self.tag)):
|
|
122
|
+
self.tk.call('bind', self.tag, sequence, '')
|
|
123
|
+
if self.grab and self._exists(self.grab[0]):
|
|
124
|
+
if not self.tk.call('grab', 'current', self.grab[0]):
|
|
125
|
+
args = ('-global', self.grab[0]) if self.grab[1] == 'global' else (self.grab[0],)
|
|
126
|
+
self.tk.call('grab', 'set', *args)
|
|
127
|
+
if self.focus and self._exists(self.focus):
|
|
128
|
+
self.tk.call('focus', '-force', self.focus)
|
|
129
|
+
except tk.TclError:
|
|
130
|
+
if self._exists('.'):
|
|
131
|
+
raise
|
|
132
|
+
finally:
|
|
133
|
+
_active_interpreters.discard(id(self.tk))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _dialog(operation: str, master: tk.Misc, backend: Backend | None, **kwargs):
|
|
137
|
+
module = resolve_backend(backend)
|
|
138
|
+
kwargs['title'] = kwargs.get('title') or ''
|
|
139
|
+
kwargs['initialdir'] = os.fspath(kwargs['initialdir']) if kwargs.get('initialdir') else '.'
|
|
140
|
+
if module.__name__.rsplit('.', 1)[-1] == 'tk':
|
|
141
|
+
return _call_backend(module, operation, parent=master, **kwargs)
|
|
142
|
+
if sys.platform != 'linux':
|
|
143
|
+
return _call_backend(module, operation, **kwargs)
|
|
144
|
+
with _TkModal(master) as modal:
|
|
145
|
+
if not modal.alive:
|
|
146
|
+
return None
|
|
147
|
+
result = _call_backend(module, operation, event_pump=modal.pump, **kwargs)
|
|
148
|
+
return result if modal.alive else None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def open_file(title: str | None = None, initialdir: PathLike | None = None,
|
|
152
|
+
filters: FilterSpec | None = None, multiple: bool = False,
|
|
153
|
+
backend: Backend | None = None, *, master: tk.Misc) -> list[str] | None:
|
|
154
|
+
return _dialog('open_file', master, backend, title=title, initialdir=initialdir,
|
|
155
|
+
filters=filters, multiple=multiple)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def save_file(title: str | None = None, initialdir: PathLike | None = None,
|
|
159
|
+
filters: FilterSpec | None = None, default_name: str | None = None,
|
|
160
|
+
backend: Backend | None = None, *, master: tk.Misc) -> str | None:
|
|
161
|
+
return _dialog('save_file', master, backend, title=title, initialdir=initialdir,
|
|
162
|
+
filters=filters, default_name=default_name)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def open_directory(title: str | None = None, initialdir: PathLike | None = None,
|
|
166
|
+
backend: Backend | None = None, *, master: tk.Misc) -> str | None:
|
|
167
|
+
return _dialog('open_directory', master, backend, title=title, initialdir=initialdir)
|