-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2392 lines (2048 loc) · 87.4 KB
/
main.py
File metadata and controls
2392 lines (2048 loc) · 87.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
# -*- coding: utf-8 -*-
'''
主模块 - 包含AI助手对话框主界面(深色主题)
'''
import os
import sys
import json
from datetime import datetime
from pymol.Qt import QtCore, QtWidgets, QtGui
from . import i18n, config, logger, ai_client, tools, get_update_info, __version__ as PLUGIN_VERSION, markdown_renderer, updater
# 版本号
__version__ = PLUGIN_VERSION
# 颜色定义 - 深色主题
COLORS = {
'bg_dark': '#2D2D2D',
'bg_darker': '#1E1E1E',
'bg_panel': '#404040',
'bg_input': '#4A4A4A',
'bg_message_user': '#2A3F2A',
'bg_message_ai': '#2A3A4A',
'bg_message_think': '#3A3A2A',
'bg_message_tool': '#2A2A3A',
'text_primary': '#FFFFFF',
'text_secondary': '#CCCCCC',
'text_muted': '#888888',
'accent_blue': '#5DADE2',
'accent_green': '#58D68D',
'accent_yellow': '#F5B041',
'accent_purple': '#AF7AC5',
'accent_cyan': '#5DDBE2',
'accent_red': '#E74C3C',
'border': '#555555',
}
class StyledButton(QtWidgets.QPushButton):
"""自定义样式按钮"""
def __init__(self, text, parent=None, accent=False, danger=False):
super().__init__(text, parent)
self.accent = accent
self.danger = danger
self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.update_style()
def update_style(self):
if self.danger:
self.setStyleSheet("""
QPushButton {
background-color: #E74C3C;
color: #FFFFFF;
border: none;
border-radius: 20px;
padding: 10px 30px;
font-size: 14px;
font-weight: bold;
}
QPushButton:hover {
background-color: #C0392B;
}
QPushButton:pressed {
background-color: #A93226;
}
QPushButton:disabled {
background-color: #555555;
color: #888888;
}
""")
elif self.accent:
self.setStyleSheet("""
QPushButton {
background-color: #5DADE2;
color: #2D2D2D;
border: none;
border-radius: 20px;
padding: 10px 30px;
font-size: 14px;
font-weight: bold;
}
QPushButton:hover {
background-color: #76C5F0;
}
QPushButton:pressed {
background-color: #4A9BC4;
}
QPushButton:disabled {
background-color: #555555;
color: #888888;
}
""")
else:
self.setStyleSheet("""
QPushButton {
background-color: #404040;
color: #FFFFFF;
border: 1px solid #555555;
border-radius: 15px;
padding: 8px 20px;
font-size: 13px;
}
QPushButton:hover {
background-color: #555555;
}
QPushButton:pressed {
background-color: #2D2D2D;
}
""")
class MessageWidget(QtWidgets.QFrame):
"""单条消息组件"""
def __init__(self, role, content, images=None, parent=None):
super().__init__(parent)
self.role = role
self.raw_content = content
self.images = images or []
self.setObjectName("messageWidget")
self.setup_ui()
self.set_content(content, self.images)
def setup_ui(self):
# 去掉边框
self.setFrameShape(QtWidgets.QFrame.NoFrame)
self.setLineWidth(0)
layout = QtWidgets.QVBoxLayout(self)
layout.setSpacing(8)
layout.setContentsMargins(15, 12, 15, 12)
# 角色标签
role_text = {
'user': 'User',
'assistant': 'AI',
'thinking': i18n._('thinking'),
'tool': i18n._('using_tool'),
'tool_result': i18n._('tool_result'),
'tool_error': i18n._('tool_error'),
}.get(self.role, self.role)
self.role_label = QtWidgets.QLabel("<b>%s:</b>" % role_text)
if self.role == 'user':
role_color = COLORS['accent_green']
self.bg_color = COLORS['bg_message_user']
elif self.role == 'assistant':
role_color = COLORS['accent_blue']
self.bg_color = COLORS['bg_message_ai']
elif self.role == 'thinking':
role_color = COLORS['accent_yellow']
self.bg_color = COLORS['bg_message_think']
elif self.role in ['tool', 'tool_result', 'tool_error']:
role_color = COLORS['accent_purple']
self.bg_color = COLORS['bg_message_tool']
else:
role_color = COLORS['text_primary']
self.bg_color = COLORS['bg_panel']
self.role_label.setStyleSheet("color: %s; font-size: 14px; background: transparent;" % role_color)
layout.addWidget(self.role_label)
# 图片显示区域
self.image_container = QtWidgets.QWidget()
self.image_layout = QtWidgets.QHBoxLayout(self.image_container)
self.image_layout.setSpacing(8)
self.image_layout.setContentsMargins(0, 0, 0, 0)
self.image_container.hide()
layout.addWidget(self.image_container)
# 内容标签 - 设置为可复制
self.content_label = QtWidgets.QLabel()
self.content_label.setWordWrap(True)
self.content_label.setTextFormat(QtCore.Qt.RichText)
self.content_label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse | QtCore.Qt.TextSelectableByKeyboard)
self.content_label.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.content_label.setStyleSheet("""
QLabel {
color: #FFFFFF;
font-size: 14px;
line-height: 1.6;
background: transparent;
}
QLabel::item:selected {
background-color: #3d8bfd;
}
""")
layout.addWidget(self.content_label)
# 设置背景 - 使用palette而不是stylesheet
self.setStyleSheet("""
#messageWidget {
background-color: %s;
border: none;
border-radius: 12px;
}
""" % self.bg_color)
def set_content(self, content, images=None):
"""设置内容,支持不同颜色的文本和Markdown渲染"""
self.raw_content = content
self.images = images or []
if self.role == 'assistant':
html_content = markdown_renderer.MarkdownRenderer.render(content)
else:
html_content = self._format_text(content)
self.content_label.setText(html_content)
# 显示图片
self._display_images()
def _display_images(self):
"""显示图片"""
# 清除现有图片
while self.image_layout.count():
item = self.image_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
# 添加图片
for img_data in self.images:
pixmap = img_data['pixmap']
# 限制最大尺寸
max_width = 300
max_height = 200
scaled_pixmap = pixmap.scaled(
max_width, max_height,
QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation
)
label = QtWidgets.QLabel()
label.setPixmap(scaled_pixmap)
label.setStyleSheet("""
QLabel {
border: 1px solid #555555;
border-radius: 8px;
padding: 5px;
}
""")
label.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.image_layout.addWidget(label)
self.image_container.setVisible(bool(self.images))
def _format_text(self, text):
"""格式化普通文本,支持不同颜色的文本"""
escaped = text.replace('&', '&').replace('<', '<').replace('>', '>')
lines = escaped.split('\n')
formatted_lines = []
for line in lines:
if line.strip().startswith('使用工具:') or line.strip().startswith('Using tool:'):
formatted_lines.append('<span style="color: #58D68D;">%s</span>' % line)
elif line.strip().startswith('思考:') or line.strip().startswith('Thinking:'):
formatted_lines.append('<span style="color: #F5B041;">%s</span>' % line)
elif any(kw in line for kw in ['成功', '完成', 'success']):
formatted_lines.append('<span style="color: #5DDBE2;">%s</span>' % line)
elif line.strip().startswith('错误:') or line.strip().startswith('Error:'):
formatted_lines.append('<span style="color: #F07178;">%s</span>' % line)
else:
formatted_lines.append(line)
return '<br>'.join(formatted_lines)
def append_content(self, text):
"""追加内容"""
self.set_content(self.raw_content + text)
class ChatWidget(QtWidgets.QWidget):
"""聊天标签页"""
message_sent = QtCore.Signal(str, list)
stop_requested = QtCore.Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.messages = []
self.current_message_widget = None
self.is_thinking = False
self.is_streaming = False
self.loading_dots = 0
self.loading_timer = QtCore.QTimer()
self.loading_timer.timeout.connect(self._update_loading_animation)
self.current_images = []
self.setup_ui()
def setup_ui(self):
layout = QtWidgets.QVBoxLayout(self)
layout.setSpacing(10)
layout.setContentsMargins(15, 15, 15, 15)
# 消息显示区域(带圆角面板)- 使用bg_panel颜色,无边框
self.chat_panel = QtWidgets.QFrame()
self.chat_panel.setStyleSheet("""
QFrame {
background-color: #404040;
border-radius: 15px;
border: none;
}
""")
chat_layout = QtWidgets.QVBoxLayout(self.chat_panel)
chat_layout.setContentsMargins(10, 10, 10, 10)
chat_layout.setSpacing(8)
# 清除按钮
clear_layout = QtWidgets.QHBoxLayout()
clear_layout.addStretch()
self.clear_btn = StyledButton(i18n._('clear_chat'))
self.clear_btn.setFixedSize(85, 30)
self.clear_btn.clicked.connect(self.clear_chat)
clear_layout.addWidget(self.clear_btn)
chat_layout.addLayout(clear_layout)
# 消息滚动区域
scroll = QtWidgets.QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
scroll.setStyleSheet("""
QScrollArea {
border: none;
background: transparent;
}
QScrollBar:vertical {
background: #2D2D2D;
width: 8px;
border-radius: 4px;
}
QScrollBar::handle:vertical {
background: #555555;
border-radius: 4px;
min-height: 30px;
}
QScrollBar::handle:vertical:hover {
background: #888888;
}
""")
# 消息容器 - 使用透明背景
self.messages_container = QtWidgets.QWidget()
self.messages_container.setStyleSheet("background: transparent;")
self.messages_layout = QtWidgets.QVBoxLayout(self.messages_container)
self.messages_layout.setSpacing(10)
self.messages_layout.setContentsMargins(5, 5, 5, 5)
self.messages_layout.addStretch()
# 创建加载指示器(始终在底部)
self._create_loading_indicator()
scroll.setWidget(self.messages_container)
chat_layout.addWidget(scroll)
layout.addWidget(self.chat_panel, stretch=1)
# 输入区域面板
self.input_panel = QtWidgets.QFrame()
self.input_panel.setStyleSheet("""
QFrame {
background-color: #4A4A4A;
border-radius: 15px;
border: none;
}
""")
input_layout = QtWidgets.QVBoxLayout(self.input_panel)
input_layout.setContentsMargins(15, 12, 15, 12)
input_layout.setSpacing(8)
# 图片预览区域
self.image_preview_container = QtWidgets.QWidget()
self.image_preview_layout = QtWidgets.QHBoxLayout(self.image_preview_container)
self.image_preview_layout.setContentsMargins(0, 0, 0, 0)
self.image_preview_layout.setSpacing(5)
self.image_preview_container.hide()
input_layout.addWidget(self.image_preview_container)
# 输入框和图片导入按钮的水平布局
input_row_layout = QtWidgets.QHBoxLayout()
# 输入框
self.input_text = QtWidgets.QTextEdit()
self.input_text.setPlaceholderText(i18n._('input_placeholder'))
self.input_text.setMaximumHeight(80)
self.input_text.setStyleSheet("""
QTextEdit {
background-color: transparent;
color: #FFFFFF;
border: none;
font-size: 14px;
line-height: 1.5;
}
QTextEdit::placeholder {
color: #888888;
}
""")
input_row_layout.addWidget(self.input_text)
# 图片导入按钮
self.image_btn = QtWidgets.QPushButton()
self.image_btn.setFixedSize(40, 40)
self.image_btn.setStyleSheet("""
QPushButton {
background-color: #4A4A4A;
border: 1px solid #555555;
border-radius: 8px;
padding: 5px;
color: #5DADE2;
font-size: 20px;
}
QPushButton:hover {
background-color: #555555;
border-color: #5DADE2;
color: #76C5F0;
}
QPushButton:pressed {
background-color: #3A3A3A;
}
""")
self.image_btn.setText("🖼️")
self.image_btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.image_btn.clicked.connect(self.import_image)
self.image_btn.setToolTip(i18n._('import_image'))
input_row_layout.addWidget(self.image_btn)
input_layout.addLayout(input_row_layout)
# 发送按钮(右下角)
btn_layout = QtWidgets.QHBoxLayout()
btn_layout.addStretch()
self.send_btn = StyledButton(i18n._('send_button'), accent=True)
self.send_btn.setFixedSize(100, 40)
self.send_btn.clicked.connect(self.on_send_clicked)
btn_layout.addWidget(self.send_btn)
input_layout.addLayout(btn_layout)
layout.addWidget(self.input_panel)
# 事件过滤器
self.input_text.installEventFilter(self)
def eventFilter(self, obj, event):
if obj == self.input_text:
event_type = event.type()
if event_type == QtCore.QEvent.Type.KeyPress:
if event.key() == QtCore.Qt.Key_Return and not event.modifiers() & QtCore.Qt.ShiftModifier:
self.on_send_clicked()
return True
elif event_type == 6:
mime_data = event.mimeData()
if mime_data.hasImage():
self.handle_pasted_image(mime_data.imageData())
return True
return super().eventFilter(obj, event)
def on_send_clicked(self):
"""发送按钮点击"""
if self.is_streaming:
self.stop_requested.emit()
return
text = self.input_text.toPlainText().strip()
if text or self.current_images:
# 在清空 current_images 之前,先创建副本用于发送
images_to_send = list(self.current_images)
self.add_message('user', text, self.current_images)
self.input_text.clear()
self.clear_images()
self.message_sent.emit(text, images_to_send)
self.set_streaming_state(True)
def import_image(self):
"""导入图片"""
filename, _ = QtWidgets.QFileDialog.getOpenFileName(
self, i18n._('import_image'), "",
"Image Files (*.png *.jpg *.jpeg *.bmp *.gif *.webp)"
)
if filename:
pixmap = QtGui.QPixmap(filename)
if not pixmap.isNull():
self.add_image_to_current(pixmap)
def handle_pasted_image(self, image_data):
"""处理粘贴的图片"""
if isinstance(image_data, QtGui.QPixmap):
if not image_data.isNull():
self.add_image_to_current(image_data)
def add_image_to_current(self, pixmap):
"""添加图片到当前图片列表"""
# 缩放图片以适应预览
scaled_pixmap = pixmap.scaled(100, 100, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
# 保存原始图片数据(使用原图,不要用预览图)
import base64
buffer = QtCore.QBuffer()
buffer.open(QtCore.QIODevice.WriteOnly)
pixmap.save(buffer, 'PNG')
image_base64 = bytes(buffer.data())
buffer.close()
self.current_images.append({
'pixmap': pixmap,
'preview': scaled_pixmap,
'data': image_base64
})
self.update_image_preview()
def update_image_preview(self):
"""更新图片预览"""
# 清除现有预览
while self.image_preview_layout.count():
item = self.image_preview_layout.takeAt(0)
if item.widget():
item.widget().deleteLater()
# 添加图片预览
for i, img_data in enumerate(self.current_images):
label = QtWidgets.QLabel()
label.setPixmap(img_data['preview'])
label.setStyleSheet("""
QLabel {
border: 1px solid #555555;
border-radius: 5px;
padding: 2px;
}
""")
# 添加删除按钮
container = QtWidgets.QWidget()
container.setStyleSheet("background: transparent;")
container_layout = QtWidgets.QVBoxLayout(container)
container_layout.setContentsMargins(0, 0, 0, 0)
container_layout.setSpacing(2)
delete_btn = QtWidgets.QPushButton("×")
delete_btn.setFixedSize(20, 20)
delete_btn.setStyleSheet("""
QPushButton {
background-color: #E74C3C;
color: white;
border: none;
border-radius: 10px;
font-size: 14px;
font-weight: bold;
}
QPushButton:hover {
background-color: #C0392B;
}
""")
delete_btn.clicked.connect(lambda idx=i: self.remove_image(idx))
wrapper = QtWidgets.QWidget()
wrapper.setStyleSheet("background: transparent;")
wrapper_layout = QtWidgets.QVBoxLayout(wrapper)
wrapper_layout.setContentsMargins(0, 0, 0, 0)
wrapper_layout.setSpacing(0)
wrapper_layout.addWidget(label)
wrapper_layout.addWidget(delete_btn, alignment=QtCore.Qt.AlignRight)
self.image_preview_layout.addWidget(wrapper)
self.image_preview_container.setVisible(bool(self.current_images))
def remove_image(self, index):
"""移除图片"""
if 0 <= index < len(self.current_images):
del self.current_images[index]
self.update_image_preview()
def clear_images(self):
"""清除所有图片"""
self.current_images.clear()
self.update_image_preview()
def update_vision_mode(self, is_vision_model):
"""根据配置更新视觉模式"""
self.image_btn.setVisible(is_vision_model)
# 如果不是视觉模式,清除当前图片
if not is_vision_model and self.current_images:
self.clear_images()
def set_streaming_state(self, streaming):
"""设置流式状态"""
self.is_streaming = streaming
if streaming:
self.send_btn.setText(i18n._('stop_button'))
self.send_btn.accent = False
self.send_btn.danger = True
self.send_btn.update_style()
else:
self.send_btn.setText(i18n._('send_button'))
self.send_btn.accent = True
self.send_btn.danger = False
self.send_btn.update_style()
def _update_loading_animation(self):
"""更新加载动画 - 旋转指示器"""
spinner_chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
self.loading_dots = (self.loading_dots + 1) % len(spinner_chars)
spinner = spinner_chars[self.loading_dots]
loading_text = "%s %s" % (spinner, i18n._('loading'))
self.loading_indicator.set_content(loading_text)
def _create_loading_indicator(self):
"""创建加载指示器(始终在底部)"""
self.loading_indicator = MessageWidget('thinking', i18n._('loading'))
self.loading_indicator.hide()
# 插入到 stretch 之前(最后一个位置)
self.messages_layout.insertWidget(self.messages_layout.count() - 1, self.loading_indicator)
def show_loading(self):
"""显示加载指示器"""
self.loading_indicator.show()
self.loading_dots = 0
self.loading_timer.start(80)
self.scroll_to_bottom()
def hide_loading(self):
"""隐藏加载指示器"""
self.loading_timer.stop()
self.loading_indicator.hide()
def add_message(self, role, content, images=None):
"""添加消息 - 插入到加载指示器之前"""
msg_widget = MessageWidget(role, content, images)
# 插入到倒数第二个位置(加载指示器之前)
insert_pos = self.messages_layout.count() - 2
if insert_pos < 0:
insert_pos = 0
self.messages_layout.insertWidget(insert_pos, msg_widget)
self.messages.append({'role': role, 'widget': msg_widget, 'images': images})
self.current_message_widget = msg_widget
self.scroll_to_bottom()
return msg_widget
def start_message(self, role):
"""开始一条新消息"""
self.current_message_widget = self.add_message(role, '')
return self.current_message_widget
def append_to_current(self, text):
"""追加到当前消息"""
if self.current_message_widget:
self.current_message_widget.append_content(text)
self.scroll_to_bottom()
def scroll_to_bottom(self):
"""滚动到底部"""
QtCore.QTimer.singleShot(50, self._do_scroll)
def _do_scroll(self):
if self.messages_container.parent():
scroll = self.messages_container.parent().parent()
if isinstance(scroll, QtWidgets.QScrollArea):
scrollbar = scroll.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
def clear_chat(self):
"""清空对话"""
reply = QtWidgets.QMessageBox.question(
self,
i18n._('clear_chat'),
i18n._('confirm_clear_chat'),
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.Yes:
for msg in self.messages:
msg['widget'].deleteLater()
self.messages.clear()
self.current_message_widget = None
def get_messages_for_api(self):
"""获取API用的消息历史"""
api_messages = []
for msg in self.messages:
role = msg['role']
if role in ['user', 'assistant']:
api_messages.append({
'role': role,
'content': msg['widget'].raw_content
})
return api_messages
class ConfigWidget(QtWidgets.QWidget):
"""配置标签页 - 支持 LiteLLM 多提供商"""
config_changed = QtCore.Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.current_config_name = None
self.labels = {}
self.setup_ui()
self.load_configs()
def update_language(self):
"""更新界面语言"""
if hasattr(self, 'labels'):
self.labels.get('list_label').setText(i18n._('saved_configs'))
self.labels.get('name_label').setText(i18n._('name'))
self.labels.get('provider_label').setText(i18n._('provider'))
self.labels.get('url_label').setText(i18n._('api_url'))
self.labels.get('key_label').setText(i18n._('api_key'))
self.labels.get('model_label').setText(i18n._('model'))
self.labels.get('version_label').setText(i18n._('api_version'))
self.labels.get('temp_label').setText(i18n._('temperature'))
self.labels.get('tokens_label').setText(i18n._('max_tokens'))
self.labels.get('timeout_label').setText(i18n._('timeout'))
if hasattr(self, 'reasoning_checkbox'):
self.reasoning_checkbox.setText(i18n._('reasoning_model'))
if hasattr(self, 'vision_checkbox'):
self.vision_checkbox.setText(i18n._('vision_model'))
if hasattr(self, 'current_checkbox'):
self.current_checkbox.setText(i18n._('set_as_current'))
if hasattr(self, 'advanced_toggle'):
self.advanced_toggle.setText(i18n._('show_advanced'))
if hasattr(self, 'new_btn'):
self.new_btn.setText(i18n._('new_button'))
if hasattr(self, 'save_btn'):
self.save_btn.setText(i18n._('save_button'))
if hasattr(self, 'delete_btn'):
self.delete_btn.setText(i18n._('delete_button'))
if hasattr(self, 'test_btn'):
self.test_btn.setText(i18n._('test_connection'))
if hasattr(self, 'import_btn'):
self.import_btn.setText(i18n._('import_button'))
if hasattr(self, 'export_btn'):
self.export_btn.setText(i18n._('export_button'))
self.update_provider_combo()
self.load_configs()
def update_provider_combo(self):
"""更新提供商下拉框"""
current_provider = self.provider_combo.currentData()
self.provider_combo.blockSignals(True)
self.provider_combo.clear()
for provider_id in config.get_provider_list():
provider_info = config.get_provider_info(provider_id)
self.provider_combo.addItem(provider_info['name'], provider_id)
idx = self.provider_combo.findData(current_provider)
if idx >= 0:
self.provider_combo.setCurrentIndex(idx)
self.provider_combo.blockSignals(False)
def setup_ui(self):
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.setContentsMargins(20, 20, 20, 20)
main_layout.setSpacing(15)
panel = QtWidgets.QFrame()
panel.setStyleSheet("""
QFrame {
background-color: #404040;
border-radius: 15px;
border: none;
}
""")
panel_layout = QtWidgets.QVBoxLayout(panel)
panel_layout.setContentsMargins(25, 20, 25, 20)
panel_layout.setSpacing(12)
self.labels['list_label'] = QtWidgets.QLabel(i18n._('saved_configs'))
self.labels['list_label'].setStyleSheet("color: #CCCCCC; font-size: 14px;")
panel_layout.addWidget(self.labels['list_label'])
self.config_list = QtWidgets.QListWidget()
self.config_list.setMaximumHeight(80)
self.config_list.setStyleSheet("""
QListWidget {
background-color: #4A4A4A;
color: #FFFFFF;
border: none;
border-radius: 8px;
padding: 3px;
font-size: 13px;
}
QListWidget::item {
padding: 6px;
border-radius: 4px;
}
QListWidget::item:selected {
background-color: #5DADE2;
color: #2D2D2D;
}
QListWidget::item:hover {
background-color: #555555;
}
""")
self.config_list.itemClicked.connect(self.on_config_selected)
panel_layout.addWidget(self.config_list)
line_style = """
QLineEdit {
background-color: #4A4A4A;
color: #FFFFFF;
border: none;
border-radius: 8px;
padding: 8px 12px;
font-size: 13px;
}
QLineEdit:focus {
border: 2px solid #5DADE2;
}
QLineEdit:disabled {
background-color: #3A3A3A;
color: #888888;
}
"""
combo_style = """
QComboBox {
background-color: #4A4A4A;
color: #FFFFFF;
border: none;
border-radius: 8px;
padding: 8px 12px;
font-size: 13px;
}
QComboBox::drop-down {
border: none;
width: 25px;
}
QComboBox::down-arrow {
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 6px solid #CCCCCC;
margin-right: 8px;
}
QComboBox QAbstractItemView {
background-color: #4A4A4A;
color: #FFFFFF;
selection-background-color: #5DADE2;
selection-color: #2D2D2D;
border: 1px solid #555555;
border-radius: 4px;
}
QComboBox:disabled {
background-color: #3A3A3A;
color: #888888;
}
"""
form_layout = QtWidgets.QGridLayout()
form_layout.setSpacing(10)
form_layout.setColumnStretch(1, 1)
row = 0
self.labels['name_label'] = QtWidgets.QLabel(i18n._('name'))
self.labels['name_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.name_edit = QtWidgets.QLineEdit()
self.name_edit.setPlaceholderText("e.g., My GPT-4")
self.name_edit.setStyleSheet(line_style)
form_layout.addWidget(self.labels['name_label'], row, 0)
form_layout.addWidget(self.name_edit, row, 1)
row += 1
self.labels['provider_label'] = QtWidgets.QLabel(i18n._('provider'))
self.labels['provider_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.provider_combo = QtWidgets.QComboBox()
self.provider_combo.setStyleSheet(combo_style)
for provider_id in config.get_provider_list():
provider_info = config.get_provider_info(provider_id)
self.provider_combo.addItem(provider_info['name'], provider_id)
self.provider_combo.currentIndexChanged.connect(self.on_provider_changed)
form_layout.addWidget(self.labels['provider_label'], row, 0)
form_layout.addWidget(self.provider_combo, row, 1)
row += 1
self.labels['model_label'] = QtWidgets.QLabel(i18n._('model'))
self.labels['model_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.model_combo = QtWidgets.QComboBox()
self.model_combo.setEditable(True)
self.model_combo.setStyleSheet(combo_style)
form_layout.addWidget(self.labels['model_label'], row, 0)
form_layout.addWidget(self.model_combo, row, 1)
row += 1
self.labels['url_label'] = QtWidgets.QLabel(i18n._('api_url'))
self.labels['url_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.url_edit = QtWidgets.QLineEdit()
self.url_edit.setPlaceholderText(i18n._('api_url_placeholder'))
self.url_edit.setStyleSheet(line_style)
form_layout.addWidget(self.labels['url_label'], row, 0)
form_layout.addWidget(self.url_edit, row, 1)
row += 1
self.labels['key_label'] = QtWidgets.QLabel(i18n._('api_key'))
self.labels['key_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.key_edit = QtWidgets.QLineEdit()
self.key_edit.setPlaceholderText(i18n._('api_key_placeholder'))
self.key_edit.setEchoMode(QtWidgets.QLineEdit.Password)
self.key_edit.setStyleSheet(line_style)
form_layout.addWidget(self.labels['key_label'], row, 0)
form_layout.addWidget(self.key_edit, row, 1)
row += 1
self.labels['version_label'] = QtWidgets.QLabel(i18n._('api_version'))
self.labels['version_label'].setStyleSheet("color: #CCCCCC; font-size: 13px;")
self.version_edit = QtWidgets.QLineEdit()
self.version_edit.setPlaceholderText(i18n._('api_version_placeholder'))
self.version_edit.setStyleSheet(line_style)
form_layout.addWidget(self.labels['version_label'], row, 0)
form_layout.addWidget(self.version_edit, row, 1)
panel_layout.addLayout(form_layout)
checkbox_style = """
QCheckBox {
color: #CCCCCC;
font-size: 12px;
spacing: 6px;
}
QCheckBox::indicator {
width: 16px;
height: 16px;
border-radius: 3px;
border: none;
background-color: #4A4A4A;
}
QCheckBox::indicator:checked {
background-color: #5DADE2;
}
"""
self.reasoning_checkbox = QtWidgets.QCheckBox(i18n._('reasoning_model'))
self.reasoning_checkbox.setStyleSheet(checkbox_style)
form_layout.addWidget(self.reasoning_checkbox, row, 0, 1, 2)
row += 1
self.vision_checkbox = QtWidgets.QCheckBox(i18n._('vision_model'))
self.vision_checkbox.setStyleSheet(checkbox_style)
form_layout.addWidget(self.vision_checkbox, row, 0, 1, 2)
row += 1
self.current_checkbox = QtWidgets.QCheckBox(i18n._('set_as_current'))
self.current_checkbox.setStyleSheet(checkbox_style)
form_layout.addWidget(self.current_checkbox, row, 0, 1, 2)
panel_layout.addLayout(form_layout)
self.advanced_toggle = QtWidgets.QPushButton(i18n._('show_advanced'))
self.advanced_toggle.setStyleSheet("""
QPushButton {
background: transparent;
color: #5DADE2;
border: none;
font-size: 12px;
text-align: left;
padding: 3px 0;
}
QPushButton:hover {
color: #7EC8E3;
}
""")
self.advanced_toggle.clicked.connect(self.toggle_advanced)
panel_layout.addWidget(self.advanced_toggle)
self.advanced_frame = QtWidgets.QFrame()
self.advanced_frame.setStyleSheet("QFrame { background: transparent; }")
advanced_layout = QtWidgets.QGridLayout(self.advanced_frame)
advanced_layout.setSpacing(8)
advanced_layout.setColumnStretch(1, 1)
spin_style = """
QSpinBox, QDoubleSpinBox {
background-color: #4A4A4A;
color: #FFFFFF;
border: none;
border-radius: 6px;
padding: 6px 10px;
font-size: 12px;
}
"""