-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex_usage_float.py
More file actions
743 lines (647 loc) · 24.9 KB
/
Copy pathcodex_usage_float.py
File metadata and controls
743 lines (647 loc) · 24.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
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
import ctypes
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tkinter import Canvas, IntVar, Menu, Tk
from PIL import Image, ImageDraw
import win32api
import win32con
import win32gui
USAGE_URL = "https://chatgpt.com/backend-api/wham/usage"
REFRESH_SECONDS = 60
BASE_WINDOW_WIDTH = 330
BASE_WINDOW_HEIGHT = 90
DPI_SCALE = 1.0
WINDOW_WIDTH = BASE_WINDOW_WIDTH
WINDOW_HEIGHT = BASE_WINDOW_HEIGHT
APP_NAME = "CodexUsageFloat"
SETTINGS_DIR = Path(os.environ.get("LOCALAPPDATA", Path.home())) / APP_NAME
SETTINGS_PATH = SETTINGS_DIR / "settings.json"
TRANSPARENT = "#010203"
PANEL = "#f7f9fc"
TEXT = "#252b33"
MUTED = "#5f6b7a"
TRACK = "#d8e0ea"
GREEN = "#58d68d"
BLUE = "#62a8ff"
AMBER = "#f7c65f"
RED = "#ff6b6b"
OPACITY_OPTIONS = (70, 80, 85, 90, 92, 95, 100)
def enable_high_dpi():
if sys.platform != "win32":
return
try:
ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
except (AttributeError, OSError):
try:
ctypes.windll.user32.SetProcessDPIAware()
except (AttributeError, OSError):
pass
def configure_display_scale():
global DPI_SCALE, WINDOW_WIDTH, WINDOW_HEIGHT
if sys.platform == "win32":
try:
DPI_SCALE = max(1.0, ctypes.windll.user32.GetDpiForSystem() / 96.0)
except (AttributeError, OSError):
DPI_SCALE = 1.0
WINDOW_WIDTH = round(BASE_WINDOW_WIDTH * DPI_SCALE)
WINDOW_HEIGHT = round(BASE_WINDOW_HEIGHT * DPI_SCALE)
def acquire_single_instance():
if sys.platform != "win32":
return True, None
kernel32 = ctypes.windll.kernel32
handle = kernel32.CreateMutexW(None, False, "Local\\CodexUsageFloat.SingleInstance")
if not handle:
return False, None
if kernel32.GetLastError() == 183:
kernel32.CloseHandle(handle)
return False, None
return True, handle
def load_settings():
try:
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except (FileNotFoundError, OSError, ValueError):
return {}
def save_settings(settings):
try:
SETTINGS_DIR.mkdir(parents=True, exist_ok=True)
SETTINGS_PATH.write_text(
json.dumps(settings, ensure_ascii=False, indent=2),
encoding="utf-8",
)
except OSError:
pass
def beijing_time(iso_text):
if not iso_text:
return None
value = str(iso_text).replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(value)
except ValueError:
return str(iso_text)
return dt.astimezone(timezone(timedelta(hours=8))).strftime("%m-%d %H:%M")
def beijing_time_from_unix(value):
if value in (None, ""):
return None
try:
dt = datetime.fromtimestamp(float(value), tz=timezone.utc)
except (TypeError, ValueError, OSError):
return str(value)
return dt.astimezone(timezone(timedelta(hours=8))).strftime("%m-%d %H:%M")
def now_text():
return datetime.now().strftime("%H:%M")
def clamp(value, lower=0, upper=100):
try:
number = float(value)
except (TypeError, ValueError):
return None
return max(lower, min(upper, number))
def read_credentials():
auth_path = Path(os.environ["USERPROFILE"]) / ".codex" / "auth.json"
data = json.loads(auth_path.read_text(encoding="utf-8"))
tokens = data.get("tokens", {})
token = tokens.get("access_token")
if not token:
raise RuntimeError("auth.json 里没有 access_token")
return token, tokens.get("account_id")
def fetch_usage():
token, account_id = read_credentials()
headers = {
"Authorization": f"Bearer {token}",
"User-Agent": "Mozilla/5.0",
"Accept": "application/json",
}
if account_id:
headers["ChatGPT-Account-Id"] = account_id
request = urllib.request.Request(
USAGE_URL,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=20) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
if exc.code == 401:
raise RuntimeError("401:Codex 登录凭证失效或无权限")
raise RuntimeError(f"HTTP {exc.code}: {exc.reason}")
except urllib.error.URLError as exc:
raise RuntimeError(f"网络错误:{exc.reason}")
def read_local_usage_file():
path = Path(__file__).with_name("codex_usage.json")
if not path.exists():
return {}
return json.loads(path.read_text(encoding="utf-8"))
def normalize_limit(raw, label):
raw = raw or {}
percent = clamp(raw.get("remaining_percent"))
if percent is None and raw.get("used_percent") is not None:
used = clamp(raw.get("used_percent"))
percent = None if used is None else 100 - used
if percent is None and raw.get("remaining") is not None and raw.get("limit"):
try:
percent = clamp(float(raw["remaining"]) / float(raw["limit"]) * 100)
except (TypeError, ValueError, ZeroDivisionError):
percent = None
reset_at = raw.get("reset_at") or raw.get("resets_at")
if reset_at and "T" in str(reset_at):
reset_at = beijing_time(reset_at)
return {
"label": raw.get("label") or label,
"percent": percent,
"remaining": raw.get("remaining"),
"limit": raw.get("limit"),
"reset_at": reset_at,
}
def normalize_wham_window(raw, label):
raw = raw or {}
used = clamp(raw.get("used_percent"))
percent = None if used is None else 100 - used
reset_at = raw.get("reset_at") or raw.get("resets_at")
return {
"label": label,
"percent": percent,
"remaining": None,
"limit": None,
"reset_at": beijing_time_from_unix(reset_at),
}
def window_seconds(raw):
raw = raw or {}
seconds = raw.get("limit_window_seconds")
if seconds is None and raw.get("window_minutes") is not None:
try:
seconds = float(raw["window_minutes"]) * 60
except (TypeError, ValueError):
return None
try:
return float(seconds) if seconds is not None else None
except (TypeError, ValueError):
return None
def select_weekly_window(rate_limit):
candidates = [
rate_limit.get("secondary_window"),
rate_limit.get("secondary"),
rate_limit.get("primary_window"),
rate_limit.get("primary"),
]
for candidate in candidates:
duration = window_seconds(candidate)
if duration is not None and duration >= 6 * 24 * 60 * 60:
return candidate
return next((candidate for candidate in candidates if candidate), {})
def build_status():
local = read_local_usage_file()
if local:
weekly = normalize_limit(local.get("weekly") or local.get("week"), "1 周限额")
source = "本地 JSON"
message = "已读取本地周额度"
else:
usage = fetch_usage()
rate_limit = usage.get("rate_limit") or {}
weekly = normalize_wham_window(select_weekly_window(rate_limit), "1 周限额")
source = "wham/usage"
message = "已读取真实周额度"
return {
"weekly": weekly,
"source": source,
"message": message,
"updated": now_text(),
"ok": True,
}
class FloatingWindow:
def __init__(self):
self.settings = load_settings()
self.locked = bool(self.settings.get("locked", False))
saved_opacity = self.settings.get("opacity", 92)
self.opacity = saved_opacity if saved_opacity in OPACITY_OPTIONS else 92
self.drag_offset_x = 0
self.drag_offset_y = 0
self.last_refresh = 0
self.status = None
self.last_error = None
self.refreshing = False
self.visible = True
self.root = Tk()
self.root.title("Codex Limits")
geometry = self.default_geometry()
self.root.geometry(geometry)
self.root.attributes("-topmost", True)
self.root.attributes("-alpha", self.opacity / 100)
self.root.resizable(False, False)
self.root.configure(bg=TRANSPARENT)
self.root.overrideredirect(True)
try:
self.root.attributes("-transparentcolor", TRANSPARENT)
except Exception:
pass
self.canvas = Canvas(
self.root,
width=WINDOW_WIDTH,
height=WINDOW_HEIGHT,
bg=TRANSPARENT,
highlightthickness=0,
)
self.canvas.pack()
self.tray = TrayIcon(
on_toggle=lambda: self.root.after(0, self.toggle_window),
on_refresh=lambda: self.root.after(0, self.refresh_async),
on_toggle_lock=lambda: self.root.after(0, self.toggle_lock),
on_set_opacity=lambda value: self.root.after(0, lambda: self.set_opacity(value)),
on_exit=lambda: self.root.after(0, self.exit_app),
get_visible=lambda: self.visible,
get_locked=lambda: self.locked,
get_opacity=lambda: self.opacity,
)
self.canvas.bind("<ButtonPress-1>", self.start_drag)
self.canvas.bind("<B1-Motion>", self.drag)
self.canvas.bind("<ButtonRelease-1>", self.end_drag)
self.canvas.bind("<Double-Button-1>", lambda _event: self.refresh_async())
self.canvas.bind("<Button-3>", self.show_window_menu)
self.root.bind("<Escape>", lambda _event: self.hide_window())
self.root.protocol("WM_DELETE_WINDOW", self.hide_window)
self.draw()
self.refresh_async()
self.root.after(1000, self.tick)
self.root.after(100, self.raise_windows)
self.tray.start()
def default_geometry(self):
saved_x = self.settings.get("x")
saved_y = self.settings.get("y")
try:
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
virtual_w = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
virtual_h = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
except (AttributeError, win32gui.error):
left, top = 0, 0
virtual_w = self.root.winfo_screenwidth()
virtual_h = self.root.winfo_screenheight()
if isinstance(saved_x, int) and isinstance(saved_y, int):
x = max(left, min(saved_x, left + virtual_w - WINDOW_WIDTH))
y = max(top, min(saved_y, top + virtual_h - WINDOW_HEIGHT))
else:
x = left + virtual_w - WINDOW_WIDTH - 24
y = top + 72
return f"{WINDOW_WIDTH}x{WINDOW_HEIGHT}+{x}+{y}"
def start_drag(self, event):
self.root.after_idle(self.raise_windows)
if self.locked:
return
self.drag_offset_x = event.x_root - self.root.winfo_x()
self.drag_offset_y = event.y_root - self.root.winfo_y()
def drag(self, event):
if self.locked:
return
x = event.x_root - self.drag_offset_x
y = event.y_root - self.drag_offset_y
self.move_windows(x, y)
def end_drag(self, _event):
if self.locked:
return
self.settings["x"] = self.root.winfo_x()
self.settings["y"] = self.root.winfo_y()
save_settings(self.settings)
def move_windows(self, x, y):
geometry = f"+{x}+{y}"
self.root.geometry(geometry)
def raise_windows(self):
if not self.visible:
return
self.root.lift()
self.root.attributes("-topmost", True)
try:
flags = win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE
win32gui.SetWindowPos(self.native_handle(self.root), win32con.HWND_TOPMOST, 0, 0, 0, 0, flags)
except win32gui.error:
pass
def native_handle(self, widget):
hwnd = widget.winfo_id()
while True:
parent = win32gui.GetParent(hwnd)
if not parent:
return hwnd
hwnd = parent
def rounded(self, canvas, x1, y1, x2, y2, radius, **kwargs):
points = [
x1 + radius, y1, x2 - radius, y1, x2, y1, x2, y1 + radius,
x2, y2 - radius, x2, y2, x2 - radius, y2, x1 + radius, y2,
x1, y2, x1, y2 - radius, x1, y1 + radius, x1, y1,
]
return canvas.create_polygon(points, smooth=True, **kwargs)
def scale_canvas(self, canvas):
if DPI_SCALE != 1.0:
canvas.scale("all", 0, 0, DPI_SCALE, DPI_SCALE)
def color_for_percent(self, percent, default=BLUE):
if percent is None:
return "#9aa6b5"
if percent <= 15:
return RED
if percent <= 35:
return AMBER
return default
def value_text(self, item):
percent = item["percent"]
if percent is None:
return "待接入"
if item.get("remaining") is not None and item.get("limit") is not None:
return f"{item['remaining']} / {item['limit']}"
return f"{percent:.0f}%"
def reset_text(self, item):
reset = item.get("reset_at")
return f"重置 {reset}" if reset else "重置时间未知"
def draw_limit_row(self, x, y, width, item, accent):
color = self.color_for_percent(item["percent"], accent)
self.canvas.create_text(x, y + 8, text=item["label"], fill=TEXT, anchor="w", font=("Microsoft YaHei UI", 10, "bold"))
self.canvas.create_text(x + width, y + 8, text=self.value_text(item), fill=color, anchor="e", font=("Segoe UI", 14, "bold"))
track_x = x
track_y = y + 30
track_w = width
self.rounded(self.canvas, track_x, track_y, track_x + track_w, track_y + 12, 7, fill=TRACK, outline="")
percent = item["percent"]
if percent is not None:
fill_w = max(9, int(track_w * percent / 100))
self.rounded(self.canvas, track_x, track_y, track_x + fill_w, track_y + 12, 7, fill=color, outline="")
self.canvas.create_text(x, y + 51, text=self.reset_text(item), fill=MUTED, anchor="w", font=("Microsoft YaHei UI", 8, "bold"))
def draw(self):
self.canvas.delete("all")
status = self.status
self.rounded(
self.canvas,
8,
8,
BASE_WINDOW_WIDTH - 8,
BASE_WINDOW_HEIGHT - 8,
18,
fill=PANEL,
outline="#d6e0eb",
)
if not status:
self.canvas.create_text(24, 45, text="读取中...", fill=TEXT, anchor="w", font=("Microsoft YaHei UI", 12, "bold"))
self.scale_canvas(self.canvas)
return
self.draw_limit_row(24, 18, BASE_WINDOW_WIDTH - 48, status["weekly"], BLUE)
state_color = BLUE if self.refreshing else (RED if self.last_error else GREEN)
self.canvas.create_oval(304, 70, 312, 78, fill=state_color, outline="")
self.scale_canvas(self.canvas)
def refresh_async(self):
if self.refreshing:
return
self.refreshing = True
self.last_refresh = time.time()
self.draw()
threading.Thread(target=self.refresh_worker, daemon=True).start()
def refresh_worker(self):
try:
status = build_status()
error = None
except Exception as exc:
status = None
error = str(exc)
try:
self.root.after(0, lambda: self.finish_refresh(status, error))
except Exception:
pass
def finish_refresh(self, status, error):
self.refreshing = False
if status is not None:
self.status = status
self.last_error = None
else:
self.last_error = error or "读取失败"
if self.status is None:
self.status = {
"weekly": normalize_limit({}, "1 周限额"),
"updated": now_text(),
"ok": False,
}
self.draw()
self.update_tray_tip()
def update_tray_tip(self):
if self.last_error:
tip = f"Codex Limits | 更新失败:{self.last_error}"
elif self.status:
week = self.value_text(self.status["weekly"])
updated = self.status.get("updated", now_text())
tip = f"1 周 {week} | 更新 {updated}"
else:
tip = "Codex Limits | 正在读取"
self.tray.update_tooltip(tip)
def tick(self):
if time.time() - self.last_refresh >= REFRESH_SECONDS:
self.refresh_async()
self.root.after(1000, self.tick)
def hide_window(self):
self.visible = False
self.root.withdraw()
def show_window(self):
self.visible = True
self.root.deiconify()
self.raise_windows()
def toggle_window(self):
if self.visible:
self.hide_window()
else:
self.show_window()
def toggle_lock(self):
self.locked = not self.locked
self.settings["locked"] = self.locked
save_settings(self.settings)
def set_opacity(self, value):
if value not in OPACITY_OPTIONS:
return
self.opacity = value
self.root.attributes("-alpha", value / 100)
self.settings["opacity"] = value
save_settings(self.settings)
def exit_app(self):
self.tray.stop()
self.root.destroy()
def show_window_menu(self, event):
menu = Menu(self.root, tearoff=0)
menu.add_command(label="隐藏窗口", command=self.hide_window)
menu.add_command(label="刷新", command=self.refresh_async)
menu.add_command(label="解锁位置" if self.locked else "锁定位置", command=self.toggle_lock)
opacity_menu = Menu(menu, tearoff=0)
opacity_var = IntVar(value=self.opacity)
for value in OPACITY_OPTIONS:
opacity_menu.add_radiobutton(
label=f"{value}%",
value=value,
variable=opacity_var,
command=lambda selected=value: self.set_opacity(selected),
)
menu.add_cascade(label="透明度", menu=opacity_menu)
menu.add_separator()
menu.add_command(label="退出程序", command=self.exit_app)
try:
menu.tk_popup(event.x_root, event.y_root)
finally:
menu.grab_release()
self.root.after_idle(self.raise_windows)
def run(self):
self.root.mainloop()
class TrayIcon:
WM_TRAY = win32con.WM_USER + 20
ID_TOGGLE = 1001
ID_REFRESH = 1002
ID_LOCK = 1003
ID_EXIT = 1004
ID_OPACITY_BASE = 1100
def __init__(self, on_toggle, on_refresh, on_toggle_lock, on_set_opacity, on_exit, get_visible, get_locked, get_opacity):
self.on_toggle = on_toggle
self.on_refresh = on_refresh
self.on_toggle_lock = on_toggle_lock
self.on_set_opacity = on_set_opacity
self.on_exit = on_exit
self.get_visible = get_visible
self.get_locked = get_locked
self.get_opacity = get_opacity
self.hwnd = None
self.thread = None
self.icon = None
self.tooltip = "Codex Limits | 正在读取"
def start(self):
self.thread = threading.Thread(target=self.run, daemon=True)
self.thread.start()
def run(self):
message_map = {
self.WM_TRAY: self.on_tray,
win32con.WM_COMMAND: self.on_command,
win32con.WM_DESTROY: self.on_destroy,
}
wc = win32gui.WNDCLASS()
wc.hInstance = win32api.GetModuleHandle(None)
wc.lpszClassName = "CodexLimitsTray"
wc.lpfnWndProc = message_map
try:
win32gui.RegisterClass(wc)
except win32gui.error:
pass
self.hwnd = win32gui.CreateWindow(wc.lpszClassName, "Codex Limits", 0, 0, 0, 0, 0, 0, 0, wc.hInstance, None)
self.icon = self.load_icon()
flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
nid = (self.hwnd, 0, flags, self.WM_TRAY, self.icon, self.tooltip)
win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)
win32gui.PumpMessages()
def load_icon(self):
icon_path = Path(__file__).with_name("codex_limits_tray.ico")
if not icon_path.exists():
self.create_icon(icon_path)
return win32gui.LoadImage(
0,
str(icon_path),
win32con.IMAGE_ICON,
0,
0,
win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE,
)
def create_icon(self, icon_path):
sizes = [16, 24, 32, 48, 64]
images = []
for size in sizes:
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
margin = max(2, size // 8)
radius = max(4, size // 4)
draw.rounded_rectangle(
(margin, margin, size - margin, size - margin),
radius=radius,
fill=(18, 25, 35, 255),
outline=(64, 82, 105, 255),
width=max(1, size // 18),
)
bar_h = max(2, size // 7)
left = margin * 2
right = size - margin * 2
y1 = int(size * 0.38)
y2 = int(size * 0.58)
draw.rounded_rectangle((left, y1, int(right * 0.78), y1 + bar_h), radius=bar_h // 2, fill=(88, 214, 141, 255))
draw.rounded_rectangle((left, y2, int(right * 0.56), y2 + bar_h), radius=bar_h // 2, fill=(98, 168, 255, 255))
images.append(img)
images[-1].save(icon_path, sizes=[(s, s) for s in sizes], append_images=images[:-1])
def on_tray(self, hwnd, msg, wparam, lparam):
if lparam == win32con.WM_LBUTTONUP:
self.on_toggle()
elif lparam == win32con.WM_RBUTTONUP:
self.show_menu()
return True
def show_menu(self):
menu = win32gui.CreatePopupMenu()
toggle_label = "隐藏窗口" if self.get_visible() else "显示窗口"
win32gui.AppendMenu(menu, win32con.MF_STRING, self.ID_TOGGLE, toggle_label)
win32gui.AppendMenu(menu, win32con.MF_STRING, self.ID_REFRESH, "刷新")
lock_flags = win32con.MF_STRING | (win32con.MF_CHECKED if self.get_locked() else 0)
win32gui.AppendMenu(menu, lock_flags, self.ID_LOCK, "锁定位置")
opacity_menu = win32gui.CreatePopupMenu()
current_opacity = self.get_opacity()
for value in OPACITY_OPTIONS:
opacity_flags = win32con.MF_STRING | (win32con.MF_CHECKED if value == current_opacity else 0)
win32gui.AppendMenu(opacity_menu, opacity_flags, self.ID_OPACITY_BASE + value, f"{value}%")
win32gui.AppendMenu(menu, win32con.MF_POPUP, opacity_menu, "透明度")
win32gui.AppendMenu(menu, win32con.MF_SEPARATOR, 0, None)
win32gui.AppendMenu(menu, win32con.MF_STRING, self.ID_EXIT, "退出程序")
pos = win32gui.GetCursorPos()
win32gui.SetForegroundWindow(self.hwnd)
command = win32gui.TrackPopupMenu(
menu,
win32con.TPM_LEFTALIGN | win32con.TPM_RETURNCMD | win32con.TPM_NONOTIFY,
pos[0],
pos[1],
0,
self.hwnd,
None,
)
if command:
win32gui.PostMessage(self.hwnd, win32con.WM_COMMAND, command, 0)
win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
def on_command(self, hwnd, msg, wparam, lparam):
command = win32api.LOWORD(wparam)
if command == self.ID_TOGGLE:
self.on_toggle()
elif command == self.ID_REFRESH:
self.on_refresh()
elif command == self.ID_LOCK:
self.on_toggle_lock()
elif command - self.ID_OPACITY_BASE in OPACITY_OPTIONS:
self.on_set_opacity(command - self.ID_OPACITY_BASE)
elif command == self.ID_EXIT:
self.on_exit()
return True
def update_tooltip(self, text):
self.tooltip = str(text)[:127]
if not self.hwnd or not self.icon:
return
try:
flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
nid = (self.hwnd, 0, flags, self.WM_TRAY, self.icon, self.tooltip)
win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, nid)
except win32gui.error:
pass
def stop(self):
if self.hwnd:
try:
win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, (self.hwnd, 0))
win32gui.PostMessage(self.hwnd, win32con.WM_CLOSE, 0, 0)
except win32gui.error:
pass
def on_destroy(self, hwnd, msg, wparam, lparam):
try:
win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, (hwnd, 0))
except win32gui.error:
pass
win32gui.PostQuitMessage(0)
return True
if __name__ == "__main__":
if sys.platform != "win32":
print("这个悬浮窗主要为 Windows/Tkinter 设计。")
enable_high_dpi()
configure_display_scale()
is_first_instance, instance_mutex = acquire_single_instance()
if is_first_instance:
FloatingWindow().run()