Repository navigation
Expand file tree
/
Copy pathwidgets.py
More file actions
1343 lines (1230 loc) · 66.9 KB
/
Copy pathwidgets.py
File metadata and controls
1343 lines (1230 loc) · 66.9 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
"""Shared themed widgets, button feedback, table layout and selection behavior."""
import ctypes
import time
import tkinter as tk
from ctypes import wintypes
from tkinter import font as tkfont, messagebox, simpledialog, ttk
from constants import GLOBAL_PURPLE, GLOBAL_TEAL, GLOBAL_YELLOW
class EntryUndo:
"""Bounded text history around Entry class edits, never application actions.
Two private bindtags bracket Tk's normal editing bindings. Variable writes
outside an edit reset history, including programmatic prefill/load/reset.
"""
def __init__(self, entry):
self.entry = entry
self.history = []
self.before = None
self.restoring = False
self.tags = ('PyFirewallUndoBefore_' + str(entry), 'PyFirewallUndoAfter_' + str(entry))
self.bindings = []
self.variable = None
self.variable_name = ''
self.trace_command = None
self.sequences = ('<KeyPress>', '<<Paste>>', '<<Cut>>', '<<Clear>>', '<<PasteSelection>>')
try:
tags = list(entry.bindtags())
index = tags.index(entry.winfo_class()) + 1
tags.insert(index, self.tags[1])
entry.bindtags((self.tags[0], *tags))
for sequence in self.sequences:
self.bindings.append(entry.bind_class(self.tags[0], sequence, self._begin_key if sequence == '<KeyPress>' else self._begin))
self.bindings.append(entry.bind_class(self.tags[1], sequence, self._finish))
for sequence in ('<Control-z>', '<Control-Z>', '<<Undo>>'):
self.bindings.append(entry.bind_class(self.tags[0], sequence, self.undo))
variable = str(entry.cget('textvariable'))
self.variable = None
if not variable:
self.variable = tk.StringVar(master=entry, value=entry.get())
entry.configure(textvariable=self.variable)
variable = str(self.variable)
self.variable_name = variable
self.trace_command = entry.register(self._written)
entry.tk.call('trace', 'add', 'variable', variable, 'write', self.trace_command)
entry.bind('<Destroy>', self._destroy, add='+')
except Exception:
self._destroy()
raise
def _editable(self):
return str(self.entry.cget('state')) not in {'disabled', 'readonly'}
def _snapshot(self):
entry = self.entry
selection = (entry.index(tk.SEL_FIRST), entry.index(tk.SEL_LAST)) if entry.selection_present() else None
return entry.get(), entry.index(tk.INSERT), selection
def _begin_key(self, event):
# Clipboard shortcuts generate virtual events which own their edit.
control_edit = event.state & 4 and event.keysym.lower() in {'h', 'd', 'k', 'u', 'w', 't'}
if (event.char and event.char.isprintable()
or event.keysym in {'BackSpace', 'Delete', 'KP_Delete'} or control_edit):
self._begin()
def _begin(self, _event=None):
self.before = self._snapshot() if self._editable() else None
def _finish(self, _event=None):
before, self.before = self.before, None
if before is not None and before[0] != self.entry.get():
self.history.append(before)
del self.history[:-100]
def edit(self, operation):
"""Make a custom menu's delete+insert one text edit."""
self._begin()
try:
return operation()
finally:
self._finish()
def reset(self):
self.history.clear()
self.before = None
def _written(self, *_):
if self.before is None and not self.restoring:
self.reset()
def undo(self, _event=None):
self.before = None
if self._editable() and self.history:
text, insertion, selection = self.history.pop()
self.restoring = True
try:
self.entry.tk.globalsetvar(self.variable_name, text)
self.entry.icursor(insertion)
self.entry.selection_clear()
if selection:
self.entry.selection_range(*selection)
finally:
self.restoring = False
return 'break'
def _destroy(self, event=None):
entry = self.entry
if entry is None or event is not None and event.widget != entry:
return
try:
for tag in self.tags:
for sequence in (*self.sequences, '<Control-z>', '<Control-Z>', '<<Undo>>'):
entry.unbind_class(tag, sequence)
entry.bindtags(tuple(tag for tag in entry.bindtags() if tag not in self.tags))
except tk.TclError:
pass # The Tcl widget can already be gone during parent teardown.
for binding in self.bindings:
try:
entry._root().deletecommand(binding)
except tk.TclError:
pass
try:
entry.tk.call('trace', 'remove', 'variable', self.variable_name, 'write', self.trace_command)
except tk.TclError:
pass
if self.trace_command is not None:
try:
entry.deletecommand(self.trace_command)
except tk.TclError:
pass
self.bindings.clear()
self.reset()
# Only internally created variables belong to this controller. Release
# their final Python reference now, on Tk, and break the entry cycle.
self.variable = None
if getattr(entry, '_text_undo', None) is self:
del entry._text_undo
self.entry = None
def enable_entry_undo(entry):
if not hasattr(entry, '_text_undo'):
entry._text_undo = EntryUndo(entry)
return entry._text_undo
def ask_undo_string(title, prompt, parent):
class StringPrompt(simpledialog.Dialog):
def body(self, master):
tk.Label(master, text=prompt, justify=tk.LEFT).grid(row=0, sticky='w')
self.entry = ttk.Entry(master, width=36)
self.entry.grid(row=1, sticky='ew')
enable_entry_undo(self.entry)
return self.entry
def apply(self):
self.result = self.entry.get()
return StringPrompt(parent, title).result
def screen_work_area(widget, x, y):
"""Find the pointer's monitor, excluding its taskbar and other app bars."""
class MonitorInfo(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('monitor', wintypes.RECT),
('work', wintypes.RECT), ('flags', wintypes.DWORD)]
try:
user32 = ctypes.windll.user32
monitor_from_point = user32.MonitorFromPoint
monitor_from_point.argtypes = [wintypes.POINT, wintypes.DWORD]
monitor_from_point.restype = wintypes.HANDLE
get_monitor_info = user32.GetMonitorInfoW
get_monitor_info.argtypes = [wintypes.HANDLE, ctypes.POINTER(MonitorInfo)]
get_monitor_info.restype = wintypes.BOOL
monitor = monitor_from_point(wintypes.POINT(int(x), int(y)), 2)
info = MonitorInfo()
info.size = ctypes.sizeof(info)
if get_monitor_info(monitor, ctypes.byref(info)):
return info.work.left, info.work.top, info.work.right, info.work.bottom
except (AttributeError, OSError):
pass
return 0, 0, widget.winfo_screenwidth(), widget.winfo_screenheight()
class ThemedContextMenu:
"""Borderless popup with a one-pixel theme border, including on Windows."""
def __init__(self, root, colors, invoke_command=None):
self.root, self.colors = root, colors
self.invoke_command = invoke_command
self.origin = None
self.window = tk.Toplevel(root, bg=colors['head'], bd=0, highlightthickness=0)
self.window.withdraw()
self.window.overrideredirect(True)
self.body = tk.Frame(self.window, bg=colors['sub'], bd=0, highlightthickness=0)
self.body.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)
self.items = []
self.active = -1
self.previous_focus = None
self.root_bindings = []
self.window.bind('<Escape>', self._close)
self.window.bind('<FocusOut>', self._close)
self.window.bind('<ButtonPress-1>', self._outside_click)
self.window.bind('<ButtonPress-3>', self._outside_click)
self.window.bind('<Up>', lambda _: self._move(-1))
self.window.bind('<Down>', lambda _: self._move(1))
self.window.bind('<Home>', lambda _: self._select(0))
self.window.bind('<End>', lambda _: self._select(len(self.items) - 1))
self.window.bind('<Return>', self._invoke)
self.window.bind('<space>', self._invoke)
self.window.bind('<Destroy>', self._destroyed, add='+')
self.closed = False
self.canvas = None
def add_command(self, label, command, foreground=None, activeforeground='#ffffff', background=None, activebackground=None, checked=None):
color = foreground or self.colors['fg']
widget = tk.Label(self.body, text=label, anchor='w', bg=background or self.colors['sub'],
fg=color, font=('Segoe UI', 9), padx=34 if checked is not None else 12, pady=5, bd=0)
widget._menu_checked = checked
widget._menu_indicator = None
if checked is not None:
indicator = tk.Label(widget, text='✓' if checked else '', font=('Segoe UI', 9),
bg=widget.cget('bg'), fg=color, bd=0, width=2)
indicator.place(x=6, rely=0.5, anchor='w')
widget._menu_indicator = indicator
widget._menu_background = background or self.colors['sub']
widget._menu_activebackground = activebackground or self.colors['select']
widget.pack(fill=tk.X)
index = len(self.items)
self.items.append((widget, command, color, activeforeground))
widget.bind('<Enter>', lambda _: self._select(index))
widget.bind('<ButtonRelease-1>', lambda _: self._invoke(index=index))
if widget._menu_indicator is not None:
widget._menu_indicator.bind('<Enter>', lambda _: self._select(index))
widget._menu_indicator.bind('<ButtonRelease-1>', lambda _: self._invoke(index=index))
def add_checkbutton(self, label, command, checked):
self.add_command(label, command, checked=bool(checked))
def add_separator(self):
tk.Frame(self.body, height=1, bg=self.colors['head'], bd=0,
highlightthickness=0).pack(fill=tk.X, padx=6, pady=4)
def _select(self, index):
if not self.items:
return 'break'
if self.active >= 0:
widget, _, color, _ = self.items[self.active]
widget.configure(bg=widget._menu_background, fg=color)
if widget._menu_indicator is not None:
widget._menu_indicator.configure(bg=widget._menu_background, fg=color)
self.active = index % len(self.items)
widget, _, _, color = self.items[self.active]
widget.configure(bg=widget._menu_activebackground, fg=color)
if widget._menu_indicator is not None:
widget._menu_indicator.configure(bg=widget._menu_activebackground, fg=color)
if self.canvas is not None:
top, bottom = widget.winfo_y(), widget.winfo_y() + widget.winfo_height()
visible_top = self.canvas.canvasy(0)
height = self.canvas.winfo_height()
if top < visible_top or bottom > visible_top + height:
self.canvas.yview_moveto((top if top < visible_top else bottom - height) /
max(1, self.body.winfo_reqheight()))
return 'break'
def _move(self, step):
return self._select((0 if step > 0 else len(self.items) - 1)
if self.active < 0 else self.active + step)
def _invoke(self, event=None, index=None):
index = self.active if index is None else index
if 0 <= index < len(self.items):
command = self.items[index][1]
invoke, origin = self.invoke_command, self.origin
self._close()
if invoke is None:
command()
else:
invoke(command, origin)
return 'break'
def _outside_click(self, event):
x, y = self.window.winfo_rootx(), self.window.winfo_rooty()
if not (x <= event.x_root < x + self.window.winfo_width() and
y <= event.y_root < y + self.window.winfo_height()):
return self._close()
def _close(self, event=None):
if self.closed:
return 'break'
self.closed = True
for sequence, binding in self.root_bindings:
try:
self.root.unbind(sequence, binding)
except tk.TclError:
pass
self.root_bindings.clear()
if self.window.winfo_exists():
self.window.destroy()
if (event is None or event.type == tk.EventType.KeyPress) and self.previous_focus is not None:
try:
self.previous_focus.focus_set()
except tk.TclError:
pass
for widget, *_ in self.items:
widget._menu_indicator = None
self.items.clear()
self.previous_focus = None
self.invoke_command = None
self.root = self.body = self.canvas = None
return 'break'
def _destroyed(self, event):
if event.widget is self.window:
self._close(event)
def post(self, x, y):
self.origin = (x, y)
self.previous_focus = self.root.focus_get()
self.window.update_idletasks()
width, height = self.window.winfo_reqwidth(), self.window.winfo_reqheight()
left, top, right, bottom = screen_work_area(self.window, x, y)
if height > bottom - top:
# Reparenting is unnecessary: a canvas window may embed a sibling.
self.body.pack_forget()
self.canvas = tk.Canvas(self.window, bg=self.colors['sub'], bd=0,
highlightthickness=0, width=width - 2,
height=max(1, bottom - top - 2), yscrollincrement=24)
scrollbar = ttk.Scrollbar(self.window, orient=tk.VERTICAL, command=self.canvas.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=1)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=1, pady=1)
self.canvas.create_window(0, 0, window=self.body, anchor='nw', width=width - 2, height=height - 2)
self.canvas.configure(scrollregion=(0, 0, width - 2, height - 2), yscrollcommand=scrollbar.set)
self.window.bind('<MouseWheel>', lambda e: self.canvas.yview_scroll(-int(e.delta / 120), 'units'))
self.window.update_idletasks()
width, height = self.window.winfo_reqwidth(), bottom - top
x = max(left, min(x, right - width))
y = max(top, min(y, bottom - height))
self.window.geometry(f'{width}x{height}+{x}+{y}')
self.window.deiconify()
self.window.lift()
self.window.focus_force()
# A Tk grab captures Windows non-client clicks (including caption buttons).
# Dismiss on outside input instead, without consuming the original event.
for sequence in ('<ButtonPress-1>', '<ButtonPress-3>', '<Unmap>', '<Configure>'):
binding = self.root.bind(sequence, self._dismiss_from_root, add='+')
self.root_bindings.append((sequence, binding))
def _dismiss_from_root(self, event):
if event.type in (tk.EventType.ButtonPress,) or event.widget == self.root:
self._close(event)
class ToolTip:
def __init__(self, widget, text, delay=400):
self.widget, self.text, self.delay = (widget, text, delay)
self.tip = None
self.after_id = None
self.owner = widget.winfo_toplevel()
if not hasattr(self.owner, '_owned_tooltips'):
self.owner._owned_tooltips = set()
owner = self.owner
def dismiss(event):
if event.widget is owner:
for tooltip in tuple(owner._owned_tooltips):
tooltip._leave()
self.owner.bind('<Unmap>', dismiss, add='+')
self.owner.bind('<Destroy>', dismiss, add='+')
self.owner._owned_tooltips.add(self)
widget.bind('<Enter>', self._enter, add='+')
widget.bind('<Leave>', self._leave, add='+')
widget.bind('<ButtonPress>', self._leave, add='+')
widget.bind('<Destroy>', self._destroy, add='+')
def _destroy(self, event):
if event.widget is self.widget:
self._leave()
self.owner._owned_tooltips.discard(self)
self.widget._tooltip = None
self.widget = self.owner = self.text = None
def _sync_stacking(self, event=None):
if event is not None and event.widget is not self.tip:
return
if self.tip is not None:
try:
if not self.owner.winfo_viewable():
self._leave()
return
self.tip.attributes('-topmost', self.owner.attributes('-topmost'))
self.tip.lift(self.owner)
except tk.TclError:
self._leave()
def _enter(self, _=None):
self._cancel()
self.after_id = self.widget.after(self.delay, self._show)
def _leave(self, _=None):
self._cancel()
if self.tip:
try:
self.tip.destroy()
except tk.TclError:
pass
self.tip = None
def _cancel(self):
if self.after_id:
try:
self.widget.after_cancel(self.after_id)
except tk.TclError:
pass
self.after_id = None
def _show(self):
self._cancel()
text = self.text() if callable(self.text) else self.text
if self.tip or not str(text or '').strip():
return
try:
if not self.widget.winfo_viewable() or not self.owner.winfo_viewable():
return
# Use the pointer's current position after the hover delay, even if
# it moved within a wide control. Leave a little room for the cursor.
x, y = self.widget.winfo_pointerxy()
x += 12
y += 18
tip = tk.Toplevel(self.owner)
self.tip = tip
tip.withdraw()
tip.transient(self.owner)
tip.wm_overrideredirect(True)
# Windows tooltips never participate in focus or prompt grabs.
if tip.tk.call('tk', 'windowingsystem') == 'win32':
tip.attributes('-disabled', True)
tip.wm_geometry(f'+{x}+{y}')
tip.configure(bg='#2b2b2b')
tk.Label(tip, text=str(text), justify=tk.LEFT, bg='#2b2b2b', fg='#f0f0f0', relief='solid', borderwidth=1, font=('Segoe UI', 9), padx=8, pady=4).pack(ipadx=1)
tip.bind('<Map>', self._sync_stacking, add='+')
tip.deiconify()
self._sync_stacking()
except tk.TclError:
self._leave()
def add_tooltip(widget, text, delay=400):
widget._tooltip = ToolTip(widget, text, delay)
return widget._tooltip
def sync_tooltip_stacking(owner):
for tooltip in tuple(getattr(owner, '_owned_tooltips', ())):
tooltip._sync_stacking()
BUTTON_TIPS = {'Block Selected': 'Choose how to block the selected application.', 'Allow Selected': 'Allow all traffic for the selected application.', 'Export CSV': 'Export the visible connection rows to a CSV file.', 'Clear List': 'Clear the Live Monitor connection list.', 'Refresh Rules': 'Refresh the Managed Rules list from Windows Firewall.', 'Add App Rule': 'Create an inbound or outbound application rule.', 'Add Global Rule': 'Create a global rule for domains/IPs, ports and TCP/UDP, optionally limited to executables.', 'Remove Selected': 'Remove the selected managed firewall rule(s).', 'Remove Selected Rule': 'Remove the selected managed firewall rule(s).', 'Export Rules': 'Export managed rules to a JSON backup.', 'Import Rules': 'Import and apply managed rules from a JSON file.', 'Windows Firewall': 'Open Windows Defender Firewall.', 'Clear Alerts': 'Clear all entries from the Alerts list.', 'Apply Settings': 'Save and apply the monitoring thresholds and options.', 'Reset to Defaults': 'Reset saved settings and remove PyFirewall-managed rules.'}
class WidgetsMixin:
"""Methods composed into FirewallMonitorApp; state is owned by that application."""
def _connection_rule_body(self, dialog, message, endpoint):
"""Shared presentation only; each caller owns its decision lifecycle."""
body = tk.Frame(dialog, bg=self.colors['frame'])
body.pack(fill=tk.BOTH, expand=True, padx=20, pady=(16, 10))
options = dict(justify=tk.LEFT, anchor=tk.W, wraplength=470,
bg=self.colors['frame'], fg=self.colors['fg'], font=('Segoe UI', 10))
tk.Label(body, text=message, **options).pack(fill=tk.X)
raw_port = endpoint.get('dport')
try:
port = (str(int(raw_port)) if not isinstance(raw_port, bool) and str(raw_port).isdigit()
and 1 <= int(raw_port) <= 65535 else 'Unknown')
except (TypeError, ValueError):
port = 'Unknown'
protocol = str(endpoint.get('protocol', '')).upper()
protocol = protocol if protocol in {'TCP', 'UDP'} else 'Unknown'
tk.Label(body, text=f"Remote IP: {endpoint.get('dst_ip') or 'Unknown'}\nRemote port: {port}\nProtocol: {protocol}\nDomain/host:",
**options).pack(fill=tk.X, pady=(10, 0))
host_area = tk.Frame(body, bg=self.colors['frame'])
host_area.pack(fill=tk.X)
scrollbar = tk.Scrollbar(host_area, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# A bounded area keeps long or late hostnames from displacing actions.
host = tk.Text(host_area, height=3, width=1, wrap=tk.CHAR, bd=0, highlightthickness=0,
bg=self.colors['frame'], fg=self.colors['fg'], font=('Segoe UI', 10),
takefocus=False, yscrollcommand=scrollbar.set)
host._connection_host_display = True
host.insert('1.0', 'Not available')
host.configure(state=tk.DISABLED)
host.pack(side=tk.LEFT, fill=tk.X, expand=True)
scrollbar.configure(command=host.yview)
return body, host
def _connection_rule_actions(self, dialog, choose, cancel, *, current=None,
cancel_label='Cancel', cancel_tip='Dismiss without changing any rule.',
allow_tip='Allow the application. Matching global blocks still take precedence.'):
buttons = tk.Frame(dialog, bg=self.colors['frame'])
buttons.pack(fill=tk.X, padx=16, pady=(0, 14))
buttons.grid_columnconfigure((0, 1, 2), weight=1)
decisions = []
def button(parent, label, command, color, tip):
widget = tk.Button(parent, text=label, command=command, bg=color, fg='white',
activebackground=color, activeforeground='white', relief='flat',
font=('Segoe UI', 9, 'bold'), padx=10, pady=5)
self._bind_button_hover(widget)
add_tooltip(widget, tip)
decisions.append(widget)
return widget
specs = (('Block In & Out', 'both', '#c62828', 'Block incoming and outgoing application traffic.'),
('Block Incoming', 'in', '#ff9800', 'Block incoming application traffic.'),
('Allow All', 'allow', '#4CAF50', allow_tip))
for column, (label, value, color, tip) in enumerate(specs):
parent = buttons
if value == current:
parent = tk.Frame(buttons, bg=self.colors['fg'])
parent._button_border_frame = True
parent.grid(row=0, column=column, sticky='nsew', padx=3, pady=(0, 6))
widget = button(parent, label, lambda v=value: choose(v), color, tip)
if parent is buttons:
widget.grid(row=0, column=column, sticky='ew', padx=3, pady=(0, 6))
else:
widget.pack(fill=tk.BOTH, expand=True, padx=2, pady=2)
add_tooltip(parent, 'Current application rule')
connections = tk.Frame(buttons, bg=self.colors['frame'])
connections.grid(row=1, column=0, columnspan=3, sticky='ew')
connections.grid_columnconfigure((0, 1), weight=1)
for column, (label, value, color) in enumerate((('Block Connection', 'block_connection', '#c62828'),
('Allow Connection', 'allow_connection', '#4CAF50'))):
widget = button(connections, label, lambda v=value: choose(v), color,
("Allow" if value == 'allow_connection' else "Block") +
" this app's traffic matching the displayed IP, port, and protocol.")
widget.grid(row=0, column=column, sticky='ew', padx=3, pady=(0, 6))
widget = button(buttons, cancel_label, cancel, self.colors.get('button', '#757575'), cancel_tip)
widget.grid(row=2, column=0, columnspan=3, sticky='ew', padx=3)
return decisions
def _bind_entry_menu(self, entry):
"""Keep the clicked entry's edit range while the themed popup owns focus."""
undo = enable_entry_undo(entry)
def show(event):
try:
insertion = entry.index(tk.INSERT)
selection = ((entry.index(tk.SEL_FIRST), entry.index(tk.SEL_LAST))
if entry.selection_present() else None)
selected = entry.get()[selection[0]:selection[1]] if selection else None
entry.focus_set()
except tk.TclError:
return 'break'
def restore():
entry.focus_set()
entry.icursor(insertion)
entry.selection_clear()
if selection:
entry.selection_range(*selection)
def copy():
try:
restore()
if selected is not None:
entry.clipboard_clear()
entry.clipboard_append(selected)
except tk.TclError:
pass
def cut():
try:
restore()
if selected and undo._editable():
entry.clipboard_clear()
entry.clipboard_append(selected)
undo.edit(lambda: entry.delete(*selection))
except tk.TclError:
pass
def paste():
try:
if not undo._editable():
return
text = entry.clipboard_get()
restore()
def replace():
if selection:
entry.delete(*selection)
entry.insert(selection[0] if selection else insertion, text)
undo.edit(replace)
except tk.TclError:
pass
menu = self._context_menu()
if selected:
menu.add_command(label='Cut', command=cut)
menu.add_command(label='Copy', command=copy)
menu.add_command(label='Paste', command=paste)
menu.post(event.x_root, event.y_root)
menu.previous_focus = entry
return 'break'
entry.bind('<Button-3>', show)
# Theme application
def apply_theme(self):
dark = self.dark_mode_var.get()
self.dark_mode = bool(dark)
self.colors = {'bg': '#181818' if dark else '#f2f2f2', 'frame': '#1e1e1e' if dark else '#f2f2f2', 'sub': '#242424' if dark else '#ffffff', 'fg': '#e8e8e8' if dark else '#333333', 'muted': '#a8a8a8' if dark else '#757575', 'entry': '#252526' if dark else '#ffffff', 'select': '#3b78c8' if dark else '#0078D7', 'head': '#2d2d30' if dark else '#e0e0e0', 'even': '#252526' if dark else '#f9f9f9', 'odd': '#1e1e1e' if dark else '#ffffff', 'blocked': '#801a1a' if dark else '#ffcaca', 'blocked_in': '#7a4b11' if dark else '#ffcc99', 'global_block': '#593570' if dark else '#dfcdeb', 'global_allow': '#17665f' if dark else '#c3eee7', 'global_block_in': '#71630f' if dark else '#fff1a8', 'allowed': '#294f31' if dark else '#cce8d2', 'watch': '#5b4a16' if dark else '#fff3cd'}
self.colors['global_rule_button'] = '#704090'
self.colors.update(global_block_out=self.colors['global_block'],
global_allow_out=self.colors['global_allow'], global_allow_in=self.colors['global_block_in'])
self.colors['wallet'] = '#bdbdbd' if dark else '#555555'
self.colors['text'] = self.colors['fg'] if dark else '#202020'
self.colors['menu_edit'] = self.colors['muted'] if dark else '#333333'
self.colors['crypto_heading'] = '#cccccc' if dark else '#202020'
self.root.configure(bg=self.colors['bg'])
style = ttk.Style(self.root)
try:
style.theme_use('clam')
except tk.TclError:
pass
style.configure('TFrame', background=self.colors['frame'])
style.configure('TLabel', background=self.colors['frame'], foreground=self.colors['fg'])
style.configure('TLabelframe', background=self.colors['sub'], foreground=self.colors['fg'], bordercolor=self.colors['blocked_in'])
style.configure('TLabelframe.Label', background=self.colors['sub'], foreground=self.colors['fg'])
style.configure('TNotebook', background=self.colors['bg'], borderwidth=0)
style.configure('TNotebook.Tab', background=self.colors['head'], foreground=self.colors['fg'], font=('Segoe UI', 10, 'bold'), padding=[10, 5, 10, 5])
style.map('TNotebook.Tab', background=[('selected', self.colors['frame']), ('active', self.colors['sub'])], foreground=[('selected', self.colors['fg']), ('active', self.colors['fg'])], padding=[('selected', [10, 8, 10, 4]), ('!selected', [10, 5, 10, 5])])
style.configure('TCheckbutton', background=self.colors['frame'], foreground=self.colors['fg'])
style.map('TCheckbutton', background=[('active', self.colors['frame'])], foreground=[('disabled', self.colors['muted']), ('active', self.colors['fg'])])
style.configure('Treeview', background=self.colors['sub'], foreground=self.colors['fg'] if dark else '#000000', fieldbackground=self.colors['sub'], rowheight=25)
style.configure('Treeview.Heading', background=self.colors['head'], foreground=self.colors['fg'], font=('Segoe UI', 9, 'bold'))
style.map('Treeview.Heading', background=[('active', '#d8d8d8'), ('pressed', '#c8c8c8')], foreground=[('active', '#000000'), ('pressed', '#000000')])
style.map('Treeview', background=[('selected', self.colors['select'])], foreground=[('selected', '#ffffff')])
style.configure('TEntry', fieldbackground=self.colors['entry'], foreground=self.colors['fg'],
insertcolor='#ffffff' if dark else self.colors['fg'])
style.map('TEntry', fieldbackground=[('disabled', self.colors['head'])], foreground=[('disabled', self.colors['muted'])])
style.configure('Search.TFrame', background=self.colors['entry'])
style.configure('Search.TEntry', borderwidth=0, relief='flat')
style.configure('SearchClear.TButton', background=self.colors['entry'], foreground=self.colors['fg'],
padding=(2, 0), borderwidth=0, relief='flat')
style.map('SearchClear.TButton', background=[('active', self.colors['head'])],
foreground=[('disabled', self.colors['muted'])])
style.configure('Settings.TLabel', foreground=self.colors['text'])
style.configure('Settings.TEntry', foreground=self.colors['text'])
style.map('Settings.TEntry', foreground=[('disabled', self.colors['muted'] if dark else self.colors['text'])])
style.configure('Settings.TCheckbutton', foreground=self.colors['text'])
style.map('Settings.TCheckbutton', foreground=[('disabled', self.colors['muted'] if dark else self.colors['text']), ('active', self.colors['text'])])
if not hasattr(self, '_original_tbutton_theme'):
self._original_tbutton_theme = (
{key: style.lookup('TButton', key) for key in ('foreground', 'bordercolor')},
{key: style.map('TButton', key) for key in ('foreground', 'bordercolor')})
if dark:
style.configure('TButton', **self._original_tbutton_theme[0])
style.map('TButton', **self._original_tbutton_theme[1])
else:
style.configure('TButton', foreground=self.colors['fg'], bordercolor=self.colors['fg'])
style.map('TButton', foreground=[('disabled', self.colors['muted']), ('active', self.colors['fg'])],
bordercolor=[('active', self.colors['fg']), ('!disabled', self.colors['fg'])])
def repaint(parent, settings=False):
settings = settings or parent is getattr(self, 'tab_settings', None)
for widget in parent.winfo_children():
try:
if isinstance(widget, tk.Toplevel) and getattr(widget, '_crypto_dialog', False):
self._theme_dialog(widget)
elif isinstance(widget, tk.LabelFrame):
widget.configure(bg=self.colors['frame'], fg=self.colors['text'] if settings else self.colors['fg'])
elif isinstance(widget, tk.Frame):
widget.configure(bg=self.colors['fg'] if getattr(widget, '_button_border_frame', False) else self.colors['frame'])
elif isinstance(widget, tk.Label):
widget.configure(bg=self.colors['frame'], fg=self.colors[getattr(widget, '_theme_foreground_key', 'text' if settings else 'fg')])
elif isinstance(widget, tk.Text) and getattr(widget, '_connection_host_display', False):
widget.configure(bg=self.colors['frame'], fg=self.colors['fg'])
elif settings and isinstance(widget, ttk.Checkbutton):
widget.configure(style='Settings.TCheckbutton')
elif settings and isinstance(widget, ttk.Label):
widget.configure(style='Settings.TLabel')
elif settings and isinstance(widget, ttk.Entry):
widget.configure(style='Settings.TEntry')
elif isinstance(widget, tk.Entry):
widget.configure(bg=self.colors['entry'], fg=self.colors['fg'], insertbackground=self.colors['fg'])
elif isinstance(widget, tk.Checkbutton):
widget.configure(bg=self.colors['frame'], fg=self.colors['fg'], activebackground=self.colors['frame'], activeforeground=self.colors['fg'], selectcolor=self.colors['entry'])
elif isinstance(widget, tk.Button) and hasattr(widget, '_pyfirewall_source_bg'):
self._apply_button_theme(widget)
except tk.TclError:
pass
repaint(widget, settings)
repaint(self.root)
if hasattr(self, 'settings_canvas'):
self.settings_canvas.configure(bg=self.colors['frame'])
self.configure_tags()
self.update_filter_ui()
self.update_status()
def configure_tags(self):
for name in ('tree', 'rules_tree', 'alerts_tree'):
tree = getattr(self, name, None)
if tree is None:
continue
for tag in ('even', 'odd', 'blocked', 'blocked_in', 'global_block', 'global_block_in', 'global_block_out', 'global_allow', 'global_allow_in', 'global_allow_out', 'allowed', 'watch'):
tree.tag_configure(tag, background=self.colors[tag], foreground=self.colors['fg'] if self.dark_mode else '#000000')
def on_theme_changed(self):
with self.lock:
self.dark_mode = bool(self.dark_mode_var.get())
self._save_settings_with_feedback()
self.apply_theme()
# Button colors and hover feedback
@staticmethod
def _hover_color(color, dark_mode=True):
try:
value = str(color).lstrip('#')
if len(value) != 6:
return str(color)
red, green, blue = (int(value[index:index + 2], 16) for index in (0, 2, 4))
factor = 0.72 if dark_mode else 0.93
return '#{:02x}{:02x}{:02x}'.format(*(max(0, int(channel * factor))
for channel in (red, green, blue)))
except (TypeError, ValueError):
return str(color)
def _bind_button_hover(self, button, border=None):
if getattr(button, '_pyfirewall_hover_bound', False):
return button
button._pyfirewall_hover_bound = True
button._pyfirewall_original_highlightthickness = button.cget('highlightthickness')
def set_normal_state(bg=None, activebackground=None):
try:
if bg is not None:
button._pyfirewall_base_bg = bg
if activebackground is not None:
button._pyfirewall_base_active_bg = activebackground
else:
button._pyfirewall_base_active_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
if border is not None:
border._pyfirewall_base_bg = getattr(button, '_pyfirewall_base_bg', border.cget('bg'))
except tk.TclError:
pass
set_normal_state(button.cget('bg'), button.cget('activebackground'))
def enter(_event=None):
try:
if str(button.cget('state')) == str(tk.DISABLED):
button.configure(cursor='arrow')
return
normal_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
hover = self._hover_color(normal_bg, self.dark_mode)
button.configure(bg=hover, activebackground=hover, cursor='hand2')
if border is not None:
border.configure(bg=hover if self.dark_mode else self.colors['fg'])
except tk.TclError:
pass
def leave(_event=None):
try:
normal_bg = getattr(button, '_pyfirewall_base_bg', button.cget('bg'))
normal_active_bg = getattr(button, '_pyfirewall_base_active_bg', normal_bg)
button.configure(bg=normal_bg, activebackground=normal_active_bg, cursor='')
if border is not None:
border.configure(bg=normal_bg if self.dark_mode else self.colors['fg'])
except tk.TclError:
pass
button.bind('<Enter>', enter, add='+')
button.bind('<Leave>', leave, add='+')
button._pyfirewall_set_normal_state = set_normal_state
def dispose(event):
if event.widget is button:
button._pyfirewall_set_normal_state = None
button._pyfirewall_border = None
button.bind('<Destroy>', dispose, add='+')
self._set_button_colors(button, border, button.cget('bg'), button.cget('fg'),
button.cget('state'), activebackground=button.cget('activebackground'))
return button
def _set_button_colors(self, button, border, color, fg='white', state=tk.NORMAL, activebackground=None):
if button is None:
return
try:
# Keep the semantic source colors so theme toggles never repeatedly
# lighten an already softened background, and dark mode restores it.
button._pyfirewall_source_bg = color
button._pyfirewall_source_fg = fg
button._pyfirewall_source_active_bg = activebackground or color
button._pyfirewall_border = border
button.configure(state=state)
self._apply_button_theme(button)
except tk.TclError:
pass
def _apply_button_theme(self, button):
try:
color = button._pyfirewall_source_bg
active = button._pyfirewall_source_active_bg
fg = '#ffffff' if self.dark_mode else self.colors['fg']
border = button._pyfirewall_border
dark_color_key = getattr(button, '_pyfirewall_dark_color_key', None)
if self.dark_mode and dark_color_key:
color = active = self.colors[dark_color_key]
elif self.dark_mode:
# Derive from the original semantic color on every update so
# theme switches and state changes never compound the shading.
channels = button.winfo_rgb(color)
color = '#{:02x}{:02x}{:02x}'.format(*(
round((channel / 257) * 0.75) for channel in channels))
active = color
else:
channels = button.winfo_rgb(color)
color = '#{:02x}{:02x}{:02x}'.format(*(
round((channel / 257) * 0.30 + 255 * 0.70) for channel in channels))
active = color
button.configure(bg=color, activebackground=active, fg=fg, activeforeground=fg)
setter = getattr(button, '_pyfirewall_set_normal_state', None)
if callable(setter):
setter(color, active)
else:
button._pyfirewall_base_bg = color
button._pyfirewall_base_active_bg = active
if border is not None:
border_color = color if self.dark_mode else self.colors['fg']
border.configure(bg=border_color)
border._pyfirewall_base_bg = border_color
else:
# Dialog actions have no surrounding frame; use Tk's one-pixel
# highlight outline, with the same color when keyboard-focused.
button.configure(highlightthickness=(
getattr(button, '_pyfirewall_original_highlightthickness', 0)
if self.dark_mode else 1),
highlightbackground=self.colors['fg'], highlightcolor=self.colors['fg'])
except tk.TclError:
pass
def _button(self, parent, text, command, color=None, pack=True, tooltip=None, dark_color_key=None, **options):
color = color or '#757575'
border = tk.Frame(parent, bg=color, bd=0, highlightthickness=0)
border._button_border_frame = True
settings = {'text': text, 'command': command, 'bg': color, 'fg': 'white', 'activebackground': color, 'activeforeground': 'white', 'relief': 'flat', 'borderwidth': 0, 'highlightthickness': 0, 'font': ('Segoe UI', 9, 'bold'), 'padx': 9}
settings.update(options)
button = tk.Button(border, **settings)
button._pyfirewall_dark_color_key = dark_color_key
self._bind_button_hover(button, border)
button.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)
if pack:
border.pack(side=tk.LEFT, padx=4)
add_tooltip(button, tooltip or BUTTON_TIPS.get(text, ''))
return button if pack else border
# Tree construction and sizing
def _make_tree(self, parent, columns, widths, order_key):
frame = ttk.Frame(parent)
frame.pack(fill=tk.BOTH, expand=True)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
tree = ttk.Treeview(frame, columns=columns, show='headings', selectmode='extended')
tree._column_order_key = order_key
tree._default_column_widths = {}
for column in columns:
width, anchor, stretch = widths.get(column, (180, tk.W, True))
tree._default_column_widths[column] = width
width = getattr(self, 'column_widths', {}).get(order_key, {}).get(column, width)
label = {'Download (MB)': 'Download', 'Upload (MB)': 'Upload'}.get(column, column) if order_key in {'monitor', 'rules'} else column
tree.heading(column, text=label)
tree.column(column, width=width, anchor=anchor, stretch=False)
order = self._normalized_column_order(order_key, columns)
tree['displaycolumns'] = tuple(c for c in order if c not in self.hidden_columns.get(order_key, [])) or (order[0],)
horizontal = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
horizontal.grid(row=1, column=0, sticky='ew')
scrollbar.grid(row=0, column=1, sticky='ns')
horizontal.grid_remove()
scrollbar.grid_remove()
tree.grid(row=0, column=0, sticky='nsew')
tree._layout_pending = None
tree._fill_column = None
tree._fit_viewport = None
tree._autosize_pending = None
tree._autosize_job = None
tree._horizontal_scrollbar = horizontal
tree._vertical_scrollbar = scrollbar
def scroll(bar, first, last):
bar.set(first, last)
visible = float(first) > 0.000001 or float(last) < 0.999999
if visible != bool(bar.winfo_manager()):
bar.grid() if visible else bar.grid_remove()
self._schedule_tree_layout(tree)
tree.configure(xscrollcommand=lambda first, last: scroll(horizontal, first, last),
yscrollcommand=lambda first, last: scroll(scrollbar, first, last))
tree.bind('<Configure>', lambda _: self._schedule_tree_layout(tree), add='+')
def cancel_layout(event):
if event.widget == tree:
for name in ('_layout_pending', '_autosize_pending'):
pending = getattr(tree, name)
if pending is not None:
tree.after_cancel(pending)
setattr(tree, name, None)
tree._autosize_job = None
tree.bind('<Destroy>', cancel_layout, add='+')
tree.bind('<Control-a>', self.select_all_rows)
tree.bind('<Control-A>', self.select_all_rows)
tree.bind('<Control-c>', self.copy_selected_rows)
tree.bind('<Control-C>', self.copy_selected_rows)
self._bind_tree_headers(tree)
return tree
def _schedule_tree_layout(self, tree):
if tree._layout_pending is None:
tree._layout_pending = tree.after_idle(lambda: self._fill_tree_column(tree))
def _fill_tree_column(self, tree):
tree._layout_pending = None
if tree._fit_viewport is not None:
if tree._fit_viewport == (tree.master.winfo_width(), tree.master.winfo_height()):
return
tree._fit_viewport = None
columns = tuple(tree['displaycolumns'])
if not columns or tree.winfo_width() <= 1:
return
previous = tree._fill_column
if previous:
current = tree.column(previous, 'width')
# Preserve a manual resize, but discard space added solely to fill.
if current != tree._fill_width:
tree._fill_base_width = current
if previous != columns[-1]:
tree.column(previous, width=tree._fill_base_width)
last = columns[-1]
if previous != last:
tree._fill_base_width = tree.column(last, 'width')
border = ttk.Style(tree).lookup(tree.cget('style') or 'Treeview', 'borderwidth') or 1
# The tree's width already excludes its sibling vertical scrollbar.
# Leave a small allowance for theme/DPI rounding at the inner borders
# so filling unused space cannot itself create horizontal overflow.
available = max(0, tree.winfo_width() - 2 * tree.winfo_pixels(border) - 4)
preceding = sum(tree.column(c, 'width') for c in columns[:-1])
width = max(tree._fill_base_width, available - preceding)
tree._fill_column, tree._fill_width = last, width
if tree.column(last, 'width') != width:
tree.column(last, width=width)
def _normalized_column_order(self, order_key, columns=None):
default = tuple(self.default_column_orders[order_key])
available = set(columns or default)
with self.lock:
saved = list(self.column_orders.get(order_key, list(default)))
result = [c for c in saved if c in available]
result.extend((c for c in default if c in available and c not in result))
if columns:
result.extend((c for c in columns if c not in result))
self.column_orders[order_key] = result
return list(result)
# Column visibility, sorting and reordering
def _tree_column_from_x(self, tree, x):
try:
token = tree.identify_column(x)
if not token.startswith('#'):
return None
index = int(token[1:]) - 1
order = list(tree['displaycolumns'])
if 0 <= index < len(order):
return order[index]
except (ValueError, tk.TclError):
pass
return None
def _bind_tree_headers(self, tree):
tree.bind('<Button-1>', self._tree_header_press, add='+')
tree.bind('<B1-Motion>', self._tree_header_motion, add='+')
tree.bind('<ButtonRelease-1>', self._tree_header_release, add='+')
def _show_header_menu(self, event, tree):
if tree.identify_region(event.x, event.y) not in {'heading', 'separator'}:
return False
column = self._tree_column_from_x(tree, event.x)
if column:
menu = self._context_menu()
menu.add_command(label='Size Columns to Fit', command=lambda: self._size_tree_columns(tree))
menu.add_command(label='Hide Column', command=lambda: self._hide_column(tree, column))
menu.add_separator()
visible = set(tree['displaycolumns'])
for item in self._normalized_column_order(tree._column_order_key, tree['columns']):
caption = tree.heading(item, 'text')
if tree._column_order_key == 'monitor' and item == 'Local Port':
caption = 'Local Ports'
menu.add_checkbutton(label=caption, checked=item in visible,
command=lambda c=item: self._toggle_column(tree, c))
menu.post(event.x_root, event.y_root)
return True