Repository navigation
Expand file tree
/
Copy pathplot_editor.pyw
More file actions
1487 lines (1374 loc) · 72.6 KB
/
Copy pathplot_editor.pyw
File metadata and controls
1487 lines (1374 loc) · 72.6 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
"""Plot Editor — riapre una figura matplotlib salvata come pickle da
KleistekManager (File → Save Figure) e permette di modificarne le proprietà
dal vivo, perché il pickle NON è un raster congelato ma l'oggetto Figure/Axes
originale con tutte le sue proprietà (font, scala, spessori, tick, colori,
legenda). Le modifiche si applicano subito sul grafico; si può poi ri-salvare
il pickle o esportare in PNG/SVG/PDF.
Uso:
pythonw plot_editor.pyw [figura.fig.pickle]
oppure trascina un pickle nella finestra / File → Open pickle.
"""
import os
import sys
import pickle
import traceback
import numpy as np
import tkinter as tk
from tkinter import filedialog, messagebox, colorchooser, simpledialog, ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.ticker import AutoLocator, MultipleLocator
import matplotlib.colors as mcolors
import matplotlib.text as mtext
import matplotlib.font_manager as fm
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
HAS_DND = True
except ImportError:
HAS_DND = False
# Stile "Origin-like" condiviso (stessa cartella), con fallback no-op se manca.
try:
import importlib.util as _ilu
_os_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'origin_style.py')
_spec = _ilu.spec_from_file_location('origin_style', _os_path)
origin_style = _ilu.module_from_spec(_spec)
_spec.loader.exec_module(origin_style)
except Exception as _e:
origin_style = None
_origin_style_error = _e
DATA_OPS = ['Aggiungi costante (y + c)', 'Moltiplica (y × c)', 'Sposta x (x + c)',
'Normalizza: massimo = c', 'Normalizza: y(x = c) = 1', 'Sottrai il minimo (y − min)']
LINESTYLES = ['-', '--', '-.', ':', 'None']
LEGEND_LOCS = ['best', 'upper right', 'upper left', 'lower left', 'lower right',
'right', 'center left', 'center right', 'lower center',
'upper center', 'center']
class PlotEditor:
def __init__(self, root, path=None):
self.root = root
self.root.title("Plot Editor (matplotlib pickle)")
try: # window icon, as a courtesy: the editor works without it (Windows only, .ico)
self.root.iconbitmap(os.path.join(os.path.dirname(os.path.abspath(__file__)), "plot_editor.ico"))
except tk.TclError:
pass
self.root.geometry("1300x820")
self.fig = None
self.ax = None
self.canvas = None
self.toolbar = None
self._txt_drag = None # a free text label being dragged: dict(text, dx, dy, x0, y0, moved)
self._path = None
self._syncing = False # blocca gli handler durante il popolamento dei controlli
self._font_family = None # famiglia font scelta (riapplicata ai tick a ogni draw)
if HAS_DND:
try:
self.root.drop_target_register(DND_FILES)
self.root.dnd_bind('<<Drop>>', self._on_drop)
except (AttributeError, tk.TclError):
pass
# --- MENU ---
menubar = tk.Menu(root)
m = tk.Menu(menubar, tearoff=0)
m.add_command(label="Open pickle...", command=self.apri_dialog)
m.add_command(label="Save pickle", command=self.salva_pickle)
m.add_command(label="Save pickle As...", command=self.salva_pickle_as)
m.add_separator()
m.add_command(label="Export image (PNG/SVG/PDF)...", command=self.esporta_immagine)
m.add_separator()
m.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=m)
root.config(menu=menubar)
# --- LAYOUT: sinistra grafico, destra controlli ---
self.paned = tk.PanedWindow(root, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=4)
self.paned.pack(fill=tk.BOTH, expand=True)
self.f_canvas = tk.Frame(self.paned, bg='#ffffff')
self.paned.add(self.f_canvas, width=920)
# Barra strumenti in alto, sotto un'area scrollabile che contiene il grafico:
# se la finestra è più piccola della figura compaiono le scrollbar e il
# grafico resta a dimensione fissa, invece di rimpicciolirsi/stirarsi.
self.f_toolbar = tk.Frame(self.f_canvas, bg='#ffffff')
self.f_toolbar.pack(side=tk.TOP, fill=tk.X)
self.vbar = tk.Scrollbar(self.f_canvas, orient=tk.VERTICAL)
self.vbar.pack(side=tk.RIGHT, fill=tk.Y)
self.hbar = tk.Scrollbar(self.f_canvas, orient=tk.HORIZONTAL)
self.hbar.pack(side=tk.BOTTOM, fill=tk.X)
self.scroll = tk.Canvas(self.f_canvas, bg='#ffffff', highlightthickness=0,
yscrollcommand=self.vbar.set, xscrollcommand=self.hbar.set)
self.scroll.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.vbar.config(command=self.scroll.yview)
self.hbar.config(command=self.scroll.xview)
self._canvas_window = None
self.scroll.bind('<Configure>', self._center_canvas) # ricentra al resize del pannello
self.f_ctrl = tk.Frame(self.paned, bg='#f0f4f7')
self._build_controls()
self.paned.add(self.f_ctrl, width=380)
# dpi di visualizzazione a schermo (l'export è sempre a 300 dpi)
self._display_dpi = 130
self._screen_ppi = None # PPI fisico reale del monitor, da calibrazione righello
self._export_in = None # dimensione di export (pollici), sorgente di verità
if path:
self.carica(path)
# ==================================================================
# COSTRUZIONE CONTROLLI
# ==================================================================
def _scrolled_tab(self, nb, title):
"""A notebook tab whose content scrolls (mouse wheel over it, or the bar): returns the inner frame."""
bg = '#f0f4f7'
outer = tk.Frame(nb, bg=bg)
nb.add(outer, text=title)
cv = tk.Canvas(outer, bg=bg, highlightthickness=0)
vb = tk.Scrollbar(outer, orient=tk.VERTICAL, command=cv.yview)
cv.configure(yscrollcommand=vb.set)
vb.pack(side=tk.RIGHT, fill=tk.Y)
cv.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
inner = tk.Frame(cv, bg=bg)
win = cv.create_window((0, 0), window=inner, anchor='nw')
inner.bind('<Configure>', lambda e: cv.configure(scrollregion=cv.bbox('all')))
cv.bind('<Configure>', lambda e: cv.itemconfigure(win, width=e.width))
def wheel(e):
if inner.winfo_reqheight() > cv.winfo_height(): # nothing to scroll: leave the wheel alone
cv.yview_scroll(-1 if e.delta > 0 else 1, 'units')
cv.bind('<Enter>', lambda e: cv.bind_all('<MouseWheel>', wheel))
cv.bind('<Leave>', lambda e: cv.unbind_all('<MouseWheel>'))
return inner
def _build_controls(self):
bg = '#f0f4f7'
# Buttons and hint stay visible under the tabs; the controls are grouped in scrollable tabs.
self._ctrl_bottom = tk.Frame(self.f_ctrl, bg=bg)
self._ctrl_bottom.pack(side=tk.BOTTOM, fill=tk.X)
nb = ttk.Notebook(self.f_ctrl)
nb.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
t_fig = self._scrolled_tab(nb, "Figura")
t_axes = self._scrolled_tab(nb, "Assi")
t_leg = self._scrolled_tab(nb, "Legenda")
t_lines = self._scrolled_tab(nb, "Linee")
# --- Titolo & assi ---
lf = tk.LabelFrame(t_fig, text="Titolo & assi", bg=bg, font=('Arial', 9, 'bold'))
lf.pack(fill=tk.X, padx=8, pady=6)
self.var_title = tk.StringVar()
self.var_title_fs = tk.DoubleVar(value=12)
self._row_text_fs(lf, 0, "Titolo:", self.var_title, self.var_title_fs, self._apply_title)
self.var_xlabel = tk.StringVar()
self.var_xlabel_fs = tk.DoubleVar(value=11)
self._row_text_fs(lf, 1, "X label:", self.var_xlabel, self.var_xlabel_fs, self._apply_xlabel)
self.var_ylabel = tk.StringVar()
self.var_ylabel_fs = tk.DoubleVar(value=11)
self._row_text_fs(lf, 2, "Y label:", self.var_ylabel, self.var_ylabel_fs, self._apply_ylabel)
tk.Label(lf, text="Font:", bg=bg, font=('Arial', 9)).grid(row=3, column=0, sticky='e', padx=2, pady=2)
self.var_font = tk.StringVar()
families = sorted({f.name for f in fm.fontManager.ttflist})
self.cb_font = ttk.Combobox(lf, values=families, textvariable=self.var_font,
width=20, state='readonly')
self.cb_font.grid(row=3, column=1, columnspan=2, sticky='w', padx=2)
self.cb_font.bind('<<ComboboxSelected>>', lambda e: self._apply_font())
tk.Label(lf, text="Numeri assi:", bg=bg, font=('Arial', 9)).grid(row=4, column=0, sticky='e', padx=2, pady=2)
self.var_tick = tk.DoubleVar(value=10)
sp_tick = tk.Spinbox(lf, from_=4, to=30, increment=1, width=5, textvariable=self.var_tick,
command=self._apply_ticks)
sp_tick.grid(row=4, column=1, sticky='w', padx=2)
sp_tick.bind('<Return>', lambda e: self._apply_ticks()) # anche digitando + Invio
sp_tick.bind('<FocusOut>', lambda e: self._apply_ticks())
tk.Label(lf, text="Etichette nel grafico:", bg=bg, font=('Arial', 9)).grid(
row=5, column=0, sticky='e', padx=2, pady=2)
self.var_intext = tk.DoubleVar(value=8)
sp_intext = tk.Spinbox(lf, from_=4, to=30, increment=1, width=5, textvariable=self.var_intext,
command=self._apply_intext_fontsize)
sp_intext.grid(row=5, column=1, sticky='w', padx=2)
sp_intext.bind('<Return>', lambda e: self._apply_intext_fontsize())
sp_intext.bind('<FocusOut>', lambda e: self._apply_intext_fontsize())
tk.Label(lf, text="(es. etichette campioni/punti)", bg=bg, font=('Arial', 8), fg='#555').grid(
row=5, column=2, sticky='w', padx=2)
tk.Button(lf, text="Nuova etichetta di testo...", command=self._new_text).grid(
row=6, column=0, columnspan=3, sticky='w', padx=6, pady=(4, 0))
tk.Label(lf, text="Etichette di testo: trascina per spostare, doppio clic per modificare il testo, "
"clic destro per colore, dimensione ed elimina.",
bg=bg, font=('Arial', 8), fg='#555', justify='left', wraplength=340).grid(
row=7, column=0, columnspan=3, sticky='w', padx=6, pady=(0, 4))
# --- Dimensione figura (fissa, per paper) ---
lfs = tk.LabelFrame(t_fig, text="Dimensione figura (cm)", bg=bg, font=('Arial', 9, 'bold'))
lfs.pack(fill=tk.X, padx=8, pady=6)
tk.Label(lfs, text="Larg.:", bg=bg, font=('Arial', 9)).grid(row=0, column=0, sticky='e', pady=2)
self.var_w_cm = tk.StringVar()
e_w = tk.Entry(lfs, width=7, textvariable=self.var_w_cm)
e_w.grid(row=0, column=1, padx=2)
tk.Label(lfs, text="Alt.:", bg=bg, font=('Arial', 9)).grid(row=0, column=2, sticky='e')
self.var_h_cm = tk.StringVar()
e_h = tk.Entry(lfs, width=7, textvariable=self.var_h_cm)
e_h.grid(row=0, column=3, padx=2)
for _e in (e_w, e_h): # Invio applica la dimensione
_e.bind('<Return>', lambda ev: self._apply_figsize())
_e.bind('<FocusOut>', lambda ev: self._apply_figsize())
tk.Button(lfs, text="Applica", command=self._apply_figsize,
font=('Arial', 8)).grid(row=0, column=4, padx=4)
tk.Label(lfs, text="DPI schermo:", bg=bg, font=('Arial', 9)).grid(row=1, column=0, sticky='e', pady=2)
self.var_dpi = tk.IntVar(value=130)
sp_dpi = tk.Spinbox(lfs, from_=50, to=600, increment=1, width=6, textvariable=self.var_dpi,
command=self._apply_display_dpi)
sp_dpi.grid(row=1, column=1, sticky='w', padx=2)
sp_dpi.bind('<Return>', lambda e: self._apply_display_dpi()) # anche digitando + Invio
sp_dpi.bind('<FocusOut>', lambda e: self._apply_display_dpi())
tk.Button(lfs, text="Adatta", command=self._fit_to_canvas, font=('Arial', 8)).grid(
row=1, column=2, sticky='w', padx=2)
tk.Button(lfs, text="1:1", command=self._apply_dpi_1to1, font=('Arial', 8)).grid(
row=1, column=3, sticky='w', padx=2)
tk.Button(lfs, text="Calibra…", command=self._calibra_schermo, font=('Arial', 8)).grid(
row=1, column=4, sticky='w', padx=2)
tk.Label(lfs, text="DPI = solo visualizzazione. Adatta = riempi il pannello; "
"1:1/Calibra = dimensione fisica reale in cm.",
bg=bg, font=('Arial', 8), fg='#555', wraplength=340, justify=tk.LEFT).grid(
row=2, column=0, columnspan=5, sticky='w')
self.var_tight = tk.BooleanVar(value=True)
tk.Checkbutton(lfs, text="Export: taglia margini (bbox tight)", variable=self.var_tight,
bg=bg, font=('Arial', 8)).grid(row=3, column=0, columnspan=5, sticky='w', pady=(2, 0))
tk.Label(lfs, text="Dimensione in cm = dimensione dell'export (a 300 dpi).",
bg=bg, font=('Arial', 8), fg='#555', wraplength=340, justify=tk.LEFT).grid(
row=4, column=0, columnspan=5, sticky='w')
# --- Scala & griglia ---
lf2 = tk.LabelFrame(t_axes, text="Scala & griglia", bg=bg, font=('Arial', 9, 'bold'))
lf2.pack(fill=tk.X, padx=8, pady=6)
tk.Label(lf2, text="X scale:", bg=bg, font=('Arial', 9)).grid(row=0, column=0, sticky='e', padx=2, pady=2)
self.var_xscale = tk.StringVar(value='linear')
cbx = ttk.Combobox(lf2, values=['linear', 'log'], textvariable=self.var_xscale, width=8, state='readonly')
cbx.grid(row=0, column=1, sticky='w', padx=2)
cbx.bind('<<ComboboxSelected>>', lambda e: self._apply_scale('x'))
tk.Label(lf2, text="Y scale:", bg=bg, font=('Arial', 9)).grid(row=0, column=2, sticky='e', padx=2)
self.var_yscale = tk.StringVar(value='linear')
cby = ttk.Combobox(lf2, values=['linear', 'log'], textvariable=self.var_yscale, width=8, state='readonly')
cby.grid(row=0, column=3, sticky='w', padx=2)
cby.bind('<<ComboboxSelected>>', lambda e: self._apply_scale('y'))
self.var_grid = tk.BooleanVar(value=True)
tk.Checkbutton(lf2, text="Griglia", variable=self.var_grid, bg=bg, font=('Arial', 9),
command=self._apply_grid).grid(row=1, column=0, columnspan=2, sticky='w', pady=2)
tk.Label(lf2, text="Passo tick X:", bg=bg, font=('Arial', 9)).grid(row=2, column=0, sticky='e', padx=2, pady=2)
self.var_tick_step_x = tk.StringVar()
e_step_x = tk.Entry(lf2, width=6, textvariable=self.var_tick_step_x)
e_step_x.grid(row=2, column=1, sticky='w', padx=2)
tk.Label(lf2, text="Y:", bg=bg, font=('Arial', 9)).grid(row=2, column=2, sticky='e', padx=2)
self.var_tick_step_y = tk.StringVar()
e_step_y = tk.Entry(lf2, width=6, textvariable=self.var_tick_step_y)
e_step_y.grid(row=2, column=3, sticky='w', padx=2)
for _e in (e_step_x, e_step_y): # indipendenti: X e Y possono avere passi diversi
_e.bind('<Return>', lambda ev: self._apply_tick_step())
_e.bind('<FocusOut>', lambda ev: self._apply_tick_step())
tk.Label(lf2, text="(vuoto = auto)", bg=bg, font=('Arial', 8),
fg='#555').grid(row=3, column=0, columnspan=4, sticky='w', padx=2)
# --- Limiti assi ---
lf3 = tk.LabelFrame(t_axes, text="Limiti assi (vuoto = auto)", bg=bg, font=('Arial', 9, 'bold'))
lf3.pack(fill=tk.X, padx=8, pady=6)
self.var_xmin, self.var_xmax = tk.StringVar(), tk.StringVar()
self.var_ymin, self.var_ymax = tk.StringVar(), tk.StringVar()
tk.Label(lf3, text="X:", bg=bg, font=('Arial', 9)).grid(row=0, column=0, sticky='e')
tk.Label(lf3, text="Y:", bg=bg, font=('Arial', 9)).grid(row=1, column=0, sticky='e')
for (r, c, var) in ((0, 1, self.var_xmin), (0, 2, self.var_xmax),
(1, 1, self.var_ymin), (1, 2, self.var_ymax)):
en = tk.Entry(lf3, width=8, textvariable=var)
en.grid(row=r, column=c, padx=2, pady=2)
en.bind('<Return>', lambda e: self._apply_limits()) # Invio applica i limiti
en.bind('<FocusOut>', lambda e: self._apply_limits())
tk.Button(lf3, text="Applica limiti", command=self._apply_limits,
font=('Arial', 8)).grid(row=0, column=3, rowspan=2, padx=4)
# --- Legenda ---
lf4 = tk.LabelFrame(t_leg, text="Legenda", bg=bg, font=('Arial', 9, 'bold'))
lf4.pack(fill=tk.X, padx=8, pady=6)
self.var_legend = tk.BooleanVar(value=True)
tk.Checkbutton(lf4, text="Mostra", variable=self.var_legend, bg=bg, font=('Arial', 9),
command=self._apply_legend).grid(row=0, column=0, sticky='w')
tk.Label(lf4, text="Size:", bg=bg, font=('Arial', 9)).grid(row=0, column=1, sticky='e')
self.var_leg_fs = tk.DoubleVar(value=8)
sp_leg = tk.Spinbox(lf4, from_=4, to=24, increment=1, width=4, textvariable=self.var_leg_fs,
command=self._apply_legend)
sp_leg.grid(row=0, column=2, sticky='w', padx=2)
sp_leg.bind('<Return>', lambda e: self._apply_legend()) # anche digitando + Invio
sp_leg.bind('<FocusOut>', lambda e: self._apply_legend())
tk.Label(lf4, text="Loc:", bg=bg, font=('Arial', 9)).grid(row=1, column=0, sticky='e')
self.var_leg_loc = tk.StringVar(value='best')
cbl = ttk.Combobox(lf4, values=LEGEND_LOCS, textvariable=self.var_leg_loc, width=14, state='readonly')
cbl.grid(row=1, column=1, columnspan=2, sticky='w', padx=2, pady=2)
cbl.bind('<<ComboboxSelected>>', lambda e: self._apply_legend())
self.var_leg_frame = tk.BooleanVar(value=True)
tk.Checkbutton(lf4, text="Frame", variable=self.var_leg_frame, bg=bg, font=('Arial', 9),
command=self._apply_legend_frame).grid(row=2, column=0, sticky='w')
tk.Button(lf4, text="Colore...", font=('Arial', 8), command=self._legend_frame_color
).grid(row=2, column=1, sticky='w', padx=2)
tk.Label(lf4, text="Width:", bg=bg, font=('Arial', 9)).grid(row=2, column=2, sticky='e')
self.var_leg_fw = tk.DoubleVar(value=0.8)
sp_fw = tk.Spinbox(lf4, from_=0.1, to=5, increment=0.1, width=4, textvariable=self.var_leg_fw,
command=self._apply_legend_frame)
sp_fw.grid(row=2, column=3, sticky='w', padx=2)
sp_fw.bind('<Return>', lambda e: self._apply_legend_frame())
sp_fw.bind('<FocusOut>', lambda e: self._apply_legend_frame())
# --- Linea selezionata ---
lf5 = tk.LabelFrame(t_lines, text="Linea selezionata", bg=bg, font=('Arial', 9, 'bold'))
lf5.pack(fill=tk.X, padx=8, pady=6)
tk.Label(lf5, text="Linea:", bg=bg, font=('Arial', 9)).grid(row=0, column=0, sticky='e', pady=2)
self.var_line = tk.StringVar()
self.cb_line = ttk.Combobox(lf5, textvariable=self.var_line, width=26, state='readonly')
self.cb_line.grid(row=0, column=1, columnspan=3, sticky='w', padx=2)
self.cb_line.bind('<<ComboboxSelected>>', lambda e: self._on_line_select())
tk.Label(lf5, text="Label:", bg=bg, font=('Arial', 9)).grid(row=1, column=0, sticky='e')
self.var_line_label = tk.StringVar()
e_lbl = tk.Entry(lf5, width=22, textvariable=self.var_line_label)
e_lbl.grid(row=1, column=1, columnspan=3, sticky='w', padx=2, pady=2)
e_lbl.bind('<Return>', lambda e: self._apply_line_label())
e_lbl.bind('<FocusOut>', lambda e: self._apply_line_label())
tk.Label(lf5, text="Colore:", bg=bg, font=('Arial', 9)).grid(row=2, column=0, sticky='e')
self.swatch = tk.Label(lf5, text=" ", bg='#cccccc', relief=tk.SUNKEN, width=4)
self.swatch.grid(row=2, column=1, sticky='w', padx=2)
tk.Button(lf5, text="Scegli...", command=self._pick_color, font=('Arial', 8)).grid(row=2, column=2, sticky='w')
tk.Label(lf5, text="Spessore:", bg=bg, font=('Arial', 9)).grid(row=3, column=0, sticky='e', pady=2)
self.var_line_lw = tk.DoubleVar(value=1.5)
sp_lw = tk.Spinbox(lf5, from_=0.2, to=10, increment=0.2, width=5, textvariable=self.var_line_lw,
command=self._apply_line_style)
sp_lw.grid(row=3, column=1, sticky='w', padx=2)
sp_lw.bind('<Return>', lambda e: self._apply_line_style()) # anche digitando + Invio
sp_lw.bind('<FocusOut>', lambda e: self._apply_line_style())
tk.Label(lf5, text="Stile:", bg=bg, font=('Arial', 9)).grid(row=3, column=2, sticky='e')
self.var_line_ls = tk.StringVar(value='-')
cbs = ttk.Combobox(lf5, values=LINESTYLES, textvariable=self.var_line_ls, width=5, state='readonly')
cbs.grid(row=3, column=3, sticky='w', padx=2)
cbs.bind('<<ComboboxSelected>>', lambda e: self._apply_line_style())
# --- Data of the selected line (simple maths) ---
lf6 = tk.LabelFrame(t_lines, text="Dati (linea selezionata)", bg=bg, font=('Arial', 9, 'bold'))
lf6.pack(fill=tk.X, padx=8, pady=6)
self.var_op = tk.StringVar(value=DATA_OPS[0])
ttk.Combobox(lf6, values=DATA_OPS, textvariable=self.var_op, width=26, state='readonly'
).grid(row=0, column=0, columnspan=3, sticky='w', padx=2, pady=2)
tk.Label(lf6, text="Valore:", bg=bg, font=('Arial', 9)).grid(row=1, column=0, sticky='e')
self.var_op_val = tk.StringVar(value='1')
e_op = tk.Entry(lf6, width=9, textvariable=self.var_op_val)
e_op.grid(row=1, column=1, sticky='w', padx=2)
e_op.bind('<Return>', lambda e: self._apply_data_op())
self.var_op_all = tk.BooleanVar(value=False)
tk.Checkbutton(lf6, text="Tutte le linee", variable=self.var_op_all, bg=bg,
font=('Arial', 9)).grid(row=1, column=2, sticky='w')
tk.Button(lf6, text="Applica", command=self._apply_data_op, font=('Arial', 8)
).grid(row=2, column=0, sticky='we', padx=2, pady=2)
tk.Button(lf6, text="Annulla", command=self._undo_data_op, font=('Arial', 8)
).grid(row=2, column=1, sticky='we', padx=2, pady=2)
# --- Stile Origin ---
of = tk.LabelFrame(t_fig, text="Stile Origin", bg=bg, font=('Arial', 9, 'bold'))
of.pack(fill=tk.X, padx=8, pady=(8, 0))
tk.Label(of, text="Layout:", bg=bg, font=('Arial', 9)).grid(row=0, column=0, sticky='e', pady=2)
self._layout_map = {'Colonna singola (4:3)': 'single', 'Doppia colonna (16:9)': 'double'}
self.var_layout = tk.StringVar(value='Colonna singola (4:3)')
ttk.Combobox(of, values=list(self._layout_map), textvariable=self.var_layout,
width=20, state='readonly').grid(row=0, column=1, sticky='w', padx=2)
tk.Button(of, text="Applica stile Origin", command=self._apply_origin_style,
bg='#fff0d0', font=('Arial', 9, 'bold')).grid(row=1, column=0, columnspan=2,
sticky='we', padx=2, pady=(4, 4))
# --- Salvataggi ---
bf = tk.Frame(self._ctrl_bottom, bg=bg)
bf.pack(fill=tk.X, padx=8, pady=10)
tk.Button(bf, text="Save pickle", command=self.salva_pickle,
bg='#e8f5e9').pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
tk.Button(bf, text="Export image", command=self.esporta_immagine,
bg='#dce8f5').pack(side=tk.LEFT, expand=True, fill=tk.X, padx=2)
self.hint = tk.Label(self._ctrl_bottom, text="Apri un .fig.pickle (menu File o drag&drop).",
bg=bg, font=('Arial', 8), fg='#555', wraplength=360, justify=tk.LEFT)
self.hint.pack(fill=tk.X, padx=10, pady=4)
def _row_text_fs(self, parent, row, label, var_text, var_fs, handler):
"""Riga con Entry di testo + Spinbox fontsize + apply su Return/change."""
bg = '#f0f4f7'
tk.Label(parent, text=label, bg=bg, font=('Arial', 9)).grid(row=row, column=0, sticky='e', padx=2, pady=2)
e = tk.Entry(parent, width=20, textvariable=var_text)
e.grid(row=row, column=1, sticky='w', padx=2)
e.bind('<Return>', lambda ev: handler())
e.bind('<FocusOut>', lambda ev: handler())
sp = tk.Spinbox(parent, from_=4, to=40, increment=1, width=4, textvariable=var_fs,
command=handler)
sp.grid(row=row, column=2, sticky='w', padx=2)
sp.bind('<Return>', lambda ev: handler()) # anche digitando + Invio
sp.bind('<FocusOut>', lambda ev: handler())
# ==================================================================
# CARICAMENTO / SALVATAGGIO
# ==================================================================
def _on_drop(self, event):
files = self.root.tk.splitlist(event.data)
if files:
self.carica(files[0].strip('{}'))
def apri_dialog(self):
path = filedialog.askopenfilename(
filetypes=[("Matplotlib Figure (pickle)", "*.pickle *.pkl"), ("All Files", "*.*")])
if path:
self.carica(path)
def carica(self, path):
try:
with open(path, 'rb') as f:
fig = pickle.load(f)
except Exception as e:
traceback.print_exc()
messagebox.showerror("Open", f"Impossibile aprire il pickle:\n{e}")
return
self._embed(fig, title=os.path.basename(path), path=path)
def carica_figura(self, fig, title="(figura corrente)"):
"""Carica un oggetto Figure già in memoria (es. aperto da KleistekManager
sulla figura corrente) invece di leggerlo da un pickle su disco."""
self._embed(fig, title=title, path=None)
def _embed(self, fig, title, path):
if not getattr(fig, 'axes', None):
messagebox.showerror("Open", "La figura non contiene assi.")
return
# Sostituisci il canvas
if self._canvas_window is not None:
self.scroll.delete(self._canvas_window)
self._canvas_window = None
if self.canvas is not None:
self.canvas.get_tk_widget().destroy()
if self.toolbar is not None:
self.toolbar.destroy()
self.fig = fig
self.ax = fig.axes[0]
self._data_undo = []
for a in fig.axes: # before any layout: a stale pixel offset puts the legend outside the figure and breaks tight_layout
if a.get_legend() is not None:
self._release_legend_offset(a.get_legend())
# Sorgente di verità della dimensione di EXPORT (pollici = cm/2.54): non
# dipende dal dpi di visualizzazione né dalle dimensioni del widget.
self._export_in = tuple(self.fig.get_size_inches())
self.fig.set_dpi(self._display_dpi)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.scroll)
tkw = self.canvas.get_tk_widget()
# Il widget del grafico vive dentro il Canvas scrollabile a dimensione fissa
# (impostata da noi): ridimensionare la FINESTRA non lo tocca (compaiono le
# scrollbar). Il <Configure> resta collegato, così quando siamo NOI a
# cambiare la dimensione del widget (cambio dpi) matplotlib ridisegna
# correttamente il buffer e non taglia la figura.
self._canvas_window = self.scroll.create_window(0, 0, window=tkw, anchor='nw')
self.toolbar = NavigationToolbar2Tk(self.canvas, self.f_toolbar)
# I tick label vengono rigenerati a ogni ridisegno: riapplica lì la famiglia font
self.canvas.mpl_connect('draw_event', self._reapply_tick_font)
# Rete di sicurezza per il drag della legenda (set_draggable): il canvas
# vive dentro un Canvas Tk scrollabile con la toolbar accanto, e se il
# rilascio del mouse avviene fuori dal widget del grafico (es. sopra la
# toolbar, o appena fuori bordo) matplotlib non riceve mai il
# button_release_event corrispondente. Il drag interno resta "armato"
# (got_artist=True) e la legenda continua a seguire il mouse a ogni
# movimento successivo, anche senza tenere premuto alcun tasto. Forziamo
# lo stop qui su qualunque rilascio o uscita dall'area del grafico.
self.canvas.mpl_connect('button_release_event', self._stop_legend_drag)
self.canvas.mpl_connect('figure_leave_event', self._stop_legend_drag)
# In questo layout (canvas Agg dentro un Canvas Tk scrollabile) il
# pick_event di matplotlib arma il drag della legenda (got_artist=True)
# anche per click ben fuori dal suo riquadro — verificato tracciando
# Legend.contains(), che nel controllo diretto risulta False mentre
# on_pick scatta comunque. Ricontrolliamo qui col nostro hit-test,
# SUBITO dopo il pick (stesso giro di 'button_press_event', prima di
# qualunque 'motion_notify_event'), e disarmiamo se il click non era
# davvero sulla legenda.
self.canvas.mpl_connect('button_press_event', self._guard_legend_drag)
# Free text labels (ax.texts) as objects: drag, double click, right click. Connected after the legend
# guard on purpose (see _texts_press).
self._txt_drag = None
self.canvas.mpl_connect('button_press_event', self._texts_press)
self.canvas.mpl_connect('motion_notify_event', self._texts_motion)
self.canvas.mpl_connect('button_release_event', self._texts_release)
self.canvas.mpl_connect('figure_leave_event', self._texts_release)
self._path = path
self.root.title(f"Plot Editor — {title}")
self._relayout()
self._resize_canvas_to_figure()
self._sync_controls_from_fig()
self.root.after(60, self._fit_to_canvas) # all'apertura: massimizza nel canvas
def _relayout(self):
"""Impagina la figura. Il GRAFICO (assi + etichette) occupa la dimensione di
export `self._export_in` (senza titolo). Un eventuale TITOLO viene aggiunto
SOPRA facendo crescere l'altezza della figura, senza rimpicciolire il grafico
(nei paper il titolo non si mette: è un extra che non conta nell'altezza).
Salva in `self._fig_in` la dimensione effettiva risultante."""
if self.fig is None or self._export_in is None:
self._fig_in = tuple(self.fig.get_size_inches()) if self.fig else None
return
w_in, h_in = self._export_in
ax = self.ax
had_title = bool(ax.get_title().strip())
# 1) layout del grafico ESCLUDENDO il titolo (nascosto, così non riserva spazio
# e non ne perde il fontsize), alla dimensione di export
ax.title.set_visible(False)
self.fig.set_size_inches(w_in, h_in)
try:
self.fig.subplots_adjust(left=0.125, right=0.9, bottom=0.11, top=0.88,
wspace=0.2, hspace=0.2)
self.fig.tight_layout()
except Exception:
pass
# 2) se c'è un titolo, cresci in altezza e tieni gli assi dov'erano
if had_title:
pos = ax.get_position()
left_in, bot_in = pos.x0 * w_in, pos.y0 * h_in
aw_in, ah_in = pos.width * w_in, pos.height * h_in
ax.title.set_visible(True)
try:
self.canvas.draw()
th_in = ax.title.get_window_extent(
renderer=self.canvas.get_renderer()).height / self.fig.dpi + 0.06
except Exception:
th_in = ax.title.get_fontsize() / 72 * 1.7
new_h = h_in + th_in
self.fig.set_size_inches(w_in, new_h)
ax.set_position([left_in / w_in, bot_in / new_h, aw_in / w_in, ah_in / new_h])
self._fig_in = tuple(self.fig.get_size_inches())
def _center_canvas(self, event=None):
"""Centra il grafico (orizzontalmente e verticalmente) nell'area scrollabile;
se il grafico è più grande del pannello compaiono le scrollbar."""
if self._canvas_window is None or self.fig is None:
return
fin = getattr(self, '_fig_in', None) or tuple(self.fig.get_size_inches())
w_px = int(round(fin[0] * self.fig.dpi))
h_px = int(round(fin[1] * self.fig.dpi))
vw, vh = self.scroll.winfo_width(), self.scroll.winfo_height()
x = max((vw - w_px) // 2, 0)
y = max((vh - h_px) // 2, 0)
self.scroll.coords(self._canvas_window, x, y)
self.scroll.configure(scrollregion=(0, 0, max(vw, w_px), max(vh, h_px)))
def _resize_canvas_to_figure(self):
"""Dimensiona il widget a pixel = pollici(figura) x dpi(visualizzazione) e
ricentra. La figura è già impaginata da `_relayout`."""
if self.fig is None or self.canvas is None:
return
fin = getattr(self, '_fig_in', None) or tuple(self.fig.get_size_inches())
self.fig.set_size_inches(*fin) # riafferma (anti-deriva da <Configure>)
w_px = int(round(fin[0] * self.fig.dpi))
h_px = int(round(fin[1] * self.fig.dpi))
tkw = self.canvas.get_tk_widget()
tkw.config(width=w_px, height=h_px)
if self._canvas_window is not None:
self.scroll.itemconfigure(self._canvas_window, width=w_px, height=h_px)
self._center_canvas()
self.canvas.draw()
def _apply_display_dpi(self):
"""Cambia il dpi di sola visualizzazione (non tocca la dimensione in cm né
l'export a 300 dpi)."""
try:
d = int(self.var_dpi.get())
except (ValueError, tk.TclError):
return
d = max(50, min(600, d))
self._display_dpi = d
if self.fig is not None:
self.fig.set_dpi(d)
self._resize_canvas_to_figure()
def _fit_to_canvas(self):
"""Massimizza la figura nel pannello (come Origin): sceglie il dpi di
visualizzazione perché la figura riempia il canvas mantenendo l'aspect.
Ridimensionando poi la finestra compaiono le scrollbar (nessuna distorsione)."""
if self.fig is None:
return
fin = getattr(self, '_fig_in', None) or tuple(self.fig.get_size_inches())
self.scroll.update_idletasks()
vw, vh = self.scroll.winfo_width(), self.scroll.winfo_height()
if vw < 20 or vh < 20: # pannello non ancora dimensionato: riprova
self.root.after(60, self._fit_to_canvas)
return
dpi = min(vw / fin[0], vh / fin[1]) * 0.97
dpi = max(50, min(600, dpi))
self.var_dpi.set(int(round(dpi)))
self._apply_display_dpi()
def _apply_dpi_1to1(self):
"""Imposta il dpi di visualizzazione al PPI reale del monitor: così a schermo
la figura ha la sua dimensione fisica (9 cm ≈ 9 cm) e i corpi in punti sono
alla dimensione reale. Usa il PPI calibrato se disponibile (più affidabile del
DPI logico di Tk, che con schermi densi / scaling di Windows sbaglia)."""
if self._screen_ppi:
dpi = self._screen_ppi
else:
try:
dpi = self.root.winfo_fpixels('1i')
except Exception:
dpi = 96
self.var_dpi.set(max(50, min(600, int(round(dpi)))))
self._apply_display_dpi()
def _set_screen_ppi(self, ppi):
self._screen_ppi = ppi
self.var_dpi.set(max(50, min(600, int(round(ppi)))))
self._apply_display_dpi()
def _calibra_schermo(self):
"""Calibrazione 1:1 per vedere la figura alla dimensione fisica reale.
Il PPI reale del monitor non è leggibile dal sistema (Tk riporta 96 finti),
quindi si ricava in due modi:
- dalla DIAGONALE (pollici) + la risoluzione vera dello schermo;
- col RIGHELLO su una barra di lunghezza nota (immune allo scaling)."""
win = tk.Toplevel(self.root)
win.title("Calibrazione 1:1")
sw, sh = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
# --- metodo diagonale ---
f1 = tk.LabelFrame(win, text="Da diagonale schermo", padx=10, pady=8)
f1.pack(fill=tk.X, padx=12, pady=(12, 6))
tk.Label(f1, text=f"Risoluzione rilevata: {sw}×{sh} px").grid(row=0, column=0, columnspan=3, sticky='w')
tk.Label(f1, text="Diagonale (pollici):").grid(row=1, column=0, sticky='e', pady=4)
var_diag = tk.StringVar(value='15.6')
tk.Entry(f1, width=8, textvariable=var_diag).grid(row=1, column=1, padx=4)
def usa_diag(*_):
try:
diag = float(var_diag.get().replace(',', '.'))
except ValueError:
return
if diag <= 0:
return
self._set_screen_ppi((sw ** 2 + sh ** 2) ** 0.5 / diag)
win.destroy()
tk.Button(f1, text="Usa diagonale", command=usa_diag).grid(row=1, column=2, padx=4)
# --- metodo righello ---
bar_px = 600
f2 = tk.LabelFrame(win, text="Col righello (immune allo scaling)", padx=10, pady=8)
f2.pack(fill=tk.X, padx=12, pady=6)
tk.Label(f2, justify=tk.LEFT,
text="Misura con un righello la barra qui sotto e inserisci i mm.").pack(anchor='w')
cv = tk.Canvas(f2, width=bar_px + 40, height=40, highlightthickness=0, bg='white')
cv.pack()
cv.create_line(20, 20, 20 + bar_px, 20, width=3)
cv.create_line(20, 8, 20, 32, width=2)
cv.create_line(20 + bar_px, 8, 20 + bar_px, 32, width=2)
fr = tk.Frame(f2)
fr.pack(anchor='w', pady=(6, 0))
tk.Label(fr, text="Lunghezza barra (mm):").pack(side=tk.LEFT)
var_mm = tk.StringVar()
e = tk.Entry(fr, width=8, textvariable=var_mm)
e.pack(side=tk.LEFT, padx=4)
def usa_righello(*_):
try:
mm = float(var_mm.get().replace(',', '.'))
except ValueError:
return
if mm <= 0:
return
self._set_screen_ppi(bar_px / (mm / 25.4))
win.destroy()
tk.Button(fr, text="Usa righello", command=usa_righello).pack(side=tk.LEFT, padx=4)
e.bind('<Return>', usa_righello)
win.transient(self.root)
win.grab_set()
@staticmethod
def _release_legend_offset(leg):
"""Give the legend back to matplotlib's own placement. A click on a draggable legend freezes its box at a
fixed PIXEL offset (DraggableOffsetBox.save_offset) that outlives the drag and goes into the pickle: on
export at another dpi/size the legend then lands somewhere unrelated to its `loc`. Dragging also stores the
new position in `loc`, so dropping the stale pixel offset loses nothing."""
box = getattr(leg, '_legend_box', None)
if box is not None and not callable(getattr(box, '_offset', None)) and hasattr(leg, '_findoffset'):
box.set_offset(leg._findoffset)
def _commit_legend_drag(self, leg):
"""Turn the pixel offset a drag leaves on the legend box into a real anchor (lower-left corner in axes
fractions, borderaxespad 0), the same form _apply_legend(preserve_pos=True) uses. Without it the dropped
position lives only in screen pixels: it is lost when the offset is released (export, save) or lands
elsewhere at another dpi/size."""
box = getattr(leg, '_legend_box', None)
if box is None or callable(getattr(box, '_offset', None)):
return
try:
self.canvas.draw()
bb = leg.get_window_extent()
x0, y0 = self.ax.transAxes.inverted().transform((bb.x0, bb.y0))
leg.set_bbox_to_anchor((x0, y0), transform=self.ax.transAxes)
leg.set_loc(3) # 'lower left'
leg.borderaxespad = 0.0
box.set_offset(leg._findoffset)
except Exception:
traceback.print_exc()
def _bake_legend(self):
"""Disattiva temporaneamente il draggable della legenda (mantenendone la
posizione) prima di pickle/savefig: i callback del DraggableLegend non
sono serializzabili e non servono nell'immagine. Ritorna True se era
attivo, per riattivarlo dopo."""
leg = self.ax.get_legend() if self.ax else None
if leg is not None and leg.get_draggable():
leg.set_draggable(False)
self._release_legend_offset(leg)
return True
return False
def _unbake_legend(self, was):
if was and self.ax is not None:
leg = self.ax.get_legend()
if leg is not None:
leg.set_draggable(True)
def salva_pickle(self):
if self.fig is None:
return
if not self._path:
return self.salva_pickle_as()
self._reapply_tick_font() # assicura il font sui tick prima di salvare
self._relayout() # dimensione/impaginazione esatta (grafico + eventuale titolo)
was = self._bake_legend()
try:
with open(self._path, 'wb') as f:
pickle.dump(self.fig, f)
except Exception as e:
traceback.print_exc()
messagebox.showerror("Save", f"Salvataggio fallito:\n{e}")
return
finally:
self._unbake_legend(was)
messagebox.showinfo("Save", f"Pickle salvato:\n{self._path}")
def salva_pickle_as(self):
if self.fig is None:
return
path = filedialog.asksaveasfilename(
defaultextension='.fig.pickle',
filetypes=[("Matplotlib Figure (pickle)", "*.pickle *.pkl"), ("All Files", "*.*")])
if not path:
return
self._path = path
self.salva_pickle()
self.root.title(f"Plot Editor — {os.path.basename(path)}")
def esporta_immagine(self):
if self.fig is None:
return
path = filedialog.asksaveasfilename(
defaultextension='.png',
filetypes=[("PNG", "*.png"), ("SVG", "*.svg"), ("PDF", "*.pdf")])
if not path:
return
self._reapply_tick_font() # assicura il font sui tick prima dell'export
self._relayout() # dimensione/impaginazione esatta (grafico + eventuale titolo)
was = self._bake_legend()
savekw = {'dpi': 300}
if self.var_tight.get():
savekw['bbox_inches'] = 'tight' # off = dimensione esatta in cm impostata
try:
self.fig.savefig(path, **savekw)
except Exception as e:
traceback.print_exc()
messagebox.showerror("Export", f"Export fallito:\n{e}")
return
finally:
self._unbake_legend(was)
messagebox.showinfo("Export", f"Immagine esportata:\n{path}")
# ==================================================================
# SINCRONIZZAZIONE CONTROLLI <- FIGURA
# ==================================================================
def _sync_controls_from_fig(self):
self._syncing = True
ax = self.ax
self.var_title.set(ax.get_title())
self.var_xlabel.set(ax.get_xlabel())
self.var_ylabel.set(ax.get_ylabel())
self.var_title_fs.set(round(ax.title.get_size(), 1))
self.var_xlabel_fs.set(round(ax.xaxis.label.get_size(), 1))
self.var_ylabel_fs.set(round(ax.yaxis.label.get_size(), 1))
ticks = ax.get_xticklabels()
self.var_tick.set(round(ticks[0].get_size(), 1) if ticks else 10)
in_texts = [t for t in ax.texts if t.get_text()]
self.var_intext.set(round(in_texts[0].get_size(), 1) if in_texts else 8)
xt = ax.get_xticks()
self.var_tick_step_x.set(f"{xt[1] - xt[0]:g}" if len(xt) >= 2 else '')
yt = ax.get_yticks()
self.var_tick_step_y.set(f"{yt[1] - yt[0]:g}" if len(yt) >= 2 else '')
# i campi cm mostrano la dimensione del GRAFICO (senza l'eventuale titolo)
w_in, h_in = self._export_in or tuple(self.fig.get_size_inches())
self.var_w_cm.set(f"{w_in * 2.54:.2f}")
self.var_h_cm.set(f"{h_in * 2.54:.2f}")
# rifletti nel dropdown il preset che combacia con la dimensione corrente:
# così "Applica stile Origin" non cambia a sorpresa l'aspect (es. una figura
# 16:9 che viene schiacciata a 4:3 perché il menu era rimasto su 'single').
if origin_style is not None:
inv = {v: k for k, v in self._layout_map.items()}
for name, (wc, hc) in origin_style.ORIGIN_PRESETS.items():
if (abs(w_in * 2.54 - wc) < 0.05 and abs(h_in * 2.54 - hc) < 0.05
and name in inv):
self.var_layout.set(inv[name])
break
# font: da attributo figura (round-trip) o dal font corrente del titolo
self._font_family = getattr(self.fig, '_editor_font_family', None)
try:
self.var_font.set(self._font_family or ax.title.get_fontname())
except Exception:
self.var_font.set('')
self.var_xscale.set(ax.get_xscale())
self.var_yscale.set(ax.get_yscale())
self.var_grid.set(any(gl.get_visible() for gl in ax.get_xgridlines()))
leg = ax.get_legend()
self.var_legend.set(leg is not None)
if leg is not None:
if leg.get_texts():
self.var_leg_fs.set(round(leg.get_texts()[0].get_size(), 1))
frame = leg.get_frame()
self.var_leg_frame.set(leg.get_frame_on())
self.var_leg_fw.set(round(frame.get_linewidth(), 2))
self._release_legend_offset(leg) # pickles saved with a frozen pixel offset heal on load
leg.set_draggable(True) # rende trascinabile la legenda già presente (senza ricrearla)
# limiti attuali come suggerimento
xlo, xhi = ax.get_xlim()
ylo, yhi = ax.get_ylim()
self.var_xmin.set(f"{xlo:.4g}"); self.var_xmax.set(f"{xhi:.4g}")
self.var_ymin.set(f"{ylo:.4g}"); self.var_ymax.set(f"{yhi:.4g}")
# elenco linee
self._line_names = []
for i, ln in enumerate(ax.lines):
lbl = ln.get_label()
if lbl.startswith('_'):
lbl = f"(senza nome {i})"
self._line_names.append(f"{i}: {lbl}")
self.cb_line['values'] = self._line_names
if self._line_names:
self.cb_line.current(0)
self._syncing = False
self._on_line_select()
else:
self._syncing = False
self.hint.config(text=f"{len(ax.lines)} linee. Le modifiche sono live; "
"usa Save pickle per conservarle o Export image.")
def _selected_line(self):
if self.ax is None or not self.ax.lines:
return None
try:
idx = int(self.var_line.get().split(':', 1)[0])
except (ValueError, AttributeError):
return None
if 0 <= idx < len(self.ax.lines):
return self.ax.lines[idx]
return None
def _apply_data_op(self):
"""Simple maths on the y (or x) values of the selected line, or of all lines. The values really change
(they are saved in the pickle); Annulla undoes the operations of this session, one at a time."""
if self.ax is None:
return
lines = list(self.ax.lines) if self.var_op_all.get() else [self._selected_line()]
lines = [ln for ln in lines if ln is not None]
if not lines:
return
op = self.var_op.get()
try:
c = float(self.var_op_val.get().replace(',', '.'))
except ValueError:
messagebox.showerror("Dati", "Il valore deve essere un numero.")
return
new = []
for ln in lines:
x = np.asarray(ln.get_xdata(), dtype=float)
y = np.asarray(ln.get_ydata(), dtype=float)
nx, ny = x, y
if op == DATA_OPS[0]: # y + c
ny = y + c
elif op == DATA_OPS[1]: # y * c
ny = y * c
elif op == DATA_OPS[2]: # x + c
nx = x + c
elif op == DATA_OPS[3]: # normalise: maximum becomes c
m = np.nanmax(np.abs(y))
if not m:
messagebox.showerror("Dati", "La linea è tutta a zero: impossibile normalizzare.")
return
ny = y / m * c
elif op == DATA_OPS[4]: # normalise: y at x = c becomes 1
order = np.argsort(x)
if not (x[order][0] <= c <= x[order][-1]):
messagebox.showerror("Dati", f"x = {c:g} è fuori dall'intervallo della linea "
f"({x[order][0]:g}–{x[order][-1]:g}).")
return
y0 = np.interp(c, x[order], y[order])
if not y0:
messagebox.showerror("Dati", f"y(x = {c:g}) è zero: impossibile normalizzare.")
return
ny = y / y0
elif op == DATA_OPS[5]: # subtract the minimum
ny = y - np.nanmin(y)
new.append((ln, x, y, nx, ny))
self._data_undo.append([(ln, x, y) for ln, x, y, _, _ in new])
for ln, _, _, nx, ny in new:
ln.set_data(nx, ny)
self._rescale_after_data_op(shift_x=(op == DATA_OPS[2]))
def _undo_data_op(self):
if not self._data_undo:
return
for ln, x, y in self._data_undo.pop():
ln.set_data(x, y)
self._rescale_after_data_op(shift_x=True)
def _rescale_after_data_op(self, shift_x):
"""The data moved: refit y (and x after a shift) so the curve stays in view, and refresh the limit boxes."""
self.ax.relim()
self.ax.autoscale_view(scalex=shift_x, scaley=True)
xlo, xhi = self.ax.get_xlim()
ylo, yhi = self.ax.get_ylim()
self.var_xmin.set(f"{xlo:.4g}"); self.var_xmax.set(f"{xhi:.4g}")
self.var_ymin.set(f"{ylo:.4g}"); self.var_ymax.set(f"{yhi:.4g}")
self._draw()
def _on_line_select(self):
ln = self._selected_line()
if ln is None:
return
self._syncing = True
lbl = ln.get_label()
self.var_line_label.set('' if lbl.startswith('_') else lbl)
self.var_line_lw.set(round(ln.get_linewidth(), 2))
ls = ln.get_linestyle()
self.var_line_ls.set(ls if ls in LINESTYLES else '-')
try:
hexcol = mcolors.to_hex(ln.get_color())
except (ValueError, TypeError):
hexcol = '#000000'
self.swatch.config(bg=hexcol)
self._syncing = False
# ==================================================================
# HANDLER (modifica -> oggetto -> redraw)
# ==================================================================
def _draw(self):
if self.canvas is not None:
self.canvas.draw_idle()
def _apply_title(self):
if self.ax is None or self._syncing:
return
self.ax.set_title(self.var_title.get(), fontsize=self.var_title_fs.get())
# il titolo cresce SOPRA il grafico senza rimpicciolirlo: reimpagina
self._relayout()
self._resize_canvas_to_figure()
def _apply_xlabel(self):
if self.ax is None or self._syncing:
return
self.ax.set_xlabel(self.var_xlabel.get(), fontsize=self.var_xlabel_fs.get())
self._draw()
def _apply_ylabel(self):
if self.ax is None or self._syncing:
return
self.ax.set_ylabel(self.var_ylabel.get(), fontsize=self.var_ylabel_fs.get())
self._draw()
def _apply_ticks(self):