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.
pyflutter_ui/theme.py ADDED
@@ -0,0 +1,1066 @@
1
+ # theme.py
2
+ """
3
+ Sistema de temas para pyflutter — inspirado na ThemeData do Flutter.
4
+
5
+ Funcionalidades:
6
+ - ThemeMode: light | dark | system (detecta o SO automaticamente)
7
+ - ColorScheme: paleta completa com primary, secondary, surface, error, etc.
8
+ - TextTheme: estilos tipográficos (displayLarge → labelSmall)
9
+ - ButtonThemeData: estilo para ElevatedButton, OutlinedButton, TextButton
10
+ - ThemeData: objeto raiz que agrega tudo e aplica no ttk.Style
11
+ - ThemeProvider(ChangeNotifier): permite trocar o tema em runtime
12
+
13
+ Uso básico:
14
+ from pyflutter.theme import ThemeData, ThemeMode, ThemeProvider
15
+
16
+ provider = ThemeProvider(ThemeData.light())
17
+ app.register_provider(provider)
18
+
19
+ # Para mudar o tema em runtime:
20
+ provider.set_mode(ThemeMode.DARK)
21
+ """
22
+
23
+ from __future__ import annotations
24
+ import sys
25
+ import tkinter as tk
26
+ from dataclasses import dataclass, field
27
+ from enum import Enum
28
+ from tkinter import ttk
29
+ from typing import Optional, TypeVar
30
+
31
+ from pyflutter_ui.ui.core import ChangeNotifier, BaseMaterialApp, Navigator
32
+ from pyflutter_ui.system_theme import SystemThemeDetector
33
+
34
+ T = TypeVar("T")
35
+
36
+ # ============================================================
37
+ # THEME MODE
38
+ # ============================================================
39
+
40
+
41
+ class ThemeMode(Enum):
42
+ """
43
+ Equivalente ao ThemeMode do Flutter.
44
+ SYSTEM detecta a preferência do sistema operacional.
45
+ """
46
+
47
+ LIGHT = "light"
48
+ DARK = "dark"
49
+ SYSTEM = "system"
50
+
51
+
52
+ def _detect_system_dark_mode() -> bool:
53
+ """
54
+ Tenta detectar se o SO está em modo escuro.
55
+ Suporta Windows, macOS e Linux (via tk).
56
+ Retorna True se dark mode estiver ativo.
57
+ """
58
+ return SystemThemeDetector.create().is_dark()
59
+
60
+
61
+ # ============================================================
62
+ # COLOR SCHEME
63
+ # ============================================================
64
+
65
+
66
+ @dataclass
67
+ class ColorScheme:
68
+ """
69
+ Paleta de cores completa, espelhando o ColorScheme do Flutter (Material 3).
70
+
71
+ Convenção:
72
+ - `primary` : cor principal da marca
73
+ - `on_primary` : texto/ícone sobre primary
74
+ - `primary_container` : variante de fundo para primary
75
+ - `on_primary_container` : texto sobre primary_container
76
+ - `secondary` : cor de destaque secundária
77
+ - `on_secondary` : texto sobre secondary
78
+ - `secondary_container`
79
+ - `on_secondary_container`
80
+ - `tertiary` / `on_tertiary` / `tertiary_container` / `on_tertiary_container`
81
+ - `error` / `on_error` / `error_container` / `on_error_container`
82
+ - `surface` : fundo dos cards/dialogs
83
+ - `on_surface` : texto sobre surface
84
+ - `surface_variant` : variante de surface
85
+ - `on_surface_variant`
86
+ - `background` : cor de fundo da janela
87
+ - `on_background` : texto sobre background
88
+ - `outline` : bordas e divisores
89
+ - `shadow` : cor de sombra
90
+ - `inverse_surface` / `on_inverse_surface` / `inverse_primary`
91
+ - `scrim` : overlay semi-transparente (Drawer, Modal)
92
+ """
93
+
94
+ # ── Primary ──────────────────────────────────────────────
95
+ primary: str = "#6750A4"
96
+ on_primary: str = "#FFFFFF"
97
+ primary_container: str = "#EADDFF"
98
+ on_primary_container: str = "#21005D"
99
+
100
+ # ── Secondary ────────────────────────────────────────────
101
+ secondary: str = "#625B71"
102
+ on_secondary: str = "#FFFFFF"
103
+ secondary_container: str = "#E8DEF8"
104
+ on_secondary_container: str = "#1D192B"
105
+
106
+ # ── Tertiary ─────────────────────────────────────────────
107
+ tertiary: str = "#7D5260"
108
+ on_tertiary: str = "#FFFFFF"
109
+ tertiary_container: str = "#FFD8E4"
110
+ on_tertiary_container: str = "#31111D"
111
+
112
+ # ── Error ────────────────────────────────────────────────
113
+ error: str = "#B3261E"
114
+ on_error: str = "#FFFFFF"
115
+ error_container: str = "#F9DEDC"
116
+ on_error_container: str = "#410E0B"
117
+
118
+ # ── Surface / Background ─────────────────────────────────
119
+ surface: str = "#FFFBFE"
120
+ on_surface: str = "#1C1B1F"
121
+ surface_variant: str = "#E7E0EC"
122
+ on_surface_variant: str = "#49454F"
123
+
124
+ background: str = "#FFFBFE"
125
+ on_background: str = "#1C1B1F"
126
+
127
+ # ── Utilities ────────────────────────────────────────────
128
+ outline: str = "#79747E"
129
+ outline_variant: str = "#CAC4D0"
130
+ shadow: str = "#000000"
131
+ scrim: str = "#000000"
132
+
133
+ # ── Inverse ──────────────────────────────────────────────
134
+ inverse_surface: str = "#313033"
135
+ on_inverse_surface: str = "#F4EFF4"
136
+ inverse_primary: str = "#D0BCFF"
137
+
138
+ @classmethod
139
+ def light(cls) -> "ColorScheme":
140
+ """Paleta Material 3 Light padrão."""
141
+ return cls()
142
+
143
+ @classmethod
144
+ def dark(cls) -> "ColorScheme":
145
+ """Paleta Material 3 Dark padrão."""
146
+ return cls(
147
+ primary="#D0BCFF",
148
+ on_primary="#381E72",
149
+ primary_container="#4F378B",
150
+ on_primary_container="#EADDFF",
151
+ secondary="#CCC2DC",
152
+ on_secondary="#332D41",
153
+ secondary_container="#4A4458",
154
+ on_secondary_container="#E8DEF8",
155
+ tertiary="#EFB8C8",
156
+ on_tertiary="#492532",
157
+ tertiary_container="#633B48",
158
+ on_tertiary_container="#FFD8E4",
159
+ error="#F2B8B5",
160
+ on_error="#601410",
161
+ error_container="#8C1D18",
162
+ on_error_container="#F9DEDC",
163
+ surface="#1C1B1F",
164
+ on_surface="#E6E1E5",
165
+ surface_variant="#49454F",
166
+ on_surface_variant="#CAC4D0",
167
+ background="#1C1B1F",
168
+ on_background="#E6E1E5",
169
+ outline="#938F99",
170
+ outline_variant="#49454F",
171
+ shadow="#000000",
172
+ scrim="#000000",
173
+ inverse_surface="#E6E1E5",
174
+ on_inverse_surface="#313033",
175
+ inverse_primary="#6750A4",
176
+ )
177
+
178
+
179
+ # ============================================================
180
+ # TEXT STYLE & TEXT THEME
181
+ # ============================================================
182
+
183
+
184
+ @dataclass
185
+ class TextStyle:
186
+ """
187
+ Estilo tipográfico individual.
188
+ Mapeia para os parâmetros de fonte do ttk.Label / tk.font.Font.
189
+ """
190
+
191
+ font_family: str = "Helvetica"
192
+ font_size: int = 10
193
+ font_weight: str = "normal" # "normal" | "bold"
194
+ font_slant: str = "roman" # "roman" | "italic"
195
+ color: Optional[str] = None # None = herda do ColorScheme
196
+
197
+ def to_tk_font(self) -> tuple:
198
+ """Retorna tupla compatível com o parâmetro `font=` do Tk."""
199
+ style = []
200
+ if self.font_weight == "bold":
201
+ style.append("bold")
202
+ if self.font_slant == "italic":
203
+ style.append("italic")
204
+ return (self.font_family, self.font_size) + (tuple(style) if style else ())
205
+
206
+
207
+ @dataclass
208
+ class TextTheme:
209
+ """
210
+ Hierarquia tipográfica completa — espelha o TextTheme do Flutter (Material 3).
211
+
212
+ Display → headings grandes (splash screens, hero)
213
+ Headline → títulos de seção
214
+ Title → AppBar, dialogs
215
+ Body → texto corrido
216
+ Label → botões, captions, chips
217
+ """
218
+
219
+ display_large: TextStyle = field(
220
+ default_factory=lambda: TextStyle(font_size=57, font_weight="normal")
221
+ )
222
+ display_medium: TextStyle = field(
223
+ default_factory=lambda: TextStyle(font_size=45, font_weight="normal")
224
+ )
225
+ display_small: TextStyle = field(
226
+ default_factory=lambda: TextStyle(font_size=36, font_weight="normal")
227
+ )
228
+
229
+ headline_large: TextStyle = field(
230
+ default_factory=lambda: TextStyle(font_size=32, font_weight="normal")
231
+ )
232
+ headline_medium: TextStyle = field(
233
+ default_factory=lambda: TextStyle(font_size=28, font_weight="normal")
234
+ )
235
+ headline_small: TextStyle = field(
236
+ default_factory=lambda: TextStyle(font_size=24, font_weight="normal")
237
+ )
238
+
239
+ title_large: TextStyle = field(
240
+ default_factory=lambda: TextStyle(font_size=22, font_weight="normal")
241
+ )
242
+ title_medium: TextStyle = field(
243
+ default_factory=lambda: TextStyle(font_size=14, font_weight="bold")
244
+ )
245
+ title_small: TextStyle = field(
246
+ default_factory=lambda: TextStyle(font_size=11, font_weight="bold")
247
+ )
248
+
249
+ body_large: TextStyle = field(
250
+ default_factory=lambda: TextStyle(font_size=16, font_weight="normal")
251
+ )
252
+ body_medium: TextStyle = field(
253
+ default_factory=lambda: TextStyle(font_size=14, font_weight="normal")
254
+ )
255
+ body_small: TextStyle = field(
256
+ default_factory=lambda: TextStyle(font_size=11, font_weight="normal")
257
+ )
258
+
259
+ label_large: TextStyle = field(
260
+ default_factory=lambda: TextStyle(font_size=14, font_weight="bold")
261
+ )
262
+ label_medium: TextStyle = field(
263
+ default_factory=lambda: TextStyle(font_size=12, font_weight="bold")
264
+ )
265
+ label_small: TextStyle = field(
266
+ default_factory=lambda: TextStyle(font_size=10, font_weight="bold")
267
+ )
268
+
269
+
270
+ # ============================================================
271
+ # BUTTON THEME DATA
272
+ # ============================================================
273
+
274
+
275
+ @dataclass
276
+ class ButtonThemeData:
277
+ """
278
+ Configuração visual dos botões.
279
+ Espelha ElevatedButtonThemeData / OutlinedButtonThemeData / TextButtonThemeData.
280
+ """
281
+
282
+ # Padding interno (px)
283
+ padding_x: int = 16
284
+ padding_y: int = 8
285
+
286
+ # Raio da borda (aproximado via relief no Tk)
287
+ border_radius: int = 12
288
+
289
+ # Altura mínima (px)
290
+ min_height: int = 20
291
+
292
+ # Estilos para cada variante
293
+ elevated_relief: str = "raised"
294
+ outlined_relief: str = "groove"
295
+ text_relief: str = "flat"
296
+
297
+
298
+ # ============================================================
299
+ # INPUT DECORATION THEME
300
+ # ============================================================
301
+
302
+
303
+ @dataclass
304
+ class InputDecorationTheme:
305
+ """
306
+ Estilo dos campos de texto (TextField).
307
+ """
308
+
309
+ border_color: Optional[str] = None # None = usa outline do ColorScheme
310
+ focused_border_color: Optional[str] = None # None = usa primary
311
+ label_color: Optional[str] = None
312
+ hint_color: Optional[str] = None
313
+ fill_color: Optional[str] = None # None = usa surface_variant
314
+ filled: bool = True
315
+ border_width: int = 1
316
+ padding_x: int = 12
317
+ padding_y: int = 8
318
+
319
+
320
+ # ============================================================
321
+ # APP BAR THEME
322
+ # ============================================================
323
+
324
+
325
+ @dataclass
326
+ class AppBarTheme:
327
+ """
328
+ Estilo da AppBar.
329
+ """
330
+
331
+ background_color: Optional[str] = None # None = usa surface do ColorScheme
332
+ foreground_color: Optional[str] = None # None = usa on_surface
333
+ elevation: int = 0
334
+ center_title: bool = False
335
+ title_text_style: Optional[TextStyle] = None
336
+
337
+
338
+ # ============================================================
339
+ # CARD THEME
340
+ # ============================================================
341
+
342
+
343
+ @dataclass
344
+ class CardTheme:
345
+ """
346
+ Estilo dos Cards.
347
+ """
348
+
349
+ color: Optional[str] = None # None = usa surface
350
+ shadow_color: Optional[str] = None # None = usa shadow
351
+ elevation: int = 1
352
+ margin: int = 4
353
+
354
+
355
+ # ============================================================
356
+ # DIVIDER THEME
357
+ # ============================================================
358
+
359
+
360
+ @dataclass
361
+ class DividerTheme:
362
+ color: Optional[str] = None # None = usa outline_variant
363
+ thickness: int = 1
364
+ indent: int = 0
365
+ end_indent: int = 0
366
+
367
+
368
+ # ============================================================
369
+ # THEME DATA
370
+ # ============================================================
371
+
372
+
373
+ class ThemeData:
374
+ """
375
+ Objeto raiz do tema — equivalente ao ThemeData do Flutter.
376
+
377
+ Agrega ColorScheme, TextTheme, ButtonThemeData e sub-temas,
378
+ e aplica tudo no ttk.Style quando `apply()` é chamado.
379
+
380
+ Exemplo:
381
+ theme = ThemeData.light()
382
+ theme.apply(root)
383
+ """
384
+
385
+ def __init__(
386
+ self,
387
+ color_scheme: ColorScheme,
388
+ text_theme: Optional[TextTheme] = None,
389
+ button_theme: Optional[ButtonThemeData] = None,
390
+ input_decoration_theme: Optional[InputDecorationTheme] = None,
391
+ app_bar_theme: Optional[AppBarTheme] = None,
392
+ card_theme: Optional[CardTheme] = None,
393
+ divider_theme: Optional[DividerTheme] = None,
394
+ font_family: str = "Helvetica",
395
+ ) -> None:
396
+ self.color_scheme = color_scheme
397
+ self.text_theme = text_theme or TextTheme()
398
+ self.button_theme = button_theme or ButtonThemeData()
399
+ self.input_decoration_theme = input_decoration_theme or InputDecorationTheme()
400
+ self.app_bar_theme = app_bar_theme or AppBarTheme()
401
+ self.card_theme = card_theme or CardTheme()
402
+ self.divider_theme = divider_theme or DividerTheme()
403
+ self.font_family = font_family
404
+
405
+ # Propaga font_family padrão para todos os TextStyle sem família definida
406
+ self._propagate_font_family()
407
+
408
+ def _propagate_font_family(self) -> None:
409
+ for attr in vars(self.text_theme).values():
410
+ if isinstance(attr, TextStyle) and attr.font_family == "Helvetica":
411
+ attr.font_family = self.font_family
412
+
413
+ # ── Factory ──────────────────────────────────────────────
414
+
415
+ @classmethod
416
+ def light(
417
+ cls,
418
+ color_scheme: Optional[ColorScheme] = None,
419
+ font_family: str = "Helvetica",
420
+ **kwargs,
421
+ ) -> "ThemeData":
422
+ """Cria um ThemeData com paleta Light."""
423
+ return cls(
424
+ color_scheme=color_scheme or ColorScheme.light(),
425
+ font_family=font_family,
426
+ **kwargs,
427
+ )
428
+
429
+ @classmethod
430
+ def dark(
431
+ cls,
432
+ color_scheme: Optional[ColorScheme] = None,
433
+ font_family: str = "Helvetica",
434
+ **kwargs,
435
+ ) -> "ThemeData":
436
+ """Cria um ThemeData com paleta Dark."""
437
+ return cls(
438
+ color_scheme=color_scheme or ColorScheme.dark(),
439
+ font_family=font_family,
440
+ **kwargs,
441
+ )
442
+
443
+ # ── Atalhos rápidos para cores ───────────────────────────
444
+
445
+ @property
446
+ def primary(self) -> str:
447
+ return self.color_scheme.primary
448
+
449
+ @property
450
+ def background(self) -> str:
451
+ return self.color_scheme.background
452
+
453
+ @property
454
+ def surface(self) -> str:
455
+ return self.color_scheme.surface
456
+
457
+ @property
458
+ def error(self) -> str:
459
+ return self.color_scheme.error
460
+
461
+ # ── Aplicação no ttk.Style ───────────────────────────────
462
+
463
+ def apply(self, root: tk.Tk) -> None:
464
+ """
465
+ Aplica o tema inteiro no ttk.Style.
466
+ Deve ser chamado APÓS tk.Tk() ser criado — nunca antes,
467
+ pois ttk.Style() sem um root existente cria uma janela tk implícita.
468
+
469
+ Args:
470
+ root: instância do tk.Tk. Obrigatório quando ainda não há
471
+ uma instância Tk ativa no processo.
472
+ """
473
+ # Garante que existe um root antes de instanciar o Style.
474
+ # Se nenhum root foi passado, usa o root padrão do Tk, que
475
+ # só existe se tk.Tk() já foi chamado antes.
476
+ if root is None and not tk._default_root: # noqa: SLF001
477
+ # Sem root ativo: não há como aplicar estilos ttk com segurança.
478
+ # O chamador deve passar o root explicitamente.
479
+ return
480
+
481
+ cs = self.color_scheme
482
+ tt = self.text_theme
483
+ bt = self.button_theme
484
+ idt = self.input_decoration_theme
485
+ abt = self.app_bar_theme
486
+ ct = self.card_theme
487
+ dt = self.divider_theme
488
+
489
+ style = ttk.Style(root) if root else ttk.Style()
490
+
491
+ # ── Tema base ────────────────────────────────────────
492
+ # Usa "clam" como base: permite sobrescrever mais configurações
493
+ try:
494
+ style.theme_use("clam")
495
+ except tk.TclError:
496
+ pass
497
+
498
+ # ── Janela principal ─────────────────────────────────
499
+ if root:
500
+ root.configure(bg=cs.background)
501
+
502
+ # ── TFrame ───────────────────────────────────────────
503
+ style.configure(
504
+ "TFrame",
505
+ background=cs.background,
506
+ )
507
+
508
+ style.configure(
509
+ "Surface.TFrame",
510
+ background=cs.surface,
511
+ )
512
+
513
+ style.configure(
514
+ "Card.TFrame",
515
+ background=ct.color or cs.surface,
516
+ relief="raised",
517
+ borderwidth=ct.elevation,
518
+ )
519
+
520
+ # ── TLabel ───────────────────────────────────────────
521
+ body_font = tt.body_small.to_tk_font()
522
+ title_font = tt.title_small.to_tk_font()
523
+ label_font = tt.label_small.to_tk_font()
524
+ display_font = tt.display_small.to_tk_font()
525
+ headline_font = tt.headline_small.to_tk_font()
526
+
527
+ style.configure(
528
+ "TLabel",
529
+ background=cs.background,
530
+ foreground=cs.on_background,
531
+ font=body_font,
532
+ padding=2,
533
+ )
534
+
535
+ # Variantes semânticas de label
536
+ _label_variants = {
537
+ "Display.TLabel": (display_font, cs.on_background),
538
+ "Headline.TLabel": (headline_font, cs.on_background),
539
+ "Title.TLabel": (title_font, cs.on_surface),
540
+ "Body.TLabel": (body_font, cs.on_background),
541
+ "Caption.TLabel": (tt.label_small.to_tk_font(), cs.on_surface_variant),
542
+ "Error.TLabel": (label_font, cs.error),
543
+ "Primary.TLabel": (label_font, cs.primary),
544
+ "OnPrimary.TLabel": (label_font, cs.on_primary),
545
+ }
546
+ for name, (font, fg) in _label_variants.items():
547
+ style.configure(
548
+ name,
549
+ background=cs.background,
550
+ foreground=fg,
551
+ font=font,
552
+ padding=2,
553
+ )
554
+
555
+ # Label sobre superfície colorida
556
+ style.configure(
557
+ "AppBar.TLabel",
558
+ background=abt.background_color or cs.surface,
559
+ foreground=abt.foreground_color or cs.on_surface,
560
+ font=(abt.title_text_style or tt.title_large).to_tk_font(),
561
+ padding=(8, 8),
562
+ )
563
+
564
+ # ── TButton (ElevatedButton) ─────────────────────────
565
+ style.configure(
566
+ "TButton",
567
+ background=cs.primary,
568
+ foreground=cs.on_primary,
569
+ font=tt.label_small.to_tk_font(),
570
+ padding=(bt.padding_x, bt.padding_y),
571
+ relief=bt.elevated_relief,
572
+ borderwidth=0,
573
+ )
574
+ style.map(
575
+ "TButton",
576
+ background=[
577
+ ("active", cs.primary_container),
578
+ ("disabled", cs.surface_variant),
579
+ ],
580
+ foreground=[
581
+ ("active", cs.on_primary_container),
582
+ ("disabled", cs.on_surface_variant),
583
+ ],
584
+ )
585
+
586
+ # ElevatedButton explícito
587
+ style.configure(
588
+ "Elevated.TButton",
589
+ background=cs.primary,
590
+ foreground=cs.on_primary,
591
+ font=tt.label_large.to_tk_font(),
592
+ padding=(bt.padding_x, bt.padding_y),
593
+ relief=bt.elevated_relief,
594
+ )
595
+ style.map(
596
+ "Elevated.TButton",
597
+ background=[
598
+ ("active", cs.primary_container),
599
+ ("disabled", cs.surface_variant),
600
+ ],
601
+ foreground=[
602
+ ("active", cs.on_primary_container),
603
+ ("disabled", cs.on_surface_variant),
604
+ ],
605
+ )
606
+
607
+ # OutlinedButton
608
+ style.configure(
609
+ "Outlined.TButton",
610
+ background=cs.surface,
611
+ foreground=cs.primary,
612
+ font=tt.label_large.to_tk_font(),
613
+ padding=(bt.padding_x, bt.padding_y),
614
+ relief=bt.outlined_relief,
615
+ borderwidth=bt.border_width if hasattr(bt, "border_width") else 1,
616
+ )
617
+ style.map(
618
+ "Outlined.TButton",
619
+ background=[
620
+ ("active", cs.primary_container),
621
+ ("disabled", cs.surface),
622
+ ],
623
+ foreground=[
624
+ ("active", cs.primary),
625
+ ("disabled", cs.on_surface_variant),
626
+ ],
627
+ )
628
+
629
+ # TextButton
630
+ style.configure(
631
+ "Text.TButton",
632
+ background=cs.background,
633
+ foreground=cs.primary,
634
+ font=tt.label_large.to_tk_font(),
635
+ padding=(bt.padding_x, bt.padding_y),
636
+ relief=bt.text_relief,
637
+ borderwidth=0,
638
+ )
639
+ style.map(
640
+ "Text.TButton",
641
+ background=[
642
+ ("active", cs.primary_container),
643
+ ("disabled", cs.background),
644
+ ],
645
+ foreground=[
646
+ ("active", cs.on_primary_container),
647
+ ("disabled", cs.on_surface_variant),
648
+ ],
649
+ )
650
+
651
+ # FloatingActionButton
652
+ style.configure(
653
+ "FAB.TButton",
654
+ background=cs.primary_container,
655
+ foreground=cs.on_primary_container,
656
+ font=tt.label_large.to_tk_font(),
657
+ padding=(16, 16),
658
+ relief="raised",
659
+ borderwidth=0,
660
+ )
661
+ style.map(
662
+ "FAB.TButton",
663
+ background=[("active", cs.primary)],
664
+ foreground=[("active", cs.on_primary)],
665
+ )
666
+
667
+ # Danger / Error button
668
+ style.configure(
669
+ "Danger.TButton",
670
+ background=cs.error,
671
+ foreground=cs.on_error,
672
+ font=tt.label_large.to_tk_font(),
673
+ padding=(bt.padding_x, bt.padding_y),
674
+ relief=bt.elevated_relief,
675
+ )
676
+ style.map(
677
+ "Danger.TButton",
678
+ background=[("active", cs.error_container)],
679
+ foreground=[("active", cs.on_error_container)],
680
+ )
681
+
682
+ # ── TEntry (TextField) ───────────────────────────────
683
+ fill = idt.fill_color or cs.surface_variant
684
+ border = idt.border_color or cs.outline
685
+ focused_border = idt.focused_border_color or cs.primary
686
+
687
+ style.configure(
688
+ "TEntry",
689
+ fieldbackground=fill,
690
+ foreground=cs.on_surface,
691
+ selectbackground=cs.primary,
692
+ selectforeground=cs.on_primary,
693
+ insertcolor=cs.primary,
694
+ font=body_font,
695
+ padding=(idt.padding_x, idt.padding_y),
696
+ relief="flat",
697
+ borderwidth=idt.border_width,
698
+ bordercolor=border,
699
+ )
700
+ style.map(
701
+ "TEntry",
702
+ fieldbackground=[("focus", cs.surface)],
703
+ bordercolor=[("focus", focused_border)],
704
+ )
705
+
706
+ # ── TCombobox (DropdownButton) ───────────────────────
707
+ style.configure(
708
+ "TCombobox",
709
+ fieldbackground=fill,
710
+ foreground=cs.on_surface,
711
+ background=cs.surface,
712
+ selectbackground=cs.primary,
713
+ selectforeground=cs.on_primary,
714
+ font=body_font,
715
+ padding=(8, 6),
716
+ relief="flat",
717
+ )
718
+ style.map(
719
+ "TCombobox",
720
+ fieldbackground=[("readonly", fill)],
721
+ foreground=[("readonly", cs.on_surface)],
722
+ )
723
+
724
+ # ── TCheckbutton ─────────────────────────────────────
725
+ style.configure(
726
+ "TCheckbutton",
727
+ background=cs.background,
728
+ foreground=cs.on_background,
729
+ font=body_font,
730
+ focuscolor=cs.primary,
731
+ indicatorcolor=cs.primary,
732
+ )
733
+ style.map(
734
+ "TCheckbutton",
735
+ background=[("active", cs.background)],
736
+ indicatorcolor=[
737
+ ("selected", cs.primary),
738
+ ("!selected", cs.surface_variant),
739
+ ],
740
+ )
741
+
742
+ # ── TRadiobutton ─────────────────────────────────────
743
+ style.configure(
744
+ "TRadiobutton",
745
+ background=cs.background,
746
+ foreground=cs.on_background,
747
+ font=body_font,
748
+ focuscolor=cs.primary,
749
+ )
750
+ style.map(
751
+ "TRadiobutton",
752
+ background=[("active", cs.background)],
753
+ indicatorcolor=[
754
+ ("selected", cs.primary),
755
+ ("!selected", cs.surface_variant),
756
+ ],
757
+ )
758
+
759
+ # ── TProgressbar ─────────────────────────────────────
760
+ style.configure(
761
+ "TProgressbar",
762
+ troughcolor=cs.surface_variant,
763
+ background=cs.primary,
764
+ bordercolor=cs.outline,
765
+ lightcolor=cs.primary,
766
+ darkcolor=cs.primary_container,
767
+ )
768
+
769
+ # ── Horizontal.TSeparator (Divider) ──────────────────
770
+ style.configure(
771
+ "TSeparator",
772
+ background=dt.color or cs.outline_variant,
773
+ )
774
+
775
+ # ── TScrollbar ───────────────────────────────────────
776
+ style.configure(
777
+ "TScrollbar",
778
+ background=cs.surface_variant,
779
+ troughcolor=cs.background,
780
+ arrowcolor=cs.on_surface_variant,
781
+ bordercolor=cs.background,
782
+ lightcolor=cs.surface_variant,
783
+ darkcolor=cs.surface_variant,
784
+ )
785
+ style.map(
786
+ "TScrollbar",
787
+ background=[("active", cs.primary)],
788
+ )
789
+
790
+ # ── Treeview (TableView) ─────────────────────────────
791
+ style.configure(
792
+ "Treeview",
793
+ background=cs.surface,
794
+ foreground=cs.on_surface,
795
+ fieldbackground=cs.surface,
796
+ font=body_font,
797
+ rowheight=28,
798
+ borderwidth=0,
799
+ )
800
+ style.configure(
801
+ "Treeview.Heading",
802
+ background=cs.surface_variant,
803
+ foreground=cs.on_surface_variant,
804
+ font=tt.label_medium.to_tk_font(),
805
+ relief="flat",
806
+ padding=(8, 6),
807
+ )
808
+ style.map(
809
+ "Treeview",
810
+ background=[("selected", cs.primary_container)],
811
+ foreground=[("selected", cs.on_primary_container)],
812
+ )
813
+
814
+ # ── AppBar Frame ─────────────────────────────────────
815
+ style.configure(
816
+ "AppBar.TFrame",
817
+ background=abt.background_color or cs.surface,
818
+ relief="flat" if abt.elevation == 0 else "raised",
819
+ borderwidth=abt.elevation,
820
+ )
821
+
822
+ # ── Notebook (TabBar) ─────────────────────────────────
823
+ style.configure(
824
+ "TNotebook",
825
+ background=cs.background,
826
+ borderwidth=0,
827
+ )
828
+ style.configure(
829
+ "TNotebook.Tab",
830
+ background=cs.surface_variant,
831
+ foreground=cs.on_surface_variant,
832
+ font=tt.label_medium.to_tk_font(),
833
+ padding=(12, 6),
834
+ )
835
+ style.map(
836
+ "TNotebook.Tab",
837
+ background=[("selected", cs.primary_container)],
838
+ foreground=[("selected", cs.on_primary_container)],
839
+ )
840
+
841
+ # ── Scale (Slider) ────────────────────────────────────
842
+ style.configure(
843
+ "TScale",
844
+ background=cs.background,
845
+ troughcolor=cs.surface_variant,
846
+ sliderrelief="flat",
847
+ )
848
+
849
+
850
+ # ============================================================
851
+ # THEME PROVIDER (ChangeNotifier)
852
+ # ============================================================
853
+
854
+
855
+ class ThemeProvider(ChangeNotifier):
856
+ """
857
+ Provider reativo do tema — permite trocar ThemeData em runtime.
858
+
859
+ Padrão de uso:
860
+ provider = ThemeProvider.from_mode(ThemeMode.SYSTEM)
861
+ app.register_provider(provider)
862
+
863
+ # Para alternar:
864
+ provider.set_mode(ThemeMode.DARK)
865
+ # Todos os Consumer(ThemeProvider) serão reconstruídos.
866
+
867
+ Nota: a re-aplicação do tema via `apply()` muda os ttk.Style globais,
868
+ mas widgets já montados precisam ser desmontados/remontados para refletir
869
+ as novas cores — isso depende do mecanismo de rebuild do pyflutter.
870
+ """
871
+
872
+ def __init__(
873
+ self,
874
+ light_theme: Optional[ThemeData] = None,
875
+ dark_theme: Optional[ThemeData] = None,
876
+ mode: ThemeMode = ThemeMode.SYSTEM,
877
+ ) -> None:
878
+ super().__init__()
879
+ self._light = light_theme or ThemeData.light()
880
+ self._dark = dark_theme or ThemeData.dark()
881
+ self._mode = mode
882
+ self._root: Optional[tk.Tk] = None
883
+
884
+ @property
885
+ def mode(self) -> ThemeMode:
886
+ return self._mode
887
+
888
+ # ── Factory ──────────────────────────────────────────────
889
+
890
+ @classmethod
891
+ def from_mode(
892
+ cls,
893
+ mode: ThemeMode = ThemeMode.SYSTEM,
894
+ light_theme: Optional[ThemeData] = None,
895
+ dark_theme: Optional[ThemeData] = None,
896
+ ) -> "ThemeProvider":
897
+ return cls(light_theme=light_theme, dark_theme=dark_theme, mode=mode)
898
+
899
+ # ── Estado atual ─────────────────────────────────────────
900
+
901
+ @property
902
+ def is_dark(self) -> bool:
903
+ if self._mode == ThemeMode.DARK:
904
+ return True
905
+ if self._mode == ThemeMode.LIGHT:
906
+ return False
907
+ return _detect_system_dark_mode()
908
+
909
+ @property
910
+ def theme(self) -> ThemeData:
911
+ """Retorna o ThemeData ativo (light ou dark)."""
912
+ return self._dark if self.is_dark else self._light
913
+
914
+ # ── Getters de conveniência (espelha context.theme no Flutter) ──
915
+
916
+ @property
917
+ def color_scheme(self) -> ColorScheme:
918
+ return self.theme.color_scheme
919
+
920
+ @property
921
+ def text_theme(self) -> TextTheme:
922
+ return self.theme.text_theme
923
+
924
+ @property
925
+ def primary(self) -> str:
926
+ return self.theme.primary
927
+
928
+ @property
929
+ def background(self) -> str:
930
+ return self.theme.background
931
+
932
+ # ── Mutação ──────────────────────────────────────────────
933
+
934
+ def set_mode(self, mode: ThemeMode) -> None:
935
+ """Alterna entre Light, Dark e System e notifica os listeners."""
936
+ if mode != self._mode:
937
+ self._mode = mode
938
+ if self._root:
939
+ self.theme.apply(self._root)
940
+ self.notify_listeners()
941
+
942
+ def toggle(self) -> None:
943
+ """Alterna entre Dark e Light (ignora System)."""
944
+ self.set_mode(ThemeMode.LIGHT if self.is_dark else ThemeMode.DARK)
945
+
946
+ def set_light_theme(self, theme: ThemeData) -> None:
947
+ self._light = theme
948
+ self.notify_listeners()
949
+
950
+ def set_dark_theme(self, theme: ThemeData) -> None:
951
+ self._dark = theme
952
+ self.notify_listeners()
953
+
954
+ # ── Aplicação ────────────────────────────────────────────
955
+
956
+ def attach_root(self, root: tk.Tk) -> None:
957
+ """
958
+ Vincula o provider à janela raiz do Tk.
959
+ Deve ser chamado em TkMaterialApp.run() antes do mainloop.
960
+ """
961
+ self._root = root
962
+ self.apply()
963
+
964
+ def apply(self) -> None:
965
+ """Aplica o tema ativo no ttk.Style."""
966
+ self.theme.apply(self._root)
967
+
968
+
969
+ # ============================================================
970
+ # ATALHO GLOBAL (equivalente ao Theme.of(context))
971
+ # ============================================================
972
+
973
+
974
+ class Theme:
975
+ """
976
+ Classe utilitária com factory methods — mantém compatibilidade
977
+ com o código existente que usava Theme.PRIMARY, Theme.apply(), etc.
978
+
979
+ Para novos projetos, prefira ThemeProvider + ThemeData.
980
+ """
981
+
982
+ # Constantes legadas (compatibilidade)
983
+ PRIMARY: str = ColorScheme.light().primary
984
+ BACKGROUND: str = ColorScheme.light().background
985
+
986
+ @staticmethod
987
+ def light(font_family: str = "Helvetica") -> ThemeData:
988
+ return ThemeData.light(font_family=font_family)
989
+
990
+ @staticmethod
991
+ def dark(font_family: str = "Helvetica") -> ThemeData:
992
+ return ThemeData.dark(font_family=font_family)
993
+
994
+ @staticmethod
995
+ def apply(root: Optional[tk.Tk] = None) -> None:
996
+ """
997
+ Compatibilidade legada: aplica um tema light padrão.
998
+ Requer que tk.Tk() já tenha sido criado, ou que `root` seja passado.
999
+ """
1000
+ ThemeData.light().apply(root)
1001
+
1002
+ @staticmethod
1003
+ def of(context) -> ThemeData:
1004
+ """
1005
+ Equivalente ao Theme.of(context) do Flutter.
1006
+ Recupera o ThemeData ativo a partir do BuildContext.
1007
+
1008
+ Uso:
1009
+ theme = Theme.of(context)
1010
+ color = theme.primary
1011
+ """
1012
+ try:
1013
+ provider: ThemeProvider = context.read(ThemeProvider)
1014
+ return provider.theme
1015
+ except (KeyError, AttributeError):
1016
+ return ThemeData.light()
1017
+
1018
+
1019
+ # ============================================================
1020
+ # INTEGRAÇÃO COM TkMaterialApp
1021
+ # ============================================================
1022
+
1023
+
1024
+ def make_themed_app(base_app_class: type[BaseMaterialApp]):
1025
+ """
1026
+ Mixin/decorator que estende qualquer subclasse de BaseMaterialApp
1027
+ para aplicar o ThemeProvider automaticamente dentro de run(),
1028
+ após tk.Tk() ser criado — sem risco de janela dupla.
1029
+
1030
+ Uso:
1031
+ from pyflutter.widgets import TkMaterialApp
1032
+ from pyflutter.theme import make_themed_app
1033
+
1034
+ ThemedApp = make_themed_app(TkMaterialApp)
1035
+ app = ThemedApp(home=MyPage(), title="App")
1036
+ app.register_provider(ThemeProvider(...))
1037
+ app.run() # aplica o tema no momento certo
1038
+ """
1039
+
1040
+ class ThemedApp(base_app_class):
1041
+
1042
+ def run(self) -> None:
1043
+
1044
+ self.root = tk.Tk()
1045
+ self.root.title(self.title)
1046
+
1047
+ # Aplica o tema AGORA — root já existe, sem janela dupla.
1048
+ try:
1049
+ provider: ThemeProvider = self.providers.get(ThemeProvider)
1050
+ if provider is not None:
1051
+ provider.attach_root(self.root)
1052
+ except Exception:
1053
+ pass
1054
+
1055
+ self.get_navigator().push(self.home)
1056
+ self.root.mainloop()
1057
+
1058
+ def get_navigator(self) -> Navigator:
1059
+ return super().get_navigator()
1060
+
1061
+ def register_notifier(self, provider: T) -> None:
1062
+ return super().register_notifier(provider)
1063
+
1064
+ ThemedApp.__name__ = f"Themed{base_app_class.__name__}"
1065
+ ThemedApp.__qualname__ = ThemedApp.__name__
1066
+ return ThemedApp