Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1056 lines (889 loc) · 37.4 KB
/
Copy pathmain.py
File metadata and controls
1056 lines (889 loc) · 37.4 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
#!/usr/bin/env python3
"""
快速记录工具
按 F2 键打开记录窗口,支持文字记录和截图/上传图片,保存到以主题命名的文件夹。
"""
import sys
import re
import io
import json
import subprocess
import tempfile
from typing import Optional, Tuple
from datetime import datetime
from pathlib import Path
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTextEdit, QLabel, QFileDialog, QScrollArea,
QFrame, QSplitter, QSystemTrayIcon, QMenu, QAction,
QMessageBox, QDialog, QLineEdit, QRubberBand, QStyle,
QGraphicsDropShadowEffect
)
from PyQt5.QtCore import (
Qt, QTimer, pyqtSignal, QObject, QThread, QRect, QRectF,
QBuffer, QByteArray, QIODevice
)
from PyQt5.QtGui import (
QPixmap, QIcon, QFont, QPainter, QColor, QPalette, QCursor, QPainterPath
)
from pynput import keyboard as pynput_keyboard
from PIL import Image
def _ui_font_family() -> str:
if sys.platform == "darwin":
return "PingFang SC"
if sys.platform.startswith("win"):
return "Microsoft YaHei UI"
return "Noto Sans CJK SC"
UI_FONT_FAMILY = _ui_font_family()
def ui_font(size: int, weight: int = QFont.Normal) -> QFont:
return QFont(UI_FONT_FAMILY, size, weight)
def configure_dpi():
# 在 Windows 上主动开启高 DPI 感知,避免系统缩放导致界面比例异常。
if sys.platform.startswith("win"):
try:
import ctypes
# PER_MONITOR_AWARE_V2
ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
except Exception:
try:
import ctypes
# PROCESS_PER_MONITOR_DPI_AWARE
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except Exception:
pass
if hasattr(Qt, "AA_EnableHighDpiScaling"):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, "AA_UseHighDpiPixmaps"):
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
# ─── 热键信号桥(跨线程) ─────────────────────────────────────────────────────
class HotkeySignals(QObject):
toggle_window = pyqtSignal()
hotkey_failed = pyqtSignal(str)
class HotkeyListener(QThread):
"""在后台线程监听全局热键 F2"""
def __init__(self, signals: HotkeySignals):
super().__init__()
self.signals = signals
self._listener = None
def run(self):
try:
def on_press(key):
if key == pynput_keyboard.Key.f2:
self.signals.toggle_window.emit()
with pynput_keyboard.Listener(on_press=on_press) as listener:
self._listener = listener
listener.join()
except Exception as e:
self.signals.hotkey_failed.emit(str(e))
def stop(self):
if self._listener:
self._listener.stop()
# ─── 可点击图片占位标签 ────────────────────────────────────────────────────────
class ClickableLabel(QLabel):
clicked = pyqtSignal()
def __init__(self, text=""):
super().__init__(text)
def mousePressEvent(self, event):
self.clicked.emit()
class FocusTextEdit(QTextEdit):
"""无硬边框文本框,聚焦时显示柔和主题色阴影。"""
def __init__(self):
super().__init__()
self._focus_shadow = QGraphicsDropShadowEffect(self)
self._focus_shadow.setBlurRadius(24)
self._focus_shadow.setOffset(0, 0)
self._focus_shadow.setColor(QColor(64, 138, 255, 80))
self._focus_shadow.setEnabled(False)
self.setGraphicsEffect(self._focus_shadow)
def focusInEvent(self, event):
self._focus_shadow.setEnabled(True)
super().focusInEvent(event)
def focusOutEvent(self, event):
self._focus_shadow.setEnabled(False)
super().focusOutEvent(event)
# ─── 区域截图覆盖层 ────────────────────────────────────────────────────────────
class ScreenshotOverlay(QWidget):
"""全屏覆盖层,显示截图并支持拖拽选择区域"""
captured = pyqtSignal(object) # QPixmap
cancelled = pyqtSignal()
def __init__(self, screenshot_pixmap: QPixmap, target_geometry: QRect):
super().__init__()
self._pix = screenshot_pixmap
self._target_geometry = target_geometry
self._start = None
self._end = None
self._rubber = None
self._build_ui()
def _build_ui(self):
self.setWindowFlags(
Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
)
self.setCursor(Qt.CrossCursor)
self.setStyleSheet("background: transparent;")
self.setGeometry(self._target_geometry)
self.setMouseTracking(True)
self._rubber = QRubberBand(QRubberBand.Rectangle, self)
self._rubber.setStyleSheet(
"QRubberBand { border: 2px solid #007AFF; background: rgba(0,122,255,0.15); }"
)
def paintEvent(self, event):
p = QPainter(self)
p.drawPixmap(self.rect(), self._pix)
p.setCompositionMode(QPainter.CompositionMode_SourceOver)
dim = QColor(0, 0, 0, 100)
if self._rubber.isVisible() and not self._rubber.geometry().isEmpty():
r = self._rubber.geometry()
# 在选中区域周围绘制半透明遮罩,使选中区更清晰
p.fillRect(0, 0, self.width(), r.top(), dim)
p.fillRect(0, r.top(), r.left(), r.height(), dim)
p.fillRect(r.right(), r.top(), self.width() - r.right(), r.height(), dim)
p.fillRect(0, r.bottom(), self.width(), self.height() - r.bottom(), dim)
else:
p.fillRect(self.rect(), dim)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self._start = event.pos()
self._end = event.pos()
self._rubber.setGeometry(QRect(self._start, self._end).normalized())
self._rubber.show()
def mouseMoveEvent(self, event):
if self._start is not None:
self._end = event.pos()
self._rubber.setGeometry(QRect(self._start, self._end).normalized())
def mouseReleaseEvent(self, event):
if event.button() != Qt.LeftButton or self._start is None:
return
self._end = event.pos()
r = QRect(self._start, self._end).normalized()
self._rubber.hide()
if r.width() < 10 or r.height() < 10:
self.cancelled.emit()
self.close()
return # 区域太小,视为取消
# 将窗口坐标映射到截图像素坐标后裁剪
scale_x = self._pix.width() / max(self.width(), 1)
scale_y = self._pix.height() / max(self.height(), 1)
x = int(r.x() * scale_x)
y = int(r.y() * scale_y)
w = max(1, int(r.width() * scale_x))
h = max(1, int(r.height() * scale_y))
crop_rect = QRect(x, y, w, h).intersected(
QRect(0, 0, self._pix.width(), self._pix.height())
)
crop = self._pix.copy(crop_rect)
if crop.isNull():
self.cancelled.emit()
self.close()
return
self.captured.emit(crop)
self.close()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
self.cancelled.emit()
self.close()
# ─── 主题名称输入对话框 ────────────────────────────────────────────────────────
class TopicDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("保存记录")
self.setFixedSize(380, 170)
self.setWindowFlags(Qt.Dialog | Qt.WindowStaysOnTopHint)
layout = QVBoxLayout(self)
layout.setContentsMargins(24, 24, 24, 20)
layout.setSpacing(14)
label = QLabel("请输入主题名称:")
label.setFont(ui_font(13))
label.setStyleSheet("color: #333;")
layout.addWidget(label)
self.input = QLineEdit()
self.input.setPlaceholderText("例如:会议记录、灵感想法、Bug分析…")
self.input.setFixedHeight(40)
self.input.setFont(ui_font(13))
self.input.setStyleSheet("""
QLineEdit {
border: 1px solid #ccc;
border-radius: 8px;
padding: 0 12px;
background: white;
color: #333;
}
QLineEdit:focus { border: 1.5px solid #007AFF; }
""")
self.input.returnPressed.connect(self.accept)
layout.addWidget(self.input)
btn_row = QHBoxLayout()
btn_row.addStretch()
cancel_btn = QPushButton("取消")
cancel_btn.setFixedSize(84, 36)
cancel_btn.clicked.connect(self.reject)
save_btn = QPushButton("保存")
save_btn.setFixedSize(84, 36)
save_btn.setObjectName("save_btn")
save_btn.clicked.connect(self.accept)
btn_row.addWidget(cancel_btn)
btn_row.addWidget(save_btn)
layout.addLayout(btn_row)
self.setStyleSheet("""
QDialog { background: #f5f5f7; }
QPushButton {
background: #e5e5ea;
border: none;
border-radius: 8px;
color: #333;
font-size: 13px;
font-family: '%s';
}
QPushButton:hover { background: #d1d1d6; }
QPushButton#save_btn {
background: #007AFF;
color: white;
font-weight: bold;
}
QPushButton#save_btn:hover { background: #0068d6; }
""" % UI_FONT_FAMILY)
def get_topic_name(self) -> str:
name = self.input.text().strip()
name = re.sub(r'[<>:"/\\|?*\n\r]', '_', name)
return name or "未命名"
# ─── 记录主窗口 ────────────────────────────────────────────────────────────────
class NoteWindow(QMainWindow):
def __init__(self, on_quit=None, app_icon: Optional[QIcon] = None):
super().__init__()
self.images: list[Image.Image] = []
self.on_quit = on_quit
self._overlay = None
if app_icon is not None:
self.setWindowIcon(app_icon)
self._build_ui()
self._apply_style()
# ── 构建界面 ────────────────────────────────────────────────────────────
def _build_ui(self):
self.setWindowTitle("QuickNote")
self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
self.resize(980, 640)
self._center()
root = QWidget()
self.setCentralWidget(root)
vbox = QVBoxLayout(root)
vbox.setContentsMargins(0, 0, 0, 0)
vbox.setSpacing(0)
# 顶部导航栏
header = QFrame()
header.setObjectName("header")
header.setFixedHeight(60)
hlay = QHBoxLayout(header)
hlay.setContentsMargins(22, 8, 12, 8)
hlay.setSpacing(0)
title = QLabel("快速记录 — F2")
title.setObjectName("header_title")
title.setFont(ui_font(17, QFont.Bold))
hlay.addWidget(title)
hlay.addStretch()
quit_btn = QPushButton("退出")
quit_btn.setObjectName("quit_btn")
quit_btn.setFixedSize(68, 30)
quit_btn.setCursor(Qt.PointingHandCursor)
quit_btn.clicked.connect(self._request_quit)
hlay.addWidget(quit_btn)
vbox.addWidget(header)
divider = QFrame()
divider.setObjectName("header_divider")
divider.setFixedHeight(1)
vbox.addWidget(divider)
# 主内容区
content = QWidget()
clayout = QVBoxLayout(content)
clayout.setContentsMargins(20, 16, 20, 12)
clayout.setSpacing(12)
splitter = QSplitter(Qt.Horizontal)
splitter.setHandleWidth(10)
# 左:文字区
left = QFrame()
left.setObjectName("panel_card")
ll = QVBoxLayout(left)
ll.setContentsMargins(14, 12, 14, 12)
ll.setSpacing(10)
ll.addWidget(self._section_label("文字记录"))
self.text_edit = FocusTextEdit()
self.text_edit.setPlaceholderText("在此输入记录内容…")
self.text_edit.setFont(ui_font(13))
self.text_edit.setMinimumWidth(320)
palette = self.text_edit.palette()
palette.setColor(QPalette.PlaceholderText, QColor("#A8AFBC"))
self.text_edit.setPalette(palette)
ll.addWidget(self.text_edit)
splitter.addWidget(left)
# 右:图片区
right = QFrame()
right.setObjectName("panel_card")
rl = QVBoxLayout(right)
rl.setContentsMargins(14, 12, 14, 12)
rl.setSpacing(10)
rl.addWidget(self._section_label("截图 / 图片"))
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setObjectName("image_scroll")
self.img_container = QWidget()
self.img_container.setStyleSheet("background: #fff;")
self.img_vbox = QVBoxLayout(self.img_container)
self.img_vbox.setAlignment(Qt.AlignTop)
self.img_vbox.setSpacing(10)
self.img_vbox.setContentsMargins(10, 10, 10, 10)
self._show_placeholder()
self.scroll.setWidget(self.img_container)
rl.addWidget(self.scroll)
tools = QFrame()
tools.setObjectName("tools_bar")
tool_layout = QHBoxLayout(tools)
tool_layout.setContentsMargins(10, 8, 10, 8)
tool_layout.setSpacing(8)
toolbar_buttons = [
("区域截图", self.take_region_screenshot, self.style().standardIcon(QStyle.SP_DesktopIcon)),
("全屏截图", self.take_full_screenshot, self.style().standardIcon(QStyle.SP_ComputerIcon)),
("上传图片", self.upload_image, self.style().standardIcon(QStyle.SP_DialogOpenButton)),
("清除", self.clear_images, self.style().standardIcon(QStyle.SP_TrashIcon)),
]
for text, slot, icon in toolbar_buttons:
b = QPushButton(text)
b.setObjectName("tool_btn")
b.setIcon(icon)
b.setFixedHeight(30)
b.clicked.connect(slot)
tool_layout.addWidget(b)
rl.addWidget(tools)
splitter.addWidget(right)
splitter.setSizes([480, 460])
clayout.addWidget(splitter)
vbox.addWidget(content)
# 底部分割线 + 操作区
footer_divider = QFrame()
footer_divider.setObjectName("footer_divider")
footer_divider.setFixedHeight(1)
vbox.addWidget(footer_divider)
footer = QFrame()
footer.setObjectName("footer")
footer.setFixedHeight(64)
f_layout = QHBoxLayout(footer)
f_layout.setContentsMargins(20, 10, 20, 10)
f_layout.setSpacing(10)
cancel_btn = QPushButton("取消")
cancel_btn.setObjectName("cancel_btn")
cancel_btn.setFixedSize(88, 38)
cancel_btn.clicked.connect(self.cancel)
done_btn = QPushButton("完成")
done_btn.setFixedSize(88, 38)
done_btn.setObjectName("done_btn")
done_btn.clicked.connect(self.done_action)
f_layout.addStretch()
f_layout.addWidget(cancel_btn)
f_layout.addWidget(done_btn)
vbox.addWidget(footer)
def _section_label(self, text: str) -> QLabel:
lbl = QLabel(text)
lbl.setObjectName("section_title")
lbl.setFont(ui_font(14, QFont.Bold))
return lbl
def _center(self):
geo = QApplication.desktop().screenGeometry()
self.move((geo.width() - 980) // 2, (geo.height() - 640) // 2)
def _request_quit(self):
if self.on_quit:
self.on_quit()
# ── 样式 ────────────────────────────────────────────────────────────────
def _apply_style(self):
self.setStyleSheet("""
QMainWindow, QWidget { background: #F7F7F9; }
QFrame#header {
background: #F7F7F9;
}
QLabel#header_title {
color: #1f2937;
background: transparent;
font-weight: 700;
}
QLabel#section_title {
color: #4B5563;
background: transparent;
padding-left: 2px;
}
QFrame#header_divider,
QFrame#footer_divider {
background: #E8EAF0;
}
QFrame#footer {
background: #F7F7F9;
}
QFrame#panel_card {
background: #FFFFFF;
border: 1px solid #ECEEF3;
border-radius: 12px;
}
QSplitter::handle {
background: transparent;
}
QTextEdit {
border: none;
border-radius: 10px;
padding: 12px;
background: #FFFFFF;
color: #1F2937;
font-family: '%s';
selection-background-color: #dbeafe;
}
QTextEdit:focus { outline: none; }
QScrollArea#image_scroll {
background: #FFFFFF;
border: none;
border-radius: 10px;
}
QScrollArea#image_scroll > QWidget > QWidget {
background: #FFFFFF;
}
QFrame#tools_bar {
background: #F7F8FB;
border: 1px solid #ECEEF3;
border-radius: 10px;
}
QPushButton {
background: #ECEFF4;
border: none;
border-radius: 8px;
padding: 6px 12px;
color: #374151;
font-size: 12px;
font-family: '%s';
}
QPushButton:hover { background: #E2E8F0; }
QPushButton#tool_btn {
background: #FFFFFF;
border: 1px solid #E6E8EF;
border-radius: 8px;
padding: 4px 10px;
}
QPushButton#tool_btn:hover { background: #F3F6FB; }
QPushButton#quit_btn {
background: transparent;
color: #6B7280;
border-radius: 8px;
font-size: 13px;
font-weight: 500;
padding: 0px 10px;
}
QPushButton#quit_btn:hover {
background: #FEE2E2;
color: #DC2626;
}
QPushButton#cancel_btn {
background: transparent;
color: #6B7280;
border-radius: 8px;
padding: 6px 12px;
}
QPushButton#cancel_btn:hover { background: #ECEFF4; }
QPushButton#done_btn {
background: #4F8DF7;
color: white;
font-weight: 600;
}
QPushButton#done_btn:hover { background: #3E7DE7; }
""" % (UI_FONT_FAMILY, UI_FONT_FAMILY))
# ── 占位图 ──────────────────────────────────────────────────────────────
def _show_placeholder(self):
self.placeholder = ClickableLabel(
"点击此处 或 使用下方按钮添加图片 / 截图"
)
self.placeholder.setAlignment(Qt.AlignCenter)
self.placeholder.setMinimumHeight(140)
self.placeholder.setStyleSheet("""
QLabel {
border: 1px dashed #D5D9E3;
border-radius: 12px;
background: #FCFCFD;
color: #A0A7B5;
font-size: 13px;
font-family: '%s';
}
""" % UI_FONT_FAMILY)
self.placeholder.clicked.connect(self.upload_image)
self.img_vbox.addWidget(self.placeholder)
# ── 截图 ────────────────────────────────────────────────────────────────
def take_full_screenshot(self):
self.hide()
QTimer.singleShot(500, self._do_full_screenshot)
def _do_full_screenshot(self):
try:
pix, temp_path = self._capture_screen_pixmap()
img = self._load_pil_from_file(temp_path) if temp_path else self._pixmap_to_pil(pix)
self._add_image(img, source="全屏截图")
except Exception as e:
QMessageBox.warning(self, "截图失败", str(e))
finally:
self._show_after_screenshot()
def take_region_screenshot(self):
self.hide()
QTimer.singleShot(500, self._do_region_screenshot)
def _do_region_screenshot(self):
# macOS 使用系统交互截图;Windows/Linux 使用程序内框选
if sys.platform == "darwin":
temp_path = None
try:
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
temp_path = tmp.name
result = subprocess.run(
["screencapture", "-i", "-x", "-t", "png", temp_path],
capture_output=True,
text=True,
timeout=120,
)
# 取消截图时返回非 0,直接恢复窗口
if result.returncode != 0:
self._show_after_screenshot()
return
pix = QPixmap(temp_path)
if pix.isNull():
raise RuntimeError("无法读取区域截图,请检查屏幕录制权限")
img = self._load_pil_from_file(temp_path)
self._add_image(img, source="区域截图")
self._show_after_screenshot()
except Exception as e:
QMessageBox.warning(self, "截图失败", str(e))
self._show_after_screenshot()
finally:
if temp_path:
Path(temp_path).unlink(missing_ok=True)
return
try:
pix, geo = self._capture_screen_pixmap_qt()
self._overlay = ScreenshotOverlay(pix, geo)
self._overlay.captured.connect(self._on_region_captured)
self._overlay.cancelled.connect(self._show_after_screenshot)
self._overlay.show()
except Exception as e:
QMessageBox.warning(self, "截图失败", str(e))
self._show_after_screenshot()
def _on_region_captured(self, pix: QPixmap):
img = self._pixmap_to_pil(pix)
self._add_image(img, source="区域截图")
self._overlay = None
self._show_after_screenshot()
def _show_after_screenshot(self):
self._overlay = None
self.show()
self.raise_()
self.activateWindow()
@staticmethod
def _capture_screen_pixmap() -> Tuple[QPixmap, Optional[str]]:
if sys.platform != "darwin":
pix, _ = NoteWindow._capture_screen_pixmap_qt()
return pix, None
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
temp_path = tmp.name
try:
# 使用 macOS 原生截图,拿到当前实际显示内容而不是 Qt 抓到的桌面层
result = subprocess.run(
["screencapture", "-x", "-t", "png", temp_path],
capture_output=True,
text=True,
timeout=8,
)
if result.returncode != 0:
error = result.stderr.strip() or "系统截图命令执行失败"
raise RuntimeError(error)
pix = QPixmap(temp_path)
if pix.isNull():
raise RuntimeError("无法读取系统截图,请检查屏幕录制权限")
return pix, temp_path
finally:
# 由调用方决定是否读取并删除文件
pass
@staticmethod
def _capture_screen_pixmap_qt() -> Tuple[QPixmap, QRect]:
cursor_pos = QCursor.pos()
screen = QApplication.screenAt(cursor_pos)
if screen is None:
screen = QApplication.primaryScreen()
if screen is None:
raise RuntimeError("未找到可用屏幕")
pix = screen.grabWindow(0)
if pix.isNull():
raise RuntimeError("无法捕获屏幕画面")
return pix, screen.geometry()
@staticmethod
def _load_pil_from_file(path: str) -> Image.Image:
try:
return Image.open(path).convert("RGB").copy()
finally:
Path(path).unlink(missing_ok=True)
@staticmethod
def _pixmap_to_pil(pix: QPixmap) -> Image.Image:
byte_array = QByteArray()
buffer = QBuffer(byte_array)
buffer.open(QIODevice.WriteOnly)
pix.save(buffer, "PNG")
buffer.close()
return Image.open(io.BytesIO(bytes(byte_array))).convert("RGB").copy()
# ── 上传图片 ─────────────────────────────────────────────────────────────
def upload_image(self):
path, _ = QFileDialog.getOpenFileName(
self, "选择图片", "",
"图片文件 (*.png *.jpg *.jpeg *.gif *.bmp *.webp *.tiff)"
)
if path:
self._add_image(Image.open(path), source=Path(path).name)
# ── 添加图片到预览 ────────────────────────────────────────────────────────
def _add_image(self, pil_img: Image.Image, source: str = ""):
if self.placeholder and self.placeholder.isVisible():
self.placeholder.hide()
self.images.append(pil_img)
idx = len(self.images)
frame = QFrame()
frame.setStyleSheet("""
QFrame {
background: #fff;
border: 1px solid #e5e5ea;
border-radius: 8px;
}
""")
fl = QVBoxLayout(frame)
fl.setContentsMargins(6, 6, 6, 6)
fl.setSpacing(4)
img_lbl = QLabel()
img_lbl.setAlignment(Qt.AlignCenter)
img_lbl.setPixmap(self._to_pixmap(pil_img, 360, 260))
fl.addWidget(img_lbl)
info = QLabel(f"图片 {idx} · {source}")
info.setStyleSheet(f"color: #aeaeb2; font-size: 11px; font-family: '{UI_FONT_FAMILY}';")
info.setAlignment(Qt.AlignCenter)
fl.addWidget(info)
self.img_vbox.addWidget(frame)
@staticmethod
def _to_pixmap(img: Image.Image, max_w: int, max_h: int) -> QPixmap:
if img.mode != "RGB":
img = img.convert("RGB")
w, h = img.size
ratio = min(max_w / w, max_h / h, 1.0)
if ratio < 1.0:
img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, "PNG")
px = QPixmap()
px.loadFromData(buf.getvalue())
return px
# ── 清除图片 ─────────────────────────────────────────────────────────────
def clear_images(self):
self.images.clear()
while self.img_vbox.count():
item = self.img_vbox.takeAt(0)
if item.widget():
item.widget().deleteLater()
self._show_placeholder()
# ── 取消 ────────────────────────────────────────────────────────────────
def cancel(self):
self.hide()
self._reset()
def _reset(self):
self.text_edit.clear()
self.clear_images()
# ── 完成 → 保存 ──────────────────────────────────────────────────────────
def done_action(self):
text = self.text_edit.toPlainText().strip()
if not text and not self.images:
QMessageBox.information(self, "提示", "请先输入文字内容或添加图片再保存。")
return
dlg = TopicDialog(self)
dlg.input.setFocus()
if dlg.exec_() == QDialog.Accepted:
topic = dlg.get_topic_name()
self._save(topic, text)
def _save(self, topic: str, text: str):
base = Path.home() / "Documents" / "QuickNotes"
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
folder = base / f"{topic}_{ts}"
folder.mkdir(parents=True, exist_ok=True)
if text:
(folder / "note.txt").write_text(text, encoding="utf-8")
for i, img in enumerate(self.images, 1):
img.save(str(folder / f"image_{i:02d}.png"), "PNG")
meta = {
"topic": topic,
"created_at": datetime.now().isoformat(),
"text_chars": len(text),
"image_count": len(self.images),
}
(folder / "meta.json").write_text(
json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8"
)
QMessageBox.information(
self, "保存成功",
f"已保存到:\n{folder}"
)
self.hide()
self._reset()
# ── 关闭事件:最小化到托盘而不退出 ──────────────────────────────────────
def closeEvent(self, event):
event.ignore()
self.hide()
# ─── 应用主体 ──────────────────────────────────────────────────────────────────
class App(QApplication):
def __init__(self, argv):
super().__init__(argv)
self.setQuitOnLastWindowClosed(False)
self.custom_icon_path = self._load_custom_icon_path()
self.app_icon = self._create_icon(self.custom_icon_path)
self.setWindowIcon(self.app_icon)
self.note_window = NoteWindow(on_quit=self._quit, app_icon=self.app_icon)
self._setup_tray()
self.signals = HotkeySignals()
self.signals.toggle_window.connect(self._toggle)
self.signals.hotkey_failed.connect(self._on_hotkey_failed)
self.hotkey_thread = HotkeyListener(self.signals)
self.hotkey_thread.start()
if sys.platform == "darwin":
QTimer.singleShot(1200, self._show_hotkey_permission_tip)
# ── 系统托盘 ─────────────────────────────────────────────────────────────
def _setup_tray(self):
tray_icon = self._create_tray_icon(self.custom_icon_path, self.app_icon)
self.tray = QSystemTrayIcon(tray_icon, self)
self.tray.setToolTip("快速记录 (按 F2 打开)")
menu = QMenu()
open_act = QAction("打开记录窗口 (F2)", menu)
open_act.triggered.connect(self._show)
quit_act = QAction("退出", menu)
quit_act.triggered.connect(self._quit)
menu.addAction(open_act)
menu.addSeparator()
menu.addAction(quit_act)
self.tray.setContextMenu(menu)
self.tray.activated.connect(
lambda r: self._show() if r == QSystemTrayIcon.DoubleClick else None
)
self.tray.show()
self.tray.showMessage(
"快速记录已启动",
"按 F2 键随时打开记录窗口",
QSystemTrayIcon.Information, 3000
)
@staticmethod
def _create_icon(custom_icon_path: Optional[Path] = None) -> QIcon:
if custom_icon_path is not None:
if custom_icon_path.suffix.lower() == ".icns":
# 打包后的 icns 直接使用,避免重复缩放导致发糊
icon = QIcon(str(custom_icon_path))
if not icon.isNull():
return icon
rounded_icon = App._build_rounded_icon(
custom_icon_path, canvas_size=512, corner_ratio=0.2, padding_ratio=0.02
)
if rounded_icon is not None:
return rounded_icon
px = QPixmap(32, 32)
px.fill(Qt.transparent)
p = QPainter(px)
p.setRenderHint(QPainter.Antialiasing)
p.setBrush(QColor("#007AFF"))
p.setPen(Qt.NoPen)
p.drawRoundedRect(2, 2, 28, 28, 7, 7)
p.setPen(QColor("white"))
p.setFont(QFont("Arial", 16, QFont.Bold))
p.drawText(px.rect(), Qt.AlignCenter, "N")
p.end()
return QIcon(px)
@staticmethod
def _load_custom_icon_path() -> Optional[Path]:
# 开发环境优先读取项目里的 icon.jpg;
# 打包后优先读取 .app/Contents/Resources 里的 icns。
candidates = [
Path(__file__).resolve().parent / "icon.png",
Path(__file__).resolve().parent / "icon.jpg",
Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) / "icon.png",
Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) / "icon.jpg",
Path(sys.executable).resolve().parent.parent / "Resources" / "QuickNote.icns",
]
for icon_path in candidates:
if icon_path.exists():
return icon_path
return None
@staticmethod
def _build_rounded_icon(
icon_path: Path, canvas_size: int, corner_ratio: float, padding_ratio: float
) -> Optional[QIcon]:
source = QPixmap(str(icon_path))
if source.isNull():
return None
canvas = QPixmap(canvas_size, canvas_size)
canvas.fill(Qt.transparent)
padding = int(canvas_size * padding_ratio)
target = QRect(padding, padding, canvas_size - 2 * padding, canvas_size - 2 * padding)
radius = target.width() * corner_ratio
painter = QPainter(canvas)
painter.setRenderHint(QPainter.Antialiasing)
painter.setRenderHint(QPainter.SmoothPixmapTransform)
path = QPainterPath()
path.addRoundedRect(QRectF(target), float(radius), float(radius))
painter.setClipPath(path)
painter.drawPixmap(target, source)
painter.end()
return QIcon(canvas)
@staticmethod
def _create_tray_icon(custom_icon_path: Optional[Path], app_icon: QIcon) -> QIcon:
# 菜单栏图标单独处理:避免继承 App 图标的额外留白
source_icon = app_icon
if custom_icon_path is not None:
if custom_icon_path.suffix.lower() == ".icns":
icns_icon = QIcon(str(custom_icon_path))
if not icns_icon.isNull():
source_icon = icns_icon
else:
tray_icon = App._build_rounded_icon(
custom_icon_path, canvas_size=128, corner_ratio=0.2, padding_ratio=0.0
)
if tray_icon is not None:
source_icon = tray_icon
source = source_icon.pixmap(128, 128)
if source.isNull():
return source_icon