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,89 @@
1
+ from .ui import (
2
+ BaseMaterialApp,
3
+ BuildContext,
4
+ PageApp,
5
+ ChangeNotifier,
6
+ CommandNotifier,
7
+ Consumer,
8
+ Element,
9
+ FlutterWidget,
10
+ ConsumerState,
11
+ LayoutData,
12
+ Navigator,
13
+ Provider,
14
+ StatefulWidget,
15
+ StatelessWidget,
16
+ State,
17
+ ValueNotifier,
18
+ ValueListenableBuilder,
19
+ Provider,
20
+ AlignElement,
21
+ Align,
22
+ AppBar,
23
+ BottomNavigationBar,
24
+ Center,
25
+ Card,
26
+ Checkbox,
27
+ CircularProgress,
28
+ Container,
29
+ Divider,
30
+ Drawer,
31
+ Column,
32
+ Row,
33
+ DropdownButton,
34
+ ElevatedButton,
35
+ Flexible,
36
+ Expanded,
37
+ FloatingActionButton,
38
+ Icon,
39
+ IconButton,
40
+ LinearProgress,
41
+ Provider,
42
+ Padding,
43
+ Image,
44
+ ListBuilder,
45
+ MainAxisAlignment,
46
+ CrossAxisAlignment,
47
+ TableView,
48
+ TkMaterialApp,
49
+ Scaffold,
50
+ Text,
51
+ SizedBox,
52
+ Alignment,
53
+ ScrollView,
54
+ GlobalKey,
55
+ TextEditingController,
56
+ TextInput,
57
+ )
58
+
59
+ from .theme import (
60
+ ColorScheme,
61
+ CardTheme,
62
+ InputDecorationTheme,
63
+ TextStyle,
64
+ Theme,
65
+ ThemeData,
66
+ ThemeMode,
67
+ ThemeProvider,
68
+ TextTheme,
69
+ make_themed_app,
70
+ )
71
+
72
+ from .file_picker import (
73
+ FilePickerController,
74
+ FilePickerResult,
75
+ FilePickerType,
76
+ PlatformFile,
77
+ )
78
+
79
+ from pyflutter_ui.ui.list_builder import (
80
+ ScrollableColumn,
81
+ ScrollableColumnElement,
82
+ ScrollableColumnOrProgress,
83
+ )
84
+
85
+ from .navigator import NavigatorApp, PageRoute, Route
86
+ from .app import run_app, SnackBar, SnackBarType
87
+
88
+ from .table_widget import TableOrProgress
89
+ from .config_app import AppConfigNotifier, FactoryMapConfig, MapConfig
pyflutter_ui/app.py ADDED
@@ -0,0 +1,295 @@
1
+ # app.py
2
+ from __future__ import annotations
3
+ from enum import Enum, auto
4
+ from tkinter import Tk
5
+ import tkinter as tk
6
+ from typing import Callable, Optional
7
+
8
+ from pyflutter_ui.ui import BuildContext, TkMaterialApp
9
+ from pyflutter_ui.theme import ThemeData, ThemeMode, ThemeProvider, ColorScheme
10
+ from pyflutter_ui.config_app import AppConfigNotifier
11
+
12
+ # ============================================================
13
+ # SNACKBAR
14
+ # ============================================================
15
+
16
+
17
+ class SnackBarType(Enum):
18
+ INFO = auto()
19
+ SUCCESS = auto()
20
+ WARNING = auto()
21
+ ERROR = auto()
22
+
23
+
24
+ class SnackBar:
25
+ """
26
+ Exibe uma mensagem temporária na parte inferior da janela,
27
+ similar ao SnackBar do Flutter.
28
+
29
+ Uso via contexto (recomendado):
30
+ SnackBar.of(context).show("Arquivo salvo!", type=SnackBarType.SUCCESS)
31
+
32
+ Uso direto com root Tk:
33
+ SnackBar.show_on(root, "Erro ao carregar", type=SnackBarType.ERROR)
34
+ """
35
+
36
+ # cores por tipo — funcionam tanto em tema claro quanto escuro
37
+ _COLORS = {
38
+ SnackBarType.INFO: {"bg": "#323232", "fg": "#FFFFFF", "accent": "#90CAF9"},
39
+ SnackBarType.SUCCESS: {"bg": "#1B5E20", "fg": "#FFFFFF", "accent": "#A5D6A7"},
40
+ SnackBarType.WARNING: {"bg": "#E65100", "fg": "#FFFFFF", "accent": "#FFE082"},
41
+ SnackBarType.ERROR: {"bg": "#B71C1C", "fg": "#FFFFFF", "accent": "#EF9A9A"},
42
+ }
43
+
44
+ _ICONS = {
45
+ SnackBarType.INFO: "ℹ",
46
+ SnackBarType.SUCCESS: "✓",
47
+ SnackBarType.WARNING: "⚠",
48
+ SnackBarType.ERROR: "✕",
49
+ }
50
+
51
+ def __init__(self, root: tk.Tk) -> None:
52
+ self._root = root
53
+ self._current: Optional[tk.Toplevel] = None
54
+ self._after_id: Optional[str] = None
55
+
56
+ @classmethod
57
+ def of(cls, context: BuildContext) -> SnackBar:
58
+ """Obtém o SnackBar a partir de um BuildContext."""
59
+ root = context.app.get_root()
60
+ # reutiliza instância já anexada ao root
61
+ if not hasattr(root, "_snackbar"):
62
+ root._snackbar = cls(root)
63
+ return root._snackbar
64
+
65
+ @classmethod
66
+ def show_on(
67
+ cls,
68
+ root: tk.Tk,
69
+ message: str,
70
+ *,
71
+ type: SnackBarType = SnackBarType.INFO,
72
+ duration: int = 3000,
73
+ action_label: Optional[str] = None,
74
+ on_action: Optional[Callable[[], None]] = None,
75
+ ) -> None:
76
+ """Atalho estático: não precisa instanciar."""
77
+ if not hasattr(root, "_snackbar"):
78
+ root._snackbar = cls(root)
79
+ root._snackbar.show(
80
+ message,
81
+ type=type,
82
+ duration=duration,
83
+ action_label=action_label,
84
+ on_action=on_action,
85
+ )
86
+
87
+ def show(
88
+ self,
89
+ message: str,
90
+ *,
91
+ type: SnackBarType = SnackBarType.INFO,
92
+ duration: int = 3000,
93
+ action_label: Optional[str] = None,
94
+ on_action: Optional[Callable[[], None]] = None,
95
+ ) -> None:
96
+ """Exibe o SnackBar. Descarta o anterior se ainda estiver visível."""
97
+ self._dismiss()
98
+
99
+ colors = self._COLORS[type]
100
+ icon = self._ICONS[type]
101
+
102
+ # ── janela sem borda flutuando sobre o root ──────────
103
+ popup = tk.Toplevel(self._root)
104
+ popup.title("Aviso")
105
+ popup.geometry("400x50")
106
+ popup.overrideredirect(True) # sem barra de título
107
+ popup.attributes("-topmost", True)
108
+ popup.configure(bg=colors["bg"])
109
+
110
+ self._current = popup
111
+
112
+ # ── frame interno com padding ─────────────────────────
113
+ frame = tk.Frame(popup, bg=colors["bg"], padx=12, pady=10)
114
+ frame.pack(fill="both", expand=True)
115
+
116
+ # ícone
117
+ tk.Label(
118
+ frame,
119
+ text=icon,
120
+ bg=colors["bg"],
121
+ fg=colors["accent"],
122
+ font=("Helvetica", 14, "bold"),
123
+ ).pack(side="left", padx=(0, 8))
124
+
125
+ # mensagem
126
+ tk.Label(
127
+ frame,
128
+ text=message,
129
+ bg=colors["bg"],
130
+ fg=colors["fg"],
131
+ font=("Helvetica", 10),
132
+ wraplength=360,
133
+ justify="left",
134
+ anchor="w",
135
+ ).pack(side="left", fill="x", expand=True)
136
+
137
+ # botão de ação opcional (ex.: "DESFAZER")
138
+ if action_label and on_action:
139
+
140
+ def _action():
141
+ on_action()
142
+ self._dismiss()
143
+
144
+ tk.Button(
145
+ frame,
146
+ text=action_label.upper(),
147
+ bg=colors["bg"],
148
+ fg=colors["accent"],
149
+ font=("Helvetica", 9, "bold"),
150
+ relief="flat",
151
+ cursor="hand2",
152
+ bd=0,
153
+ highlightthickness=0,
154
+ command=_action,
155
+ ).pack(side="right", padx=(12, 0))
156
+
157
+ # botão X para fechar manualmente
158
+ tk.Button(
159
+ frame,
160
+ text="✕",
161
+ bg=colors["bg"],
162
+ fg=colors["fg"],
163
+ font=("Helvetica", 8),
164
+ relief="flat",
165
+ cursor="hand2",
166
+ bd=0,
167
+ highlightthickness=0,
168
+ command=self._dismiss,
169
+ ).pack(side="right", padx=(8, 0))
170
+
171
+ # ── posicionamento: canto inferior esquerdo do root ──
172
+ popup.update_idletasks()
173
+ self._reposition(popup)
174
+
175
+ # reposiciona se o root for movido ou redimensionado
176
+ self._root.bind("<Configure>", lambda e: self._reposition(popup), add="+")
177
+
178
+ # ── animação de entrada (slide up) ───────────────────
179
+ self._animate_in(popup)
180
+
181
+ # ── auto-dismiss ──────────────────────────────────────
182
+ if duration > 0:
183
+ self._after_id = self._root.after(duration, self._dismiss)
184
+
185
+ def _reposition(self, popup: tk.Toplevel) -> None:
186
+ if popup is None or not popup.winfo_exists():
187
+ return
188
+
189
+ root = self._root
190
+ rx = root.winfo_x()
191
+ ry = root.winfo_y()
192
+ rw = root.winfo_width()
193
+ rh = root.winfo_height()
194
+
195
+ pw = popup.winfo_width()
196
+ ph = popup.winfo_height()
197
+
198
+ margin = 16
199
+ x = rx + margin
200
+ y = ry + rh - ph - margin
201
+
202
+ popup.geometry(f"+{x}+{y}")
203
+
204
+ def _animate_in(self, popup: tk.Toplevel, steps: int = 8) -> None:
205
+ """Desliza o popup de baixo para cima em `steps` passos."""
206
+ if not popup.winfo_exists():
207
+ return
208
+
209
+ root = self._root
210
+ rh = root.winfo_height()
211
+ ry = root.winfo_y()
212
+ ph = popup.winfo_reqheight()
213
+ margin = 16
214
+
215
+ target_y = ry + rh - ph - margin
216
+ start_y = ry + rh # começa fora da janela
217
+
218
+ def _step(current_y: int, step: int) -> None:
219
+ if not popup.winfo_exists():
220
+ return
221
+ if step >= steps:
222
+ popup.geometry(f"+{popup.winfo_x()}+{target_y}")
223
+ return
224
+ new_y = current_y + (target_y - current_y) // 2
225
+ popup.geometry(f"+{popup.winfo_x()}+{new_y}")
226
+ popup.after(16, lambda: _step(new_y, step + 1))
227
+
228
+ popup.geometry(f"+{popup.winfo_x()}+{start_y}")
229
+ _step(start_y, 0)
230
+
231
+ def _dismiss(self) -> None:
232
+ if self._after_id:
233
+ self._root.after_cancel(self._after_id)
234
+ self._after_id = None
235
+
236
+ if self._current and self._current.winfo_exists():
237
+ self._animate_out(self._current)
238
+ self._current = None
239
+
240
+ def _animate_out(self, popup: tk.Toplevel, steps: int = 6) -> None:
241
+ """Desliza o popup para baixo antes de destruir."""
242
+ if not popup.winfo_exists():
243
+ return
244
+
245
+ root = self._root
246
+ rh = root.winfo_height()
247
+ ry = root.winfo_y()
248
+ target = ry + rh + 10 # fora da janela
249
+
250
+ def _step(current_y: int, step: int) -> None:
251
+ if not popup.winfo_exists():
252
+ return
253
+ if step >= steps:
254
+ popup.destroy()
255
+ return
256
+ new_y = current_y + (target - current_y) // 2 + 2
257
+ popup.geometry(f"+{popup.winfo_x()}+{new_y}")
258
+ popup.after(16, lambda: _step(new_y, step + 1))
259
+
260
+ _step(popup.winfo_y(), 0)
261
+
262
+
263
+ def create_theme_provider(mode: ThemeMode = ThemeMode.DARK) -> ThemeProvider:
264
+
265
+ return ThemeProvider(
266
+ light_theme=ThemeData.light(color_scheme=ColorScheme.light()),
267
+ dark_theme=ThemeData.dark(color_scheme=ColorScheme.dark()),
268
+ mode=mode,
269
+ )
270
+
271
+
272
+ def include_theme_app(app: TkMaterialApp) -> TkMaterialApp:
273
+
274
+ if app._root is None:
275
+ app._root = Tk()
276
+
277
+ try:
278
+ notifier: ThemeProvider = app.read_state(ThemeProvider)
279
+ notifier.attach_root(app.get_root())
280
+ except KeyError as e:
281
+ print(f"ThemeProvider não registrado: {e}")
282
+
283
+ # NÃO fazer push(app.home) aqui: TkMaterialApp.run() já faz.
284
+ return app
285
+
286
+
287
+ def run_app(app: TkMaterialApp) -> None:
288
+ mode = ThemeMode.DARK
289
+ try:
290
+ mode = app.read_state(AppConfigNotifier).value.theme_mode
291
+ except KeyError:
292
+ pass # config não registrado: usa o padrão
293
+
294
+ app.register_notifier(create_theme_provider(mode))
295
+ include_theme_app(app).run()
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+ from typing import Any
3
+ from dataclasses import dataclass
4
+ from table_stream import (
5
+ File,
6
+ Directory,
7
+ UserFileSystem,
8
+ JsonConvert,
9
+ HashMapDict,
10
+ HashMap,
11
+ ArrayList,
12
+ )
13
+ from pyflutter_ui.theme import ThemeMode
14
+ from pyflutter_ui.ui.core import ValueNotifier
15
+
16
+
17
+ @dataclass
18
+ class MapConfig:
19
+ initial_dir: Directory
20
+ last_dir: Directory
21
+ work_dir: Directory
22
+ documents_dir: Directory
23
+ theme_mode: ThemeMode
24
+ initial_dir_map: HashMap[str, Directory]
25
+ cartas_dir: Directory | None = None # None = padrão do módulo cartas
26
+ # ^^ apagar isso futuramente, pois cartas_dir é algo especifico de responds_forms
27
+ # enquanto pyflutter_ui deve ser bem generico para ser usado em qualquer app.
28
+
29
+
30
+ class FactoryMapConfig(object):
31
+
32
+ def __init__(self) -> None:
33
+ self._conf: MapConfig = self._create()
34
+
35
+ def _create(self) -> MapConfig:
36
+
37
+ self._conf: MapConfig = MapConfig(
38
+ initial_dir=UserFileSystem().get_user_downloads(),
39
+ last_dir=UserFileSystem().get_user_downloads(),
40
+ work_dir=UserFileSystem().get_user_downloads().concat("RFA", True),
41
+ documents_dir=UserFileSystem().get_user_downloads().concat("RFA", True),
42
+ theme_mode=ThemeMode.DARK,
43
+ initial_dir_map=HashMapDict(),
44
+ )
45
+ return self._conf
46
+
47
+ def set_name_initial_dir(self, name: str, d: Directory):
48
+ self._conf.initial_dir_map.set_value(name, d)
49
+
50
+ def create_default(self) -> MapConfig:
51
+ return self._conf
52
+
53
+ def create_from_dict(self, h: HashMapDict[str, Any]) -> MapConfig:
54
+ if h.header().contains("work_dir"):
55
+ self._conf.work_dir = Directory(h["work_dir"])
56
+
57
+ if h.header().contains("documents_dir"):
58
+ self._conf.documents_dir = Directory(h["documents_dir"])
59
+
60
+ if h.header().contains("cartas_dir"):
61
+ self._conf.cartas_dir = Directory(h["cartas_dir"])
62
+
63
+ if h.header().contains("initial_dir"):
64
+ self._conf.initial_dir = Directory(h["initial_dir"])
65
+
66
+ if h.header().contains("last_dir"):
67
+ self._conf.last_dir = Directory(h["last_dir"])
68
+
69
+ if h.header().contains("theme_mode"):
70
+ if h["theme_mode"] == "dark":
71
+ self._conf.theme_mode = ThemeMode.DARK
72
+ elif h["theme_mode"] == "light":
73
+ self._conf.theme_mode = ThemeMode.LIGHT
74
+ else:
75
+ self._conf.theme_mode = ThemeMode.SYSTEM
76
+
77
+ if h.header().contains("initial_dir_map"):
78
+ _map_initial_dict: dict[str, str] = h.get_value("initial_dir_map")
79
+ final_map = HashMapDict[str, Directory]()
80
+ keys_initial_dir = ArrayList.from_list(list(_map_initial_dict.keys()))
81
+
82
+ keys_initial_dir.for_each(
83
+ lambda k: final_map.set_value(k, Directory(_map_initial_dict[k]))
84
+ )
85
+ self._conf.initial_dir_map = final_map
86
+
87
+ return self._conf
88
+
89
+ def create_from_file(self, file_json: File) -> MapConfig:
90
+ converter = JsonConvert.from_file(file_json)
91
+ map_data = converter.data.to_dict()
92
+ return self.create_from_dict(HashMapDict(map_data))
93
+
94
+
95
+ class AppConfigNotifier(ValueNotifier[MapConfig]):
96
+
97
+ file_config: File = UserFileSystem().cache_dir().join_file("RFA-config.json")
98
+
99
+ def __init__(self, value: MapConfig = FactoryMapConfig().create_default()) -> None:
100
+ super().__init__(value)
101
+ # self._file_config: File = self.value.work_dir.concat("config", True).join_file("app_config.json")
102
+
103
+ def set_work_dir(self, d: Directory):
104
+ self._value.work_dir = d
105
+ self.notify_listeners()
106
+
107
+ def set_initial_dir(self, d: Directory):
108
+ self._value.initial_dir = d
109
+ self.notify_listeners()
110
+
111
+ def set_documents_dir(self, d: Directory):
112
+ self._value.documents_dir = d
113
+ self.notify_listeners()
114
+
115
+ def set_initial_dir_named(self, name: str, d: Directory):
116
+ cfg = self._value
117
+ cfg.initial_dir_map[name] = d
118
+ self._value = cfg
119
+ self.notify_listeners()
120
+
121
+ def get_file_config(self) -> File:
122
+ return AppConfigNotifier.file_config
123
+
124
+ def set_theme_mode(self, mode: ThemeMode) -> None:
125
+ self._value.theme_mode = mode
126
+ self.notify_listeners()
127
+
128
+ def set_cartas_dir(self, d: Directory | None) -> None:
129
+ self._value.cartas_dir = d
130
+ self.notify_listeners()
131
+
132
+ def get_dict_config(self) -> dict[str, object]:
133
+ return self.config_to_map()
134
+
135
+ def config_to_map(self) -> dict[str, object]:
136
+ final = dict[str, object]()
137
+ cfg = self.value
138
+ final = dict[str, Any]()
139
+ cfg = self.value
140
+
141
+ # Converter initial_dir_map para dict/json
142
+ json_initial_dir_map = dict[str, str]()
143
+ header_initial_dir = cfg.initial_dir_map.header()
144
+ header_initial_dir.for_each(
145
+ lambda h_name: json_initial_dir_map.setdefault(
146
+ h_name, cfg.initial_dir_map.get_value(h_name).absolute()
147
+ )
148
+ )
149
+
150
+ final["initial_dir_map"] = json_initial_dir_map
151
+ final["initial_dir"] = cfg.initial_dir.absolute()
152
+ final["last_dir"] = cfg.last_dir.absolute()
153
+ final["work_dir"] = cfg.work_dir.absolute()
154
+ final["documents_dir"] = cfg.documents_dir.absolute()
155
+ final["theme_mode"] = cfg.theme_mode.value
156
+
157
+ if cfg.cartas_dir is not None:
158
+ final["cartas_dir"] = cfg.cartas_dir.absolute()
159
+
160
+ return final
161
+
162
+ def save_config(self):
163
+ converter = JsonConvert.from_dict(self.get_dict_config())
164
+ converter.data.to_file(self.get_file_config())
165
+ print(f"Configurações salvas em ... {self.get_file_config().absolute()}")
166
+
167
+ def notify_listeners(self) -> None:
168
+ """
169
+ Salvar a nova configuração em arquivo local e notificar os observadores.
170
+ """
171
+ self.save_config()
172
+ return super().notify_listeners()
173
+
174
+ @classmethod
175
+ def create(cls) -> AppConfigNotifier:
176
+ src = Directory(cls.file_config.dirname())
177
+ src.mkdir()
178
+
179
+ config: MapConfig
180
+ if cls.file_config.exists():
181
+ print(f"Lendo configração em ... {cls.file_config.absolute()}")
182
+ config = FactoryMapConfig().create_from_file(cls.file_config)
183
+ else:
184
+ config = FactoryMapConfig().create_default()
185
+ return cls(config)