-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtela.py
More file actions
2397 lines (2025 loc) · 94.3 KB
/
tela.py
File metadata and controls
2397 lines (2025 loc) · 94.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import customtkinter as ctk
from PIL import Image, ImageTk
import os
import warnings
from criterios_estabilidade import CriteriosEstabilidade, ErroValidacao
from analise_segunda_ordem import AnalisadorSegundaOrdem, ErroValidacao as ErroValidacao2
from controladores import JanelaControladores
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
import control.matlab as matlab
import numpy as np
import platform
import sys
import json
import threading
import queue
from logger_sistema import logger # import logger
from gerenciador_excecoes import gerenciador_excecoes, TipoErro, GerenciadorExcecoes # import exception handler
from utilidades_ui import GerenciadorResponsividade, UtiliadadesGraficos # import UI utilities
from lugar_geometrico_raizes import AnalisadorLGR, ErroValidacaoLGR
from tema_config import GerenciadorTemas, gerenciador_temas, obter_caminho_recurso
CORES = gerenciador_temas.obter_cores()
# Configuração do tema inicial
ctk.set_appearance_mode(CORES["mode"])
ctk.set_default_color_theme("blue")
class GerenciadorExcecoes:
"""Novo sistema centralizado de tratamento de exceções"""
def __init__(self):
self.historico_erros = []
self.max_historico = 100
def registrar_erro(self, tipo, mensagem, contexto=None):
"""Registra erro para debug e análise"""
import datetime
registro = {
"timestamp": datetime.datetime.now().isoformat(),
"tipo": tipo,
"mensagem": mensagem,
"contexto": contexto
}
self.historico_erros.append(registro)
if len(self.historico_erros) > self.max_historico:
self.historico_erros.pop(0)
def obter_ultimo_erro(self):
"""Retorna o último erro registrado"""
if self.historico_erros:
return self.historico_erros[-1]
return None
def limpar_historico(self):
"""Limpa histórico de erros"""
self.historico_erros = []
gerenciador_excecoes = GerenciadorExcecoes()
class TransicaoSuave:
"""Sistema de transições suaves entre telas com efeitos visuais"""
def __init__(self, duracao_ms=300):
self.duracao = duracao_ms
self.em_transicao = False
def animar_entrada(self, widget, callback=None):
"""Anima entrada de widget"""
if self.em_transicao:
return
self.em_transicao = True
widget.configure(fg_color="transparent")
passos = 10
delay = self.duracao // passos
def animar(passo):
if passo < passos:
widget.update()
widget.after(delay, lambda: animar(passo + 1))
else:
self.em_transicao = False
if callback:
callback()
animar(0)
transicao = TransicaoSuave()
class ResponsiveConfig:
"""Classe para gerenciar configurações responsivas multiplataforma"""
def __init__(self):
self.platform = platform.system()
self.is_windows = self.platform == "Windows"
self.is_linux = self.platform == "Linux"
self.is_mac = self.platform == "Darwin"
self.dpi_scale = self.get_dpi_scale()
self.scaling_factor = self.get_scaling_factor()
self.config_acessibilidade = {
"tamanho_fonte_aumentado": False,
"alto_contraste": False,
"animacoes_reduzidas": False,
"leitor_tela": False
}
def get_dpi_scale(self):
"""Detecta o fator de escala DPI do sistema"""
try:
if self.is_windows:
from ctypes import windll
try:
windll.shcore.SetProcessDPIAware()
hdc = windll.user32.GetDC(0)
dpi = windll.gdi32.GetDeviceCaps(hdc, 88)
windll.user32.ReleaseDC(0, hdc)
return dpi / 96.0
except:
return 1.0
elif self.is_mac:
# macOS geralmente usa Retina (2x)
return 2.0 if 'retina' in str(sys.platform).lower() else 1.0
else:
# Linux - tentar detectar via Xrandr
try:
import subprocess
output = subprocess.check_output(['xrandr']).decode()
if 'current' in output:
return 1.0
except:
pass
except:
pass
return 1.0
def get_scaling_factor(self):
"""Retorna fator de escala baseado no sistema"""
if self.is_mac:
return 1.2 # macOS precisa de ajuste
elif self.is_linux:
return 1.0
else: # Windows
return 1.0 / self.dpi_scale if self.dpi_scale > 1 else 1.0
def get_screen_info(self, root):
"""Obtém informações precisas da tela"""
try:
root.update_idletasks()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
if self.is_windows:
try:
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
except:
pass
elif self.is_mac:
# macOS Retina adjustment
screen_width = int(screen_width / self.dpi_scale)
screen_height = int(screen_height / self.dpi_scale)
elif self.is_linux:
# Linux - usar valores diretos do Tk
pass
return screen_width, screen_height
except:
return 1920, 1080 # Fallback
def calculate_window_size(self, screen_width, screen_height, scale=0.8):
"""Calcula tamanho ideal da janela baseado na resolução"""
if self.is_mac:
min_width, min_height = 1100, 650
max_width, max_height = 2560, 1440
elif self.is_linux:
min_width, min_height = 1000, 600
max_width, max_height = 1920, 1080
else: # Windows
min_width, min_height = 1200, 700
max_width, max_height = 1920, 1080
# Calcular tamanho proporcional
window_width = int(screen_width * scale)
window_height = int(screen_height * scale)
# Aplicar limites
window_width = max(min_width, min(window_width, max_width))
window_height = max(min_height, min(window_height, max_height))
if screen_height <= 768: # Notebooks com tela pequena
window_height = min(window_height, 650)
scale = 0.75
elif screen_height <= 900: # Notebooks médios
window_height = min(window_height, 800)
scale = 0.78
elif screen_height <= 1080: # Full HD
window_height = min(window_height, 950)
scale = 0.85
elif screen_height <= 1440: # 2K
window_height = min(window_height, 1300)
scale = 0.88
else: # 4K e superior
window_height = min(window_height, 1600)
scale = 0.90
return window_width, window_height
def get_font_scale(self, screen_height):
"""Retorna escala de fonte baseada na altura da tela e plataforma"""
base_scale = 1.0
if self.is_mac:
base_scale = 0.95 # macOS tem fontes maiores
elif self.is_linux:
base_scale = 1.0
else: # Windows
base_scale = 1.0
# Ajuste por resolução
if screen_height <= 768:
return 0.80 * base_scale
elif screen_height <= 900:
return 0.85 * base_scale
elif screen_height <= 1080:
return 0.95 * base_scale
elif screen_height <= 1440:
return 1.05 * base_scale
else:
return 1.15 * base_scale
def get_padding_scale(self, screen_width):
"""Retorna escala de padding baseada na largura da tela"""
if screen_width <= 1366:
return 0.7
elif screen_width <= 1600:
return 0.85
elif screen_width <= 1920:
return 1.0
else:
return 1.1
def aumentar_fonte(self, tamanho_base):
"""Aumenta tamanho da fonte para acessibilidade"""
if self.config_acessibilidade["tamanho_fonte_aumentado"]:
return int(tamanho_base * 1.3)
return tamanho_base
def alternar_tamanho_fonte(self):
"""Alterna entre tamanho normal e aumentado"""
self.config_acessibilidade["tamanho_fonte_aumentado"] = not self.config_acessibilidade["tamanho_fonte_aumentado"]
return self.config_acessibilidade["tamanho_fonte_aumentado"]
class SistemaTCC(ctk.CTk):
"""Janela principal do sistema"""
def __init__(self):
super().__init__()
logger.info("Iniciando aplicação SistemaTCC")
self.config = ResponsiveConfig()
self.gerenciador_temas = gerenciador_temas
self.contexto_sistema = {
"num": [4.0],
"den": [1.0, 0.8, 4.0],
"tipo_malha": "fechada",
"tipo_entrada": "degrau"
}
self.font_titulo = ctk.CTkFont(family="Segoe UI", size=20, weight="bold")
self.font_subtitulo = ctk.CTkFont(family="Segoe UI", size=16, weight="bold")
self.font_corpo = ctk.CTkFont(family="Segoe UI", size=14)
self.font_label = ctk.CTkFont(family="Segoe UI", size=12, weight="bold")
self.font_pequeno = ctk.CTkFont(family="Segoe UI", size=10)
if self.config.is_windows:
try:
from ctypes import windll
windll.shcore.SetProcessDPIAwareness(1)
except:
pass
# Configuração da janela principal
self.title("ANÁLISE DE CONTROLADORES - Sistema de Controle")
# self.title("FERRAMENTA COMPUTACIONAL PARA ANÁLISE E CARACTERIZAÇÃO DE SISTEMAS DE CONTROLE")
self.set_window_icon()
# Obter informações da tela
self.screen_width, self.screen_height = self.config.get_screen_info(self)
# Calcular tamanho da janela
window_width, window_height = self.config.calculate_window_size(
self.screen_width, self.screen_height
)
# Definir geometria
self.geometry(f"{window_width}x{window_height}")
self.maxsize(width=self.screen_width, height=self.screen_height)
self.minsize(width=1000, height=600)
# Aplicar cor de fundo
self.configure(fg_color=CORES["fundo_escuro"])
# Centralizar janela
self.centralizar_janela()
# Obter escalas responsivas
self.font_scale = self.config.get_font_scale(self.screen_height)
self.padding_scale = self.config.get_padding_scale(self.screen_width)
# Carregar imagens
self.carregar_imagens()
# Configurar layout
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
# Criar container principal
self.container = ctk.CTkFrame(self, corner_radius=0, fg_color=CORES["fundo_escuro"])
self.container.grid(row=0, column=0, sticky="nsew")
self.container.grid_columnconfigure(0, weight=1)
self.container.grid_rowconfigure(0, weight=1)
self.frame_atual = None
# Dicionário para rastrear janelas abertas
self.janelas_abertas = {}
# Criar tela principal
self.tela_principal = TelaPrincipal(parent=self.container, controlador=self)
self.tela_principal.grid(row=0, column=0, sticky="nsew")
self.frame_atual = self.tela_principal
self.configurar_atalhos()
self.criar_menu_acessibilidade()
# Garantir visibilidade
self.lift()
self.focus_force()
# Bind para redimensionamento
self.bind("<Configure>", self.on_window_resize)
self.protocol("WM_DELETE_WINDOW", self._on_closing)
# self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.fila_operacoes = queue.Queue()
self.processando_fila = False
self.thread_background = threading.Thread(target=self._processar_fila, daemon=True)
self.thread_background.start()
def _processar_fila(self):
"""Processa operações da fila de forma assíncrona"""
while True:
try:
operacao = self.fila_operacoes.get(timeout=1)
if operacao:
funcao, args, kwargs = operacao
try:
funcao(*args, **kwargs)
except Exception as e:
gerenciador_excecoes.registrar_erro("background", str(e), "fila")
except queue.Empty:
continue
except Exception as e:
gerenciador_excecoes.registrar_erro("thread", str(e), "processamento")
def agendar_operacao(self, funcao, *args, **kwargs):
"""Agenda operação para execução em background"""
self.fila_operacoes.put((funcao, args, kwargs))
def set_window_icon(self):
"""Define o ícone da janela de forma multiplataforma"""
try:
if self.config.is_windows:
icon_path = obter_caminho_recurso("image/icons/papel.ico") # Usar obter_caminho_recurso
if os.path.exists(icon_path):
self.iconbitmap(icon_path)
elif self.config.is_linux:
icon_path = obter_caminho_recurso("image/icons/papel.ico") # Usar obter_caminho_recurso
if os.path.exists(icon_path):
icon = Image.open(icon_path)
photo = ImageTk.PhotoImage(icon)
self.iconphoto(True, photo)
elif self.config.is_mac:
# macOS usa o ícone do app bundle
pass
except Exception as e:
print(f"Aviso: Não foi possível carregar ícone: {e}")
self.logo_image = None
def configurar_atalhos(self):
"""Configura atalhos de teclado multiplataforma"""
self.bind("<F11>", lambda e: self.toggle_fullscreen())
self.bind("<Escape>", lambda e: self.exit_fullscreen())
# Atalhos específicos por plataforma
if self.config.is_mac:
self.bind("<Command-q>", lambda e: self._on_closing())
self.bind("<Command-w>", lambda e: self._on_closing())
else:
self.bind("<Control-q>", lambda e: self._on_closing())
self.bind("<Alt-F4>", lambda e: self._on_closing())
# Atalhos de teclado para acessibilidade
self.bind("<Control-plus>", lambda e: self.aumentar_fonte_global())
self.bind("<Control-minus>", lambda e: self.diminuir_fonte_global())
self.bind("<Control-t>", lambda e: self.alternar_tema())
self.bind("<Control-h>", lambda e: self.mostrar_ajuda())
self.bind("<Control-c>", lambda e: self.toggle_alto_contraste())
self.bind("<F1>", lambda e: self.mostrar_ajuda())
def toggle_fullscreen(self):
"""Alterna tela cheia de forma multiplataforma"""
if not hasattr(self, '_fullscreen'):
self._fullscreen = False
self._fullscreen = not self._fullscreen
if self.config.is_windows:
if self._fullscreen:
self.state('zoomed')
else:
self.state('normal')
elif self.config.is_mac:
self.attributes('-fullscreen', self._fullscreen)
else: # Linux
self.attributes('-zoomed', self._fullscreen)
def exit_fullscreen(self):
"""Sai do modo tela cheia"""
if hasattr(self, '_fullscreen') and self._fullscreen:
self._fullscreen = False
if self.config.is_windows:
self.state('normal')
elif self.config.is_mac:
self.attributes('-fullscreen', False)
else:
self.attributes('-zoomed', False)
def _on_closing(self): # rename on_closing to _on_closing
"""Fecha a aplicação de forma segura"""
logger.info("Fechando aplicação SistemaTCC")
try:
# Fechar todas as janelas abertas
for janela in list(self.janelas_abertas.values()):
try:
janela.destroy()
except:
pass
# Limpar matplotlib
plt.close('all')
# Destruir janela principal
self.destroy()
logger.info("Aplicação SistemaTCC encerrada com sucesso.")
except Exception as e:
logger.error(f"Erro ao fechar aplicação: {e}", exc_info=True)
self.destroy()
def centralizar_janela(self):
"""Centraliza a janela na tela de forma robusta"""
self.update_idletasks()
largura = self.winfo_width()
altura = self.winfo_height()
# Garantir valores válidos
if largura < 100:
largura = 1200
if altura < 100:
altura = 700
x = max(0, (self.screen_width - largura) // 2)
y = max(0, (self.screen_height - altura) // 2)
self.geometry(f'{largura}x{altura}+{x}+{y}')
def on_window_resize(self, event):
"""Callback para redimensionamento da janela"""
# Atualizar escalas quando a janela for redimensionada
if event.widget == self:
pass # Pode adicionar lógica adicional se necessário
def carregar_imagens(self):
"""Carrega as imagens utilizadas no sistema"""
self.foto_fundo = None
self.logo_image = None
try:
logo_path = obter_caminho_recurso("logo.png") # Usar obter_caminho_recurso
if os.path.exists(logo_path):
img_pil = Image.open(logo_path).convert("RGBA")
if self.screen_height <= 768:
max_h_logo = 40
elif self.screen_height <= 900:
max_h_logo = 45
elif self.screen_height <= 1080:
max_h_logo = 55
elif self.screen_height <= 1440:
max_h_logo = 65
else:
max_h_logo = 75
if self.config.is_mac:
max_h_logo = int(max_h_logo * 0.9)
ratio = min(1.0, max_h_logo / img_pil.height)
new_size = (int(img_pil.width * ratio), int(img_pil.height * ratio))
img_pil_resized = img_pil.resize(new_size, Image.Resampling.LANCZOS)
self.logo_image = ctk.CTkImage(light_image=img_pil_resized,
dark_image=img_pil_resized,
size=new_size)
except Exception as e:
print(f"Erro ao carregar logo.png: {e}")
self.logo_image = None
def scale_font(self, base_size):
"""Retorna tamanho de fonte escalado"""
return int(base_size * self.font_scale)
def scale_padding(self, base_padding):
"""Retorna padding escalado"""
return int(base_padding * self.padding_scale)
def abrir_criterios_estabilidade(self):
"""Abre o módulo de critérios de estabilidade"""
logger.info("Abrindo módulo de critérios de estabilidade")
self.trocar_para_frame(FrameCriterio, titulo="CRITÉRIOS DE ESTABILIDADE")
def abrir_analise_segunda_ordem(self):
"""Abre o módulo de análise de segunda ordem"""
logger.info("Abrindo módulo de análise de segunda ordem")
self.trocar_para_frame(FrameAnalise, titulo="ANÁLISE DE SISTEMAS DE 2ª ORDEM")
def abrir_lgr(self):
"""Abre o módulo de Lugar Geométrico das Raízes"""
logger.info("Abrindo módulo LGR")
self.trocar_para_frame(JanelaLGR, titulo="📌 LUGAR GEOMÉTRICO DAS RAÍZES")
def abrir_controladores(self):
"""Abre o módulo de controladores"""
logger.info("Abrindo módulo de controladores")
try:
from controladores import JanelaControladores
janela = JanelaControladores(self)
self.janelas_abertas['controladores'] = janela
except Exception as e:
logger.error(f"Erro ao abrir controladores: {e}")
self.mostrar_erro(f"Erro ao abrir módulo de controladores: {str(e)}")
# ================== MÉTODO ATUALIZADO ==================
def abrir_janela(self, tipo_janela, titulo):
"""Abre uma nova janela com gerenciamento adequado"""
# Fechar janela anterior do mesmo tipo se existir
if tipo_janela in self.janelas_abertas:
try:
self.janelas_abertas[tipo_janela].destroy()
except:
pass
finally:
self.janelas_abertas.pop(tipo_janela, None)
# Criar nova janela
if tipo_janela == "criterio":
janela = FrameCriterio(self, titulo)
elif tipo_janela == "analise":
janela = FrameAnalise(self, titulo)
# --- Bloco LGR removido מכאן ---
elif tipo_janela == "controladores":
janela = JanelaControladores(self)
else:
return
# Configurações para garantir visibilidade
janela.transient(self)
janela.grab_set()
janela.lift()
janela.focus_force()
# Armazenar referência
self.janelas_abertas[tipo_janela] = janela
# Callback para limpar ao fechar
def ao_fechar():
self.janelas_abertas.pop(tipo_janela, None)
janela.destroy()
self.lift()
self.focus_force()
janela.protocol("WM_DELETE_WINDOW", ao_fechar)
# =======================================================
def criar_menu_acessibilidade(self):
"""Cria menu de acessibilidade e configurações"""
# Frame flutuante para configurações
self.frame_config = None
self.config_visivel = False
# Atalhos de teclado para acessibilidade já configurados em configurar_atalhos
def toggle_configuracoes(self):
"""Mostra/oculta painel de configurações"""
if self.config_visivel:
if self.frame_config:
self.frame_config.destroy()
self.frame_config = None
self.config_visivel = False
else:
self.mostrar_painel_configuracoes()
self.config_visivel = True
def mostrar_painel_configuracoes(self):
"""Mostra painel de configurações flutuante"""
if self.frame_config:
self.frame_config.destroy()
# Frame flutuante
self.frame_config = ctk.CTkFrame(
self,
fg_color=CORES["fundo_claro"],
corner_radius=15,
border_width=2,
border_color=CORES["primaria"]
)
self.frame_config.place(relx=0.5, rely=0.5, anchor="center")
# Título
ctk.CTkLabel(
self.frame_config,
text="⚙️ CONFIGURAÇÕES E ACESSIBILIDADE",
font=("Segoe UI", self.scale_font(18), "bold"),
text_color=CORES["texto_principal"]
).pack(pady=20, padx=30)
# Seção de Temas
frame_temas = ctk.CTkFrame(self.frame_config, fg_color="transparent")
frame_temas.pack(fill="x", padx=30, pady=10)
ctk.CTkLabel(
frame_temas,
text="🎨 Tema:",
font=("Segoe UI", self.scale_font(14), "bold"),
text_color=CORES["texto_principal"]
).pack(anchor="w", pady=5)
frame_botoes_tema = ctk.CTkFrame(frame_temas, fg_color="transparent")
frame_botoes_tema.pack(fill="x", pady=5)
ctk.CTkButton(
frame_botoes_tema,
text="🌙 Escuro",
command=lambda: self.aplicar_tema("dark"),
width=120,
height=40,
font=("Segoe UI", self.scale_font(12), "bold"),
fg_color=CORES["primaria"],
hover_color=CORES["primaria_hover"]
).pack(side="left", padx=5)
ctk.CTkButton(
frame_botoes_tema,
text="☀️ Claro",
command=lambda: self.aplicar_tema("light"),
width=120,
height=40,
font=("Segoe UI", self.scale_font(12), "bold"),
fg_color=CORES["secundaria"],
hover_color=CORES["secundaria_hover"]
).pack(side="left", padx=5)
ctk.CTkButton(
frame_botoes_tema,
text="🔆 Alto Contraste",
command=lambda: self.aplicar_tema("high_contrast"),
width=150,
height=40,
font=("Segoe UI", self.scale_font(12), "bold"),
fg_color=CORES["terciaria"],
hover_color=CORES["terciaria_hover"]
).pack(side="left", padx=5)
# Seção de Acessibilidade
frame_acess = ctk.CTkFrame(self.frame_config, fg_color="transparent")
frame_acess.pack(fill="x", padx=30, pady=10)
ctk.CTkLabel(
frame_acess,
text="♿ Acessibilidade:",
font=("Segoe UI", self.scale_font(14), "bold"),
text_color=CORES["texto_principal"]
).pack(anchor="w", pady=5)
ctk.CTkButton(
frame_acess,
text="🔤 Aumentar Fonte (Ctrl++)",
command=self.aumentar_fonte_global,
width=250,
height=40,
font=("Segoe UI", self.scale_font(14), "bold"),
fg_color=CORES["primaria"],
hover_color=CORES["primaria_hover"]
).pack(pady=5)
ctk.CTkButton(
frame_acess,
text="🔡 Diminuir Fonte (Ctrl+-)",
command=self.diminuir_fonte_global,
width=250,
height=40,
font=("Segoe UI", self.scale_font(14), "bold"),
fg_color=CORES["primaria"],
hover_color=CORES["primaria_hover"]
).pack(pady=5)
# Atalhos
frame_atalhos = ctk.CTkFrame(self.frame_config, fg_color=CORES["acento"], corner_radius=10)
frame_atalhos.pack(fill="x", padx=30, pady=15)
ctk.CTkLabel(
frame_atalhos,
text="⌨️ Atalhos de Teclado:",
font=("Segoe UI", self.scale_font(15), "bold"),
text_color=CORES["texto_principal"]
).pack(anchor="w", padx=15, pady=(10, 5))
atalhos_texto = """
F1 - Ajuda
F11 - Tela Cheia
Ctrl+T - Alternar Tema
Ctrl++ - Aumentar Fonte
Ctrl+- - Diminuir Fonte
Ctrl+H - Ajuda
ESC - Sair Tela Cheia
"""
ctk.CTkLabel(
frame_atalhos,
text=atalhos_texto,
font=("Consolas", self.scale_font(14)),
text_color=CORES["texto_secundario"],
justify="left"
).pack(anchor="w", padx=15, pady=(0, 10))
# Botão fechar
ctk.CTkButton(
self.frame_config,
text="✖ Fechar",
command=self.toggle_configuracoes,
width=200,
height=45,
font=("Segoe UI", self.scale_font(13), "bold"),
fg_color=CORES["terciaria"],
hover_color=CORES["terciaria_hover"]
).pack(pady=20)
def aplicar_tema(self, nome_tema):
"""Aplica um tema específico"""
global CORES
self.gerenciador_temas.definir_tema(nome_tema)
CORES = self.gerenciador_temas.obter_cores()
ctk.set_appearance_mode(CORES["mode"])
# Recriar interface
self.recriar_interface()
def alternar_tema(self):
"""Alterna entre temas disponíveis"""
global CORES
novo_tema = self.gerenciador_temas.alternar_tema()
CORES = self.gerenciador_temas.obter_cores()
ctk.set_appearance_mode(CORES["mode"])
# Recriar interface
self.recriar_interface()
def toggle_alto_contraste(self):
"""Ativa/desativa modo alto contraste"""
if self.gerenciador_temas.tema_atual == "high_contrast":
self.aplicar_tema("dark")
else:
self.aplicar_tema("high_contrast")
def aumentar_fonte_global(self):
"""Aumenta o tamanho das fontes do sistema em todos os frames ativos"""
# Ajusta o tamanho base das fontes
if self.font_corpo.cget("size") < 20: # Limite para evitar fontes gigantes
self.font_titulo.configure(size=self.font_titulo.cget("size") + 2)
self.font_subtitulo.configure(size=self.font_subtitulo.cget("size") + 2)
self.font_corpo.configure(size=self.font_corpo.cget("size") + 1)
self.font_label.configure(size=self.font_label.cget("size") + 1)
self.font_pequeno.configure(size=self.font_pequeno.cget("size") + 1)
# Atualiza fontes em módulos abertos
for widget in self.winfo_children():
if isinstance(widget, FrameBase):
widget.atualizar_fontes()
logger.info("Fontes aumentadas globalmente")
def diminuir_fonte_global(self):
"""Diminui o tamanho das fontes do sistema em todos os frames ativos"""
if self.font_corpo.cget("size") > 10: # Limite para evitar fontes muito pequenas
self.font_titulo.configure(size=self.font_titulo.cget("size") - 2)
self.font_subtitulo.configure(size=self.font_subtitulo.cget("size") - 2)
self.font_corpo.configure(size=self.font_corpo.cget("size") - 1)
self.font_label.configure(size=self.font_label.cget("size") - 1)
self.font_pequeno.configure(size=self.font_pequeno.cget("size") - 1)
# Atualiza fontes em módulos abertos
for widget in self.winfo_children():
if isinstance(widget, FrameBase):
widget.atualizar_fontes()
logger.info("Fontes diminuídas globalmente")
def resetar_fonte(self):
"""Reseta as fontes para o tamanho padrão"""
self.font_titulo.configure(size=20)
self.font_subtitulo.configure(size=16)
self.font_corpo.configure(size=14)
self.font_label.configure(size=12)
self.font_pequeno.configure(size=10)
logger.info("Fontes resetadas")
def mostrar_ajuda(self):
"""Mostra janela de ajuda"""
janela_ajuda = ctk.CTkToplevel(self)
janela_ajuda.title("Ajuda - Sistema de Controle")
janela_ajuda.geometry("700x600")
janela_ajuda.configure(fg_color=CORES["fundo_escuro"])
# Centralizar
janela_ajuda.update_idletasks()
x = (self.winfo_screenwidth() - 700) // 2
y = (self.winfo_screenheight() - 600) // 2
janela_ajuda.geometry(f"700x600+{x}+{y}")
# Conteúdo
frame_scroll = ctk.CTkScrollableFrame(
janela_ajuda,
fg_color=CORES["fundo_claro"]
)
frame_scroll.pack(fill="both", expand=True, padx=20, pady=20)
ctk.CTkLabel(
frame_scroll,
text="📚 GUIA DE USO DO SISTEMA",
font=("Segoe UI", 20, "bold"),
text_color=CORES["texto_principal"]
).pack(pady=15)
ajuda_texto = """
MÓDULOS DISPONÍVEIS:
1. ANÁLISE DE ESTABILIDADE
• Critério de Routh-Hurwitz
• Análise de polos e zeros
• Determinação de estabilidade
2. ANÁLISE DE SISTEMA 2ª ORDEM
• Resposta ao degrau e rampa
• Cálculo de parâmetros (ωn, ζ, K)
• Características temporais
• Gráficos de resposta
3. ANÁLISE DE CONTROLADORES
• Controladores PI, PD e PID
• Lugar das raízes
• Resposta temporal comparativa
• Diagrama de polos e zeros
ACESSIBILIDADE:
• Temas: Escuro, Claro e Alto Contraste
• Ajuste de tamanho de fonte
• Atalhos de teclado
• Interface responsiva
ATALHOS DE TECLADO:
F1 - Ajuda
F11 - Tela Cheia
Ctrl+T - Alternar Tema
Ctrl++ - Aumentar Fonte
Ctrl+- - Diminuir Fonte
Ctrl+H - Ajuda
ESC - Sair Tela Cheia
COMO USAR:
1. Selecione o módulo desejado
2. Insira os coeficientes da função de transferência
3. Configure os parâmetros necessários
4. Clique em "Analisar" ou "Plotar"
5. Visualize os resultados e gráficos
FORMATO DE ENTRADA:
• Coeficientes separados por espaço
• Do maior para o menor grau
• Use ponto (.) para decimais
• Exemplo: 1 2 4 (para s² + 2s + 4)
SUPORTE:
Para mais informações, consulte a documentação
ou entre em contato com o desenvolvedor.
"""
ctk.CTkLabel(
frame_scroll,
text=ajuda_texto,
font=("Segoe UI", 12),
text_color=CORES["texto_secundario"],
justify="left"
).pack(pady=10, padx=20)
ctk.CTkButton(
janela_ajuda,
text="Fechar",
command=janela_ajuda.destroy,
width=150,
height=40,
font=("Segoe UI", 13, "bold"),
fg_color=CORES["primaria"],
hover_color=CORES["primaria_hover"]
).pack(pady=15)
def mostrar_erro(self, mensagem):
"""Mostra uma janela de erro simples"""
janela_erro = ctk.CTkToplevel(self)
janela_erro.title("❌ Erro Inesperado")
janela_erro.geometry("450x250")
janela_erro.configure(fg_color=CORES["fundo_escuro"])
# Centralizar
janela_erro.update_idletasks()
x = (self.winfo_screenwidth() - 450) // 2
y = (self.winfo_screenheight() - 250) // 2
janela_erro.geometry(f"450x250+{x}+{y}")
janela_erro.grid_columnconfigure(0, weight=1)
janela_erro.grid_rowconfigure(0, weight=1)
ctk.CTkLabel(
janela_erro,
text="❌ Ocorreu um Erro:",
font=self.font_subtitulo,
text_color=CORES["erro"]
).pack(pady=(20, 10))
erro_textbox = ctk.CTkTextbox(
janela_erro,
font=self.font_corpo,
text_color=CORES["texto_principal"],
fg_color=CORES["fundo_claro"],
width=400,
height=100,
wrap="word",
activate_scrollbars=True
)
erro_textbox.pack(pady=10, padx=20, fill="both", expand=True)
erro_textbox.insert("1.0", mensagem)
erro_textbox.configure(state="disabled")
ctk.CTkButton(
janela_erro,
text="Fechar",
command=janela_erro.destroy,
fg_color=CORES["primaria"],
hover_color=CORES["primaria_hover"]
).pack(pady=20)
janela_erro.transient(self)
janela_erro.grab_set()
janela_erro.focus_force()
def recriar_interface(self):
"""Recria a interface com novo tema"""
# Destruir container atual
if hasattr(self, 'container'):
self.container.destroy()
# Reconfigurar cor de fundo
self.configure(fg_color=CORES["fundo_escuro"])