Repository navigation
Expand file tree
/
Copy pathmain_window.py
More file actions
2322 lines (2020 loc) · 93.3 KB
/
Copy pathmain_window.py
File metadata and controls
2322 lines (2020 loc) · 93.3 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
from pathlib import Path
import sys
import time
from PyQt5.QtCore import Qt, QTranslator, QTimer, QLocale, QUrl, QEvent, pyqtSignal
from PyQt5.QtGui import QPixmap, QPainter, QDesktopServices, QIcon
from PyQt5.QtWidgets import QApplication, QStackedWidget, QHBoxLayout, QWidget, QMessageBox, QSplitter, QLabel
from widgets.editor_widget import EditorWidget
from qfluentwidgets import (NavigationInterface, NavigationItemPosition, InfoBar,
isDarkTheme, setTheme, Theme, InfoBarPosition, FluentIcon as FIF, FluentTranslator, MessageBox, NavigationAvatarWidget, MessageBoxBase, SubtitleLabel, CheckBox, Dialog)
from tools.animation_manager import PageTransitionAnimator
from qfluentwidgets.common.config import qconfig
from qframelesswindow import FramelessWindow, StandardTitleBar
from widgets.setting_page import SettingPage
from widgets.home_interface import MainInterface
from tools.font_config import font_config
from tools.session_manager import SessionManager
from tools.logger import setup_global_logging, main_logger
from tools.ssh import SSHWorker
from tools.remote_file_manage import RemoteFileManager, FileManagerHandler
from widgets.sync_widget import SycnWidget
import os
import shutil
import subprocess
from tools.atool import resource_path
from tools.setting_config import SCM
from widgets.ssh_widget import SSHPage, SSHWidget
from tools.icons import My_Icons
from functools import partial
from tools.watching_saved import FileWatchThread
from widgets.side_panel import SidePanelWidget, AutoFitImageLabel
from widgets.expander_bar import ExpanderBar
import magic
import traceback
from tools.check_update import CheckUpdate, get_version
import sys
import os
import pyperclip as cb
import psutil
from widgets.session_dialog import PasswordDialog
import re
from widgets.account_widget import AccountPage
from widgets.terminal import SshClient
try:
import ctypes
except:
ctypes = None
try:
import pyi_splash
except ImportError:
pyi_splash = None
font_ = font_config()
setting_ = SCM()
mime_types = [
"text/plain",
"text/html",
"text/css",
"text/javascript",
"application/json",
"application/xml",
"application/x-empty"
]
def setup_webengine_environment():
"""设置WebEngine运行环境"""
# 设置必要的环境变量
env_vars = {
"QT_PLUGIN_PATH": "/usr/lib/x86_64-linux-gnu/qt5/plugins",
"QT_QPA_PLATFORM_PLUGIN_PATH": "/usr/lib/x86_64-linux-gnu/qt5/plugins/platforms",
"QT_QPA_PLATFORM": "xcb",
"QTWEBENGINE_CHROMIUM_FLAGS": "--no-sandbox --disable-gpu"
}
for key, value in env_vars.items():
os.environ[key] = value
# 检查并安装最小依赖
try:
# 检查是否已安装必要的系统包
check_cmd = "dpkg -l | grep -E 'libqt5webengine5|python3-pyqt5.qtwebengine'"
result = subprocess.run(check_cmd, shell=True,
capture_output=True, text=True)
if not result.stdout.strip():
print("安装必要的WebEngine依赖...")
subprocess.run(
"sudo apt-get install -y python3-pyqt5.qtwebengine libqt5webengine5",
shell=True,
check=True
)
except subprocess.CalledProcessError:
print("WebEngine依赖安装失败,某些功能可能不可用")
except Exception:
pass
print("WebEngine环境设置完成")
def isDebugMode():
"""Check if the application is running under a debugger."""
# return True
return sys.gettrace() is not None
class PermissionDialog(MessageBoxBase):
def __init__(self, file_name: str, permission_num: int = None, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint)
self.titleLabel = SubtitleLabel(file_name)
self.yesButton.setText(self.tr("Apply"))
self.cancelButton.setText(self.tr("Cancel"))
# Owner permissions
owner_group = QHBoxLayout()
owner_group.addWidget(QLabel(self.tr("Owner: ")))
self.owner_read = CheckBox(self.tr("Read"))
self.owner_write = CheckBox(self.tr("Write"))
self.owner_exec = CheckBox(self.tr("Execute"))
owner_group.addWidget(self.owner_read)
owner_group.addWidget(self.owner_write)
owner_group.addWidget(self.owner_exec)
# Group permissions
group = QHBoxLayout()
group.addWidget(QLabel(self.tr("Group: ")))
self.group_read = CheckBox(self.tr("Read"))
self.group_write = CheckBox(self.tr("Write"))
self.group_exec = CheckBox(self.tr("Execute"))
group.addWidget(self.group_read)
group.addWidget(self.group_write)
group.addWidget(self.group_exec)
# Other permissions
other = QHBoxLayout()
other.addWidget(QLabel(self.tr("Other: ")))
self.other_read = CheckBox(self.tr("Read"))
self.other_write = CheckBox(self.tr("Write"))
self.other_exec = CheckBox(self.tr("Execute"))
other.addWidget(self.other_read)
other.addWidget(self.other_write)
other.addWidget(self.other_exec)
self.permission_label = QLabel("")
self.permission_label.setAlignment(Qt.AlignCenter)
# Add all to layout
self.viewLayout.addWidget(self.titleLabel)
self.viewLayout.addLayout(owner_group)
self.viewLayout.addLayout(group)
self.viewLayout.addLayout(other)
self.viewLayout.addWidget(self.permission_label)
self._parent = parent
if permission_num is not None:
self.set_permission_state(permission_num)
self._connect_checkbox_signals()
def set_permission_state(self, permission_num: int):
owner_perm = (permission_num >> 6) & 0o7
group_perm = (permission_num >> 3) & 0o7
other_perm = permission_num & 0o7
self.owner_read.setChecked(bool(owner_perm & 4))
self.owner_write.setChecked(bool(owner_perm & 2))
self.owner_exec.setChecked(bool(owner_perm & 1))
self.group_read.setChecked(bool(group_perm & 4))
self.group_write.setChecked(bool(group_perm & 2))
self.group_exec.setChecked(bool(group_perm & 1))
self.other_read.setChecked(bool(other_perm & 4))
self.other_write.setChecked(bool(other_perm & 2))
self.other_exec.setChecked(bool(other_perm & 1))
self._update_permission_display()
def get_permission_num(self) -> int:
permission_num = 0
if self.owner_read.isChecked():
permission_num |= 0o400
if self.owner_write.isChecked():
permission_num |= 0o200
if self.owner_exec.isChecked():
permission_num |= 0o100
if self.group_read.isChecked():
permission_num |= 0o040
if self.group_write.isChecked():
permission_num |= 0o020
if self.group_exec.isChecked():
permission_num |= 0o010
if self.other_read.isChecked():
permission_num |= 0o004
if self.other_write.isChecked():
permission_num |= 0o002
if self.other_exec.isChecked():
permission_num |= 0o001
return permission_num
def _connect_checkbox_signals(self):
checkboxes = [
self.owner_read, self.owner_write, self.owner_exec,
self.group_read, self.group_write, self.group_exec,
self.other_read, self.other_write, self.other_exec
]
for checkbox in checkboxes:
checkbox.stateChanged.connect(self._update_permission_display)
def _update_permission_display(self):
permission_num = self.get_permission_num()
owner_perm = (permission_num >> 6) & 0o7
group_perm = (permission_num >> 3) & 0o7
other_perm = permission_num & 0o7
def to_symbol(perm):
return f"{'r' if perm & 4 else '-'}{'w' if perm & 2 else '-'}{'x' if perm & 1 else '-'}"
owner_symbol = to_symbol(owner_perm)
group_symbol = to_symbol(group_perm)
other_symbol = to_symbol(other_perm)
display_text = self.tr(
f"Current permissions: {owner_symbol}{group_symbol}{other_symbol} ({permission_num:03o})")
self.permission_label.setText(display_text)
def showEvent(self, event):
super().showEvent(event)
if self._parent:
parent_geometry = self._parent.geometry()
self.setGeometry(parent_geometry)
self.raise_()
self.activateWindow()
class Window(FramelessWindow):
windowResized = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent=parent)
if isDebugMode():
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = '3354'
print('Debug mode enabled: http://localhost:' +
os.environ['QTWEBENGINE_REMOTE_DEBUGGING'])
self.icons = My_Icons()
self.expander_bar_width = 8
self.active_transfers = {}
self.watching_dogs = {}
self.last_session_click_time = {}
self.file_id_to_path = {}
self._download_debounce_timer = QTimer(self)
self._download_debounce_timer.setSingleShot(True)
self._download_debounce_timer.setInterval(500)
self._download_debounce_timer.timeout.connect(
self._process_pending_downloads)
self._pending_download_paths = {}
self.page_animator = PageTransitionAnimator(duration=500)
self._animation_in_progress = False
self._resize_timer = QTimer(self)
self._resize_timer.setSingleShot(True)
self._resize_timer.timeout.connect(self.apply_locked_ratio)
self.setMinimumSize(800, 600)
self.setTitleBar(StandardTitleBar(self))
self._bg_ratio = None
self.setWindowTitle("NeoSSH Beta")
icon = QIcon(resource_path("resource/icons/icon.ico"))
self.setWindowIcon(icon)
QApplication.setWindowIcon(icon)
self.titleBar.raise_()
self.connect_status_dict = {}
self.ssh_session = {}
self.sessionmanager = SessionManager()
self.session_widgets = {}
self.file_tree_object = {}
self._bg_opacity = 1.0
# self.unprocessed_tasks = ["systemd","kthreadd","pool_workqueue_release","kworker/R-rcu_g"]
self._bg_pixmap = None
self.hBoxLayout = QHBoxLayout(self)
self.navigationInterface = NavigationInterface(
self, showMenuButton=True)
self.stackWidget = QStackedWidget(self)
try:
self.sidePanel = SidePanelWidget(self, main_window=self)
self.sidePanel.aichat_widget.bridge.userinfo_got.connect(
partial(self.update_user_info, local=True))
# self.sidePanel.aichat_widget.bridge.userinfo_got.connect(
# lambda name, qid: self.account_widget.update_account_info(name, qid, email=f"{qid}@qq.com", avatar_url=f'http://q.qlogo.cn/headimg_dl?dst_uin={qid}&spec=640&img_type=png'))
self.sidePanel.tabActivity.connect(self._ensure_side_panel_visible)
except: # 关闭后会有报错
pass
# create sub interface
self.MainInterface = MainInterface(self)
self.MainInterface.sessionClicked.connect(self._on_session_selected)
self.sync_widget = SycnWidget(self)
self.sync_widget.setWindowModality(Qt.ApplicationModal)
self.sync_widget.setWindowFlags(
self.sync_widget.windowFlags() |
Qt.Dialog
)
self.sync_widget.center_on_parent()
self.sync_widget.sync_finished.connect(
lambda status, msg: InfoBar.success(
title=msg if status == "updated" or status == "created" else self.tr(
"Error"),
content="",
orient=Qt.Vertical,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=5000 if status == "updated" or status == "created" else -1,
parent=self
) if status == "updated" or status == "created" else InfoBar.error(
title=self.tr("Error"),
content=msg,
orient=Qt.Vertical,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=-1,
parent=self
)
)
self.sync_widget.hide()
# self.sessions = Widget(
# self.tr('No conversation selected yet'), True, self)
self.ssh_page = SSHPage()
self.ssh_page.menuActionTriggered.connect(self._handle_action)
self.navigationInterface.setStyleSheet("background: transparent;")
self.navigationInterface.setCollapsible(True)
self.stackWidget.setStyleSheet("background: transparent;")
self.settingInterface = SettingPage(self,)
self.settingInterface.themeChanged.connect(self._on_theme_changed)
self.settingInterface.lock_ratio_card.checkedChanged.connect(
self.apply_locked_ratio)
self.settingInterface.opacityEdit.valueChanged.connect(
self.set_background_opacity)
self.settingInterface.themeColorChanged.connect(
self.on_theme_color_changed)
# Connect transparency setting signal
# self.settingInterface.bgOpacityChanged.connect(
# self.set_background_opacity)
self._on_theme_changed(
self.settingInterface.cfg.background_color.value)
self.init_account()
self.initLayout()
self.initNavigation()
self.expanderBar = ExpanderBar(self, width=self.expander_bar_width)
self.expanderBar.hide()
self.expanderBar.clicked.connect(self._expand_side_panel)
self.initWindow()
if setting_.read_config()["maximized"]:
self.showMaximized()
# self.switchTo(self.MainInterface)
self.checker = CheckUpdate()
self.checker.start()
if isDebugMode():
print("\\\\ Debuger Done \\\\")
print(config.get("first_start", True))
if config.get("first_start", True):
msg_box = MessageBox(
self.tr("Welcome to NeoSSH!"),
self.tr("Thank you for choosing NeoSSH.\n\n"
"The default terminal is driven by WebEngine, which may experience lag but is the most stable.\n\n"
"You can also try the high-performance solution implemented purely in Python, but stability may be an issue.\n\n"
"If there are any problems, please submit them on GitHub."),
self)
msg_box.yesButton.setText(self.tr("Got it"))
msg_box.cancelButton.hide()
msg_box.show()
configer.revise_config("first_start", False)
def set_background_opacity(self, opacity: float):
if not self._bg_pixmap:
return
# In the case of int, only setting is passed in
if isinstance(opacity, int):
opacity = opacity / 100
self._bg_opacity = max(0.0, min(1.0, opacity))
self.update()
def _on_ssh_connected(self, success: bool, msg: str):
if success:
InfoBar.success(
title=msg,
content="",
orient=Qt.Vertical,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=2000,
parent=self
)
def _on_ssh_error(self, msg: str):
InfoBar.error(
title=self.tr("Connection failed"),
content=self.tr(f"Error:\n{msg}\nPlease close this session"),
orient=Qt.Vertical,
isClosable=True,
position=InfoBarPosition.TOP_RIGHT,
duration=-1,
parent=self
)
def _set_usage(self, widget_key, usage):
try:
# print(usage)
result = dict(usage)
parent_key = widget_key.split("-", 1)[0].strip()
widget = self.session_widgets.get(widget_key)
if not widget:
print(f"Failed to obtain the SSH Widget: {widget_key}")
return
if result.get("type") == "info":
# 动态更新各个组件,只有提供的数据才更新
# 更新网络监控
if "net_usage" in result:
widget.start_loading_animation("net")
try:
net_usage = result["net_usage"]
# print(f"Net Usage: {net_usage}")
if not widget.task.netmonitor.init_interface and net_usage:
interfaces = []
for i in net_usage:
name = i.get("iface")
if name and name not in interfaces:
interfaces.append(name)
if interfaces:
success = widget.task.netmonitor.initialize_interfaces(
interfaces)
if success:
widget.task.netmonitor.init_interface = True
print(f"初始化网卡成功: {interfaces}")
if net_usage:
current_interface = widget.task.netmonitor.interface_combo.currentText()
target_dict = next((item for item in net_usage if item.get(
'iface') == current_interface), None)
if target_dict:
upload = target_dict.get("tx_kbps", 0)
download = target_dict.get("rx_kbps", 0)
widget.task.netmonitor.update_speed(
upload, download, current_interface)
else:
if net_usage:
first_interface = net_usage[0].get('iface')
if first_interface:
widget.task.netmonitor.interface_combo.setCurrentText(
first_interface)
upload = net_usage[0].get("tx_kbps", 0)
download = net_usage[0].get(
"rx_kbps", 0)
widget.task.netmonitor.update_speed(
upload, download, first_interface)
except Exception as e:
print(f"网络监控更新失败: {e}")
finally:
widget.stop_loading_animation("net")
# 更新进程监控
if "top_processes" in result:
widget.start_loading_animation("task")
try:
top_processes = result["top_processes"]
# print(f"Top Processes: {top_processes}")
widget.task.clear_rows()
for process in top_processes:
processes_cpu_percent = process.get("cpu", 0)
processes_name = process.get("name", "")
processes_mem = process.get("mem_mb", 0)
widget.task.add_row(
f"{processes_mem:.1f}",
f"{processes_cpu_percent:.1f}",
processes_name
)
except Exception as e:
print(f"进程监控更新失败: {e}")
finally:
widget.stop_loading_animation("task")
# 更新详细进程信息
if "all_processes" in result:
try:
all_processes = result["all_processes"]
if all_processes:
widget.task_detaile.updateProcessData(
all_processes)
except Exception as e:
print(f"详细进程更新失败: {e}")
# 更新网络连接信息
if "connections" in result:
try:
connections = result["connections"]
if connections:
widget.net_monitor.updateProcessData(connections)
except Exception as e:
print(f"网络连接更新失败: {e}")
# 更新磁盘使用情况
if "disk_usage" in result:
try:
disk_usage = result["disk_usage"]
if disk_usage:
for disk in disk_usage:
device = disk.get("device", "")
mount = disk.get("mount", "")
disk_id = f"{device}:{mount}"
widget.disk_usage.update_disk_item(disk_id, {
"device": device,
"mount": mount,
"used_percent": disk.get("used_percent"),
"size_kb": disk.get("size_kb"),
"used_kb": disk.get("used_kb"),
"avail_kb": disk.get("avail_kb"),
"read_kbps": disk.get("read_kbps"),
"write_kbps": disk.get("write_kbps"),
})
except Exception as e:
print(f"磁盘使用情况更新失败: {e}")
# 更新监控栏指标
metrics = {}
# 动态构建指标数据
if "uptime_seconds" in result:
metrics["uptime_seconds"] = result["uptime_seconds"]
if "load" in result:
metrics["load"] = result["load"]
if "cpu_percent" in result:
metrics["cpu_percent"] = result["cpu_percent"]
if "mem_percent" in result:
metrics["ram_percent"] = result["mem_percent"]
if "mem_used" in result:
metrics["ram_used_mb"] = result["mem_used"]
# 网络指标
upload, download = 0, 0
if "net_usage" in result:
net_usage = result["net_usage"]
if net_usage:
current_interface = widget.task.netmonitor.interface_combo.currentText()
target_dict = next((item for item in net_usage if item.get(
'iface') == current_interface), None)
if target_dict:
upload = target_dict.get("tx_kbps", 0)
download = target_dict.get("rx_kbps", 0)
metrics["net_up_kbps"] = upload
metrics["net_down_kbps"] = download
# 磁盘指标(使用第一个磁盘的使用率)
disk_percent = 0
if "disk_usage" in result and result["disk_usage"]:
disk_percent = result["disk_usage"][0].get(
"used_percent", 0)
metrics["disk_percent"] = disk_percent
# 更新监控栏
if metrics:
widget.monitorbar.update_metrics(metrics)
elif result.get("type") == "sysinfo":
# 系统信息更新
try:
sys_info = f'''
System : {result.get("system", "N/A")} kernel {result.get("kernel", "N/A")}
Arch : {result.get("arch", "N/A")}
Host name : {result.get("hostname", "N/A")}
CPU : {result.get("cpu_model", "N/A")} with {result.get("cpu_cores", "N/A")} cores
Freq : {result.get("cpu_freq", "N/A")} Cache : {result.get("cpu_cache", "N/A")}
Memory : {result.get("mem_total", "N/A")}
Host IP : {result.get("ip", "N/A")}
'''
widget.sys_info_msg = sys_info
print("系统信息已更新")
except Exception as e:
print(f"系统信息更新失败: {e}")
except Exception as e:
print(f"_set_usage 方法错误: {e}")
def _show_info(self, path: str = None, status: bool = None, msg: str = None, type_: str = None, widget_key: str = None, local_path: str = None, open_it: bool = False):
no_refresh_types = ["download",
"start_upload", "start_download", "info"]
# print(f"showinfo : {type_} {widget_key}")
duration = 3000
session_widget = self.session_widgets[widget_key]
if not session_widget:
return
title = ""
if type_ == "upload":
paths = path if isinstance(path, list) else [path]
for p in paths:
# The 'path' from the finished signal is the unique identifier
file_id = self.active_transfers.get(p, {}).get("id")
if not file_id:
# Fallback for safety, though it should exist
file_id = f"{widget_key}_{p}_{time.time()}"
if status:
if p not in self.active_transfers:
# This can happen if the file is very small and finishes
# before any progress signal is emitted.
self._add_transfer_item_if_not_exists(
widget_key, p, "upload")
file_id = self.active_transfers[p]["id"]
if p in self.active_transfers:
self.active_transfers[p]['type'] = 'completed'
self.active_transfers[p]['progress'] = 100
data = {"type": "completed", "progress": 100}
session_widget.transfer_progress.update_transfer_item(
file_id, data)
title = self.tr(f"Upload {p} completed")
duration = 2000
else:
title = f"Uoload {p} failure"
duration = -1
if p in self.active_transfers:
session_widget.transfer_progress.remove_transfer_item(
self.active_transfers[p]["id"])
del self.active_transfers[p]
elif type_ == "start_upload":
# This is now handled by _add_transfer_item_if_not_exists
# It will be called from _handle_files for single files/compressed,
# or dynamically from progress/finished signals for expanded dirs.
pass
elif type_ == "start_download":
paths = path if isinstance(path, list) else [path]
for p in paths:
file_id = f"{widget_key}_{os.path.basename(p)}_{time.time()}"
data = {
"type": "download",
"filename": os.path.basename(p),
"progress": 0
}
self.active_transfers[file_id] = data
session_widget.transfer_progress.add_transfer_item(
file_id, data)
elif type_ == "download":
# 'path' is the unique remote path identifier
if path in self.active_transfers:
file_id = self.active_transfers[path]["id"]
if status:
self.active_transfers[path]['type'] = 'completed'
self.active_transfers[path]['progress'] = 100
data = {"type": "completed", "progress": 100}
session_widget.transfer_progress.update_transfer_item(
file_id, data)
if open_it and local_path:
try:
print(f"From Remote Path : {path}")
self._open_downloaded_file(
local_path, widget_key, path)
except Exception as e:
print(f"Error opening file/folder: {e}")
else:
session_widget.transfer_progress.remove_transfer_item(
file_id)
del self.active_transfers[path]
elif status: # Finished signal for a small file that sent no progress
self._add_transfer_item_if_not_exists(
widget_key, path, "download", open_it=open_it)
if path in self.active_transfers:
file_id = self.active_transfers[path]["id"]
self.active_transfers[path]['type'] = 'completed'
self.active_transfers[path]['progress'] = 100
data = {"type": "completed", "progress": 100}
session_widget.transfer_progress.update_transfer_item(
file_id, data)
else:
duration = 5000
title = ""
if type_ in ("compression", "uncompression"):
title = self.tr(f"Start to {type_} : {path}")
msg = ""
elif type_ == "delete":
print("delete showinfo")
if status:
title = self.tr(f"Deleted {path} successfully")
else:
title = self.tr(f"Failed to delete {path}\n{msg}")
duration = -1
elif type_ == "paste":
if status:
title = self.tr("Paste Successful")
msg = self.tr(f"Pasted {path} to {local_path}")
else:
title = self.tr("Paste Failed")
duration = -1
elif type_ == "rename":
if status:
title = self.tr("Rename Successful")
msg = self.tr(f"Renamed {path} to {local_path}")
else:
title = self.tr("Rename Failed")
duration = -1
elif type_ == "mkdir":
if status:
title = self.tr(f"Created directory {path} successfully")
else:
title = self.tr(
f"Failed to create directory {path}\n{msg}")
duration = -1
elif type_ == "mkfile":
if status:
title = self.tr(f"Created file {path} successfully")
else:
title = self.tr(
f"Failed to create file {path}\n{msg}")
duration = -1
elif type_ == "kill":
if status:
title = self.tr(f"Kill process of pid {path}")
duration = 2000
else:
title = self.tr(f"Kill process of pid {path} failed")
duration = -1
if title:
InfoBar.info(
title=title,
content=msg,
orient=Qt.Horizontal,
isClosable=True,
position=InfoBarPosition.BOTTOM_RIGHT,
duration=duration,
parent=self.window()
)
if type_ not in no_refresh_types and widget_key:
self._refresh_paths(widget_key)
print(f"刷新路径: {widget_key}")
def _show_progresses(self, path, percentage, bytes_so_far, total_bytes, widget_key, transfer_type):
"""Handles progress updates for both uploads and downloads."""
session_widget = self.session_widgets[widget_key]
if not session_widget:
return
# 'path' is the unique identifier (local for upload, remote for download)
if path not in self.active_transfers:
self._add_transfer_item_if_not_exists(
widget_key, path, transfer_type)
if path in self.active_transfers:
file_id = self.active_transfers[path]["id"]
data = self.active_transfers[path]
data["progress"] = percentage
data["bytes_so_far"] = bytes_so_far
data["total_bytes"] = total_bytes
if percentage >= 100:
if data.get("type") == "compression":
data["type"] = "download"
data["progress"] = 0
elif data.get("type") == "download":
data["type"] = "completed"
session_widget.transfer_progress.update_transfer_item(
file_id, data)
def update_user_info(self, name, qid, local=True):
config = configer.read_config()
try:
if config["account"]["apikey"]:
return # apikey exists, do not modify account info
except KeyError:
return # no apikey, do not modify account info
noneed_change = False
if local:
name = self.tr(f"{name} (Local)")
if "account" not in config:
config["account"] = {}
account_config = config["account"]
expected_values = {
"user": name,
"qid": qid,
"email": f"{qid}@qq.com",
"avatar_url": f'http://q.qlogo.cn/headimg_dl?dst_uin={qid}&spec=640&img_type=png'
}
updates = {
key: value for key, value in expected_values.items()
if account_config.get(key) != value
}
if not updates:
noneed_change = True
else:
account_config.update(updates)
config["account"] = account_config
configer.write_config(config)
if not noneed_change:
self.account_widget.update_account_info(
username=name,
qid=qid,
email=f"{qid}@qq.com",
avatar_url=f'http://q.qlogo.cn/headimg_dl?dst_uin={qid}&spec=640&img_type=png'
)
def _open_downloaded_file(self, local_path: str, widget_key: str, remote_path: str):
"""打开下载的文件"""
config = setting_.read_config()
external_editor = config.get("external_editor", "")
open_mode = config.get("open_mode", False)
is_text = False
mime = None
try:
with open(local_path, "rb") as f:
content = f.read(2048)
mime = magic.from_buffer(content, mime=True)
if mime in mime_types or mime.startswith("text/"):
is_text = True
elif mime == "application/octet-stream":
try:
content.decode('utf-8')
is_text = True
except UnicodeDecodeError:
try:
content.decode('gbk')
is_text = True
except UnicodeDecodeError:
is_text = False
except Exception as e:
print(f"Error checking file type: {e}")
if mime.startswith("image/"):
self.open_media_in_panel(local_path, widget_key)
return
if (external_editor and os.path.isfile(external_editor)) and open_mode:
try:
subprocess.Popen([external_editor, local_path])
except Exception as editor_error:
print(
f"Error opening with external editor: {editor_error}, fallback to internal editor")
if is_text:
self._open_in_internal_editor(
local_path, widget_key, remote_path)
else:
if is_text:
self._open_in_internal_editor(
local_path, widget_key, remote_path)
else:
print(
f"File {local_path} is not a text file (MIME: {mime}), cannot open in editor")
self._start_file_watching_if_text(
local_path, widget_key, remote_path)
def open_media_in_panel(self, local_path: str, widget_key: str):
if os.path.exists(local_path):
try:
img = AutoFitImageLabel(local_path)
img.set_tab_id = lambda tid: setattr(img, "tab_id", tid)
base_name = os.path.basename(local_path)
self.sidePanel.add_new_tab(img, f"{widget_key} - {base_name}")
except Exception as e:
img = QLabel(str(e))
img.setAlignment(Qt.AlignCenter)
base_name = os.path.basename(local_path)
self.sidePanel.add_new_tab(img, f"{widget_key} - {base_name}")
def _open_in_internal_editor(self, local_path: str, widget_key: str, remote_path: str):
"""在内置编辑器中打开文件"""
try:
existing_tab_id = self.sidePanel.find_tab_by_remote_path(
remote_path)
if existing_tab_id:
self.sidePanel.switch_to_tab(existing_tab_id)
tab_info = self.sidePanel.tabs[existing_tab_id]
editor_widget = tab_info['page']
if isinstance(editor_widget, EditorWidget):
editor_widget.load_file(local_path)
else:
tab_title = os.path.basename(remote_path)
tab_id = self.sidePanel.add_new_tab(EditorWidget(), f'{widget_key} - {tab_title}', {
"path": local_path, "remote_path": remote_path, "widget_key": widget_key})
except Exception as e:
print(f"Error opening in internal editor: {e}")
import traceback
traceback.print_exc()
def _start_file_watching_if_text(self, local_path: str, widget_key: str, remote_path: str):
"""如果是文本文件,启动文件监视以便自动重新上传"""
try:
with open(local_path, "rb") as f:
content = f.read(2048)
mime = magic.from_buffer(content, mime=True)
is_text = False
if mime in mime_types or mime.startswith("text/"):
is_text = True
elif mime == "application/octet-stream":
try:
content.decode('utf-8')
is_text = True
print(
f"File detected as text by content analysis (MIME: {mime})")
except UnicodeDecodeError:
try:
content.decode('gbk')
is_text = True
print(
f"File detected as text (GBK encoding) by content analysis (MIME: {mime})")
except UnicodeDecodeError:
is_text = False
if is_text:
if widget_key in self.watching_dogs:
for watcher in self.watching_dogs[widget_key]:
if os.path.abspath(watcher.file_path) == os.path.abspath(local_path):
print(
f"Watcher for {local_path} already exists. Skipping.")
return
print(
f"Text file detected (MIME: {mime}), starting file watching: {local_path}")
file_thread = FileWatchThread(local_path)
file_thread.file_saved.connect(
lambda local: self.reupload_when_saved(widget_key, local, remote_path))
file_thread.start()
if widget_key not in self.watching_dogs:
self.watching_dogs[widget_key] = []
self.watching_dogs[widget_key].append(file_thread)
else:
print(
f"File type {mime} is not text file, won't start watching")
except Exception as e:
print(f"Error checking file type: {e}")
def reupload_when_saved(self, widget_name, local_path, remote_path,):
remote_path = os.path.dirname(remote_path)
# print(f"将上传 {local_path} 到 {widget_name}的 {remote_path}")
file_manager: RemoteFileManager = self.file_tree_object[widget_name]
if file_manager:
self._handle_upload_request(widget_key=widget_name, local_path=local_path,
remote_path=remote_path, compression=False, file_manager=file_manager)
def _start_ssh_connect(self, widget_key):
mode = config.get("terminal_mode", 0)
parent_key = widget_key.split("-")[0].strip()
session = self.sessionmanager.get_session_by_name(parent_key)
jumpbox = None
worker = None
session_widget = self.session_widgets[widget_key]
if session.jump_server != "None" and session.jump_server:
print(f"{session.name} use Jumpbox")
jumpbox = self.sessionmanager.get_session_by_name(
session.jump_server)
def on_auth_error(e=None):
update_password, reshow = self.verify_password(
session, reinput=True)
if update_password and (not reshow):
start_processes()
elif reshow: