Repository navigation
Expand file tree
/
Copy pathfloat_ball_line.py
More file actions
1564 lines (1361 loc) · 65.6 KB
/
Copy pathfloat_ball_line.py
File metadata and controls
1564 lines (1361 loc) · 65.6 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 sys
import os
import subprocess
import math
import json
import time
import threading
# 使用环境变量抑制PyQt5的警告
os.environ['QT_LOGGING_RULES'] = '*.warning=false;*.critical=false'
# 更直接地抑制所有DeprecationWarning
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# 首先导入Qt核心模块,确保在创建QApplication前设置高DPI属性
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
# 设置高DPI缩放属性,必须在创建QApplication之前设置
sys.argv += ['--no-sandbox']
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
# 导入其他模块
import cv2
import numpy as np
from PyQt5.QtWidgets import (QWidget, QLabel, QDesktopWidget, QMainWindow,
QLineEdit, QHBoxLayout, QVBoxLayout, QPushButton, QFrame, QTextEdit, QMenu, QAction)
from PyQt5.QtCore import QTimer, QPropertyAnimation, QEasingCurve, QRect, QPoint, pyqtSignal, QObject, Qt
from PyQt5.QtGui import QPixmap, QPainter, QBrush, QPen, QColor, QGuiApplication, QScreen, QIcon
# 尝试导入markdown库,如果没有则使用简单的文本格式
markdown_available = False
try:
import markdown
markdown_available = True
except ImportError:
print("未找到markdown库,将使用纯文本显示。请安装markdown库以支持markdown格式。")
# 用于进程间通信的文件路径
INPUT_FILE = "data/input_message.json"
OUTPUT_FILE = "data/output_message.json"
# 用于控制悬浮球输入框禁用状态的标志文件路径
INPUT_DISABLE_FLAG = "data/input_disabled.flag"
class MessageCommunicator(QObject):
"""消息通信器,负责与test_float.py进行通信"""
response_received = pyqtSignal(str)
def __init__(self):
super().__init__()
self.running = False
self.listener_thread = None
self.last_output_time = 0
self.current_request_id = None
def start(self):
"""启动通信器"""
self.running = True
self.listener_thread = threading.Thread(target=self.listen_for_responses)
self.listener_thread.daemon = True
self.listener_thread.start()
def stop(self):
"""停止通信器"""
self.running = False
if self.listener_thread:
self.listener_thread.join(timeout=1.0)
def send_message(self, message, screenshot_filename=None):
"""发送消息到test_float.py"""
try:
# 确保数据目录存在
if not os.path.exists("data"):
os.makedirs("data")
# 创建请求ID
request_id = str(time.time())
self.current_request_id = request_id
# 构建消息数据
data = {
'request_id': request_id,
'content': message,
'timestamp': time.time()
}
# 添加缩略图文件名(如果有)
if screenshot_filename:
data['screenshot_filename'] = screenshot_filename
print(f"缩略图文件名已添加: {screenshot_filename}")
# 写入输入文件
with open(INPUT_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
print(f"消息已发送: {message}")
return True
except Exception as e:
print(f"发送消息失败: {e}")
return False
def listen_for_responses(self):
"""监听test_float.py的响应,任何时候OUTPUT_FILE内容被修改都会显示"""
while self.running:
try:
# 检查输出文件是否存在且有更新
if os.path.exists(OUTPUT_FILE):
file_time = os.path.getmtime(OUTPUT_FILE)
if file_time > self.last_output_time:
# 读取响应消息
with open(OUTPUT_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
# 直接获取content,不检查request_id,确保任何修改都能显示
response = data.get('content', '')
if response: # 确保内容不为空
print(f"检测到OUTPUT_FILE更新,显示内容: {response}")
# 通过信号发送响应
self.response_received.emit(response)
# 记录最后读取时间
self.last_output_time = file_time
except Exception as e:
print(f"监听响应时出错: {e}")
# 短暂休眠,减少CPU占用
time.sleep(0.1)
# 创建全局消息通信器实例
comm_manager = MessageCommunicator()
class TrajectoryWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_ShowWithoutActivating)
self.screen_geometry = None
def set_screen(self, screen_geometry):
self.screen_geometry = screen_geometry
self.setGeometry(screen_geometry)
def update_trajectory(self, points):
self.trajectory_points = points[:]
self.update()
def paintEvent(self, event):
if not hasattr(self, 'trajectory_points') or not self.trajectory_points:
return
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
if len(self.trajectory_points) > 1:
total_points = len(self.trajectory_points)
for i in range(total_points - 1):
age_ratio = i / (total_points - 1)
alpha = int(255 * (1 - age_ratio * 0.7))
pen = QPen(QColor(30, 144, 255, alpha), 4)
painter.setPen(pen)
if self.screen_geometry:
p1 = QPoint(self.trajectory_points[i].x() - self.screen_geometry.x(),
self.trajectory_points[i].y() - self.screen_geometry.y())
p2 = QPoint(self.trajectory_points[i + 1].x() - self.screen_geometry.x(),
self.trajectory_points[i + 1].y() - self.screen_geometry.y())
painter.drawLine(p1, p2)
class ScreenshotThumbnail(QWidget):
def __init__(self, image_path, parent=None):
super().__init__(parent)
self.image_path = image_path
self.parent_input = parent
self.init_ui()
def init_ui(self):
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(5)
# 创建图片标签
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setStyleSheet("background-color: rgba(68, 68, 68, 0.9); border-radius: 4px;")
# 创建删除按钮
self.delete_btn = QPushButton()
self.delete_btn.setFixedSize(16, 16)
self.delete_btn.setStyleSheet("""
QPushButton {
background-color: #ff4444;
color: white;
border-radius: 8px;
font-weight: bold;
}
QPushButton:hover {
background-color: #cc0000;
}
""")
self.delete_btn.setText("×")
self.delete_btn.clicked.connect(self.delete_thumbnail)
layout.addWidget(self.image_label, alignment=Qt.AlignLeft)
layout.addWidget(self.delete_btn, alignment=Qt.AlignTop)
self.setLayout(layout)
# 加载并缩放图片
self.load_and_scale_image()
def load_and_scale_image(self):
if os.path.exists(self.image_path):
pixmap = QPixmap(self.image_path)
if not pixmap.isNull():
# 获取输入框宽度作为参考
max_size = self.parent_input.width() // 2
# 计算缩放比例
width = pixmap.width()
height = pixmap.height()
if width > height:
if width > max_size:
scale = max_size / width
new_width = max_size
new_height = int(height * scale)
else:
new_width = width
new_height = height
else:
if height > max_size:
scale = max_size / height
new_height = max_size
new_width = int(width * scale)
else:
new_width = width
new_height = height
scaled_pixmap = pixmap.scaled(new_width, new_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.image_label.setPixmap(scaled_pixmap)
self.setFixedSize(new_width + 20, new_height) # +20 为删除按钮留出空间
def delete_thumbnail(self):
# 删除缩略图和对应的图片文件
if os.path.exists(self.image_path):
try:
os.remove(self.image_path)
print(f"图片已删除: {self.image_path}")
except Exception as e:
print(f"删除图片时出错: {e}")
# 通知父窗口更新状态
if self.parent_input and hasattr(self.parent_input, 'thumbnail_deleted'):
self.parent_input.thumbnail_deleted()
self.hide()
self.deleteLater()
class StyledInputWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.screenshot_thumbnail = None
self.init_ui()
def init_ui(self):
self.setWindowTitle("美观输入框")
base_width, base_height = 280, 40
scaled_width, scaled_height = self.get_scaled_size(base_width, base_height)
self.setGeometry(0, 0, scaled_width, scaled_height)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
input_container = QFrame()
scaled_radius, scaled_padding = self.get_scaled_size(8, 6)
input_container.setStyleSheet(f"""
QFrame {{
background-color: #333;
border-radius: {scaled_radius}px;
padding: {scaled_padding}px;
margin: {self.get_scaled_size(5, 5)[0]}px;
}}
""")
input_layout = QHBoxLayout()
input_layout.setContentsMargins(0, 0, 0, 0)
input_layout.setSpacing(self.get_scaled_size(4, 4)[0])
self.input_line = QLineEdit()
self.input_line.setPlaceholderText("与 start_AI 交流")
scaled_border_radius = self.get_scaled_size(4, 4)[0]
scaled_padding_lr, scaled_padding_tb = self.get_scaled_size(6, 4)
input_font_size = self.get_scaled_font_size(12)
self.input_line.setStyleSheet(f"""
QLineEdit {{
background-color: #444;
border: 1px solid #666;
border-radius: {scaled_border_radius}px;
padding: {scaled_padding_tb}px {scaled_padding_lr}px;
color: white;
font-size: {input_font_size}px;
}}
QLineEdit:focus {{
border-color: #0078d4;
outline: none;
}}
""")
self.input_line.returnPressed.connect(self.handle_return_pressed)
input_layout.addWidget(self.input_line)
input_container.setLayout(input_layout)
layout.addWidget(input_container)
self.setLayout(layout)
def get_scaled_size(self, base_width, base_height):
if self.parent():
try:
parent = self.parent()
current_screen = parent.screen() if hasattr(parent, 'screen') else None
if not current_screen and hasattr(parent, 'get_current_screen'):
screen_rect = parent.get_current_screen()
for screen in QApplication.screens():
if screen.geometry() == screen_rect:
current_screen = screen
break
if not current_screen:
current_screen = QApplication.primaryScreen()
if current_screen:
scale_factor = current_screen.logicalDotsPerInch() / 96.0
return int(base_width * scale_factor), int(base_height * scale_factor)
except Exception as e:
print(f"Error getting scaled size: {e}")
return base_width, base_height
def get_scaled_font_size(self, base_size):
if self.parent():
try:
parent = self.parent()
current_screen = parent.screen() if hasattr(parent, 'screen') else None
if not current_screen and hasattr(parent, 'get_current_screen'):
screen_rect = parent.get_current_screen()
for screen in QApplication.screens():
if screen.geometry() == screen_rect:
current_screen = screen
break
if not current_screen:
current_screen = QApplication.primaryScreen()
if current_screen:
scale_factor = current_screen.logicalDotsPerInch() / 96.0
return int(base_size * scale_factor)
except Exception as e:
print(f"Error getting scaled font size: {e}")
return base_size
def hide_input(self):
self.hide()
# 同时隐藏缩略图
self.hide_thumbnail()
if self.parent():
self.parent().is_input_visible = False
self.parent().is_hovered_on_input = False
def hide_thumbnail(self):
if self.screenshot_thumbnail:
self.screenshot_thumbnail.hide()
self.screenshot_thumbnail.deleteLater()
self.screenshot_thumbnail = None
def set_scaled_geometry(self, x, y):
if self.parent():
current_screen = self.parent().get_current_screen()
if current_screen:
self.move(x, y)
# 调整缩略图位置
if self.screenshot_thumbnail:
thumbnail_y = y + self.height() + 5 # 输入框下方5像素
self.screenshot_thumbnail.move(x, thumbnail_y)
return
self.move(x, y)
def handle_return_pressed(self):
# 检查输入是否被禁用
if os.path.exists(INPUT_DISABLE_FLAG):
# 显示禁用提示
if self.parent() and hasattr(self.parent(), 'display_widget') and self.parent().display_widget:
self.parent().display_widget.waiting_input_label.setText("语音模式下禁用输入")
self.parent().display_widget.show_waiting_message()
return
# 检查父窗口是否处于等待状态
if self.parent() and hasattr(self.parent(), 'is_waiting') and self.parent().is_waiting:
# 显示等待提示
if self.parent() and hasattr(self.parent(), 'display_widget') and self.parent().display_widget:
self.parent().display_widget.show_waiting_message()
return
text = self.input_line.text()
if text:
if self.parent() and hasattr(self.parent(), 'display_widget') and self.parent().display_widget:
self.parent().display_widget.show_message(text)
# 设置父窗口为等待状态
if self.parent():
self.parent().is_waiting = True
# 检查是否有缩略图,并获取文件名
screenshot_filename = None
if hasattr(self, 'screenshot_thumbnail') and self.screenshot_thumbnail:
# 假设缩略图有image_path属性存储文件路径
if hasattr(self.screenshot_thumbnail, 'image_path'):
screenshot_filename = os.path.basename(self.screenshot_thumbnail.image_path)
print(f"找到缩略图文件: {screenshot_filename}")
# 复制截图到test.png并删除原test2.png
original_path = self.screenshot_thumbnail.image_path
if original_path == "imgs/test2.png":
try:
# 确保imgs目录存在
if not os.path.exists("imgs"):
os.makedirs("imgs")
# 复制图片到test.png
import shutil
new_path = "imgs/test.png"
shutil.copy2(original_path, new_path)
print(f"图片已复制到: {new_path}")
# 删除原图片
if os.path.exists(original_path):
os.remove(original_path)
print(f"原图片已删除: {original_path}")
# 更新文件名
screenshot_filename = "test.png"
except Exception as e:
print(f"处理图片时出错: {e}")
# 通过通信管理器发送消息,包含缩略图文件名
comm_manager.send_message(text, screenshot_filename)
# 发送消息后隐藏缩略图
self.hide_thumbnail()
self.input_line.clear()
# def write_text_to_file(self, text):
# try:
# if not os.path.exists("data"):
# os.makedirs("data")
# with open("user_content_text.txt", "a", encoding="utf-8") as f:
# f.write(text + "\n")
# print(f"文字已写入文件: {text}")
# except Exception as e:
# print(f"写入文件时出错: {e}")
def show_screenshot_thumbnail(self, image_path):
# 如果已有缩略图,先删除
self.hide_thumbnail()
# 创建新的缩略图
self.screenshot_thumbnail = ScreenshotThumbnail(image_path, self)
# 放置在输入框下方
input_pos = self.pos()
thumbnail_x = input_pos.x()
thumbnail_y = input_pos.y() + self.height() + 5 # 输入框下方5像素
self.screenshot_thumbnail.move(thumbnail_x, thumbnail_y)
self.screenshot_thumbnail.show()
def thumbnail_deleted(self):
# 通知父窗口截图已删除
if self.parent() and hasattr(self.parent(), 'on_thumbnail_deleted'):
self.parent().on_thumbnail_deleted()
self.screenshot_thumbnail = None
class StyledDisplayWidget(QWidget):
def __init__(self, parent=None, saved_content=""):
super().__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.display_text = saved_content # 初始化时使用保存的内容
# 高度调整相关变量
self.is_resizing = False
self.resize_start_y = 0
self.min_height = 100 # 最小高度限制
self.init_ui()
# 连接通信器的响应信号
comm_manager.response_received.connect(self.on_response_received)
def init_ui(self):
self.setWindowTitle("显示框")
base_width, base_height = 280, 200
scaled_width, scaled_height = self.get_scaled_size(base_width, base_height)
self.setGeometry(0, 0, scaled_width, scaled_height)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
display_container = QFrame()
scaled_radius, scaled_padding = self.get_scaled_size(8, 6)
display_container.setStyleSheet(f"""
QFrame {{
background-color: #333;
border-radius: {scaled_radius}px;
padding: {scaled_padding}px;
margin: {self.get_scaled_size(5, 5)[0]}px;
border: 0.2px solid #555; /* 更细的边框 */
}}
""")
# 使用QTextEdit支持文本选择和复制
self.display_text_edit = QTextEdit()
self.display_text_edit.setReadOnly(True) # 设置为只读
self.display_text_edit.setUndoRedoEnabled(False)
scaled_border_radius = self.get_scaled_size(4, 4)[0]
scaled_padding_lr, scaled_padding_tb = self.get_scaled_size(6, 4)
input_font_size = self.get_scaled_font_size(12)
self.display_text_edit.setStyleSheet(f"""
QTextEdit {{
background-color: #444;
border: 0.5px solid #555; /* 更细的边框 */
border-radius: {scaled_border_radius}px;
padding: {scaled_padding_tb}px {scaled_padding_lr}px;
color: white;
font-size: {input_font_size}px;
}}
""")
self.display_text_edit.setWordWrapMode(True)
self.display_text_edit.setAlignment(Qt.AlignTop | Qt.AlignLeft)
# 启用HTML支持以显示markdown
self.display_text_edit.setAcceptRichText(True)
# 初始化时设置保存的内容
if self.display_text:
self.set_display_content(self.display_text)
else:
self.display_text_edit.clear()
self.waiting_label = QLabel("等待中...\n请快速将鼠标移动到被控窗口并单击😁")
self.waiting_label.setStyleSheet(f"""
QLabel {{
background-color: #444;
border: 1px solid #666;
border-radius: {self.get_scaled_size(4, 4)[0]}px;
padding: {self.get_scaled_size(6, 4)[1]}px {self.get_scaled_size(6, 4)[0]}px;
color: white;
font-size: {self.get_scaled_font_size(12)}px;
}}
""")
self.waiting_label.setAlignment(Qt.AlignCenter)
self.waiting_label.hide()
# 等待提示标签
self.waiting_input_label = QLabel("等待时不能上传指令")
self.waiting_input_label.setStyleSheet(f"""
QLabel {{
background-color: #444;
border: 1px solid #ff4444;
border-radius: {self.get_scaled_size(4, 4)[0]}px;
padding: {self.get_scaled_size(6, 4)[1]}px {self.get_scaled_size(6, 4)[0]}px;
color: #ff4444;
font-size: {self.get_scaled_font_size(12)}px;
}}
""")
self.waiting_input_label.setAlignment(Qt.AlignCenter)
self.waiting_input_label.hide()
layout.addWidget(self.display_text_edit)
layout.addWidget(self.waiting_label)
layout.addWidget(self.waiting_input_label)
display_container.setLayout(layout)
main_layout = QVBoxLayout()
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
main_layout.addWidget(display_container)
self.setLayout(main_layout)
def get_scaled_size(self, base_width, base_height):
if self.parent():
try:
parent = self.parent()
current_screen = parent.screen() if hasattr(parent, 'screen') else None
if not current_screen and hasattr(parent, 'get_current_screen'):
screen_rect = parent.get_current_screen()
for screen in QApplication.screens():
if screen.geometry() == screen_rect:
current_screen = screen
break
if not current_screen:
current_screen = QApplication.primaryScreen()
if current_screen:
scale_factor = current_screen.logicalDotsPerInch() / 96.0
return int(base_width * scale_factor), int(base_height * scale_factor)
except Exception as e:
print(f"Error getting scaled size: {e}")
return base_width, base_height
def get_scaled_font_size(self, base_size):
if self.parent():
try:
parent = self.parent()
current_screen = parent.screen() if hasattr(parent, 'screen') else None
if not current_screen and hasattr(parent, 'get_current_screen'):
screen_rect = parent.get_current_screen()
for screen in QApplication.screens():
if screen.geometry() == screen_rect:
current_screen = screen
break
if not current_screen:
current_screen = QApplication.primaryScreen()
if current_screen:
scale_factor = current_screen.logicalDotsPerInch() / 96.0
return int(base_size * scale_factor)
except Exception as e:
print(f"Error getting scaled font size: {e}")
return base_size
def show_message(self, text):
self.display_text = text
self.display_text_edit.setText(text)
self.display_text_edit.hide()
self.waiting_label.setText("等待中...\n请快速将鼠标移动到被控窗口并单击😁")
self.waiting_label.show()
self.waiting_input_label.hide()
#self.wait_timer.start(5000) # 5秒后显示回答
def set_display_content(self, text):
"""设置显示内容,支持markdown格式"""
self.display_text = text
# 创建禁用输入标志文件,确保显示内容后2秒内无法输入
try:
with open(INPUT_DISABLE_FLAG, 'w') as f:
f.write('')
print(f"已创建输入禁用标志,2秒内无法输入")
# 设置2秒后自动删除标志文件,恢复输入功能
QTimer.singleShot(2000, self.remove_disable_flag)
except Exception as e:
print(f"设置输入禁用标志失败: {e}")
if markdown_available:
# 将markdown转换为HTML
html_content = markdown.markdown(text)
# 添加基本的CSS样式以美化显示
styled_html = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {{
color: white;
font-family: Arial, sans-serif;
font-size: 12px;
}}
h1, h2, h3, h4, h5, h6 {{
color: #0078d4;
margin-top: 10px;
margin-bottom: 5px;
}}
p {{
margin: 5px 0;
}}
code {{
background-color: #555;
padding: 2px 4px;
border-radius: 3px;
}}
pre {{
background-color: #555;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}}
blockquote {{
border-left: 3px solid #0078d4;
margin-left: 0;
padding-left: 10px;
color: #aaa;
}}
ul, ol {{
margin: 5px 0;
padding-left: 20px;
}}
</style>
</head>
<body>
{html_content}
</body>
</html>
"""
self.display_text_edit.setHtml(styled_html)
else:
# 不支持markdown时,使用纯文本
self.display_text_edit.setText(text)
def on_response_received(self, response_text):
# 收到响应时显示
self.display_text = response_text
self.waiting_label.hide()
self.set_display_content(response_text)
self.display_text_edit.show()
# 通知父窗口等待状态结束
if self.parent() and hasattr(self.parent(), 'set_waiting_state'):
self.parent().set_waiting_state(False)
# 将内容保存到父窗口
self.parent().saved_display_content = response_text
def show_waiting_message(self):
self.waiting_input_label.show()
QTimer.singleShot(2000, self.hide_waiting_message)
def hide_waiting_message(self):
self.waiting_input_label.hide()
def remove_disable_flag(self):
"""删除输入禁用标志文件,恢复输入功能"""
try:
if os.path.exists(INPUT_DISABLE_FLAG):
os.remove(INPUT_DISABLE_FLAG)
print("已删除输入禁用标志,恢复输入功能")
# 隐藏等待消息标签
if hasattr(self, 'waiting_input_label'):
self.waiting_input_label.hide()
except Exception as e:
print(f"删除输入禁用标志失败: {e}")
def mousePressEvent(self, event):
# 检查是否点击了窗口顶部边缘用于调整高度
if event.button() == Qt.LeftButton and event.pos().y() <= 10:
self.is_resizing = True
self.resize_start_y = event.globalY()
self.setCursor(Qt.SizeVerCursor)
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
# 处理高度调整
if self.is_resizing:
current_y = event.globalY()
delta = self.resize_start_y - current_y
new_height = self.height() + delta
# 确保高度不小于最小值
if new_height >= self.min_height:
self.resize(self.width(), new_height)
self.resize_start_y = current_y
# 调整显示文本框的大小
self.display_text_edit.setMinimumHeight(new_height - 40)
# 更新父窗口中的位置信息
if self.parent() and hasattr(self.parent(), 'update_display_position'):
self.parent().update_display_position()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
# 结束调整大小
if self.is_resizing:
self.is_resizing = False
self.setCursor(Qt.ArrowCursor)
# 保存高度到父窗口
if self.parent() and hasattr(self.parent(), 'saved_display_height'):
self.parent().saved_display_height = self.height()
super().mouseReleaseEvent(event)
def hide_display(self):
self.hide()
if self.parent():
self.parent().is_display_visible = False
# 隐藏时保存内容到父窗口
self.parent().saved_display_content = self.display_text
class FloatingBall(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
self.setup_hover_effects()
self.setup_context_menu() # 添加右键菜单设置
self.move_to_corner()
self.dragging = False
self.drag_position = QPoint()
self.trajectory_points = []
self.trajectory_window = TrajectoryWindow()
self.current_screen = None
self.saved_display_content = "" # 用于保存显示框内容的变量
self.saved_display_height = None # 用于保存显示框高度的变量
self.input_widget = StyledInputWidget(self)
self.display_widget = StyledDisplayWidget(self)
self.is_input_visible = False
self.is_display_visible = False
self.is_hovered_on_input = False
self.is_hovered_on_display = False
self.is_hovered = False
self.last_screen_geometry = None
self.leave_check_timer = QTimer()
self.leave_check_timer.setSingleShot(True)
self.leave_check_timer.timeout.connect(self.check_mouse_leave)
self.is_waiting = False # 等待状态标记
self.screenshot_path = None # 保存当前截图路径
# 边缘隐藏相关属性
self.is_hidden = False # 悬浮球是否隐藏在边缘
self.edge_margin = 10 # 边缘检测的像素范围
self.hidden_width = 8 # 隐藏时显示的宽度,增加可见性
def init_ui(self):
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setAttribute(Qt.WA_NativeWindow)
self.small_size = 50
self.large_size = 50
self.current_size = self.small_size
self.setGeometry(0, 0, self.small_size, self.small_size)
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
# 隐藏时的透明蓝色背景标签 - 使用更醒目的颜色和更高的透明度
self.edge_label = QLabel(self)
self.edge_label.setGeometry(0, 0, 0, 0)
self.edge_label.setStyleSheet("background-color: rgba(0, 120, 215, 180); border-radius: 2px;")
self.edge_label.hide()
# 为边缘标签添加鼠标跟踪
self.edge_label.setMouseTracking(True)
self.load_image()
self.show()
def load_image(self):
img_path = "downloads/圆AI.png"
if os.path.exists(img_path):
pixmap = QPixmap(img_path)
if not pixmap.isNull():
self.original_pixmap = pixmap
self.small_pixmap = self.original_pixmap.scaled(
self.small_size, self.small_size,
Qt.KeepAspectRatio, Qt.SmoothTransformation
)
self.label.setPixmap(self.small_pixmap)
self.label.setGeometry(0, 0, self.small_size, self.small_size)
return
self.create_default_circle()
def create_default_circle(self):
size = max(self.small_size, self.large_size)
pixmap = QPixmap(size, size)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(QBrush(QColor(0, 120, 215)))
painter.setPen(QPen(QColor(0, 120, 215), 2))
painter.drawEllipse(0, 0, size - 1, size - 1)
painter.end()
self.original_pixmap = pixmap
self.small_pixmap = self.original_pixmap.scaled(
self.small_size, self.small_size,
Qt.KeepAspectRatio, Qt.SmoothTransformation
)
self.label.setPixmap(self.small_pixmap)
self.label.setGeometry(0, 0, self.small_size, self.small_size)
def setup_hover_effects(self):
self.setMouseTracking(True)
self.animation = QPropertyAnimation(self, b"geometry")
self.animation.setDuration(300)
self.animation.setEasingCurve(QEasingCurve.OutBack)
def enterEvent(self, event):
# 当鼠标进入边缘标签时恢复悬浮球
if self.is_hidden:
self.restore_from_edge()
self.leave_check_timer.stop()
current_screen = self.get_current_screen()
if self.last_screen_geometry is None or self.last_screen_geometry != current_screen:
self.last_screen_geometry = current_screen
if self.input_widget:
self.input_widget.hide()
if self.display_widget:
self.display_widget.hide()
self.input_widget = StyledInputWidget(self)
# 重新创建显示框时传入保存的内容
self.display_widget = StyledDisplayWidget(self, self.saved_display_content)
self.is_input_visible = False
self.is_display_visible = False
self.is_hovered_on_input = False
self.is_hovered_on_display = False
if not self.is_hovered:
self.is_hovered = True
self.animate_to_large()
self.show_input_components()
def leaveEvent(self, event):
# 只有在非隐藏状态下才启动离开检查
if not self.is_hidden:
self.leave_check_timer.start(50)
def check_mouse_leave(self):
# 检查鼠标是否离开所有相关组件
if not self.underMouse() and \
not (self.input_widget and self.input_widget.underMouse()) and \
not (self.display_widget and self.display_widget.underMouse()) and \
not (self.input_widget and self.input_widget.screenshot_thumbnail and
self.input_widget.screenshot_thumbnail.underMouse()):
self.is_hovered = False
self.animate_to_small()
# 只有当输入框和输入行都没有焦点时才隐藏
if self.input_widget and not self.input_widget.hasFocus() and not self.input_widget.input_line.hasFocus():
# 隐藏前保存显示内容
if self.display_widget:
self.saved_display_content = self.display_widget.display_text
# 关键修改:明确删除缩略图
if self.input_widget:
self.input_widget.hide_thumbnail()
# 隐藏输入框和显示框
self.input_widget.hide()
self.display_widget.hide()
# 更新状态变量
self.is_input_visible = False
self.is_display_visible = False
self.is_hovered_on_input = False
self.is_hovered_on_display = False
# 检查是否需要隐藏到边缘
self.check_and_hide_to_edge()
def on_input_hover_enter(self):
self.leave_check_timer.stop()
self.is_hovered_on_input = True
self.is_hovered = True
# 如果处于隐藏状态,恢复正常显示后再处理悬停逻辑
if self.is_hidden:
self.restore_from_edge()
def on_input_hover_leave(self):
self.leave_check_timer.start(50)
def update_display_position(self):
"""更新显示框位置,当显示框高度改变时调用"""
if not self.is_input_visible:
return
# 获取当前屏幕信息
current_screen = self.get_current_screen()
# 获取各组件尺寸
ball_pos = self.pos()
ball_width = self.width()
ball_height = self.height()
scaled_input_width = self.input_widget.width()
scaled_input_height = self.input_widget.height()
scaled_display_width = self.display_widget.width()
scaled_display_height = self.display_widget.height()
# 重新计算位置
input_x = self.input_widget.x()
input_y = self.input_widget.y()
# 显示框底部 = 输入框顶部(无空隙)
display_x = input_x
display_y = input_y - scaled_display_height
# 边界检查(确保在屏幕内)
if display_y < current_screen.y():
offset = current_screen.y() - display_y
display_y += offset
input_y += offset
if input_y + scaled_input_height > current_screen.y() + current_screen.height():
offset = (input_y + scaled_input_height) - (current_screen.y() + current_screen.height()) + 5
input_y -= offset
display_y -= offset
# 更新位置
self.input_widget.move(input_x, input_y)
self.display_widget.move(display_x, display_y)
def show_input_components(self):
if not self.is_input_visible:
# 获取悬浮球基础信息
ball_pos = self.pos()
ball_width = self.width()
ball_height = self.height()
current_screen = self.get_current_screen()
self.last_screen_geometry = current_screen
# 重新初始化输入框和显示框时传入保存的内容
if hasattr(self, 'input_widget') and self.input_widget: