-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
640 lines (532 loc) · 23.7 KB
/
Copy pathapp.py
File metadata and controls
640 lines (532 loc) · 23.7 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
import ttkbootstrap as tb
from ttkbootstrap.constants import *
import tkinter as tk
from tkinter import ttk, messagebox
import subprocess
import json
import os
import tempfile
import threading
import base64
import io
import sys
import math
from PIL import Image, ImageTk, ImageDraw
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except:
pass
if getattr(sys, 'frozen', False):
BASE_DIR = sys._MEIPASS
else:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PS_SCRIPT = os.path.join(BASE_DIR, 'scripts', 'app-controller.ps1')
app_data = []
filtered_apps = []
toggled_app_names = []
icon_cache = {}
is_admin = False
default_icon_img = None
default_icon_tk = None
def is_process_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
def run_powershell_list():
out_file = os.path.join(tempfile.gettempdir(), f'anc_out_{os.urandom(4).hex()}.json')
args = ['-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', PS_SCRIPT,
'-Action', 'list', '-OutputFile', out_file]
try:
r = subprocess.run(['powershell'] + args, capture_output=True, timeout=180,
creationflags=subprocess.CREATE_NO_WINDOW)
stderr = r.stderr.decode('utf-8', errors='replace')
if r.returncode != 0:
return None, stderr or f'PowerShell exited with code {r.returncode}'
if os.path.exists(out_file):
with open(out_file, 'r', encoding='utf-8') as f:
data = f.read()
os.remove(out_file)
return json.loads(data), None
return None, 'Output file was not created'
except subprocess.TimeoutExpired:
if os.path.exists(out_file): os.remove(out_file)
return None, 'PowerShell script timed out (180s). Too many applications.'
except Exception as e:
if os.path.exists(out_file): os.remove(out_file)
return None, str(e)
def run_powershell_toggle(action, app_name, exe_path):
args = ['-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', PS_SCRIPT,
'-Action', action, '-AppName', app_name, '-ExePath', exe_path]
try:
r = subprocess.run(['powershell'] + args, capture_output=True, timeout=30,
creationflags=subprocess.CREATE_NO_WINDOW)
stdout = r.stdout.decode('utf-8', errors='replace').strip()
stderr = r.stderr.decode('utf-8', errors='replace').strip()
if r.returncode != 0:
return False, stderr or stdout or f'Exit code {r.returncode}'
if stdout.startswith('ERROR:'):
return False, stdout[6:]
return True, stdout
except Exception as e:
return False, str(e)
def request_admin_toggle(action, app_name, exe_path):
tmp_ps = os.path.join(tempfile.gettempdir(), f'anc_toggle_{os.urandom(4).hex()}.ps1')
ps_content = f'''param()
$ruleName = "ANC:{app_name}"
try {{
if ("{action}" -eq "block") {{
$existing = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
if (-not $existing) {{
New-NetFirewallRule -DisplayName $ruleName -Direction Outbound -Program "{exe_path}" -Action Block -Description "AppNetworkController" -ErrorAction Stop | Out-Null
Write-Output "BLOCKED"
}} else {{ Write-Output "ALREADY_BLOCKED" }}
}} else {{
$existing = Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue
if ($existing) {{
Remove-NetFirewallRule -DisplayName $ruleName -ErrorAction Stop
Write-Output "UNBLOCKED"
}} else {{ Write-Output "NOT_FOUND" }}
}}
}} catch {{
Write-Output "ERROR:$($_.Exception.Message)"
exit 1
}}
'''
try:
with open(tmp_ps, 'w', encoding='utf-8') as f:
f.write(ps_content)
r = subprocess.run(
['powershell', '-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', tmp_ps],
capture_output=True, timeout=30
)
if os.path.exists(tmp_ps): os.remove(tmp_ps)
stdout = r.stdout.decode('utf-8', errors='replace').strip()
stderr = r.stderr.decode('utf-8', errors='replace').strip()
if r.returncode != 0:
return False, stderr or stdout or f'Exit code {r.returncode}'
if stdout.startswith('ERROR:'):
return False, stdout[6:]
return True, stdout
except subprocess.TimeoutExpired:
if os.path.exists(tmp_ps): os.remove(tmp_ps)
return False, 'Operation timed out'
except Exception as e:
if os.path.exists(tmp_ps): os.remove(tmp_ps)
return False, str(e)
def load_apps():
global app_data
result, error = run_powershell_list()
if error:
app_data = []
return error
if result:
app_data = sorted(result, key=lambda x: x.get('name', '').lower())
return None
def generate_default_icon(size=32):
global default_icon_img, default_icon_tk
if default_icon_img is None:
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.rounded_rectangle([2, 2, size-3, size-3], radius=6, fill='#cbd5e1')
cx, cy = size/2, size/2 - 2
draw.rectangle([cx-5, cy-3, cx+5, cy+3], fill='#94a3b8')
draw.rectangle([cx-6, cy-5, cx+6, cy-3], fill='#94a3b8')
draw.rectangle([cx-3, cy+3, cx+3, cy+7], fill='#94a3b8')
draw.ellipse([cx-4, cy-6, cx+4, cy-2], fill='#94a3b8')
default_icon_img = img
default_icon_tk = ImageTk.PhotoImage(img)
return default_icon_tk
def get_app_icon(app, size=32):
b64 = app.get('iconBase64', '')
if b64:
if b64 not in icon_cache:
try:
img_data = base64.b64decode(b64)
img = Image.open(io.BytesIO(img_data))
img = img.resize((size, size), Image.LANCZOS)
icon_cache[b64] = ImageTk.PhotoImage(img)
except:
icon_cache[b64] = generate_default_icon(size)
return icon_cache[b64]
return generate_default_icon(size)
class ToggleSwitch(tk.Canvas):
SW = 44
SH = 24
KNOB = 18
RAD = 12
def __init__(self, parent, variable=None, command=None, **kwargs):
super().__init__(parent, width=self.SW, height=self.SH,
highlightthickness=0, bd=0, **kwargs)
self.var = variable if variable else tk.BooleanVar()
self.command = command
self._on = self.var.get()
self.bind('<Button-1>', self._on_click)
self.draw()
def draw(self):
self.delete('all')
pad = 2
w = self.SW - pad * 2
h = self.SH - pad * 2
r = self.RAD - pad
if self._on:
track = '#6366f1'
glow = '#a5b4fc'
else:
track = '#cbd5e1'
glow = '#e2e8f0'
self.create_rounded_rect(pad, pad, pad+w, pad+h, r, fill=track, outline='')
gx = pad + w - r - 3 if self._on else pad + r + 3
gy = pad + h//2
self.create_oval(gx-6, gy-6, gx+6, gy+6, fill=glow, outline='', stipple='gray25')
kx = pad + w - self.KNOB//2 - 2 if self._on else pad + self.KNOB//2 + 2
ky = self.SH // 2
kr = self.KNOB // 2
self.create_oval(kx-kr, ky-kr, kx+kr, ky+kr, fill='#ffffff', outline='#e2e8f0', width=1)
def create_rounded_rect(self, x1, y1, x2, y2, r, **kw):
pts = [x1+r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y2-r, x2, y2, x2-r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y1+r, x1, y1]
self.create_polygon(pts, smooth=True, **kw)
def _on_click(self, event):
self._on = not self._on
self.var.set(self._on)
self.draw()
if self.command:
self.command()
def set(self, value):
self._on = bool(value)
self.var.set(self._on)
self.draw()
class AnimatedButton(tk.Canvas):
def __init__(self, parent, text='', command=None, width=80, height=32, **kwargs):
super().__init__(parent, width=width, height=height, highlightthickness=0, bd=0, **kwargs)
self.text = text
self.cmd = command
self.w = width
self.h = height
self.bind('<Button-1>', lambda e: self.cmd() if self.cmd else None)
self.bind('<Enter>', lambda e: self._draw('#e2e8f0'))
self.bind('<Leave>', lambda e: self._draw('#f1f5f9'))
self._draw('#f1f5f9')
def _draw(self, bg):
self.delete('all')
r = 8
self.create_rounded_rect(1, 1, self.w-1, self.h-1, r, fill=bg, outline='#cbd5e1', width=1)
self.create_text(self.w//2, self.h//2, text=self.text, fill='#334155',
font=('Segoe UI', 10, 'bold'))
def create_rounded_rect(self, x1, y1, x2, y2, r, **kw):
pts = [x1+r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y2-r, x2, y2, x2-r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y1+r, x1, y1]
self.create_polygon(pts, smooth=True, **kw)
class StatusBadge(tk.Canvas):
H = 20
def __init__(self, parent, text='Allowed', state='allowed', **kwargs):
super().__init__(parent, height=self.H, highlightthickness=0, bd=0, **kwargs)
self.text = text
if state == 'allowed':
self.fg = '#059669'
self.bg = '#d1fae5'
elif state == 'blocked':
self.fg = '#dc2626'
self.bg = '#fee2e2'
else:
self.fg = '#6366f1'
self.bg = '#e0e7ff'
tw = len(text) * 7 + 24
self.configure(width=tw)
r = self.H // 2
self.create_rounded_rect(1, 1, tw-1, self.H-1, r, fill=self.bg, outline='')
dot_r = 3
self.create_oval(8-dot_r, self.H//2-dot_r, 8+dot_r, self.H//2+dot_r, fill=self.fg, outline='')
self.create_text(16, self.H//2, text=text, fill=self.fg, font=('Segoe UI', 9, 'bold'), anchor=W)
def create_rounded_rect(self, x1, y1, x2, y2, r, **kw):
pts = [x1+r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y2-r, x2, y2, x2-r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y1+r, x1, y1]
self.create_polygon(pts, smooth=True, **kw)
class AppNetworkController(tb.Window):
def __init__(self):
super().__init__(themename='flatly')
self.title('App Network Controller')
self.geometry('1100x720+200+50')
self.minsize(860, 620)
global is_admin
is_admin = is_process_admin()
self._configure_styles()
self._build_header()
self._build_search()
self._build_progress()
self._build_list_area()
self._build_footer()
self.after(300, self._start_loading)
def _configure_styles(self):
s = self.style
s.configure('TFrame', borderwidth=0)
s.configure('TLabel', background=s.lookup('TFrame', 'background'))
s.configure('Section.TLabel', font=('Segoe UI', 12, 'bold'))
s.configure('Search.TEntry', padding=(14, 12))
s.configure('Stats.TLabel', font=('Segoe UI', 10))
def _bg(self):
return self.style.lookup('TFrame', 'background')
def _build_header(self):
self.header_bg = tk.Canvas(self, height=100, highlightthickness=0)
self.header_bg.pack(fill=X)
self.header_bg.bind('<Configure>', lambda e: self._draw_header_bg(e.width, e.height))
hdr = ttk.Frame(self.header_bg, padding=(24, 16, 24, 12))
hdr.place(x=0, y=0, relwidth=1, relheight=1)
left = ttk.Frame(hdr)
left.pack(side=LEFT)
ttk.Label(left, text='\u25b6 Gateway Control', font=('Segoe UI', 22, 'bold')).pack(anchor=W)
self.status_lbl = ttk.Label(left, text='Loading...', font=('Segoe UI', 11))
self.status_lbl.pack(anchor=W)
right = ttk.Frame(hdr)
right.pack(side=RIGHT)
self.theme_btn = AnimatedButton(right, text='\u263E Dark', command=self._toggle_theme, width=76, height=30)
self.theme_btn.pack(side=RIGHT, padx=2)
self.stats_frame = ttk.Frame(hdr)
self.stats_frame.pack(side=BOTTOM, fill=X, pady=(6, 0))
self.total_badge = ttk.Label(self.stats_frame, text='', style='Stats.TLabel')
self.total_badge.pack(side=LEFT, padx=(0, 12))
self.blocked_badge = ttk.Label(self.stats_frame, text='', style='Stats.TLabel')
self.blocked_badge.pack(side=LEFT, padx=(0, 12))
self.allowed_badge = ttk.Label(self.stats_frame, text='', style='Stats.TLabel')
self.allowed_badge.pack(side=LEFT, padx=(0, 12))
self.toggled_badge = ttk.Label(self.stats_frame, text='', style='Stats.TLabel')
self.toggled_badge.pack(side=LEFT)
self.admin_lbl = ttk.Label(self.stats_frame, text='', style='Stats.TLabel')
self.admin_lbl.pack(side=RIGHT)
if not is_admin:
self.admin_lbl.config(text='\u26a0 Run as Admin to toggle', foreground='#dc2626')
def _draw_header_bg(self, w, h):
self.header_bg.delete('all')
bg = self._bg()
self.header_bg.create_rectangle(0, 0, w, h, fill=bg, outline='')
def _build_search(self):
sf = ttk.Frame(self, padding=(24, 6, 24, 4))
sf.pack(fill=X)
inner = ttk.Frame(sf)
inner.pack(fill=X)
entry = ttk.Entry(inner, style='Search.TEntry')
entry.pack(fill=X, side=LEFT, expand=True)
entry.insert(0, '\U0001F50D Search applications...')
entry.bind('<FocusIn>', lambda e: self._search_focus(entry))
entry.bind('<FocusOut>', lambda e: self._search_blur(entry))
entry.bind('<KeyRelease>', lambda e: self._do_search())
self.search_entry = entry
self.search_text = ''
def _search_focus(self, entry):
if entry.get() == '\U0001F50D Search applications...':
entry.delete(0, END)
entry.config(foreground=self.style.lookup('TLabel', 'foreground'))
def _search_blur(self, entry):
if entry.get().strip() == '':
entry.delete(0, END)
entry.insert(0, '\U0001F50D Search applications...')
entry.config(foreground='#94a3b8')
def _do_search(self):
raw = self.search_entry.get()
if raw == '\U0001F50D Search applications...':
self.search_text = ''
else:
self.search_text = raw.strip().lower()
self._filter_apps()
def _build_progress(self):
self.progress = ttk.Progressbar(self, mode='indeterminate', style='info.Horizontal.TProgressbar')
self.progress.pack(fill=X, padx=24)
def _build_list_area(self):
c = tk.Canvas(self, highlightthickness=0)
sb = ttk.Scrollbar(self, orient=VERTICAL, command=c.yview)
self.list_frame = ttk.Frame(c)
self.list_frame.bind('<Configure>', lambda e: c.configure(scrollregion=c.bbox('all')))
c.create_window((0, 0), window=self.list_frame, anchor=NW, tags='inner')
c.configure(yscrollcommand=sb.set)
c.pack(side=LEFT, fill=BOTH, expand=True, padx=(24, 0), pady=(4, 20))
sb.pack(side=RIGHT, fill=Y, pady=(4, 20))
self.canvas = c
c.bind('<Configure>', lambda e: c.itemconfig('inner', width=e.width))
def _on_mw(e):
c.yview_scroll(int(-1*(e.delta/120)), 'units')
c.bind('<MouseWheel>', _on_mw)
self.bind_all('<MouseWheel>', _on_mw)
def _build_footer(self):
f = ttk.Frame(self, padding=(0, 4, 0, 6))
f.pack(side=BOTTOM, fill=X)
link = ttk.Label(f, text='\u2615 Support on Ko-fi', font=('Segoe UI', 9),
foreground='#6366f1', cursor='hand2')
link.pack()
link.bind('<Button-1>', lambda e: os.system('start https://ko-fi.com/gauravdubeypro'))
link.bind('<Enter>', lambda e: link.config(foreground='#818cf8'))
link.bind('<Leave>', lambda e: link.config(foreground='#6366f1'))
def _toggle_theme(self):
cur = self.style.theme.name
if cur == 'flatly':
self.style.theme_use('darkly')
self.theme_btn.text = '\u2600 Light'
else:
self.style.theme_use('flatly')
self.theme_btn.text = '\u263E Dark'
self._selected_card = None
self.theme_btn._draw('#f1f5f9')
self._update_canvas_bg()
self._draw_header_bg(self.header_bg.winfo_width(), self.header_bg.winfo_height())
self._refresh_list()
def _update_canvas_bg(self):
self.canvas.configure(bg=self._bg())
def _start_loading(self):
self.progress.start(12)
self.status_lbl.config(text='\u23f3 Scanning installed applications...')
self._clear_list()
lbl = ttk.Label(self.list_frame, text='')
lbl.pack(pady=30)
dots = ttk.Label(self.list_frame, text='\u25cf \u25cf \u25cf',
font=('Segoe UI', 18), foreground='#6366f1')
dots.pack()
self._animate_dots(dots, 0)
threading.Thread(target=self.load_data, daemon=True).start()
def _animate_dots(self, lbl, n):
if not lbl.winfo_exists():
return
colors = ['#6366f1', '#818cf8', '#a5b4fc', '#c7d2fe']
c = colors[n % len(colors)]
lbl.config(foreground=c)
self.after(300, lambda: self._animate_dots(lbl, n+1) if hasattr(self, 'progress') else None)
def _clear_list(self):
for w in self.list_frame.winfo_children():
w.destroy()
def load_data(self):
error = load_apps()
self.after(0, self._on_data_loaded, error)
def _on_data_loaded(self, error):
self.progress.stop()
self._clear_list()
if error:
self.status_lbl.config(text='\u2716 Failed to scan applications')
self._show_error(error)
return
if not app_data:
self.status_lbl.config(text='No applications found')
self._show_empty()
return
self.status_lbl.config(text=f'{len(app_data)} applications loaded')
self._filter_apps()
def _show_error(self, msg):
f = ttk.Frame(self.list_frame, padding=40)
f.pack(pady=40)
ttk.Label(f, text='\u26a0 Something went wrong', font=('Segoe UI', 16)).pack()
ttk.Label(f, text=msg, wraplength=600, foreground='#dc2626',
font=('Segoe UI', 11)).pack(pady=12)
btn = AnimatedButton(f, text='Retry', command=self._start_loading, width=100, height=34)
btn.pack(pady=8)
def _show_empty(self):
f = ttk.Frame(self.list_frame, padding=60)
f.pack(pady=40)
ttk.Label(f, text='\U0001F50D', font=('Segoe UI', 36)).pack()
ttk.Label(f, text='No applications match your search',
font=('Segoe UI', 14), foreground='#64748b').pack(pady=6)
def _filter_apps(self):
global filtered_apps, toggled_app_names
q = self.search_text
if q:
filtered_apps = [a for a in app_data
if q in a.get('name', '').lower()
or q in a.get('publisher', '').lower()]
else:
filtered_apps = list(app_data)
self._refresh_list()
def _refresh_list(self):
self._clear_list()
shown = [a for a in filtered_apps if a.get('name') in toggled_app_names]
rest = [a for a in filtered_apps if a.get('name') not in toggled_app_names]
shown.sort(key=lambda x: toggled_app_names.index(x['name']) if x['name'] in toggled_app_names else 999)
blocked = [a for a in rest if a.get('networkBlocked')]
allowed = [a for a in rest if not a.get('networkBlocked')]
total = len(filtered_apps)
self.total_badge.config(text=f'\U0001F4CA {total} total')
self.blocked_badge.config(text=f'\u26d4 {len(blocked)} blocked', foreground='#dc2626')
self.allowed_badge.config(text=f'\u2714\ufe0f {len(allowed)} allowed', foreground='#059669')
self.toggled_badge.config(text=f'\U0001F504 {len(shown)} toggled' if shown else '', foreground='#6366f1')
if shown:
self._add_section('\U0001F504 Recently Toggled', shown, '#6366f1', '#e0e7ff')
self._add_section('\u26d4 Blocked Network Access', blocked, '#dc2626', '#fee2e2')
self._add_section('\u2714\ufe0f Allowed Network Access', allowed, '#059669', '#d1fae5')
if not filtered_apps:
self._show_empty()
def _add_section(self, title, items, accent, bg):
if not items:
return
sec = ttk.Frame(self.list_frame, padding=(0, 6, 0, 6))
sec.pack(fill=X, padx=4)
c = ttk.Frame(sec, padding=(12, 8, 12, 6))
c.pack(fill=X)
hdr = ttk.Frame(c)
hdr.pack(fill=X)
ttk.Label(hdr, text=title, font=('Segoe UI', 11, 'bold'), foreground=accent).pack(side=LEFT)
ttk.Label(hdr, text=str(len(items)), font=('Segoe UI', 10),
foreground='#64748b').pack(side=LEFT, padx=6)
for app in items:
self._add_app_card(c, app, accent)
def _add_app_card(self, parent, app, accent):
normal_bg = self._bg()
highlight_bg = '#1e293b' if self.style.theme.name == 'darkly' else '#eef2ff'
card = tk.Frame(parent, bg=normal_bg, padx=8, pady=6, cursor='hand2')
card.pack(fill=X, pady=2)
card.app_name = app.get('name', '')
icon = get_app_icon(app)
i = ttk.Label(card, image=icon)
i.image = icon
i.pack(side=LEFT, padx=(0, 10))
info = ttk.Frame(card)
info.pack(side=LEFT, fill=X, expand=True)
ttk.Label(info, text=app.get('name', ''), font=('Segoe UI', 12)).pack(anchor=W)
pub = app.get('publisher', '') or 'Unknown Publisher'
ttk.Label(info, text=pub, font=('Segoe UI', 9), foreground='#64748b').pack(anchor=W)
state = 'blocked' if app.get('networkBlocked') else 'allowed'
badge = StatusBadge(card, text='Blocked' if state == 'blocked' else 'Allowed', state=state)
badge.pack(side=RIGHT, padx=4)
tv = tk.BooleanVar(value=app.get('networkBlocked', False))
ts = ToggleSwitch(card, variable=tv,
command=lambda a=app, v=tv: self._on_toggle(a, v))
ts.pack(side=RIGHT, padx=4)
def select_card(event=None):
if hasattr(self, '_selected_card') and self._selected_card and self._selected_card != card:
self._selected_card.configure(bg=normal_bg)
if card.cget('bg') == highlight_bg:
card.configure(bg=normal_bg)
self._selected_card = None
else:
card.configure(bg=highlight_bg)
self._selected_card = card
card.bind('<Button-1>', select_card)
i.bind('<Button-1>', select_card)
info.bind('<Button-1>', select_card)
for child in info.winfo_children():
child.bind('<Button-1>', select_card)
badge.bind('<Button-1>', select_card)
def _on_toggle(self, app, var):
name = app.get('name', '')
exe_path = app.get('exePath', '')
block = var.get()
if not exe_path:
messagebox.showwarning('Cannot Toggle', f'No executable path found for "{name}"')
var.set(not block)
return
if name not in toggled_app_names:
toggled_app_names.insert(0, name)
if len(toggled_app_names) > 20:
toggled_app_names.pop()
action = 'block' if block else 'unblock'
def do_toggle():
if is_admin:
ok, msg = run_powershell_toggle(action, name, exe_path)
else:
ok, msg = request_admin_toggle(action, name, exe_path)
if ok:
app['networkBlocked'] = block
self.after(0, self._refresh_list)
else:
self.after(0, lambda: var.set(not block))
self.after(0, lambda: messagebox.showerror(
'Failed',
f'Could not {action} "{name}".\n\n{msg}\n\nTip: Run as Administrator'))
self.after(0, self._refresh_list)
threading.Thread(target=do_toggle, daemon=True).start()
if __name__ == '__main__':
app = AppNetworkController()
app.mainloop()