-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCODE.py
More file actions
1849 lines (1601 loc) · 78.8 KB
/
Copy pathCODE.py
File metadata and controls
1849 lines (1601 loc) · 78.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import ctypes
import math
import random
import threading
import subprocess
import webbrowser
import winsound
import urllib.request
import json
import socket
import winreg
import customtkinter as ctk
from PIL import Image
import pystray
import psutil
#version & urls
CURRENT_VERSION = "10.07.26"
UPDATE_URL = "https://raw.githubusercontent.com/shprttx/Proximity/main/update.json"
#design tokens
COLOR_MAIN = "#00f2ff"
COLOR_SECONDARY = "#00c8d4"
COLOR_HOVER = "#0b1c2c"
COLOR_BG = "#050508"
COLOR_FRAME = "#0c0d14"
COLOR_BORDER = "#1b142c"
COLOR_ACCENT = "#ff0844"
FONT_NAME = "Segoe UI"
PULSE_COLORS = ["#00f2ff", "#1ae5ff", "#33d8ff", "#4dcaff", "#66bdff", "#4dcaff", "#33d8ff", "#1ae5ff"]
#local state (persisted across restarts, e.g. which notice was last seen)
def get_state_dir():
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
path = os.path.join(base, "Proximity")
try:
os.makedirs(path, exist_ok=True)
except Exception:
pass
return path
def get_state_path():
return os.path.join(get_state_dir(), "state.json")
def load_local_state():
try:
with open(get_state_path(), "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def save_local_state(data):
try:
with open(get_state_path(), "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
except Exception:
pass
def pick_localized(value, lang):
"""notice title/text in update.json can be either a plain string
(same for both languages) or a {'ru':..., 'en':...} dict."""
if isinstance(value, dict):
key = (lang or "").lower()
return value.get(key) or value.get("ru") or value.get("en") or ""
return value or ""
#system
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
AUTOSTART_KEY_PATH = r"Software\Microsoft\Windows\CurrentVersion\Run"
AUTOSTART_VALUE = "Proximity"
def _autostart_command():
# frozen (PyInstaller .exe) -> just the exe path.
# running as a raw .py -> launch through the same interpreter.
if getattr(sys, "frozen", False):
return f'"{sys.executable}"'
return f'"{sys.executable}" "{os.path.abspath(sys.argv[0])}"'
def _ensure_autostart():
"""Registers Proximity in the classic HKCU Run key so it launches at
Windows logon. This is deliberately the plain registry key (not a
scheduled task) so it shows up in Task Manager's Startup tab, where
the user can switch it off themselves without touching the app.
Re-elevation on logon still goes through the normal admin check at
the top of this file -- this only adds the entry, it doesn't grant
or bypass anything."""
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, AUTOSTART_KEY_PATH,
0, winreg.KEY_SET_VALUE)
winreg.SetValueEx(key, AUTOSTART_VALUE, 0, winreg.REG_SZ, _autostart_command())
winreg.CloseKey(key)
except Exception:
pass
SINGLE_INSTANCE_PORT = 51837
if not ctypes.windll.shell32.IsUserAnAdmin():
# Cheap, non-binding check done BEFORE asking for admin rights: if an
# instance is already listening on the lock port, just signal it and
# exit -- this skips the UAC prompt entirely for repeat launches while
# Proximity is already running (the elevated instance is the one that
# actually binds/listens, further down, once it's confirmed admin).
try:
with socket.create_connection(("127.0.0.1", SINGLE_INSTANCE_PORT), timeout=0.3) as c:
c.sendall(b"SHOW")
sys.exit()
except OSError:
pass # nothing listening yet -- this really is the first launch
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
sys.exit()
# single instance guard
#
# A loopback-only socket is used purely as a lock: only one process can ever
# bind it. If binding fails, another copy of Proximity is already running
# (in the window or minimized in the tray), so instead of opening a second
# window we ping that instance (it will restore/focus itself) and exit.
def _acquire_single_instance_lock():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", SINGLE_INSTANCE_PORT))
s.listen(5)
return s
except OSError:
try:
with socket.create_connection(("127.0.0.1", SINGLE_INSTANCE_PORT), timeout=2) as c:
c.sendall(b"SHOW")
except Exception:
pass
return None
_single_instance_lock = _acquire_single_instance_lock()
if _single_instance_lock is None:
sys.exit()
_ensure_autostart()
TOOLS_DIR = resource_path("Tools")
CREATE_NO_WINDOW = 0x08000000
ICON_PATH = os.path.join(TOOLS_DIR, "Proximity.ico")
# real process names used to detect whether a service is already running
# (e.g. left over from a previous session) so toggle state can reflect reality
SERVICE_PROCESS_NAMES = {
"happ": ("happ.exe",),
"tg": ("tgwsproxy_windows.exe",),
"zprtx": ("winws.exe",),
"warp": ("cloudflare warp.exe",),
}
#helpers
def color_fade(c1, c2, steps):
r1, g1, b1 = int(c1[1:3], 16), int(c1[3:5], 16), int(c1[5:7], 16)
r2, g2, b2 = int(c2[1:3], 16), int(c2[3:5], 16), int(c2[5:7], 16)
return [
f"#{int(r1+(r2-r1)*i/(steps-1)):02x}"
f"{int(g1+(g2-g1)*i/(steps-1)):02x}"
f"{int(b1+(b2-b1)*i/(steps-1)):02x}"
for i in range(steps)
]
def get_running_service_keys():
"""Scan real OS processes and return the set of service keys
(happ / tg / zprtx / warp) that are actually running right now.
Used at startup so toggles reflect reality instead of assuming 'off'."""
running_names = set()
for proc in psutil.process_iter(["name"]):
try:
name = (proc.info.get("name") or "").strip().lower()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
if name:
running_names.add(name)
detected = set()
for key, proc_names in SERVICE_PROCESS_NAMES.items():
if any(pn in running_names for pn in proc_names):
detected.add(key)
return detected
def play_ui_sound(sound_type):
sound_map = {
"click": "click.wav",
"switch": "toggle.wav",
"startup": "welcome.wav",
"master": "master.wav",
"warning": "warning.wav",
}
path = resource_path(os.path.join("sounds", sound_map.get(sound_type, "")))
if os.path.exists(path):
threading.Thread(target=winsound.PlaySound, args=(path, winsound.SND_FILENAME), daemon=True).start()
#locales
LOCALES = {
"EN": {
"lang_btn": "RU",
"header": "PROXIMITY",
"sw_happ": "Happ",
"sw_tg": "TG Proxy",
"sw_zprtx": "YouTube + Discord ZPRTX",
"sw_warp": "Cloudflare WARP",
"btn_installer": "SETUP WIZARD",
"btn_pdf": "Happ + Cloudflare WARP Manual",
"btn_about": "GITHUB",
"installer_title": "SETUP WIZARD",
"installer_label": "Select what you want to install",
"installer_happ": "INSTALL HAPP",
"installer_warp": "INSTALL CLOUDFLARE WARP",
"installer_close": "Close Setup Wizard",
"info_happ": "Happ VPN is an advanced routing tool.\n\nDevelopers: Flyfrog LLC\n\nPlease read the instructions\n\nbefore installing!",
"info_tg": "Telegram Proxy creates a secure WebSocket tunnel.\n\nDeveloper: Flowseal",
"info_zprtx": "ZPRTX is a DPI bypass engine.\n\nDeveloper: shprot\n\nIt modifies packets at the driver level to unblock websites.",
"info_warp": "Cloudflare WARP is a utility that combines VPN features with a secure DNS resolver.\n\nIt speeds up website loading and provides access to AI models [Gemini, Claude, GPT, etc.].\n\nDevelopers: Cloudflare, Inc.",
"warn_title": "⚠️ WARNING",
"warn_msg_bold": "Are you sure you want to close the application?",
"warn_msg_norm": "Active toggles will be disabled after restart.\nRe-enabling toggles for an already active service\nmay cause system bugs.",
"btn_yes": "Yes",
"btn_no": "No",
"tray_show": "Open",
"tray_exit": "Exit",
"upd_title": "UPDATE AVAILABLE",
"upd_msg": "A new version of the application is available.\nPlease update to ensure stable performance.\nThe changelog is available on GitHub.",
"upd_warn": "NOTE: The website is temporarily unavailable,\nplease use instant download instead.",
"btn_upd_site": "Instant Download",
"btn_upd_gh": "Changelog",
"notice_title_default": "WARNING",
"notice_close": "Ok",
},
"RU": {
"lang_btn": "EN",
"header": "PROXIMITY",
"sw_happ": "Happ",
"sw_tg": "TG Прокси",
"sw_zprtx": "Ютуб + Дискорд ZPRTX",
"sw_warp": "Cloudflare WARP",
"btn_installer": "МАСТЕР УСТАНОВКИ",
"btn_pdf": "Инструкция Happ + Cloudflare WARP",
"btn_about": "GITHUB",
"installer_title": "МАСТЕР УСТАНОВКИ",
"installer_label": "Выберите что хотите установить",
"installer_happ": "УСТАНОВИТЬ HAPP",
"installer_warp": "УСТАНОВИТЬ CLOUDFLARE WARP",
"installer_close": "Закрыть Мастер установки",
"info_happ": "Happ vpn - это продвинутый инструмент маршрутизации.\n\nРазработчики - Flyfrog LLC\n\nПеред тем как установить\n\nпрочтите инструкцию!\n\nТРЕБУЕТСЯ УСТАНОВКА В Мастер установки!",
"info_tg": "Telegram Proxy создает защищенный WebSocket туннель\n\nРазработчик - Flowseal",
"info_zprtx": "ZPRTX - движок обхода DPI.\n\nРазработчик - shprot\n\nМодифицирует пакеты на уровне драйвера для разблокировки сайтов.",
"info_warp": "Cloudflare WARP - утилита объединяющий функции VPN и безопасного DNS-резолвера.\n\nУскоряет загрузку сайтов, дотуп к нейросетям [Gemini, Claude, GPT и др]\n\nРазработчики- Cloudflare, Inc.\n\nТРЕБУЕТСЯ УСТАНОВКА В Мастер установки!",
"warn_title": "⚠️ ВНИМАНИЕ",
"warn_msg_bold": "Вы уверены, что хотите закрыть приложение?",
"warn_msg_norm": "Включенные ползунки будут отключены после перезапуска,\nПовторное включение ползунков уже активного сервиса\nможет привести к возможным багам в системе.",
"btn_yes": "Да",
"btn_no": " Нет",
"tray_show": "Открыть",
"tray_exit": "Выход",
"upd_title": "ДОСТУПНО ОБНОВЛЕНИЕ",
"upd_msg": "Вышло новое обновление приложения.\nПожалуйста, обновитесь для стабильной работы.\nСписок изменений доступен на GitHub.",
"upd_warn": "ВНИМАНИЕ: Сайт временно приостановил свою работу,\nвоспользуйтесь мгновенным скачиванием.",
"btn_upd_site": "Мгновенное скачивание",
"btn_upd_gh": "Список изменений",
"notice_title_default": "ВНИМАНИЕ",
"notice_close": "Ок",
},
}
#bubble
class BubbleBackground(ctk.CTkCanvas):
def __init__(self, master, **kwargs):
super().__init__(master, bg=COLOR_BG, highlightthickness=0, **kwargs)
self.bubbles = []
self.animating = False
self.bind("<Configure>", self._on_resize)
def _on_resize(self, event):
self.width = event.width
self.height = event.height
if not self.bubbles:
for _ in range(30):
self._spawn(init=True)
def _spawn(self, init=False):
size = random.randint(12, 30)
x = random.randint(10, max(100, getattr(self, "width", 300) - 10))
y = random.randint(10, getattr(self, "height", 500)) if init else getattr(self, "height", 500) + random.randint(10, 60)
r = size // 2
color = random.choice([COLOR_MAIN, COLOR_SECONDARY, "#00c8d4"])
glow_id = self.create_oval(x-r-2, y-r-2, x+r+2, y+r+2, outline=color, width=1)
core_id = self.create_oval(x-r, y-r, x+r, y+r, fill="#0c0d14", outline="")
self.bubbles.append({
"glow_id": glow_id,
"core_id": core_id,
"x": x, "y": y, "r": r,
"speed": random.uniform(0.3, 1.0),
"color": color,
"swing_offset": random.uniform(0, 10),
"push_x": 0.0,
"push_y": 0.0,
})
def start_animation(self):
if not self.animating:
self.animating = True
self._loop()
def stop_animation(self):
self.animating = False
def _loop(self):
if not self.animating:
return
for b in self.bubbles[:]:
b["y"] -= b["speed"]
b["x"] += math.sin(b["y"] / 40.0 + b["swing_offset"]) * 0.25
# shockwave displacement left over from a panic-button hit,
# decays back to zero over ~15-20 frames
if b["push_x"] or b["push_y"]:
b["x"] += b["push_x"]
b["y"] += b["push_y"]
b["push_x"] *= 0.82
b["push_y"] *= 0.82
if abs(b["push_x"]) < 0.05: b["push_x"] = 0.0
if abs(b["push_y"]) < 0.05: b["push_y"] = 0.0
r = b["r"]
self.coords(b["glow_id"], b["x"]-r-2, b["y"]-r-2, b["x"]+r+2, b["y"]+r+2)
self.coords(b["core_id"], b["x"]-r, b["y"]-r, b["x"]+r, b["y"]+r)
if b["y"] < -r * 2:
self.delete(b["glow_id"])
self.delete(b["core_id"])
self.bubbles.remove(b)
self._spawn(init=False)
self.after(16, self._loop)
def trigger_shockwave(self, origin_x=None, origin_y=None):
"""Red expanding ring from the panic button, physically pushing
nearby bubbles outward as the wavefront passes them."""
if origin_x is None:
origin_x = getattr(self, "width", 400) - 40
if origin_y is None:
origin_y = 40
ring_id = self.create_oval(origin_x, origin_y, origin_x, origin_y,
outline=COLOR_ACCENT, width=3)
colors = color_fade(COLOR_ACCENT, COLOR_BG, 24)
MAX_R = 620
SPEED = 26
state = {"r": 0, "hit": set()}
def step():
try:
if not self.winfo_exists():
return
except Exception:
return
state["r"] += SPEED
r = state["r"]
fade_idx = min(23, int((r / MAX_R) * 23))
try:
self.coords(ring_id, origin_x-r, origin_y-r, origin_x+r, origin_y+r)
self.itemconfig(ring_id, outline=colors[fade_idx])
except Exception:
return
for b in self.bubbles:
bid = id(b)
if bid in state["hit"]:
continue
dx, dy = b["x"] - origin_x, b["y"] - origin_y
dist = math.hypot(dx, dy)
if dist <= r:
state["hit"].add(bid)
if dist > 1:
nx, ny = dx / dist, dy / dist
else:
nx, ny = random.uniform(-1, 1), random.uniform(-1, 1)
b["push_x"] += nx * 30
b["push_y"] += ny * 30
if r < MAX_R:
self.after(16, step)
else:
try:
self.delete(ring_id)
except Exception:
pass
step()
#update
class UpdateNotificationWindow(ctk.CTkToplevel):
def __init__(self, parent, lang, update_data):
super().__init__(parent)
self.title(LOCALES[lang]["upd_title"])
WIN_W, WIN_H = 380, 300
self.geometry(f"{WIN_W}x{WIN_H}")
self.configure(fg_color=COLOR_BG)
self.resizable(False, False)
self.transient(parent)
self.grab_set()
self.attributes("-alpha", 0.0)
self.update_idletasks()
x = parent.winfo_rootx() + (parent.winfo_width() - WIN_W) // 2
y = parent.winfo_rooty() + (parent.winfo_height() - WIN_H) // 2
self.geometry(f"+{x}+{y}")
if os.path.exists(ICON_PATH):
self.after(200, lambda: self.iconbitmap(ICON_PATH))
release_url = update_data.get("release_url", "https://github.com/shprttx/Proximity/releases")
download_url = update_data.get("download_url", release_url)
self._canvas = ctk.CTkCanvas(self, bg=COLOR_BG, highlightthickness=0, width=WIN_W, height=WIN_H)
self._canvas.place(x=0, y=0, relwidth=1, relheight=1)
self._content = ctk.CTkFrame(self, fg_color=COLOR_FRAME, corner_radius=16,
border_color=COLOR_MAIN, border_width=2)
ctk.CTkLabel(self._content, text=LOCALES[lang]["upd_title"],
font=(FONT_NAME, 18, "bold"), text_color=COLOR_MAIN
).pack(pady=(18, 4))
ctk.CTkLabel(self._content, text=LOCALES[lang]["upd_msg"],
font=(FONT_NAME, 13, "bold"), justify="center", text_color="#e0e0e0"
).pack(pady=(0, 4))
ctk.CTkLabel(self._content, text=LOCALES[lang]["upd_warn"],
font=(FONT_NAME, 11, "bold"), justify="center", text_color="#ffffff"
).pack(pady=(0, 12))
btn_site = ctk.CTkButton(
self._content, text=LOCALES[lang]["btn_upd_site"],
fg_color="transparent", border_width=2, border_color=COLOR_MAIN,
hover_color="#0b2e35", corner_radius=10, text_color=COLOR_MAIN,
font=(FONT_NAME, 12, "bold"), height=34,
command=lambda u=download_url: [play_ui_sound("click"), webbrowser.open(u)]
)
btn_site.bind("<Enter>", lambda e: btn_site.configure(text_color="#ffffff"))
btn_site.bind("<Leave>", lambda e: btn_site.configure(text_color=COLOR_MAIN))
btn_site.pack(pady=3, fill="x", padx=30)
btn_gh = ctk.CTkButton(
self._content, text=LOCALES[lang]["btn_upd_gh"],
fg_color="#12121e", border_width=1, border_color=COLOR_BORDER,
hover_color=COLOR_SECONDARY, corner_radius=10, text_color="#ffffff",
font=(FONT_NAME, 12, "bold"), height=34,
command=lambda u=release_url: [play_ui_sound("click"), webbrowser.open(u)]
)
btn_gh.pack(pady=3, fill="x", padx=30)
self._pulse_colors = PULSE_COLORS
self._pulse_step = 0
self._pulsing = False
self.after(80, self._fade_in)
#animation
def _fade_in(self, alpha=0.0):
alpha = min(alpha + 0.07, 1.0)
self.attributes("-alpha", alpha)
if alpha < 1.0:
self.after(14, lambda: self._fade_in(alpha))
else:
self._anim_line()
def _anim_line(self):
cx, cy = 190, 150
line = self._canvas.create_line(cx, cy, cx, cy, fill=COLOR_MAIN, width=2)
self._line_id = line
def grow(w=0):
if not self._alive(): return
if w < 130:
self._canvas.coords(line, cx-w, cy, cx+w, cy)
self.after(8, lambda: grow(w+7))
else:
self._canvas.coords(line, cx-130, cy, cx+130, cy)
self._fade_title()
grow()
def _fade_title(self):
self._pulsing = True
self._pulse_loop()
cx, cy = 190, 150
colors = color_fade(COLOR_BG, COLOR_MAIN, 28)
glows = color_fade(COLOR_BG, "#004455", 28)
def step(i=0):
if not self._alive(): return
if i < len(colors):
self._canvas.delete("upd_title")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="UPDATE", fill=glows[i],
font=(FONT_NAME, 24, "bold"), tags="upd_title")
self._canvas.create_text(cx, cy-24, text="UPDATE", fill=colors[i],
font=(FONT_NAME, 24, "bold"), tags="upd_title")
self.after(14, lambda: step(i+1))
else:
self._fade_subtitle()
step()
def _fade_subtitle(self):
cx, cy = 190, 150
colors = color_fade(COLOR_BG, "#ffffff", 25)
def step(i=0):
if not self._alive(): return
if i < len(colors):
self._canvas.delete("upd_sub")
self._canvas.create_text(cx, cy+24, text="AVAILABLE", fill=colors[i],
font=(FONT_NAME, 14, "bold"), tags="upd_sub")
self.after(14, lambda: step(i+1))
else:
self.after(1200, self._fade_out_and_show_content)
step()
def _pulse_loop(self):
if not self._pulsing or not self._alive(): return
cx, cy = 190, 150
self._pulse_step = (self._pulse_step + 1) % len(self._pulse_colors)
color = self._pulse_colors[self._pulse_step]
glow = color_fade(color, COLOR_BG, 5)[1]
try:
self._canvas.delete("upd_title")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="UPDATE", fill=glow,
font=(FONT_NAME, 24, "bold"), tags="upd_title")
self._canvas.create_text(cx, cy-24, text="UPDATE", fill=color,
font=(FONT_NAME, 24, "bold"), tags="upd_title")
except Exception:
pass
self.after(140, self._pulse_loop)
def _fade_out_and_show_content(self):
self._pulsing = False
cx, cy = 190, 150
color = self._pulse_colors[self._pulse_step]
c_title = color_fade(color, COLOR_BG, 22)
c_sub = color_fade("#ffffff", COLOR_BG, 22)
c_line = color_fade(COLOR_MAIN,COLOR_BG, 22)
def step(i=0):
if not self._alive(): return
if i < 22:
glow = color_fade(color, COLOR_BG, 5)[1]
self._canvas.delete("upd_title")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="UPDATE", fill=glow,
font=(FONT_NAME, 24, "bold"), tags="upd_title")
self._canvas.create_text(cx, cy-24, text="UPDATE", fill=c_title[i],
font=(FONT_NAME, 24, "bold"), tags="upd_title")
self._canvas.delete("upd_sub")
self._canvas.create_text(cx, cy+24, text="AVAILABLE", fill=c_sub[i],
font=(FONT_NAME, 14, "bold"), tags="upd_sub")
self._canvas.itemconfig(self._line_id, fill=c_line[i])
self.after(14, lambda: step(i+1))
else:
self._canvas.place_forget()
self._content.place(x=0, y=0, relwidth=1, relheight=1)
step()
def _alive(self):
try:
return self.winfo_exists()
except Exception:
return False
#notice (data-driven via update.json, deliberately NOT styled like the update popup)
class NoticeWindow(ctk.CTkToplevel):
"""One-off notice popup whose title/text come entirely from update.json's
'notice' field. Uses the same intro-animation *language* as
UpdateNotificationWindow (grow line -> pulse a big glyph -> fade into
content) but roughly twice as fast and with a '!' mark instead of the
word UPDATE, and COLOR_ACCENT instead of COLOR_MAIN, so it reads as
related but clearly distinct from the update dialog."""
def __init__(self, parent, lang, notice_data, on_dismiss=None, on_close_show_next=None):
super().__init__(parent)
self._on_dismiss = on_dismiss
self._on_close_show_next = on_close_show_next
title = pick_localized(notice_data.get("title"), lang) or LOCALES[lang]["notice_title_default"]
body = pick_localized(notice_data.get("text"), lang)
self.title(title)
WIN_W, WIN_H = 380, 260
self.geometry(f"{WIN_W}x{WIN_H}")
self.configure(fg_color=COLOR_BG)
self.resizable(False, False)
self.transient(parent)
self.grab_set()
self.attributes("-alpha", 0.0)
self.update_idletasks()
x = parent.winfo_rootx() + (parent.winfo_width() - WIN_W) // 2
y = parent.winfo_rooty() + (parent.winfo_height() - WIN_H) // 2
self.geometry(f"+{x}+{y}")
if os.path.exists(ICON_PATH):
self.after(200, lambda: self.iconbitmap(ICON_PATH))
self._canvas = ctk.CTkCanvas(self, bg=COLOR_BG, highlightthickness=0, width=WIN_W, height=WIN_H)
self._canvas.place(x=0, y=0, relwidth=1, relheight=1)
self._content = ctk.CTkFrame(self, fg_color=COLOR_FRAME, corner_radius=16,
border_color=COLOR_ACCENT, border_width=2)
ctk.CTkLabel(self._content, text=title, font=(FONT_NAME, 17, "bold"),
text_color=COLOR_ACCENT, wraplength=320, justify="center"
).pack(pady=(22, 8), padx=20)
ctk.CTkLabel(self._content, text=body, font=(FONT_NAME, 12), justify="center",
text_color="#e0e0e0", wraplength=320
).pack(pady=(0, 10), padx=20)
btn_ok = ctk.CTkButton(
self._content, text=LOCALES[lang]["notice_close"],
fg_color="transparent", border_width=2, border_color=COLOR_ACCENT,
hover_color="#3a0b16", corner_radius=10, text_color=COLOR_ACCENT,
font=(FONT_NAME, 12, "bold"), height=34,
command=self._close
)
btn_ok.bind("<Enter>", lambda e: btn_ok.configure(text_color="#ffffff"))
btn_ok.bind("<Leave>", lambda e: btn_ok.configure(text_color=COLOR_ACCENT))
btn_ok.pack(pady=(4, 20), fill="x", padx=30, side="bottom")
self._pulse_colors = ["#ff0844", "#ff2f5c", "#ff4d74", "#ff2f5c"]
self._pulse_step = 0
self._pulsing = False
self.after(80, self._fade_in)
#animation (~2x faster than UpdateNotificationWindow's intro)
def _fade_in(self, alpha=0.0):
alpha = min(alpha + 0.14, 1.0)
self.attributes("-alpha", alpha)
if alpha < 1.0:
self.after(14, lambda: self._fade_in(alpha))
else:
self._anim_line()
def _anim_line(self):
cx, cy = 190, 120
line = self._canvas.create_line(cx, cy, cx, cy, fill=COLOR_ACCENT, width=2)
self._line_id = line
def grow(w=0):
if not self._alive(): return
if w < 65:
self._canvas.coords(line, cx-w, cy, cx+w, cy)
self.after(8, lambda: grow(w+7))
else:
self._canvas.coords(line, cx-65, cy, cx+65, cy)
self._fade_mark()
grow()
def _fade_mark(self):
self._pulsing = True
self._pulse_loop()
cx, cy = 190, 120
colors = color_fade(COLOR_BG, COLOR_ACCENT, 14)
glows = color_fade(COLOR_BG, "#550018", 14)
def step(i=0):
if not self._alive(): return
if i < len(colors):
self._canvas.delete("notice_mark")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="!", fill=glows[i],
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
self._canvas.create_text(cx, cy-24, text="!", fill=colors[i],
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
self.after(14, lambda: step(i+1))
else:
self.after(600, self._fade_out_and_show_content)
step()
def _pulse_loop(self):
if not self._pulsing or not self._alive(): return
cx, cy = 190, 120
self._pulse_step = (self._pulse_step + 1) % len(self._pulse_colors)
color = self._pulse_colors[self._pulse_step]
glow = color_fade(color, COLOR_BG, 5)[1]
try:
self._canvas.delete("notice_mark")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="!", fill=glow,
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
self._canvas.create_text(cx, cy-24, text="!", fill=color,
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
except Exception:
pass
self.after(140, self._pulse_loop)
def _fade_out_and_show_content(self):
self._pulsing = False
cx, cy = 190, 120
color = self._pulse_colors[self._pulse_step]
c_mark = color_fade(color, COLOR_BG, 11)
c_line = color_fade(COLOR_ACCENT, COLOR_BG, 11)
def step(i=0):
if not self._alive(): return
if i < 11:
glow = color_fade(color, COLOR_BG, 5)[1]
self._canvas.delete("notice_mark")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
self._canvas.create_text(cx+dx, cy-24+dy, text="!", fill=glow,
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
self._canvas.create_text(cx, cy-24, text="!", fill=c_mark[i],
font=(FONT_NAME, 30, "bold"), tags="notice_mark")
self._canvas.itemconfig(self._line_id, fill=c_line[i])
self.after(14, lambda: step(i+1))
else:
self._canvas.place_forget()
self._content.place(x=0, y=0, relwidth=1, relheight=1)
step()
def _alive(self):
try:
return self.winfo_exists()
except Exception:
return False
def _close(self):
play_ui_sound("click")
if self._on_dismiss:
try:
self._on_dismiss()
except Exception:
pass
try:
self.grab_release()
except Exception:
pass
self.destroy()
if self._on_close_show_next:
try:
self._on_close_show_next()
except Exception:
pass
#custom warning
class CustomWarningWindow(ctk.CTkToplevel):
def __init__(self, parent, lang, callback_yes, callback_no):
super().__init__(parent)
self.title(LOCALES[lang]["warn_title"])
self.geometry("420x240")
self.configure(fg_color=COLOR_BG)
self.resizable(False, False)
self.transient(parent)
self.grab_set()
self.update_idletasks()
x = parent.winfo_rootx() + (parent.winfo_width() - 420) // 2
y = parent.winfo_rooty() + (parent.winfo_height() - 240) // 2
self.geometry(f"+{x}+{y}")
if os.path.exists(ICON_PATH):
self.after(200, lambda: self.iconbitmap(ICON_PATH))
frame = ctk.CTkFrame(self, fg_color=COLOR_FRAME, corner_radius=16,
border_color=COLOR_MAIN, border_width=2)
frame.pack(fill="both", expand=True, padx=12, pady=12)
ctk.CTkLabel(frame, text=LOCALES[lang]["warn_msg_bold"],
font=(FONT_NAME, 14, "bold"), text_color=COLOR_MAIN
).pack(pady=(15, 6))
ctk.CTkLabel(frame, text=LOCALES[lang]["warn_msg_norm"],
font=(FONT_NAME, 11), justify="center", text_color="#cccccc"
).pack(pady=(0, 15))
btn_yes = ctk.CTkButton(
frame, text=LOCALES[lang]["btn_yes"],
fg_color="transparent", border_width=2, border_color=COLOR_MAIN,
hover_color="#0b2e35", corner_radius=10, text_color=COLOR_MAIN,
font=(FONT_NAME, 11, "bold"), height=32,
command=callback_yes
)
btn_yes.bind("<Enter>", lambda e: btn_yes.configure(text_color="#ffffff"))
btn_yes.bind("<Leave>", lambda e: btn_yes.configure(text_color=COLOR_MAIN))
btn_yes.pack(pady=4, fill="x", padx=30)
btn_no = ctk.CTkButton(
frame, text=LOCALES[lang]["btn_no"],
fg_color="#12121e", border_width=1, border_color=COLOR_BORDER,
hover_color=COLOR_SECONDARY, corner_radius=10, text_color="#ffffff",
font=(FONT_NAME, 11), height=32,
command=callback_no
)
btn_no.pack(pady=4, fill="x", padx=30)
#main
class ProximityApp(ctk.CTk):
#init
def __init__(self):
super().__init__()
self.current_lang = "RU"
self.title("Proximity")
self.configure(fg_color=COLOR_BG)
self.resizable(False, False)
self.pulse_step = 0
if os.path.exists(ICON_PATH):
self.after(200, lambda: self.iconbitmap(ICON_PATH))
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.bind("<Unmap>", self._on_minimize)
# detect services that are already running from a previous session,
# so toggles reflect the real system state instead of assuming everything is off
try:
already_running = get_running_service_keys()
except Exception:
already_running = set()
# toggle
self.var_happ = ctk.StringVar(value="on" if "happ" in already_running else "off")
self.var_tg = ctk.StringVar(value="on" if "tg" in already_running else "off")
self.var_zprtx = ctk.StringVar(value="on" if "zprtx" in already_running else "off")
self.var_warp = ctk.StringVar(value="on" if "warp" in already_running else "off")
self.open_buttons = {}
self.switch_widgets = {}
self.tray_icon = None
self.update_data = None
self.pending_notice = None
self._popup_shown = False # guards against showing update/notice popup twice
self._zprtx_proc = None # Popen handle of the MAIN.bat console window, for cleanup
self._panic_running = False # guards against overlapping panic-button sequences
self._check_for_updates()
self.attributes("-alpha", 0.0)
self.withdraw()
self._show_splash()
# pdate check
def _check_for_updates(self):
def fetch():
try:
req = urllib.request.Request(UPDATE_URL, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=8) as r:
data = json.loads(r.read().decode("utf-8"))
if data.get("version") and data["version"] != CURRENT_VERSION:
self.update_data = data
notice = data.get("notice")
if isinstance(notice, dict) and notice.get("id"):
state = load_local_state()
if state.get("last_seen_notice_id") != notice.get("id"):
self.pending_notice = notice
except Exception:
pass
finally:
# the fetch can finish before OR after the splash animation --
# whichever happens later is the one that actually shows the popup
self.after(0, self._maybe_show_startup_popup)
threading.Thread(target=fetch, daemon=True).start()
def _maybe_show_startup_popup(self):
if self._popup_shown:
return
if not self.winfo_viewable():
return # splash still on screen / main window not shown yet -- fade-in will retry
if self.pending_notice:
self._popup_shown = True
NoticeWindow(self, self.current_lang, self.pending_notice,
on_dismiss=self._mark_notice_seen,
on_close_show_next=self._show_update_after_notice if self.update_data else None)
elif self.update_data:
self._popup_shown = True
UpdateNotificationWindow(self, self.current_lang, self.update_data)
def _show_update_after_notice(self):
if self.update_data:
UpdateNotificationWindow(self, self.current_lang, self.update_data)
def _mark_notice_seen(self):
notice = self.pending_notice
if not notice:
return
state = load_local_state()
state["last_seen_notice_id"] = notice.get("id")
save_local_state(state)
self.pending_notice = None
#splash
def _show_splash(self):
W, H = 480, 300
splash = ctk.CTkToplevel(self)
splash.geometry(f"{W}x{H}")
splash.overrideredirect(True)
splash.configure(fg_color=COLOR_BG)
self.update_idletasks()
sw, sh = self.winfo_screenwidth(), self.winfo_screenheight()
splash.geometry(f"+{(sw-W)//2}+{(sh-H)//2}")
if os.path.exists(ICON_PATH):
splash.after(200, lambda: splash.iconbitmap(ICON_PATH))
canvas = ctk.CTkCanvas(splash, bg=COLOR_BG, highlightthickness=0)
canvas.pack(fill="both", expand=True)
self.splash_canvas = canvas
play_ui_sound("startup")
cx, cy = W // 2, H // 2
try:
user = os.getlogin().title()
except Exception:
user = os.environ.get("USERNAME", "USER").title()
welcome_text = f"WELCOME, {user.upper()}"
line_id = canvas.create_line(cx, cy, cx, cy, fill=COLOR_MAIN, width=2)
pulse_step = [0]
current_state = ["none"]
def pulse_tick():
try:
if not splash.winfo_exists(): return
except Exception:
return
if current_state[0] == "prox":
pulse_step[0] = (pulse_step[0] + 1) % len(PULSE_COLORS)
color = PULSE_COLORS[pulse_step[0]]
glow = color_fade(color, COLOR_BG, 5)[1]
try:
canvas.delete("text_prox")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
canvas.create_text(cx+dx, cy-30+dy, text="PROXIMITY", fill=glow,
font=(FONT_NAME, 26, "bold"), tags="text_prox")
canvas.create_text(cx, cy-30, text="PROXIMITY", fill=color,
font=(FONT_NAME, 26, "bold"), tags="text_prox")
except Exception:
pass
splash.after(140, pulse_tick)
def grow_line(w=0):
try:
if not splash.winfo_exists(): return
except Exception:
return
if w < 150:
canvas.coords(line_id, cx-w, cy, cx+w, cy)
splash.after(10, lambda: grow_line(w+8))
else:
fade_in_prox()
def fade_in_prox():
colors = color_fade(COLOR_BG, COLOR_MAIN, 30)
glows = color_fade(COLOR_BG, "#004455", 30)
def step(i=0):
try:
if not splash.winfo_exists(): return
except Exception:
return
if i < len(colors):
canvas.delete("text_prox")
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
canvas.create_text(cx+dx, cy-30+dy, text="PROXIMITY", fill=glows[i],
font=(FONT_NAME, 26, "bold"), tags="text_prox")
canvas.create_text(cx, cy-30, text="PROXIMITY", fill=colors[i],
font=(FONT_NAME, 26, "bold"), tags="text_prox")
splash.after(16, lambda: step(i+1))
else:
current_state[0] = "prox"
fade_in_welc()
step()
def fade_in_welc():
colors = color_fade(COLOR_BG, "#ffffff", 30)
def step(i=0):
try:
if not splash.winfo_exists(): return