-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu.py
More file actions
1985 lines (1687 loc) · 76.4 KB
/
menu.py
File metadata and controls
1985 lines (1687 loc) · 76.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
import sys
import os
import yaml
import subprocess
import markdown
import re
import unicodedata
from datetime import datetime
import json
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QVBoxLayout,
QWidget, QLabel, QTextEdit, QFrame, QStackedWidget,
QHBoxLayout, QGridLayout, QDialog, QSplitter, QLineEdit,
QTextBrowser, QListWidget, QListWidgetItem, QScrollArea,
QFileDialog, QMessageBox)
from PyQt5.QtGui import QIcon, QPixmap, QFont, QDesktopServices
from PyQt5.QtCore import Qt, QProcess, pyqtSignal, QObject, QUrl
from font_manager import get_font_manager
class ThemeManager:
"""Manages application themes (light/dark mode)"""
def __init__(self):
self.current_theme = "light"
self.themes = {
"light": {
# Background colors
"bg_primary": "#ffffff",
"bg_secondary": "#f8f8f8",
"bg_tertiary": "#f0f0f0",
"bg_code": "#f8f9fa",
# Text colors
"text_primary": "#333333",
"text_secondary": "#6a737d",
"text_heading": "#2c3e50",
"text_link": "#0366d6",
"text_error": "#cc0000",
"text_disabled": "#666666",
# Border colors
"border_primary": "#cccccc",
"border_secondary": "#e9ecef",
# Button colors
"btn_primary": "#4a86e8",
"btn_primary_hover": "#3d76d1",
"btn_primary_pressed": "#2c5aa0",
"btn_success": "#5cb85c",
"btn_success_hover": "#4cae4c",
"btn_success_alt": "#6aa84f",
"btn_success_alt_hover": "#5d9745",
"btn_success_alt_pressed": "#4d7e3a",
"btn_danger": "#e06666",
"btn_danger_hover": "#cc5050",
"btn_danger_pressed": "#b94343",
"btn_danger_alt": "#d9534f",
"btn_danger_alt_hover": "#c9302c",
"btn_warning": "#f0ad4e",
"btn_warning_hover": "#ec971f",
"btn_info": "#5bc0de",
"btn_info_hover": "#46b8da",
"btn_secondary": "#6c757d",
"btn_secondary_hover": "#5a6268",
},
"dark": {
# Background colors
"bg_primary": "#2b2b2b",
"bg_secondary": "#3c3c3c",
"bg_tertiary": "#404040",
"bg_code": "#1e1e1e",
# Text colors
"text_primary": "#ffffff",
"text_secondary": "#b0b0b0",
"text_heading": "#ffffff",
"text_link": "#4fc3f7",
"text_error": "#ff6b6b",
"text_disabled": "#808080",
# Border colors
"border_primary": "#555555",
"border_secondary": "#666666",
# Button colors
"btn_primary": "#5c6bc0",
"btn_primary_hover": "#7986cb",
"btn_primary_pressed": "#3f51b5",
"btn_success": "#66bb6a",
"btn_success_hover": "#81c784",
"btn_success_alt": "#81c784",
"btn_success_alt_hover": "#a5d6a7",
"btn_success_alt_pressed": "#66bb6a",
"btn_danger": "#ef5350",
"btn_danger_hover": "#f44336",
"btn_danger_pressed": "#d32f2f",
"btn_danger_alt": "#e57373",
"btn_danger_alt_hover": "#ef5350",
"btn_warning": "#ffb74d",
"btn_warning_hover": "#ffa726",
"btn_info": "#29b6f6",
"btn_info_hover": "#03a9f4",
"btn_secondary": "#90a4ae",
"btn_secondary_hover": "#78909c",
}
}
self.load_theme_preference()
def get_theme(self):
"""Get current theme colors"""
return self.themes[self.current_theme]
def set_theme(self, theme_name):
"""Set the current theme"""
if theme_name in self.themes:
self.current_theme = theme_name
self.save_theme_preference()
def get_current_theme_name(self):
"""Get current theme name"""
return self.current_theme
def load_theme_preference(self):
"""Load theme preference from file"""
try:
if os.path.exists("theme_preference.json"):
with open("theme_preference.json", "r") as f:
data = json.load(f)
theme = data.get("theme", "light")
if theme in self.themes:
self.current_theme = theme
except Exception:
# If there's any error, use default theme
self.current_theme = "light"
def save_theme_preference(self):
"""Save theme preference to file"""
try:
with open("theme_preference.json", "w") as f:
json.dump({"theme": self.current_theme}, f)
except Exception:
# If save fails, just continue without saving
pass
def get_button_style(self, button_type="primary"):
"""Get button stylesheet for the given type"""
theme = self.get_theme()
button_styles = {
"primary": f"""
QPushButton {{
background-color: {theme['btn_primary']};
color: white;
border-radius: 5px;
font-size: 14px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_primary_hover']};
}}
QPushButton:pressed {{
background-color: {theme['btn_primary_pressed']};
}}
""",
"success": f"""
QPushButton {{
background-color: {theme['btn_success']};
color: white;
border-radius: 3px;
padding: 5px 10px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_success_hover']};
}}
""",
"success_alt": f"""
QPushButton {{
background-color: {theme['btn_success_alt']};
color: white;
border-radius: 5px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_success_alt_hover']};
}}
QPushButton:pressed {{
background-color: {theme['btn_success_alt_pressed']};
}}
""",
"danger": f"""
QPushButton {{
background-color: {theme['btn_danger']};
color: white;
border-radius: 5px;
font-size: 14px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_danger_hover']};
}}
QPushButton:pressed {{
background-color: {theme['btn_danger_pressed']};
}}
""",
"danger_alt": f"""
QPushButton {{
background-color: {theme['btn_danger_alt']};
color: white;
border-radius: 3px;
padding: 5px 10px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_danger_alt_hover']};
}}
""",
"warning": f"""
QPushButton {{
background-color: {theme['btn_warning']};
color: white;
border-radius: 3px;
padding: 5px 10px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_warning_hover']};
}}
""",
"info": f"""
QPushButton {{
background-color: {theme['btn_info']};
color: white;
border-radius: 3px;
padding: 5px 10px;
font-weight: bold;
}}
QPushButton:hover {{
background-color: {theme['btn_info_hover']};
}}
""",
"secondary": f"""
QPushButton {{
background-color: {theme['btn_secondary']};
color: white;
border-radius: 5px;
padding: 8px 16px;
font-weight: bold;
margin: 5px;
}}
QPushButton:hover {{
background-color: {theme['btn_secondary_hover']};
}}
""",
"submenu": f"""
QPushButton {{
background-color: {theme['btn_primary']};
color: white;
border-radius: 5px;
font-size: 13px;
text-align: left;
padding-left: 15px;
}}
QPushButton:hover {{
background-color: {theme['btn_primary_hover']};
}}
QPushButton:pressed {{
background-color: {theme['btn_primary_pressed']};
}}
"""
}
return button_styles.get(button_type, button_styles["primary"])
def get_terminal_style(self):
"""Get terminal stylesheet"""
theme = self.get_theme()
font_manager = get_font_manager()
monospace_css = font_manager.get_monospace_font_css()
return f"""
QTextEdit {{
background-color: {theme['bg_tertiary']};
color: {theme['text_primary']};
border-radius: 5px;
padding: 10px;
{monospace_css}
font-size: 12px;
}}
"""
def get_input_style(self):
"""Get input field stylesheet"""
theme = self.get_theme()
font_manager = get_font_manager()
monospace_css = font_manager.get_monospace_font_css()
return f"""
QLineEdit {{
background-color: {theme['bg_primary']};
color: {theme['text_primary']};
border: 1px solid {theme['border_primary']};
border-radius: 3px;
padding: 5px;
{monospace_css}
font-size: 12px;
}}
QLineEdit:disabled {{
background-color: {theme['bg_tertiary']};
color: {theme['text_disabled']};
}}
"""
def get_label_style(self):
"""Get label stylesheet"""
theme = self.get_theme()
return f"""
QLabel {{
color: {theme['text_primary']};
font-weight: bold;
padding: 5px;
}}
"""
def get_frame_style(self):
"""Get frame stylesheet"""
theme = self.get_theme()
return f"background-color: {theme['bg_secondary']}; border-radius: 5px;"
def get_main_window_style(self):
"""Get main window stylesheet"""
theme = self.get_theme()
return f"""
QMainWindow {{
background-color: {theme['bg_primary']};
color: {theme['text_primary']};
}}
QWidget {{
background-color: {theme['bg_primary']};
color: {theme['text_primary']};
}}
"""
def get_title_label_style(self):
"""Get title label stylesheet"""
theme = self.get_theme()
return f"""
QLabel {{
color: {theme['text_heading']};
background-color: transparent;
}}
"""
def get_help_content_style(self):
"""Get help content browser stylesheet"""
theme = self.get_theme()
return f"""
QTextBrowser {{
background-color: {theme['bg_primary']};
color: {theme['text_primary']};
border: 1px solid {theme['border_primary']};
border-radius: 5px;
padding: 10px;
font-size: 14px;
line-height: 1.6;
}}
"""
def get_help_markdown_css(self):
"""Get CSS for markdown content in help"""
theme = self.get_theme()
return f"""
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: {theme['text_primary']};
background-color: {theme['bg_primary']};
max-width: none;
margin: 0;
padding: 20px;
}}
h1, h2, h3, h4, h5, h6 {{
color: {theme['text_heading']};
margin-top: 24px;
margin-bottom: 16px;
}}
h1 {{
border-bottom: 2px solid {theme['border_secondary']};
padding-bottom: 10px;
}}
h2 {{
border-bottom: 1px solid {theme['border_secondary']};
padding-bottom: 8px;
}}
code {{
background-color: {theme['bg_code']};
color: {theme['text_primary']};
padding: 2px 6px;
border-radius: 3px;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}}
pre {{
background-color: {theme['bg_code']};
color: {theme['text_primary']};
border: 1px solid {theme['border_secondary']};
border-radius: 6px;
padding: 16px;
overflow-x: auto;
}}
pre code {{
background-color: transparent;
padding: 0;
}}
blockquote {{
border-left: 4px solid {theme['border_primary']};
padding: 0 16px;
color: {theme['text_secondary']};
margin: 16px 0;
}}
table {{
border-collapse: collapse;
width: 100%;
margin: 16px 0;
}}
th, td {{
border: 1px solid {theme['border_primary']};
padding: 8px 12px;
text-align: left;
}}
th {{
background-color: {theme['bg_code']};
font-weight: 600;
}}
img {{
max-width: 100%;
height: auto;
display: block;
margin: 16px auto;
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}}
a {{
color: {theme['text_link']};
text-decoration: none;
}}
a:hover {{
text-decoration: underline;
}}
ul, ol {{
margin: 16px 0;
padding-left: 32px;
}}
li {{
margin: 4px 0;
}}
"""
class OutputTerminal(QTextEdit):
"""Custom QTextEdit that formats and displays terminal output"""
def __init__(self, parent=None, theme_manager=None):
super().__init__(parent)
self.setReadOnly(True)
self.theme_manager = theme_manager
self.apply_theme()
self.document().setMaximumBlockCount(5000) # Limit to prevent memory issues
def apply_theme(self):
"""Apply the current theme to the terminal"""
if self.theme_manager:
self.setStyleSheet(self.theme_manager.get_terminal_style())
else:
# Fallback to default light theme
font_manager = get_font_manager()
monospace_css = font_manager.get_monospace_font_css()
self.setStyleSheet(f"""
QTextEdit {{
background-color: #f0f0f0;
border-radius: 5px;
padding: 10px;
{monospace_css}
font-size: 12px;
}}
""")
def append_output(self, text, error=False):
"""Append text to the terminal with appropriate formatting"""
# Clean and format the text first (this includes ANSI-to-HTML conversion)
text = self.clean_and_format_text(text)
# Process text to handle newlines properly
if self.theme_manager:
theme = self.theme_manager.get_theme()
default_color = theme["text_error"] if error else theme["text_primary"]
else:
default_color = "#cc0000" if error else "#333333"
# Check if text already contains HTML spans (from ANSI conversion)
has_html_formatting = '<span' in text
if not has_html_formatting:
# HTML escape only if no HTML formatting is present
text = text.replace("&", "&").replace("<", "<").replace(">", ">")
# Replace newlines with HTML line breaks
text = text.replace("\n", "<br>")
# Ensure carriage returns are handled correctly (terminal-like behavior)
if "\r" in text and not text.endswith("\r"):
lines = text.split("\r")
# Replace the last line in the document
cursor = self.textCursor()
cursor.movePosition(cursor.End)
cursor.select(cursor.LineUnderCursor)
cursor.removeSelectedText()
if has_html_formatting:
cursor.insertHtml(lines[-1])
else:
cursor.insertHtml(f"<span style='color: {default_color};'>{lines[-1]}</span>")
else:
# Normal append for text without carriage returns
if has_html_formatting:
# Text already has HTML formatting from ANSI conversion
self.insertHtml(text)
else:
# Apply default color
self.append(f"<span style='color: {default_color};'>{text}</span>")
# Scroll to bottom
self.verticalScrollBar().setValue(self.verticalScrollBar().maximum())
def clean_and_format_text(self, text):
"""Convert ANSI escape sequences to HTML formatting and clean non-printable characters"""
if not text:
return text
# Convert ANSI escape sequences to HTML
text = self.ansi_to_html(text)
# Remove other common escape sequences
# Bell character (ASCII 7)
text = text.replace('\x07', '')
# Backspace (ASCII 8) - remove it and the previous character
while '\x08' in text:
pos = text.find('\x08')
if pos > 0:
text = text[:pos-1] + text[pos+1:]
else:
text = text[pos+1:]
# Form feed (ASCII 12)
text = text.replace('\x0c', '\n')
# Vertical tab (ASCII 11)
text = text.replace('\x0b', '\n')
# Handle other control characters (0-31 except tab, newline, carriage return)
cleaned_chars = []
for char in text:
code = ord(char)
if code < 32: # Control characters
if char in ['\t', '\n', '\r']:
# Keep these useful control characters
cleaned_chars.append(char)
else:
# Replace other control characters with placeholder or remove
continue
elif code == 127: # DEL character
continue
elif unicodedata.category(char).startswith('C') and char not in ['\t', '\n', '\r']:
# Other Unicode control characters (except tab, newline, carriage return)
continue
else:
cleaned_chars.append(char)
return ''.join(cleaned_chars)
def ansi_to_html(self, text):
"""Convert ANSI escape sequences to HTML formatting"""
if not text:
return text
# ANSI color mapping to HTML colors
ansi_colors = {
'30': '#000000', # Black
'31': '#cd0000', # Red
'32': '#00cd00', # Green
'33': '#cdcd00', # Yellow
'34': '#0000ee', # Blue
'35': '#cd00cd', # Magenta
'36': '#00cdcd', # Cyan
'37': '#e5e5e5', # White
'90': '#7f7f7f', # Bright Black (Gray)
'91': '#ff0000', # Bright Red
'92': '#00ff00', # Bright Green
'93': '#ffff00', # Bright Yellow
'94': '#5c5cff', # Bright Blue
'95': '#ff00ff', # Bright Magenta
'96': '#00ffff', # Bright Cyan
'97': '#ffffff', # Bright White
}
ansi_bg_colors = {
'40': '#000000', # Black background
'41': '#cd0000', # Red background
'42': '#00cd00', # Green background
'43': '#cdcd00', # Yellow background
'44': '#0000ee', # Blue background
'45': '#cd00cd', # Magenta background
'46': '#00cdcd', # Cyan background
'47': '#e5e5e5', # White background
'100': '#7f7f7f', # Bright Black background
'101': '#ff0000', # Bright Red background
'102': '#00ff00', # Bright Green background
'103': '#ffff00', # Bright Yellow background
'104': '#5c5cff', # Bright Blue background
'105': '#ff00ff', # Bright Magenta background
'106': '#00ffff', # Bright Cyan background
'107': '#ffffff', # Bright White background
}
# Current formatting state
current_style = {
'color': None,
'bg_color': None,
'bold': False,
'italic': False,
'underline': False
}
result = []
i = 0
while i < len(text):
# Look for ANSI escape sequence
if text[i:i+2] == '\x1b[':
# Find the end of the escape sequence
j = i + 2
while j < len(text) and text[j] not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
j += 1
if j < len(text):
# Extract the command
command = text[i+2:j]
end_char = text[j]
if end_char == 'm': # Color/formatting command
# Parse the parameters
params = command.split(';') if command else ['0']
for param in params:
param = param.strip()
if not param:
param = '0'
if param == '0': # Reset
current_style = {
'color': None,
'bg_color': None,
'bold': False,
'italic': False,
'underline': False
}
elif param == '1': # Bold
current_style['bold'] = True
elif param == '3': # Italic
current_style['italic'] = True
elif param == '4': # Underline
current_style['underline'] = True
elif param == '22': # Normal intensity (not bold)
current_style['bold'] = False
elif param == '23': # Not italic
current_style['italic'] = False
elif param == '24': # Not underlined
current_style['underline'] = False
elif param in ansi_colors: # Foreground color
current_style['color'] = ansi_colors[param]
elif param in ansi_bg_colors: # Background color
current_style['bg_color'] = ansi_bg_colors[param]
elif param == '39': # Default foreground
current_style['color'] = None
elif param == '49': # Default background
current_style['bg_color'] = None
# Close any open span
if result and result[-1] != '</span>':
result.append('</span>')
# Open new span with current style
style_parts = []
if current_style['color']:
style_parts.append(f"color: {current_style['color']}")
if current_style['bg_color']:
style_parts.append(f"background-color: {current_style['bg_color']}")
if current_style['bold']:
style_parts.append("font-weight: bold")
if current_style['italic']:
style_parts.append("font-style: italic")
if current_style['underline']:
style_parts.append("text-decoration: underline")
if style_parts:
style_str = '; '.join(style_parts)
result.append(f'<span style="{style_str}">')
else:
result.append('<span>')
i = j + 1
else:
# Malformed escape sequence, just add the character
result.append(text[i])
i += 1
else:
result.append(text[i])
i += 1
# Close any remaining open span
text_result = ''.join(result)
if '<span' in text_result and not text_result.endswith('</span>'):
text_result += '</span>'
return text_result
def get_plain_text_content(self):
"""Extract plain text content from the terminal, removing HTML formatting"""
# Get the HTML content
html_content = self.toHtml()
# Remove HTML tags but preserve line breaks
# First, replace <br> tags with newlines
text_content = html_content.replace('<br>', '\n').replace('<br/>', '\n').replace('<br />', '\n')
# Remove all other HTML tags
text_content = re.sub(r'<[^>]+>', '', text_content)
# Decode HTML entities
text_content = text_content.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace(''', "'")
# Clean up extra whitespace while preserving intentional formatting
lines = text_content.split('\n')
cleaned_lines = []
for line in lines:
# Remove leading/trailing whitespace but preserve internal spacing
cleaned_line = line.strip()
if cleaned_line or (cleaned_lines and cleaned_lines[-1]): # Keep empty lines between content
cleaned_lines.append(cleaned_line)
# Remove trailing empty lines
while cleaned_lines and not cleaned_lines[-1]:
cleaned_lines.pop()
return '\n'.join(cleaned_lines)
class ProcessManager(QObject):
"""Manages command execution and emits output signals"""
output_received = pyqtSignal(str, bool) # text, is_error
process_finished = pyqtSignal(int, QProcess.ExitStatus) # exit code, exit status
process_started = pyqtSignal() # Signal when process starts
def __init__(self, parent=None):
super().__init__(parent)
self.process = QProcess()
self.process.readyReadStandardOutput.connect(self.handle_stdout)
self.process.readyReadStandardError.connect(self.handle_stderr)
self.process.finished.connect(self.process_finished)
self.process.started.connect(self.process_started)
def execute_command(self, command):
"""Execute a shell command"""
if self.process.state() == QProcess.Running:
self.process.kill()
self.process.waitForFinished()
# Use bash for better terminal compatibility
self.process.start('bash', ['-c', command])
def handle_stdout(self):
"""Handle standard output data"""
raw_data = self.process.readAllStandardOutput().data()
data = self.decode_output(raw_data)
if data:
self.output_received.emit(data, False)
def handle_stderr(self):
"""Handle standard error data"""
raw_data = self.process.readAllStandardError().data()
data = self.decode_output(raw_data)
if data:
self.output_received.emit(data, True)
def decode_output(self, raw_data):
"""Decode raw output data with proper error handling"""
try:
# Try UTF-8 first
return raw_data.decode('utf-8')
except UnicodeDecodeError:
try:
# Try Latin-1 as fallback (can decode any byte sequence)
decoded = raw_data.decode('latin-1')
# Add a note about encoding issues if there are suspicious characters
if any(ord(c) > 127 for c in decoded):
return f"[Encoding issue detected - displaying as Latin-1]\n{decoded}"
return decoded
except UnicodeDecodeError:
# Last resort: replace problematic characters
return raw_data.decode('utf-8', errors='replace')
def send_input(self, text):
"""Send input to the running process"""
if self.process.state() == QProcess.Running:
# Add newline if not present
if not text.endswith('\n'):
text += '\n'
self.process.write(text.encode('utf-8'))
return True
return False
def is_running(self):
"""Check if process is running"""
return self.process.state() == QProcess.Running
class OutputWindow(QDialog):
"""Detachable window for command output"""
input_sent = pyqtSignal(str) # Signal when user sends input
def __init__(self, parent=None, theme_manager=None):
super().__init__(parent)
self.setWindowTitle("Command Output")
self.setMinimumSize(600, 400)
self.theme_manager = theme_manager
layout = QVBoxLayout(self)
# Output terminal
self.output_terminal = OutputTerminal(theme_manager=self.theme_manager)
layout.addWidget(self.output_terminal)
# Add input field
input_layout = QHBoxLayout()
input_layout.setContentsMargins(0, 0, 0, 0)
input_layout.setSpacing(5)
input_label = QLabel("Input:")
input_label.setFixedWidth(50)
if self.theme_manager:
input_label.setStyleSheet(self.theme_manager.get_label_style())
else:
input_label.setStyleSheet("""
QLabel {
color: #333333;
font-weight: bold;
padding: 5px;
}
""")
input_layout.addWidget(input_label)
self.input_field = QLineEdit()
self.input_field.setMinimumHeight(30) # Match send button height
if self.theme_manager:
self.input_field.setStyleSheet(self.theme_manager.get_input_style())
else:
# Get monospace font for input field
font_manager = get_font_manager()
monospace_css = font_manager.get_monospace_font_css()
self.input_field.setStyleSheet(f"""
QLineEdit {{
background-color: white;
color: #333333;
border: 1px solid #ccc;
border-radius: 3px;
padding: 5px;
{monospace_css}
font-size: 12px;
}}
QLineEdit:disabled {{
background-color: #f0f0f0;
color: #666666;
}}
""")
self.input_field.returnPressed.connect(self.send_input)
input_layout.addWidget(self.input_field)
self.send_button = QPushButton("Send")
self.send_button.clicked.connect(self.send_input)
self.send_button.setEnabled(False) # Initially disabled
self.send_button.setFixedWidth(60) # Ensure button has adequate width
self.send_button.setMinimumHeight(30) # Ensure button is not cut off vertically
input_layout.addWidget(self.send_button)
layout.addLayout(input_layout)
# Create buttons for the dialog
button_layout = QHBoxLayout()
# Clear button
self.clear_button = QPushButton("Clear Output")
self.clear_button.clicked.connect(self.output_terminal.clear)
button_layout.addWidget(self.clear_button)
# Save button
self.save_button = QPushButton("Save Output")
self.save_button.clicked.connect(self.save_output_to_file)
if self.theme_manager:
self.save_button.setStyleSheet(self.theme_manager.get_button_style("success"))
else:
self.save_button.setStyleSheet("""
QPushButton {
background-color: #5cb85c;
color: white;
border-radius: 3px;
padding: 5px 10px;
font-weight: bold;
}
QPushButton:hover {
background-color: #4cae4c;
}
""")
button_layout.addWidget(self.save_button)
# Close button
self.close_button = QPushButton("Close")
self.close_button.clicked.connect(self.hide)
button_layout.addWidget(self.close_button)
layout.addLayout(button_layout)
def send_input(self):
"""Send input from the input field"""
text = self.input_field.text()
if text:
self.input_sent.emit(text)
# Display the input in the terminal (user feedback)
self.output_terminal.append_output(f"> {text}\n", False)
self.input_field.clear()
def set_input_enabled(self, enabled):
"""Enable or disable the input controls"""
self.input_field.setEnabled(enabled)
self.send_button.setEnabled(enabled)
def apply_theme(self):
"""Apply the current theme to all components"""
if self.theme_manager:
# Apply theme to window background
self.setStyleSheet(self.theme_manager.get_main_window_style())
# Apply theme to terminal
self.output_terminal.apply_theme()
# Apply theme to input controls
for label in self.findChildren(QLabel):
if label.text() == "Input:":
label.setStyleSheet(self.theme_manager.get_label_style())
self.input_field.setStyleSheet(self.theme_manager.get_input_style())
# Apply theme to buttons
self.save_button.setStyleSheet(self.theme_manager.get_button_style("success"))
self.close_button.setStyleSheet(self.theme_manager.get_button_style("secondary"))
self.clear_button.setStyleSheet(self.theme_manager.get_button_style("danger_alt"))
self.send_button.setStyleSheet(self.theme_manager.get_button_style("primary"))
def save_output_to_file(self):
"""Save the current output content to a file"""
# Get the plain text content
content = self.output_terminal.get_plain_text_content()
if not content.strip():
QMessageBox.information(self, "Save Output", "No output content to save.")
return
# Create default filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
default_filename = f"command_output_{timestamp}.txt"
# Open file dialog
file_path, _ = QFileDialog.getSaveFileName(
self,
"Save Command Output",