pyflutter-ui 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,274 @@
1
+ # file_picker.py
2
+ # Implementação de FilePicker para PyFlutter no padrão do Flutter real.
3
+ #
4
+ # No Flutter, FilePicker não é um widget — é um controller/serviço que
5
+ # expõe um método pickFiles() e notifica os listeners com o resultado.
6
+ # Este arquivo replica essa arquitetura usando os primitivos do PyFlutter.
7
+ #
8
+ # ─────────────────────────────────────────────────────────────
9
+ # USO BÁSICO
10
+ # ─────────────────────────────────────────────────────────────
11
+ #
12
+ # picker = FilePickerController(
13
+ # type=FilePickerType.image, # filtro de tipo
14
+ # allow_multiple=True, # seleção múltipla
15
+ # )
16
+ #
17
+ # # Abrir o diálogo e aguardar o resultado:
18
+ # result: FilePickerResult | None = picker.pick_files()
19
+ # if result:
20
+ # for f in result.files:
21
+ # print(f.name, f.path, f.size)
22
+ #
23
+ # # Ou de forma reativa (integrado ao build do widget):
24
+ # ValueListenableBuilder(
25
+ # notifier=picker.result_notifier,
26
+ # builder=lambda ctx, result: Text(
27
+ # result.files[0].name if result else "Nenhum arquivo"
28
+ # ),
29
+ # )
30
+ # ─────────────────────────────────────────────────────────────
31
+
32
+ from __future__ import annotations
33
+ import os
34
+ from dataclasses import dataclass, field
35
+ from enum import Enum
36
+ from tkinter import filedialog
37
+ from typing import Optional
38
+ from pyflutter_ui.ui.core import ValueNotifier
39
+
40
+
41
+ # ============================================================
42
+ # TIPOS DE ARQUIVO — espelha o FileType do flutter_file_picker
43
+ # ============================================================
44
+
45
+ class FilePickerType(Enum):
46
+ """Filtro de tipo de arquivo para o diálogo."""
47
+ any = "any" # sem filtro
48
+ image = "image" # png, jpg, jpeg, gif, bmp, webp, svg
49
+ pdf = "pdf" # pdf
50
+ spreadsheet = "spreadsheet" # xlsx, xls, csv, ods
51
+ video = "video" # mp4, mov, avi, mkv, webm
52
+ audio = "audio" # mp3, wav, ogg, flac, aac
53
+ custom = "custom" # usa allowed_extensions fornecido pelo dev
54
+
55
+
56
+ # Mapeamento interno: tipo → lista de extensões tk-compatíveis
57
+ _TYPE_FILTERS: dict[FilePickerType, list[tuple[str, str]]] = {
58
+ FilePickerType.any: [("Todos os arquivos", "*.*")],
59
+ FilePickerType.image: [
60
+ ("Imagens", "*.png *.jpg *.jpeg *.gif *.bmp *.webp *.svg"),
61
+ ("Todos os arquivos", "*.*"),
62
+ ],
63
+ FilePickerType.pdf: [
64
+ ("PDF", "*.pdf"),
65
+ ("Todos os arquivos", "*.*"),
66
+ ],
67
+ FilePickerType.spreadsheet: [
68
+ ("Planilhas", "*.xlsx *.xls *.csv *.ods"),
69
+ ("Todos os arquivos", "*.*"),
70
+ ],
71
+ FilePickerType.video: [
72
+ ("Vídeos", "*.mp4 *.mov *.avi *.mkv *.webm"),
73
+ ("Todos os arquivos", "*.*"),
74
+ ],
75
+ FilePickerType.audio: [
76
+ ("Áudios", "*.mp3 *.wav *.ogg *.flac *.aac"),
77
+ ("Todos os arquivos", "*.*"),
78
+ ],
79
+ }
80
+
81
+
82
+ # ============================================================
83
+ # MODELO DE RESULTADO — espelha PlatformFile do Flutter
84
+ # ============================================================
85
+
86
+ @dataclass(frozen=True)
87
+ class PlatformFile:
88
+ """Representa um arquivo selecionado pelo usuário."""
89
+ path: str # caminho absoluto no disco
90
+ name: str = field(init=False) # nome do arquivo (sem diretório)
91
+ extension: str = field(init=False) # extensão sem ponto, ex: "pdf"
92
+ size: int = field(init=False) # tamanho em bytes (0 se inacessível)
93
+
94
+ def __post_init__(self) -> None:
95
+ # dataclass frozen=True exige object.__setattr__ para init tardio
96
+ object.__setattr__(self, "name", os.path.basename(self.path))
97
+ ext = os.path.splitext(self.path)[1].lstrip(".")
98
+ object.__setattr__(self, "extension", ext.lower())
99
+ try:
100
+ object.__setattr__(self, "size", os.path.getsize(self.path))
101
+ except OSError:
102
+ object.__setattr__(self, "size", 0)
103
+
104
+ @property
105
+ def size_readable(self) -> str:
106
+ """Tamanho formatado (bytes / KB / MB / GB)."""
107
+ n = self.size
108
+ for unit in ("B", "KB", "MB", "GB"):
109
+ if n < 1024:
110
+ return f"{n:.1f} {unit}" if unit != "B" else f"{n} {unit}"
111
+ n /= 1024
112
+ return f"{n:.1f} TB"
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class FilePickerResult:
117
+ """Resultado de uma seleção de arquivos. Equivale a FilePickerResult do Flutter."""
118
+ files: list[PlatformFile]
119
+
120
+ @property
121
+ def paths(self) -> list[str]:
122
+ """Atalho: lista de caminhos absolutos."""
123
+ return [f.path for f in self.files]
124
+
125
+ @property
126
+ def names(self) -> list[str]:
127
+ """Atalho: lista de nomes de arquivo."""
128
+ return [f.name for f in self.files]
129
+
130
+ @property
131
+ def is_single(self) -> bool:
132
+ return len(self.files) == 1
133
+
134
+ def single(self) -> PlatformFile | None:
135
+ """Retorna o único arquivo ou None se houver 0 ou mais de 1."""
136
+ return self.files[0] if self.is_single else None
137
+
138
+
139
+ # ============================================================
140
+ # CONTROLLER — o equivalente ao FilePicker.platform do Flutter
141
+ # ============================================================
142
+
143
+ class FilePickerController:
144
+ """
145
+ Controller que encapsula a lógica de seleção de arquivos.
146
+
147
+ Não é um widget — vive no State do seu widget pai, exatamente
148
+ como FilePickerController no Flutter.
149
+
150
+ Parâmetros
151
+ ----------
152
+ type : FilePickerType
153
+ Filtro de tipo de arquivo. Use FilePickerType.custom junto com
154
+ allowed_extensions para filtros personalizados.
155
+ allow_multiple : bool
156
+ Se True, permite selecionar vários arquivos de uma vez.
157
+ allowed_extensions : list[str] | None
158
+ Usado apenas quando type=FilePickerType.custom.
159
+ Ex.: ["json", "toml", "yaml"]
160
+ dialog_title : str
161
+ Título da janela de diálogo do SO.
162
+ initial_directory : str | None
163
+ Diretório inicial do diálogo. Padrão: pasta home do usuário.
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ type: FilePickerType = FilePickerType.any,
169
+ allow_multiple: bool = False,
170
+ allowed_extensions: Optional[list[str]] = None,
171
+ dialog_title: str = "Selecionar arquivo",
172
+ initial_directory: Optional[str] = None,
173
+ ) -> None:
174
+
175
+ self.type = type
176
+ self.allow_multiple = allow_multiple
177
+ self.allowed_extensions = allowed_extensions
178
+ self.dialog_title = dialog_title
179
+ self.initial_directory = initial_directory #or os.path.expanduser("~")
180
+
181
+ if self.initial_directory is None:
182
+ self.initial_directory = os.path.join(f"{os.path.expanduser("~")}", "Downloads")
183
+
184
+ # Expõe o resultado de forma reativa — use em ValueListenableBuilder
185
+ self.result_notifier: ValueNotifier[FilePickerResult | None] = ValueNotifier(None)
186
+
187
+ # ── API pública ───────────────────────────────────────────
188
+
189
+ def pick_files(self) -> FilePickerResult | None:
190
+ """
191
+ Abre o diálogo de seleção de arquivos do SO.
192
+
193
+ Retorna FilePickerResult se o usuário confirmou, None se cancelou.
194
+ Também atualiza result_notifier para notificar widgets ouvintes.
195
+ """
196
+ filters = self._resolve_filters()
197
+
198
+ if self.allow_multiple:
199
+ paths = filedialog.askopenfilenames(
200
+ title=self.dialog_title,
201
+ filetypes=filters,
202
+ initialdir=self.initial_directory,
203
+ )
204
+ raw = list(paths) if paths else []
205
+ else:
206
+ path = filedialog.askopenfilename(
207
+ title=self.dialog_title,
208
+ filetypes=filters,
209
+ initialdir=self.initial_directory,
210
+ )
211
+ raw = [path] if path else []
212
+
213
+ result = FilePickerResult(files=[PlatformFile(p) for p in raw]) if raw else None
214
+ if raw is not None:
215
+ first = raw[0] if len(raw) > 0 else None
216
+ if first is not None:
217
+ self.initial_directory = os.path.dirname(first)
218
+ print(f'{__class__.__name__} [INITIAL_DIR] ... {self.initial_directory}')
219
+
220
+ self.result_notifier.value = result
221
+ return result
222
+
223
+ def pick_directory(self) -> str | None:
224
+ """
225
+ Abre o diálogo para selecionar uma pasta.
226
+
227
+ Retorna o caminho absoluto ou None se cancelado.
228
+ """
229
+ path = filedialog.askdirectory(
230
+ title=self.dialog_title,
231
+ initialdir=self.initial_directory,
232
+ mustexist=True,
233
+ )
234
+ return path or None
235
+
236
+ def save_file(
237
+ self,
238
+ suggested_name: str = "",
239
+ ) -> str | None:
240
+ """
241
+ Abre o diálogo "Salvar como".
242
+
243
+ Retorna o caminho escolhido ou None se cancelado.
244
+ """
245
+ filters = self._resolve_filters()
246
+ default_ext = (
247
+ "." + self.allowed_extensions[0]
248
+ if self.allowed_extensions
249
+ else ""
250
+ )
251
+ path = filedialog.asksaveasfilename(
252
+ title=self.dialog_title,
253
+ filetypes=filters,
254
+ initialdir=self.initial_directory,
255
+ initialfile=suggested_name,
256
+ defaultextension=default_ext,
257
+ )
258
+ return path or None
259
+
260
+ def clear_result(self) -> None:
261
+ """Limpa o resultado atual e notifica os ouvintes."""
262
+ self.result_notifier.value = None
263
+
264
+ # ── privado ───────────────────────────────────────────────
265
+
266
+ def _resolve_filters(self) -> list[tuple[str, str]]:
267
+ if self.type == FilePickerType.custom:
268
+ if not self.allowed_extensions:
269
+ return [("Todos os arquivos", "*.*")]
270
+ pattern = " ".join(f"*.{ext}" for ext in self.allowed_extensions)
271
+ label = ", ".join(self.allowed_extensions).upper()
272
+ return [(label, pattern), ("Todos os arquivos", "*.*")]
273
+ return _TYPE_FILTERS.get(self.type, [("Todos os arquivos", "*.*")])
274
+
@@ -0,0 +1,94 @@
1
+ # navigator.py
2
+ from __future__ import annotations
3
+ from abc import ABC, abstractmethod
4
+ from typing import Callable
5
+ from pyflutter_ui.ui.core import (
6
+ BuildContext,
7
+ Element,
8
+ FlutterWidget,
9
+ BaseMaterialApp,
10
+ Navigator,
11
+ PageApp,
12
+ )
13
+
14
+
15
+ # ============================================================
16
+ # NAVIGATOR
17
+ # ============================================================
18
+ class Route(ABC):
19
+
20
+ def __init__(self) -> None:
21
+ super().__init__()
22
+
23
+ @abstractmethod
24
+ def build(self, context: BuildContext) -> PageApp:
25
+ pass
26
+
27
+
28
+ class PageRoute(Route):
29
+
30
+ def __init__(self, builder: Callable[[BuildContext], PageApp]) -> None:
31
+ super().__init__()
32
+ self.builder = builder
33
+
34
+ def build(self, context: BuildContext) -> PageApp:
35
+ return self.builder(context)
36
+
37
+
38
+ class NavigatorApp(Navigator):
39
+
40
+ def __init__(self, app: BaseMaterialApp) -> None:
41
+ super().__init__(app)
42
+
43
+ def push(self, page: PageApp) -> None:
44
+
45
+ if self.stack:
46
+ current = self.stack[-1]
47
+
48
+ if current.widget_tk is not None:
49
+ current.widget_tk.pack_forget()
50
+
51
+ self.app.get_root().title(page.name)
52
+
53
+ element = page.create_element()
54
+ context = BuildContext(self.app, parent_widget=self.app.get_root())
55
+ element.mount(context)
56
+ self.stack.append(element)
57
+ self.current_element = element
58
+
59
+ def pop(self) -> None:
60
+
61
+ if len(self.stack) <= 1:
62
+ return
63
+
64
+ current = self.stack.pop()
65
+ current.unmount()
66
+
67
+ previous = self.stack[-1]
68
+
69
+ if previous.widget_tk is not None:
70
+ previous.widget_tk.pack(fill="both", expand=True)
71
+ self.app.get_root().title(previous.get_widget_flutter().name)
72
+
73
+ self.current_element = previous
74
+
75
+ def replace(self, page: PageApp) -> None:
76
+
77
+ if self.stack:
78
+ current = self.stack.pop()
79
+
80
+ current.unmount()
81
+
82
+ element = page.create_element()
83
+
84
+ context = BuildContext(app=self.app, parent_widget=self.app.get_root())
85
+
86
+ element.mount(context)
87
+
88
+ self.stack.append(element)
89
+
90
+ self.current_element = element
91
+ self.app.get_root().title(self.current_element.get_widget_flutter().name)
92
+
93
+ def render(self) -> None:
94
+ pass
@@ -0,0 +1,154 @@
1
+ # pyflutter_ui/scheduler.py
2
+ from __future__ import annotations
3
+
4
+ import queue
5
+ import threading
6
+ import tkinter as tk
7
+ from typing import Callable, Optional
8
+
9
+
10
+ class MainThreadScheduler:
11
+
12
+ _root: Optional[tk.Tk] = None
13
+ _ui_thread_id: Optional[int] = None
14
+
15
+ _queue: queue.Queue[Callable[[], None]] = queue.Queue()
16
+
17
+ _polling: bool = False
18
+ _poll_interval_ms: int = 15
19
+
20
+ # ============================================================
21
+ # CICLO DE VIDA
22
+ # ============================================================
23
+
24
+ @classmethod
25
+ def attach(cls, root: tk.Tk) -> None:
26
+ """
27
+ Registra a janela Tk e a thread responsável pela UI.
28
+
29
+ Deve ser chamado na mesma thread que criou o tk.Tk().
30
+ """
31
+
32
+ cls._root = root
33
+ cls._ui_thread_id = threading.get_ident()
34
+
35
+ if not cls._polling:
36
+ cls._polling = True
37
+ cls._poll()
38
+
39
+ @classmethod
40
+ def detach(cls) -> None:
41
+ """
42
+ Remove o scheduler e descarta callbacks pendentes.
43
+ """
44
+
45
+ cls._polling = False
46
+ cls._root = None
47
+ cls._ui_thread_id = None
48
+
49
+ while True:
50
+ try:
51
+ cls._queue.get_nowait()
52
+ except queue.Empty:
53
+ break
54
+
55
+ @classmethod
56
+ def is_attached(cls) -> bool:
57
+ return (
58
+ cls._root is not None
59
+ and cls._ui_thread_id is not None
60
+ )
61
+
62
+ @classmethod
63
+ def is_ui_thread(cls) -> bool:
64
+ return (
65
+ cls._ui_thread_id is not None
66
+ and threading.get_ident() == cls._ui_thread_id
67
+ )
68
+
69
+ # ============================================================
70
+ # EXECUÇÃO
71
+ # ============================================================
72
+
73
+ @classmethod
74
+ def run(cls, callback: Callable[[], None]) -> None:
75
+ """
76
+ Executa callback na thread da interface.
77
+
78
+ Se já estiver na thread do Tk:
79
+ executa imediatamente.
80
+
81
+ Se estiver em uma worker thread:
82
+ coloca na fila para execução pelo Tk.
83
+ """
84
+
85
+ if not cls.is_attached():
86
+ raise RuntimeError(
87
+ f"{cls.__name__}: scheduler não está anexado. "
88
+ f"Crie o Tk() e chame attach(root) antes de usar run()."
89
+ )
90
+
91
+ if cls.is_ui_thread():
92
+ callback()
93
+ return
94
+
95
+ cls._queue.put(callback)
96
+
97
+ root = cls._root
98
+
99
+ if root is None:
100
+ return
101
+
102
+ try:
103
+ root.after(0, cls._drain)
104
+ except (tk.TclError, RuntimeError):
105
+ pass
106
+
107
+ # ============================================================
108
+ # FILA
109
+ # ============================================================
110
+
111
+ @classmethod
112
+ def _drain(cls) -> None:
113
+ """
114
+ Executa os callbacks pendentes na thread do Tk.
115
+ """
116
+
117
+ if not cls.is_ui_thread():
118
+ return
119
+
120
+ while True:
121
+
122
+ try:
123
+ callback = cls._queue.get_nowait()
124
+ except queue.Empty:
125
+ break
126
+
127
+ try:
128
+ callback()
129
+ except Exception as e:
130
+ print(
131
+ f"{cls.__name__} "
132
+ f"erro ao executar callback: {e}"
133
+ )
134
+
135
+ @classmethod
136
+ def _poll(cls) -> None:
137
+ """
138
+ Mantém o processamento da fila ativo.
139
+ """
140
+
141
+ root = cls._root
142
+
143
+ if root is None or not cls._polling:
144
+ return
145
+
146
+ cls._drain()
147
+
148
+ try:
149
+ root.after(
150
+ cls._poll_interval_ms,
151
+ cls._poll
152
+ )
153
+ except (tk.TclError, RuntimeError):
154
+ cls._polling = False
@@ -0,0 +1,80 @@
1
+ # system_theme.py
2
+ """
3
+ Detecção do tema do SO SEM subprocess/shell (somente stdlib e leitura de arquivos).
4
+
5
+ Substitui o corpo de `_detect_system_dark_mode()` do theme.py, que usava
6
+ `subprocess` (macOS) e criava uma segunda janela tk.Tk() (Linux).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import configparser
11
+ import os
12
+ import plistlib
13
+ import sys
14
+ from abc import ABC, abstractmethod
15
+ from pathlib import Path
16
+
17
+
18
+ class SystemThemeDetector(ABC):
19
+ """Strategy: uma implementação por sistema operacional."""
20
+
21
+ @abstractmethod
22
+ def is_dark(self) -> bool:
23
+ """True se o SO estiver em modo escuro. Na dúvida, False (claro)."""
24
+
25
+ @staticmethod
26
+ def create() -> SystemThemeDetector:
27
+ if sys.platform == "win32":
28
+ return WindowsThemeDetector()
29
+ if sys.platform == "darwin":
30
+ return MacThemeDetector()
31
+ return LinuxThemeDetector()
32
+
33
+
34
+ class WindowsThemeDetector(SystemThemeDetector):
35
+ _KEY = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
36
+
37
+ def is_dark(self) -> bool:
38
+ try:
39
+ import winreg # stdlib, só existe no Windows
40
+
41
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self._KEY) as key:
42
+ value, _ = winreg.QueryValueEx(key, "AppsUseLightTheme")
43
+ return int(value) == 0
44
+ except (ImportError, OSError, ValueError):
45
+ return False
46
+
47
+
48
+ class MacThemeDetector(SystemThemeDetector):
49
+ def is_dark(self) -> bool:
50
+ path = Path.home() / "Library" / "Preferences" / ".GlobalPreferences.plist"
51
+ try:
52
+ with path.open("rb") as fh:
53
+ data: dict[str, object] = plistlib.load(fh)
54
+ except (OSError, ValueError):
55
+ return False
56
+ return str(data.get("AppleInterfaceStyle", "")).lower() == "dark"
57
+
58
+
59
+ class LinuxThemeDetector(SystemThemeDetector):
60
+ """
61
+ Lê GTK_THEME e ~/.config/gtk-3.0/settings.ini.
62
+ Limitação: a chave moderna do GNOME (color-scheme) só é legível via
63
+ gsettings/dbus, que não usamos de propósito. Nesse caso o app assume
64
+ claro; basta escolher Escuro/Claro manualmente nas Configurações.
65
+ """
66
+
67
+ def is_dark(self) -> bool:
68
+ if "dark" in os.environ.get("GTK_THEME", "").lower():
69
+ return True
70
+
71
+ base = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
72
+ parser = configparser.ConfigParser(interpolation=None)
73
+ try:
74
+ parser.read(base / "gtk-3.0" / "settings.ini", encoding="utf-8")
75
+ except (OSError, configparser.Error, UnicodeDecodeError):
76
+ return False
77
+
78
+ if parser.getboolean("Settings", "gtk-application-prefer-dark-theme", fallback=False):
79
+ return True
80
+ return "dark" in parser.get("Settings", "gtk-theme-name", fallback="").lower()