-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonBox_v8.py
More file actions
3630 lines (2932 loc) · 135 KB
/
PythonBox_v8.py
File metadata and controls
3630 lines (2932 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python Code Architect (Baukasten v8)
FEATURES v5:
- Suchen & Ersetzen (Ctrl+F / Ctrl+H)
- Integriertes Output-Panel
- Tab-System für mehrere Dateien
- Undo/Redo Buttons
- Statusbar mit Zeilen/Spalten-Anzeige
- Zuletzt geöffnete Dateien
FEATURES v6:
- Auto-Completion für Python Keywords und Builtins
- Code Folding (Klassen/Funktionen einklappen)
- Einstellungs-Dialog (Schriftgröße, Tab-Größe, Theme)
- Gehe zu Zeile (Ctrl+G)
- Bracket Matching (Klammer-Hervorhebung)
FEATURES v7:
- Minimap (Code-Vorschau rechts)
- Code Folding (Klassen/Funktionen einklappen mit +/- Buttons)
- Linter-Integration (Pylint/Flake8 Fehleranzeige)
- Git-Integration (Status, Diff, Modified-Anzeige)
- Fehler-Markierungen im Editor (rote Wellenlinien)
NEUE FEATURES v8:
- VS Code Integration (In VS Code öffnen/debuggen)
- PDB Debugger im Output-Panel (interaktiv)
- Breakpoint-Verwaltung (visuell im Editor)
- Debug-Toolbar mit Step-Controls
- PyCharm Integration (optional)
"""
import sys
import os
import shutil
import json
import ast
import subprocess
import re
import threading
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, List, Tuple
# GUI Imports
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QSplitter, QTreeWidget, QTreeWidgetItem,
QMessageBox, QInputDialog, QPlainTextEdit, QFrame, QComboBox,
QDialog, QFormLayout, QDialogButtonBox, QTextEdit, QMenu,
QFileDialog, QProgressBar, QCheckBox, QStyle, QSystemTrayIcon,
QTabWidget, QTabBar, QLineEdit, QToolBar, QStatusBar,
QDockWidget, QGroupBox, QRadioButton, QCompleter, QSpinBox,
QScrollBar, QSlider, QSizePolicy, QListWidget, QListWidgetItem,
QToolTip
)
from PySide6.QtCore import (
Qt, QSize, QRect, QRegularExpression, QUrl, QMimeData, QProcess,
QTimer, Signal, QSettings, QStringListModel, QPoint, QEvent
)
from PySide6.QtGui import (
QFont, QColor, QPainter, QTextFormat, QSyntaxHighlighter,
QTextCharFormat, QPalette, QIcon, QKeySequence, QTextCursor,
QTextDocument, QFontMetrics, QPen, QBrush, QAction, QShortcut
)
def build_external_python_command(script_path: Path) -> List[str]:
"""Build a command that runs a script with the current Python interpreter."""
interpreter = sys.executable or ("python.exe" if sys.platform == "win32" else "python3")
script = str(script_path)
if sys.platform == "win32":
return ['cmd', '/c', 'start', '', 'cmd', '/k', interpreter, script]
terminal = shutil.which("x-terminal-emulator")
if terminal:
return [terminal, '-e', interpreter, script]
return [interpreter, script]
# ============================================================================
# MODERN UI THEME
# ============================================================================
def set_dark_theme(app):
app.setStyle("Fusion")
dark_palette = QPalette()
dark_color = QColor(40, 40, 40)
dark_palette.setColor(QPalette.ColorRole.Window, dark_color)
dark_palette.setColor(QPalette.ColorRole.WindowText, Qt.white)
dark_palette.setColor(QPalette.ColorRole.Base, QColor(30, 30, 30))
dark_palette.setColor(QPalette.AlternateBase, dark_color)
dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
dark_palette.setColor(QPalette.ToolTipText, Qt.white)
dark_palette.setColor(QPalette.ColorRole.Text, Qt.white)
dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
dark_palette.setColor(QPalette.ButtonText, Qt.white)
dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
dark_palette.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218))
dark_palette.setColor(QPalette.ColorRole.HighlightedText, Qt.black)
app.setPalette(dark_palette)
app.setStyleSheet("""
QTreeWidget { background-color: #252525; border: 1px solid #444; color: #ddd; }
QHeaderView::section { background-color: #353535; border: 1px solid #444; }
QPlainTextEdit { background-color: #1e1e1e; color: #d4d4d4; font-family: Consolas, monospace; }
QPushButton {
background-color: #3a3a3a; border: 1px solid #555;
padding: 6px 12px; border-radius: 4px; color: white;
}
QPushButton:hover { background-color: #4a4a4a; border-color: #2a82da; }
QPushButton:pressed { background-color: #2a82da; }
QPushButton:disabled { background-color: #2a2a2a; color: #666; }
QSplitter::handle { background-color: #444; width: 2px; }
QMenuBar { background-color: #353535; color: white; }
QMenuBar::item:selected { background-color: #2a82da; }
QMenu { background-color: #353535; color: white; border: 1px solid #555; }
QMenu::item:selected { background-color: #2a82da; }
QTabWidget::pane { border: 1px solid #444; background: #1e1e1e; }
QTabBar::tab {
background: #353535; color: #aaa; padding: 8px 16px;
border: 1px solid #444; border-bottom: none; margin-right: 2px;
}
QTabBar::tab:selected { background: #1e1e1e; color: white; border-bottom: 1px solid #1e1e1e; }
QTabBar::tab:hover { background: #4a4a4a; }
QLineEdit {
background: #2a2a2a; border: 1px solid #555; color: white;
padding: 4px 8px; border-radius: 3px;
}
QLineEdit:focus { border-color: #2a82da; }
QToolBar { background: #353535; border: none; spacing: 3px; padding: 3px; }
QToolBar QToolButton { background: transparent; border: none; padding: 4px; }
QToolBar QToolButton:hover { background: #4a4a4a; border-radius: 3px; }
QDockWidget { color: white; }
QDockWidget::title { background: #353535; padding: 6px; }
""")
# ============================================================================
# EDITOR KOMPONENTEN
# ============================================================================
class LineNumberArea(QWidget):
"""Widget für Zeilennummern-Anzeige und Breakpoint-Verwaltung.
Zeigt Zeilennummern links vom Code-Editor an und ermöglicht das Setzen
von Breakpoints durch Klick auf die Zeilennummer.
"""
def __init__(self, editor):
super().__init__(editor)
self.codeEditor = editor
def sizeHint(self):
return QSize(self.codeEditor.lineNumberAreaWidth(), 0)
def paintEvent(self, event):
self.codeEditor.lineNumberAreaPaintEvent(event)
def mousePressEvent(self, event):
"""Weiterleitung an Editor für Breakpoint-Toggle (NEU v8)"""
self.codeEditor.lineNumberAreaMousePress(event)
class CodeEditor(QPlainTextEdit):
"""Erweiterter Code-Editor mit umfangreichen Entwicklungs-Features.
Features:
- Zeilennummern-Anzeige mit Breakpoint-Support
- Syntax-Highlighting für Python
- Auto-Completion (Keywords, Builtins)
- Bracket Matching (Klammer-Hervorhebung)
- Code Folding (Klassen/Funktionen einklappbar)
- Linter-Integration (Pylint/Flake8 Fehleranzeige)
- Git-Integration (Modified/Added Lines Anzeige)
- Minimap (Code-Vorschau)
- Suchen & Ersetzen mit Highlighting
Signals:
cursorPositionInfo(int, int): Sendet Cursor-Position (Zeile, Spalte)
modificationChanged(bool): Sendet Änderungsstatus des Dokuments
"""
cursorPositionInfo = Signal(int, int) # Zeile, Spalte
modificationChanged = Signal(bool)
# Klammer-Paare für Matching
BRACKETS = {'(': ')', '[': ']', '{': '}', ')': '(', ']': '[', '}': '{'}
OPEN_BRACKETS = '([{'
CLOSE_BRACKETS = ')]}'
def __init__(self, parent=None):
super().__init__(parent)
# Search highlighting - MUSS vor highlightCurrentLine() initialisiert werden!
self.search_selections = []
self.bracket_selections = []
self.error_selections = [] # NEU v7: Linter-Fehler
# Settings
self.autocomplete_enabled = True
self.bracket_matching_enabled = True
self.show_line_numbers = True
self.show_folding = True # NEU v7
# Linter Errors (NEU v7)
self.linter_errors: List[Dict] = []
self.git_modified_lines: set = set()
self.git_added_lines: set = set()
# Breakpoints (NEU v8)
self.breakpoints: set = set() # Set von Zeilennummern
self.current_debug_line: int = -1 # Aktuelle Debug-Zeile
self.lineNumberArea = LineNumberArea(self)
# Folding Area (NEU v7)
self.foldingArea = FoldingArea(self)
self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
self.updateRequest.connect(self.updateLineNumberArea)
self.cursorPositionChanged.connect(self.highlightCurrentLine)
self.cursorPositionChanged.connect(self.emitCursorPosition)
self.cursorPositionChanged.connect(self.matchBrackets)
self.document().modificationChanged.connect(self.modificationChanged.emit)
self.updateLineNumberAreaWidth(0)
self.highlightCurrentLine()
font = QFont("Consolas", 10)
font.setStyleHint(QFont.Monospace)
self.setFont(font)
self.setLineWrapMode(QPlainTextEdit.NoWrap)
self.setTabStopDistance(self.fontMetrics().horizontalAdvance(' ') * 4)
# Auto-Completion Setup
self.completer = None
self.setup_completer()
def setup_completer(self):
"""Initialisiert den Auto-Completer"""
words = sorted(set(PYTHON_KEYWORDS + PYTHON_BUILTINS + list(PYTHON_SNIPPETS.keys())))
self.completer = QCompleter(words, self)
self.completer.setWidget(self)
self.completer.setCompletionMode(QCompleter.PopupCompletion)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.activated.connect(self.insert_completion)
# Popup Style
popup = self.completer.popup()
popup.setStyleSheet("""
QListView {
background-color: #2d2d2d;
color: #ddd;
border: 1px solid #555;
selection-background-color: #2a82da;
}
""")
def insert_completion(self, completion: str):
"""Fügt die Completion ein"""
tc = self.textCursor()
extra = len(completion) - len(self.completer.completionPrefix())
tc.movePosition(QTextCursor.MoveOperation.Left)
tc.movePosition(QTextCursor.MoveOperation.EndOfWord)
# Prüfe ob es ein Snippet ist
if completion in PYTHON_SNIPPETS:
tc.movePosition(QTextCursor.MoveOperation.StartOfWord, QTextCursor.MoveMode.KeepAnchor)
tc.removeSelectedText()
tc.insertText(PYTHON_SNIPPETS[completion])
else:
tc.insertText(completion[-extra:])
self.setTextCursor(tc)
def text_under_cursor(self) -> str:
"""Gibt das Wort unter dem Cursor zurück"""
tc = self.textCursor()
tc.select(QTextCursor.SelectionType.WordUnderCursor)
return tc.selectedText()
def keyPressEvent(self, event):
"""Überschriebenes Key Event für Auto-Completion und Auto-Indent"""
# Completer aktiv?
if self.completer and self.completer.popup().isVisible():
if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape,
Qt.Key_Tab, Qt.Key_Backtab):
event.ignore()
return
# Auto-Indent bei Enter
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
cursor = self.textCursor()
line = cursor.block().text()
indent = len(line) - len(line.lstrip())
# Extra Indent nach :
if line.rstrip().endswith(':'):
indent += 4
super().keyPressEvent(event)
cursor = self.textCursor()
cursor.insertText(' ' * indent)
return
# Auto-Close Brackets
bracket_pairs = {'(': ')', '[': ']', '{': '}', '"': '"', "'": "'"}
if event.text() in bracket_pairs:
cursor = self.textCursor()
# Prüfe ob Cursor innerhalb eines String-Literals ist
full_text = self.toPlainText()
cursor_pos = cursor.position()
mask = self._build_string_comment_mask(full_text)
if cursor_pos < len(mask) and mask[cursor_pos]:
# Innerhalb von String/Kommentar: kein Auto-Close
super().keyPressEvent(event)
return
super().keyPressEvent(event)
cursor = self.textCursor()
cursor.insertText(bracket_pairs[event.text()])
cursor.movePosition(QTextCursor.MoveOperation.Left)
self.setTextCursor(cursor)
return
super().keyPressEvent(event)
# Auto-Completion Trigger
if self.autocomplete_enabled and self.completer:
prefix = self.text_under_cursor()
if len(prefix) < 2:
self.completer.popup().hide()
return
if prefix != self.completer.completionPrefix():
self.completer.setCompletionPrefix(prefix)
self.completer.popup().setCurrentIndex(
self.completer.completionModel().index(0, 0)
)
cr = self.cursorRect()
cr.setWidth(self.completer.popup().sizeHintForColumn(0) +
self.completer.popup().verticalScrollBar().sizeHint().width())
self.completer.complete(cr)
def matchBrackets(self):
"""Hebt passende Klammern hervor"""
self.bracket_selections = []
if not self.bracket_matching_enabled:
self.highlightCurrentLine()
return
cursor = self.textCursor()
text = self.toPlainText()
pos = cursor.position()
if pos >= len(text):
self.highlightCurrentLine()
return
char_at_pos = text[pos] if pos < len(text) else ''
char_before = text[pos - 1] if pos > 0 else ''
bracket_char = None
bracket_pos = None
if char_at_pos in self.BRACKETS:
bracket_char = char_at_pos
bracket_pos = pos
elif char_before in self.BRACKETS:
bracket_char = char_before
bracket_pos = pos - 1
if bracket_char and bracket_pos is not None:
match_pos = self.find_matching_bracket(text, bracket_pos, bracket_char)
if match_pos is not None:
# Hervorhebungs-Format
fmt = QTextCharFormat()
fmt.setBackground(QColor(80, 80, 0))
fmt.setForeground(QColor(255, 255, 0))
# Erste Klammer
sel1 = QTextEdit.ExtraSelection()
sel1.format = fmt
cur1 = self.textCursor()
cur1.setPosition(bracket_pos)
cur1.setPosition(bracket_pos + 1, QTextCursor.MoveMode.KeepAnchor)
sel1.cursor = cur1
self.bracket_selections.append(sel1)
# Zweite Klammer
sel2 = QTextEdit.ExtraSelection()
sel2.format = fmt
cur2 = self.textCursor()
cur2.setPosition(match_pos)
cur2.setPosition(match_pos + 1, QTextCursor.MoveMode.KeepAnchor)
sel2.cursor = cur2
self.bracket_selections.append(sel2)
self.highlightCurrentLine()
@staticmethod
def _build_string_comment_mask(text: str) -> list:
"""Gibt eine Bool-Maske zurück: True an jeder Position die in einem String oder Kommentar liegt."""
mask = [False] * len(text)
i = 0
n = len(text)
while i < n:
# Triple-quotes (muessen vor single-quotes geprueft werden)
for delim in ('"""', "'''"):
if text[i:i + 3] == delim:
end = text.find(delim, i + 3)
if end == -1:
end = n - 3
end += 3
for j in range(i, min(end, n)):
mask[j] = True
i = end
break
else:
# Single-line comment
if text[i] == '#':
j = i
while j < n and text[j] != '\n':
mask[j] = True
j += 1
i = j
# Single/double quoted string
elif text[i] in ('"', "'"):
q = text[i]
mask[i] = True
i += 1
while i < n and text[i] != q:
if text[i] == '\\':
mask[i] = True
i += 1 # escape char
if i < n:
mask[i] = True
i += 1
if i < n:
mask[i] = True # closing quote
i += 1
else:
i += 1
return mask
def find_matching_bracket(self, text: str, pos: int, bracket: str) -> int:
"""Findet die passende Klammer; ignoriert Strings und Kommentare."""
mask = self._build_string_comment_mask(text)
if bracket in self.OPEN_BRACKETS:
# Suche vorwärts
target = self.BRACKETS[bracket]
direction = 1
start = pos + 1
end = len(text)
else:
# Suche rückwärts
target = self.BRACKETS[bracket]
direction = -1
start = pos - 1
end = -1
count = 1
i = start
while i != end:
if not mask[i]:
char = text[i]
if char == bracket:
count += 1
elif char == target:
count -= 1
if count == 0:
return i
i += direction
return None
def emitCursorPosition(self):
cursor = self.textCursor()
line = cursor.blockNumber() + 1
col = cursor.columnNumber() + 1
self.cursorPositionInfo.emit(line, col)
def lineNumberAreaWidth(self):
digits = 1
max_val = max(1, self.blockCount())
while max_val >= 10:
max_val //= 10
digits += 1
width = 20 + self.fontMetrics().horizontalAdvance('9') * digits
# Platz für Git-Markierung
width += 4
return width
def foldingAreaWidth(self):
return 14 if self.show_folding else 0
def updateLineNumberAreaWidth(self, _):
total_margin = self.lineNumberAreaWidth() + self.foldingAreaWidth()
self.setViewportMargins(total_margin, 0, 0, 0)
def updateLineNumberArea(self, rect, dy):
if dy:
self.lineNumberArea.scroll(0, dy)
self.foldingArea.scroll(0, dy)
else:
self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())
self.foldingArea.update(0, rect.y(), self.foldingArea.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.updateLineNumberAreaWidth(0)
def resizeEvent(self, event):
super().resizeEvent(event)
cr = self.contentsRect()
line_width = self.lineNumberAreaWidth()
fold_width = self.foldingAreaWidth()
self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), line_width, cr.height()))
self.foldingArea.setGeometry(QRect(cr.left() + line_width, cr.top(), fold_width, cr.height()))
def lineNumberAreaPaintEvent(self, event):
painter = QPainter(self.lineNumberArea)
painter.fillRect(event.rect(), QColor(35, 35, 35))
block = self.firstVisibleBlock()
blockNumber = block.blockNumber()
top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
bottom = top + int(self.blockBoundingRect(block).height())
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
line_num = blockNumber + 1
number = str(line_num)
# Breakpoint-Markierung (NEU v8) - roter Kreis
if line_num in self.breakpoints:
painter.setBrush(QColor(200, 50, 50))
painter.setPen(Qt.NoPen)
circle_size = min(12, self.fontMetrics().height() - 2)
painter.drawEllipse(2, top + 2, circle_size, circle_size)
# Aktuelle Debug-Zeile (NEU v8) - gelber Pfeil
if line_num == self.current_debug_line:
painter.setBrush(QColor(255, 255, 0))
painter.setPen(Qt.NoPen)
# Pfeil zeichnen
arrow_y = top + self.fontMetrics().height() // 2
painter.drawPolygon([
QPoint(4, arrow_y - 4),
QPoint(12, arrow_y),
QPoint(4, arrow_y + 4)
])
# Git-Markierung (NEU v7)
if line_num in self.git_added_lines:
painter.fillRect(14, top, 3, self.fontMetrics().height(), QColor(0, 180, 0))
elif line_num in self.git_modified_lines:
painter.fillRect(14, top, 3, self.fontMetrics().height(), QColor(200, 150, 0))
# Linter-Fehler-Markierung (NEU v7)
has_error = any(e['line'] == line_num and e['severity'] == 'error' for e in self.linter_errors)
has_warning = any(e['line'] == line_num and e['severity'] == 'warning' for e in self.linter_errors)
if has_error:
painter.setPen(QColor(255, 80, 80))
elif has_warning:
painter.setPen(QColor(255, 200, 80))
else:
painter.setPen(QColor(100, 100, 100))
painter.drawText(18, top, self.lineNumberArea.width() - 22,
self.fontMetrics().height(), Qt.AlignRight, number)
block = block.next()
top = bottom
bottom = top + int(self.blockBoundingRect(block).height())
blockNumber += 1
def lineNumberAreaMousePress(self, event):
"""Klick auf Zeilennummer-Bereich zum Setzen von Breakpoints (NEU v8)"""
if event.button() == Qt.LeftButton:
# Finde angeklickte Zeile
block = self.firstVisibleBlock()
top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
while block.isValid():
block_height = int(self.blockBoundingRect(block).height())
if top <= event.y() < top + block_height:
line = block.blockNumber() + 1
self.toggle_breakpoint(line)
break
top += block_height
block = block.next()
def toggle_breakpoint(self, line: int) -> bool:
"""Setzt oder entfernt Breakpoint, gibt neuen Status zurück (NEU v8)"""
if line in self.breakpoints:
self.breakpoints.remove(line)
status = False
else:
self.breakpoints.add(line)
status = True
self.lineNumberArea.update()
return status
def set_debug_line(self, line: int):
"""Setzt aktuelle Debug-Zeile (NEU v8)"""
self.current_debug_line = line
self.lineNumberArea.update()
# Zeile zentrieren
if line > 0:
cursor = self.textCursor()
cursor.movePosition(QTextCursor.MoveOperation.Start)
cursor.movePosition(QTextCursor.MoveOperation.Down, QTextCursor.MoveMode.MoveAnchor, line - 1)
self.setTextCursor(cursor)
self.centerCursor()
def clear_debug_state(self):
"""Löscht Debug-Zustand (NEU v8)"""
self.current_debug_line = -1
self.lineNumberArea.update()
def set_linter_errors(self, errors: List[Dict]):
"""Setzt Linter-Fehler und aktualisiert Markierungen (NEU v7)"""
self.linter_errors = errors
self.error_selections = []
for error in errors:
line = error.get('line', 1) - 1
block = self.document().findBlockByNumber(line)
if not block.isValid():
continue
selection = QTextEdit.ExtraSelection()
# Fehler = rot unterstrichen, Warnung = gelb
if error.get('severity') == 'error':
selection.format.setUnderlineColor(QColor(255, 80, 80))
else:
selection.format.setUnderlineColor(QColor(255, 200, 80))
selection.format.setUnderlineStyle(QTextCharFormat.WaveUnderline)
cursor = QTextCursor(block)
cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor)
selection.cursor = cursor
self.error_selections.append(selection)
self.lineNumberArea.update()
self.highlightCurrentLine()
def set_git_status(self, added: set, modified: set):
"""Setzt Git-Status für Zeilen (NEU v7)"""
self.git_added_lines = added
self.git_modified_lines = modified
self.lineNumberArea.update()
def highlightCurrentLine(self):
extraSelections = list(self.search_selections) + list(self.bracket_selections) + list(self.error_selections)
if not self.isReadOnly():
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(QColor(45, 45, 45))
selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extraSelections.insert(0, selection)
self.setExtraSelections(extraSelections)
def highlightSearchResults(self, pattern: str, case_sensitive: bool = False):
"""Hebt alle Suchergebnisse hervor"""
self.search_selections = []
if not pattern:
self.highlightCurrentLine()
return 0
flags = QTextDocument.FindFlag(0)
if case_sensitive:
flags |= QTextDocument.FindFlag.FindCaseSensitively
cursor = QTextCursor(self.document())
highlight_format = QTextCharFormat()
highlight_format.setBackground(QColor(100, 100, 0))
highlight_format.setForeground(QColor(255, 255, 255))
count = 0
while True:
cursor = self.document().find(pattern, cursor, flags)
if cursor.isNull():
break
selection = QTextEdit.ExtraSelection()
selection.format = highlight_format
selection.cursor = cursor
self.search_selections.append(selection)
count += 1
self.highlightCurrentLine()
return count
def clearSearchHighlight(self):
self.search_selections = []
self.highlightCurrentLine()
class PythonSyntaxHighlighter(QSyntaxHighlighter):
"""Syntax-Highlighter für Python-Code.
Hebt folgende Elemente farblich hervor:
- Keywords (and, if, def, class, etc.) - Blau
- Decorators (@decorator) - Lila
- Strings ("text", 'text') - Orange
- Kommentare (# comment) - Grün
- Funktions-/Klassendefinitionen - Gelb
- Zahlen - Hellgrün
"""
def __init__(self, document):
super().__init__(document)
self.highlighting_rules = []
# Keywords (Blau)
keyword_format = QTextCharFormat()
keyword_format.setForeground(QColor(86, 156, 214))
keyword_format.setFontWeight(QFont.Weight.Bold)
keywords = [
'and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with',
'yield', 'True', 'False', 'None', 'self'
]
for word in keywords:
self.highlighting_rules.append((QRegularExpression(r'\b' + word + r'\b'), keyword_format))
# Decorators (Lila)
dec_format = QTextCharFormat()
dec_format.setForeground(QColor(189, 147, 249))
self.highlighting_rules.append((QRegularExpression(r'@[^\n]+'), dec_format))
# Strings (Orange)
string_format = QTextCharFormat()
string_format.setForeground(QColor(206, 145, 120))
self.highlighting_rules.append((QRegularExpression(r'"[^"\\]*(\\.[^"\\]*)*"'), string_format))
self.highlighting_rules.append((QRegularExpression(r"'[^'\\]*(\\.[^'\\]*)*'"), string_format))
# Comments (Grün)
comment_format = QTextCharFormat()
comment_format.setForeground(QColor(106, 153, 85))
comment_format.setFontItalic(True)
self.highlighting_rules.append((QRegularExpression(r'#[^\n]*'), comment_format))
# Function/Class Definitions (Gelb)
func_format = QTextCharFormat()
func_format.setForeground(QColor(220, 220, 170))
self.highlighting_rules.append((QRegularExpression(r'\bdef\s+(\w+)'), func_format))
self.highlighting_rules.append((QRegularExpression(r'\bclass\s+(\w+)'), func_format))
# Numbers (Hellgrün)
number_format = QTextCharFormat()
number_format.setForeground(QColor(181, 206, 168))
self.highlighting_rules.append((QRegularExpression(r'\b[0-9]+\.?[0-9]*\b'), number_format))
def highlightBlock(self, text):
for pattern, fmt in self.highlighting_rules:
match_iterator = pattern.globalMatch(text)
while match_iterator.hasNext():
match = match_iterator.next()
self.setFormat(match.capturedStart(), match.capturedLength(), fmt)
# ============================================================================
# MINIMAP (NEU v7!)
# ============================================================================
class Minimap(QPlainTextEdit):
"""Minimap für Code-Vorschau und schnelle Navigation.
Zeigt eine miniaturisierte Version des gesamten Code-Dokuments an und
ermöglicht schnelles Springen zu beliebigen Code-Stellen durch Klick.
Hebt den aktuell sichtbaren Bereich im Haupteditor hervor.
Args:
editor: Referenz zum Haupt-CodeEditor
parent: Optional parent widget
"""
def __init__(self, editor: 'CodeEditor', parent=None):
super().__init__(parent)
self.editor = editor
self.setReadOnly(True)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setTextInteractionFlags(Qt.NoTextInteraction)
self.setCursor(Qt.PointingHandCursor)
# Sehr kleine Schrift für Minimap
font = QFont("Consolas", 1)
self.setFont(font)
# Styling
self.setStyleSheet("""
QPlainTextEdit {
background-color: #1a1a1a;
border: none;
border-left: 1px solid #333;
}
""")
self.setFixedWidth(80)
self.setLineWrapMode(QPlainTextEdit.NoWrap)
# Viewport-Rechteck
self.viewport_rect = QRect()
# Debounce-Timer für textChanged (verhindert Update bei jedem Tastendruck)
self._update_timer = QTimer()
self._update_timer.setSingleShot(True)
self._update_timer.setInterval(300)
self._update_timer.timeout.connect(self._do_update_content)
# Verbindungen
self.editor.textChanged.connect(self._update_timer.start)
self.editor.verticalScrollBar().valueChanged.connect(self.update_viewport)
self.update_content()
def update_content(self):
"""Aktualisiert den Minimap-Inhalt sofort (z.B. beim ersten Laden)."""
self._do_update_content()
def _do_update_content(self):
"""Führt die eigentliche Minimap-Aktualisierung durch."""
self.setPlainText(self.editor.toPlainText())
self.update_viewport()
def update_viewport(self):
"""Aktualisiert die Viewport-Anzeige"""
editor_scrollbar = self.editor.verticalScrollBar()
if editor_scrollbar.maximum() == 0:
# Keine Scrollbar nötig
self.viewport_rect = QRect(0, 0, self.width(), self.height())
else:
# Berechne sichtbaren Bereich
ratio = editor_scrollbar.value() / max(1, editor_scrollbar.maximum())
visible_ratio = self.editor.viewport().height() / max(1, self.editor.document().size().height())
y = int(ratio * self.height())
h = int(visible_ratio * self.height())
h = max(20, min(h, self.height()))
self.viewport_rect = QRect(0, y, self.width(), h)
self.viewport().update()
def paintEvent(self, event):
super().paintEvent(event)
# Zeichne Viewport-Rechteck
painter = QPainter(self.viewport())
painter.setOpacity(0.3)
painter.fillRect(self.viewport_rect, QColor(100, 100, 200))
painter.setOpacity(1.0)
painter.setPen(QPen(QColor(100, 100, 200), 1))
painter.drawRect(self.viewport_rect)
def mousePressEvent(self, event):
"""Springt zur geklickten Position"""
if event.button() == Qt.LeftButton:
self._scroll_to_position(event.pos().y())
def mouseMoveEvent(self, event):
"""Scrollt beim Ziehen"""
if event.buttons() & Qt.LeftButton:
self._scroll_to_position(event.pos().y())
def _scroll_to_position(self, y: int):
"""Scrollt den Editor zur Y-Position"""
ratio = y / max(1, self.height())
scrollbar = self.editor.verticalScrollBar()
scrollbar.setValue(int(ratio * scrollbar.maximum()))
# ============================================================================
# FOLDING AREA (NEU v7!)
# ============================================================================
class FoldingArea(QWidget):
"""Bereich für Code-Folding Buttons (+/-).
Ermöglicht das Ein- und Ausklappen von Code-Blöcken wie Funktionen,
Klassen, if/for/while-Statements. Zeigt +/- Buttons für alle faltbaren
Blöcke an. Erkennt faltbare Blöcke automatisch anhand der Einrückung
und ':' am Zeilenende.
Args:
editor: Referenz zum Haupt-CodeEditor
"""
def __init__(self, editor: 'CodeEditor'):
super().__init__(editor)
self.editor = editor
self.folded_blocks = set() # Set von gefalteten Block-Nummern
self.foldable_blocks = {} # {block_number: end_block_number}
self.setFixedWidth(14)
self.setCursor(Qt.PointingHandCursor)
# Debounce-Timer für textChanged (verhindert Update bei jedem Tastendruck)
self._fold_timer = QTimer()
self._fold_timer.setSingleShot(True)
self._fold_timer.setInterval(300)
self._fold_timer.timeout.connect(self.update_foldable_blocks)
# Verbindungen
self.editor.blockCountChanged.connect(self.update_foldable_blocks)
self.editor.textChanged.connect(self._fold_timer.start)
def update_foldable_blocks(self):
"""Ermittelt faltbare Blöcke (def, class, if, for, etc.)"""
self.foldable_blocks = {}
text = self.editor.toPlainText()
lines = text.split('\n')
stack = [] # (start_line, indent)
for i, line in enumerate(lines):
stripped = line.strip()
if not stripped:
continue
indent = len(line) - len(line.lstrip())
# Schließe vorherige Blöcke wenn Einrückung zurückgeht
while stack and indent <= stack[-1][1]:
start_line, start_indent = stack.pop()
if i > start_line + 1: # Mindestens 2 Zeilen
self.foldable_blocks[start_line] = i - 1
# Neuen Block starten bei :
if stripped.endswith(':') and not stripped.startswith('#'):
stack.append((i, indent))
# Verbleibende Blöcke schließen
for start_line, _ in stack:
if len(lines) > start_line + 1:
self.foldable_blocks[start_line] = len(lines) - 1
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(event.rect(), QColor(35, 35, 35))
block = self.editor.firstVisibleBlock()
top = int(self.editor.blockBoundingGeometry(block).translated(
self.editor.contentOffset()).top())
bottom = top + int(self.editor.blockBoundingRect(block).height())
while block.isValid() and top <= event.rect().bottom():
block_number = block.blockNumber()
if block_number in self.foldable_blocks:
# Zeichne +/- Symbol
is_folded = block_number in self.folded_blocks
symbol = "+" if is_folded else "−"
painter.setPen(QColor(150, 150, 150))
painter.drawText(0, top, self.width(),
self.editor.fontMetrics().height(),
Qt.AlignCenter, symbol)
block = block.next()
top = bottom
bottom = top + int(self.editor.blockBoundingRect(block).height())
def mousePressEvent(self, event):
"""Toggle Folding beim Klick"""
if event.button() != Qt.LeftButton:
return
# Finde geklickten Block
block = self.editor.firstVisibleBlock()
top = int(self.editor.blockBoundingGeometry(block).translated(
self.editor.contentOffset()).top())
while block.isValid():
block_height = int(self.editor.blockBoundingRect(block).height())
if top <= event.y() < top + block_height:
block_number = block.blockNumber()
if block_number in self.foldable_blocks:
self.toggle_fold(block_number)