Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1183 lines (1030 loc) · 53.6 KB
/
Copy pathapp.py
File metadata and controls
1183 lines (1030 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
from PySide6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QTabWidget, QFileDialog, QMessageBox
from PySide6.QtGui import QAction, QIcon, QKeySequence, QTextCursor
from PySide6.QtCore import Qt
def get_app_icon_path() -> str:
"""
Return the path to the application icon (medha-icon-256.png).
Works both from the source repo and from inside the Snap ($SNAP/app).
The snapcraft.yaml dump part ships docs/assets/icon/ to $SNAP/app/docs/assets/icon/.
"""
# Try 1: Relative to this module (medha/app.py -> project root -> docs/assets/icon/)
module_dir = os.path.dirname(os.path.abspath(__file__))
repo_icon = os.path.join(module_dir, "..", "..", "docs", "assets", "icon", "medha-icon-256.png")
repo_icon = os.path.normpath(repo_icon)
if os.path.exists(repo_icon):
return repo_icon
# Try 2: Snap environment ($SNAP/app/docs/assets/icon/medha-icon-256.png)
snap_root = os.environ.get("SNAP")
if snap_root:
snap_icon = os.path.join(snap_root, "app", "docs", "assets", "icon", "medha-icon-256.png")
if os.path.exists(snap_icon):
return snap_icon
# Try 3: Installed system location (/usr/share/icons/hicolor/256x256/apps/io.github.Kanak234.Medha.png)
# This is where the snap desktop integration would place it
system_icon = "/usr/share/icons/hicolor/256x256/apps/io.github.Kanak234.Medha.png"
if os.path.exists(system_icon):
return system_icon
# Fallback: return the repo path anyway (Qt will handle missing gracefully)
return repo_icon
from PySide6.QtWidgets import QTextEdit, QMenu
from medha.workbench import ToolDock, Workbench
from medha.editor import CodeEditorWidget
from medha.editor_widget import AdvancedCodeEditorWidget, CodeOutlineWidget
from medha.project_manager import ProjectExplorerWidget
from medha.terminal import IntegratedTerminalWidget
from medha.problems import ProblemsPanelWidget
from medha.runner import ProcessRunner
from medha.build_system import MultiTargetBuildEngine
from medha.debugger_engine import GdbDebuggerEngine, GdbDebuggerPanelWidget
from medha.analyzers.linter import StaticAnalyzerEngine, SafetyDiagnosticsPanelWidget
from medha.visualizers.memory_view import MemoryVisualizerWidget
from medha.compiler.disassembly import DisassemblyInspectorWidget
from medha.core.workspace import HybridWorkspaceController
from medha.dsa_visualizer.dsa_widget import DSAVisualizerWidget
from medha.dsa_visualizer.tracers.dsa_tracer import UniversalDSATracer
from medha.extensions.ui.panel import ExtensionsPanel
# --- MEDHĀ v2 additions -----------------------------------------------------
# turbo/panel.py : 640×480 graphics.h / conio.h screen (PRABHA runtime)
# security.py : offline beginner security scan (PyraSec rules for code)
# settings / platform_info : cross-platform paths + user choices (Windows/Linux)
from medha.turbo.panel import TurboPanel
from medha.analyzers.security import SecurityPanel, scan_file
from medha import settings
from medha import platform_info
def default_workspace(path):
"""Return a folder the student can write to.
WHY: an MSIX/Store install starts MEDHĀ with the read-only install folder (or
C:\\Windows\\System32) as the current directory; writing main.c there crashed v1.
FLOW: MedhaMainWindow.__init__ → this → ~/Documents/MEDHA Projects if needed.
"""
import tempfile
from pathlib import Path
def writable(folder):
try:
folder = Path(folder).resolve()
install = platform_info.app_root().resolve()
if folder == install or install in folder.parents:
return False
if platform_info.IS_WINDOWS:
windows = Path(os.environ.get("WINDIR", r"C:\Windows")).resolve()
if folder == windows or windows in folder.parents:
return False
# os.access(W_OK) does not reliably check Windows ACLs. Exercise an
# actual write before selecting a folder for the welcome file.
with tempfile.TemporaryFile(dir=folder):
pass
return True
except OSError:
return False
if path and writable(path):
return str(Path(path).resolve())
docs = Path.home() / "Documents"
candidates = [(docs if docs.is_dir() else Path.home()) / "MEDHA Projects",
platform_info.user_data_dir() / "Projects"]
for target in candidates:
try:
target.mkdir(parents=True, exist_ok=True)
if writable(target):
return str(target)
except OSError:
continue
raise OSError("No writable MEDHA workspace is available")
class MedhaMainWindow(QMainWindow):
def __init__(self, workspace_path=None):
super().__init__()
workspace_path = default_workspace(workspace_path if workspace_path is not None else (None if platform_info.IS_FROZEN else os.getcwd()))
self.workspace_path = workspace_path
from medha import __version__
self.setWindowTitle(f"MEDHĀ IDE {__version__} — C · C++ · Java · Python · Turbo C")
self.resize(1440, 850)
# Set application window icon (works in repo and in snap)
icon_path = get_app_icon_path()
if os.path.exists(icon_path):
self.setWindowIcon(QIcon(icon_path))
self.active_build_config = "Debug"
self.workspace_ctrl = HybridWorkspaceController(workspace_path)
# Main Central Tabbed Editor
self.tab_widget = QTabWidget()
self.tab_widget.setTabsClosable(True)
self.tab_widget.tabCloseRequested.connect(self.close_tab)
self.tab_widget.currentChanged.connect(self.on_tab_changed)
# Appearance is inherited from the shared workbench QSS.
self.setCentralWidget(self.tab_widget)
# Dock Widget 1 — Project Explorer (Left)
self.explorer = ProjectExplorerWidget(workspace_path=self.workspace_path)
self.explorer.file_selected.connect(self.open_file_path)
self.explorer.config_changed.connect(self.on_project_config_changed)
self.dock_explorer = ToolDock("Project Explorer", self)
self.dock_explorer.setWidget(self.explorer)
self.dock_explorer.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea)
self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, self.dock_explorer)
# Dock Widget 2 — Bottom Panel (Terminal, Problems, Safety Linter)
self.bottom_tabs = QTabWidget()
self.terminal = IntegratedTerminalWidget(workspace_path=self.workspace_path)
self.problems = ProblemsPanelWidget()
self.problems.problem_selected.connect(self.navigate_to_problem)
self.safety_panel = SafetyDiagnosticsPanelWidget()
self.safety_panel.diagnostic_selected.connect(self.navigate_to_problem)
self.bottom_tabs.addTab(self.terminal, "Terminal")
self.output_log = QTextEdit()
self.output_log.setReadOnly(True)
self.bottom_tabs.addTab(self.output_log, "Output")
self.bottom_tabs.addTab(self.problems, "Problems")
self.bottom_tabs.addTab(self.safety_panel, "Safety Linter (cppcheck)")
# v2: offline security scan of the student's own code (CWE + explanation)
self.security_panel = SecurityPanel()
self.security_panel.finding_selected.connect(self.navigate_to_problem)
self.bottom_tabs.addTab(self.security_panel, "Security")
# Appearance is inherited from the shared workbench QSS.
self.dock_bottom = ToolDock("Console && Safety Diagnostics", self)
self.dock_bottom.setWidget(self.bottom_tabs)
self.dock_bottom.setAllowedAreas(Qt.DockWidgetArea.BottomDockWidgetArea | Qt.DockWidgetArea.TopDockWidgetArea)
self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.dock_bottom)
# Dock Widget 3 — Universal DSA Visualizer (Right)
self.dsa_tracer = UniversalDSATracer(self)
self.dsa_widget = DSAVisualizerWidget(tracer=self.dsa_tracer, parent=self)
self.dock_dsa = ToolDock("DSA Visualizer Engine", self)
self.dock_dsa.setWidget(self.dsa_widget)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_dsa)
# Dock Widget 4 — Visual Memory & Pointer Inspector (Right)
self.memory_view = MemoryVisualizerWidget(self)
self.dock_memory = ToolDock("Live Memory && Pointers", self)
self.dock_memory.setWidget(self.memory_view)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_memory)
# Dock Widget 5 — Assembly Inspector (Right)
self.asm_inspector = DisassemblyInspectorWidget(self)
self.dock_asm = ToolDock("Live Disassembly (gcc -S)", self)
self.dock_asm.setWidget(self.asm_inspector)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_asm)
# Dock Widget 6 — GDB Debugger Engine & Panels (Right)
self.gdb_engine = GdbDebuggerEngine(self)
self.gdb_panel = QWidget()
gdb_layout = QVBoxLayout(self.gdb_panel)
gdb_layout.setContentsMargins(0, 0, 0, 0)
self.real_gdb_panel = GdbDebuggerPanelWidget(self.gdb_engine, self)
gdb_layout.addWidget(self.real_gdb_panel)
self.gdb_engine.stopped_at.connect(self.on_gdb_stopped_at)
self.gdb_engine.variables_updated.connect(self.on_gdb_variables_updated)
self.dock_gdb = ToolDock("GDB Interactive Debugger", self)
self.dock_gdb.setWidget(self.gdb_panel)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_gdb)
# Dock Widget 7 — Symbol Outline (Right)
self.outline_panel = CodeOutlineWidget(self)
self.outline_panel.symbol_selected.connect(self.navigate_to_line)
self.dock_outline = ToolDock("Symbol Outline", self)
self.dock_outline.setWidget(self.outline_panel)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_outline)
# AI Assistant Right Dock (P7)
from medha.ai_panel import AiAssistantPanelWidget
self.ai_panel = AiAssistantPanelWidget(self)
self.dock_ai = ToolDock("Offline AI Assistant", self)
self.dock_ai.setWidget(self.ai_panel)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_ai)
# Extensions Panel (Right Dock) - P8 Extensions
self.extensions_panel = ExtensionsPanel(self)
self.extensions_panel.theme_apply_requested.connect(self._on_theme_apply_requested)
self.dock_extensions = ToolDock("Extensions", self)
self.dock_extensions.setWidget(self.extensions_panel)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_extensions)
# v2: Turbo C screen — graphics.h / conio.h output drawn from the real framebuffer
self.turbo_panel = TurboPanel(self)
self.dock_turbo = ToolDock("Turbo C Screen (640×480)", self)
self.dock_turbo.setWidget(self.turbo_panel)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dock_turbo)
# Process Runner & Analyzer Engines
self.runner = ProcessRunner(self)
self.runner.output_received.connect(self.on_runner_output)
self.runner.finished.connect(self.on_runner_finished)
# Turbo mode: frames → screen panel, keys from the panel → program stdin
self.runner.turbo_started.connect(self.on_turbo_started)
self.runner.turbo_frame.connect(self.turbo_panel.on_frame)
self.runner.turbo_message.connect(self.turbo_panel.on_message)
self.turbo_panel.key_for_program.connect(self.runner.write_stdin)
self.turbo_panel.stop_requested.connect(self.runner.stop)
# typed terminal lines go to the RUNNING program first (scanf / cin / input())
self.terminal.input_override = self.runner.write_stdin
self.build_engine = MultiTargetBuildEngine(self)
self.build_engine.output_stream.connect(self.on_runner_output)
self.linter_engine = StaticAnalyzerEngine(self)
self.linter_engine.analysis_finished.connect(self.safety_panel.set_diagnostics)
# Setup MenuBar & StatusBar
self.create_menu_bar()
self.workbench = Workbench(self)
self.arrange_menus()
self.setCentralWidget(self.workbench)
self.create_status_bar()
self.apply_dark_theme()
self.show_welcome()
def show_welcome(self):
from medha.welcome import WelcomePage
for index in range(self.tab_widget.count()):
if isinstance(self.tab_widget.widget(index), WelcomePage):
self.tab_widget.widget(index).refresh_recent()
self.tab_widget.setCurrentIndex(index)
return
page = WelcomePage(self)
index = self.tab_widget.addTab(page, 'Welcome')
self.install_tab_close(page)
self.tab_widget.setCurrentIndex(index)
def show_turbo_examples(self):
menu = QMenu(self)
root = os.path.join(str(platform_info.app_root()), 'examples', 'turboc')
if os.path.isdir(root):
for name in sorted(os.listdir(root)):
if os.path.isfile(os.path.join(root, name)):
action = menu.addAction(name.replace('&', '&&'))
action.triggered.connect(lambda _=False, p=os.path.join(root, name): self.open_lab_program(p))
menu.exec(self.mapToGlobal(self.rect().center()))
def create_menu_bar(self):
menu_bar = self.menuBar()
# Appearance is inherited from the shared workbench QSS.
# File Menu
file_menu = menu_bar.addMenu("&File")
act_new = QAction("&New Scratchpad File", self)
act_new.setShortcut(QKeySequence.StandardKey.New)
act_new.triggered.connect(lambda: self.create_untitled_tab("untitled.c"))
file_menu.addAction(act_new)
act_open_file = QAction("&Open File...", self)
act_open_file.setShortcut(QKeySequence.StandardKey.Open)
act_open_file.triggered.connect(self.action_open_file)
file_menu.addAction(act_open_file)
act_open_folder = QAction("Open &Workspace Folder...", self)
act_open_folder.triggered.connect(self.action_open_folder)
file_menu.addAction(act_open_folder)
file_menu.addSeparator()
act_save = QAction("&Save File", self)
act_save.setShortcut(QKeySequence.StandardKey.Save)
act_save.triggered.connect(self.action_save_file)
file_menu.addAction(act_save)
act_save_as = QAction("Save &As...", self)
act_save_as.setShortcut(QKeySequence.StandardKey.SaveAs)
act_save_as.triggered.connect(self.action_save_as_file)
file_menu.addAction(act_save_as)
# v2: Lab Programs — copies a ready example into the workspace and opens it
lab_menu = file_menu.addMenu("Open &Lab Program")
self.build_lab_menu(lab_menu)
file_menu.addSeparator()
act_exit = QAction("E&xit", self)
act_exit.setShortcut(QKeySequence.StandardKey.Quit)
act_exit.triggered.connect(self.close)
file_menu.addAction(act_exit)
# Edit Menu
edit_menu = menu_bar.addMenu("&Edit")
act_undo = QAction("&Undo", self)
act_undo.setShortcut(QKeySequence.StandardKey.Undo)
act_undo.triggered.connect(lambda: self.get_current_editor().undo() if self.get_current_editor() else None)
edit_menu.addAction(act_undo)
act_redo = QAction("&Redo", self)
act_redo.setShortcut(QKeySequence.StandardKey.Redo)
act_redo.triggered.connect(lambda: self.get_current_editor().redo() if self.get_current_editor() else None)
edit_menu.addAction(act_redo)
# View Menu
view_menu = menu_bar.addMenu("&View")
view_menu.addAction(self.dock_explorer.toggleViewAction())
view_menu.addAction(self.dock_bottom.toggleViewAction())
view_menu.addAction(self.dock_dsa.toggleViewAction())
view_menu.addAction(self.dock_memory.toggleViewAction())
view_menu.addAction(self.dock_asm.toggleViewAction())
view_menu.addAction(self.dock_gdb.toggleViewAction())
view_menu.addAction(self.dock_outline.toggleViewAction())
view_menu.addAction(self.dock_ai.toggleViewAction())
view_menu.addAction(self.dock_extensions.toggleViewAction())
view_menu.addAction(self.dock_turbo.toggleViewAction())
# Extensions shortcut
act_extensions = QAction("Extensions", self)
act_extensions.setShortcut(QKeySequence("Ctrl+Shift+X"))
act_extensions.triggered.connect(self.dock_extensions.toggleViewAction().trigger)
self.addAction(act_extensions)
# Run Menu
run_menu = menu_bar.addMenu("&Run")
act_run = QAction("&Run Active Scratchpad File", self)
act_run.setShortcut(QKeySequence("Ctrl+F5"))
act_run.triggered.connect(self.action_run_active_file)
run_menu.addAction(act_run)
act_stop = QAction("&Stop Program", self)
act_stop.setShortcut(QKeySequence("Shift+F5"))
act_stop.triggered.connect(self.runner_stop)
run_menu.addAction(act_stop)
# Analysis Menu
analyze_menu = menu_bar.addMenu("&Analyze")
act_lint = QAction("Run &Static Safety Linter (cppcheck)", self)
act_lint.triggered.connect(self.action_run_linter)
analyze_menu.addAction(act_lint)
act_sec = QAction("&Security Scan (offline, CWE)", self)
act_sec.setShortcut(QKeySequence("Ctrl+Alt+S"))
act_sec.triggered.connect(self.action_security_scan)
analyze_menu.addAction(act_sec)
act_disasm = QAction("Inspect &Live Assembly (gcc -S)", self)
act_disasm.triggered.connect(self.action_run_disassembly)
analyze_menu.addAction(act_disasm)
# Debug Menu (P4 + GDB)
debug_menu = menu_bar.addMenu("&Debug")
act_dbg_start = QAction("Start &Debugging (F5)", self)
act_dbg_start.setShortcut(QKeySequence("F5"))
act_dbg_start.triggered.connect(self.action_start_debug)
debug_menu.addAction(act_dbg_start)
act_dbg_next = QAction("Step &Over (F10)", self)
act_dbg_next.setShortcut(QKeySequence("F10"))
act_dbg_next.triggered.connect(lambda: self.gdb_engine.step_over())
debug_menu.addAction(act_dbg_next)
act_dbg_step = QAction("Step &Into (F11)", self)
act_dbg_step.setShortcut(QKeySequence("F11"))
act_dbg_step.triggered.connect(lambda: self.gdb_engine.step_into())
debug_menu.addAction(act_dbg_step)
act_dbg_out = QAction("Step &Out (Shift+F11)", self)
act_dbg_out.setShortcut(QKeySequence("Shift+F11"))
act_dbg_out.triggered.connect(lambda: self.gdb_engine.step_out())
debug_menu.addAction(act_dbg_out)
act_dbg_stop = QAction("&Stop Debugging", self)
act_dbg_stop.triggered.connect(lambda: self.gdb_engine.stop_debug())
debug_menu.addAction(act_dbg_stop)
# LSP Menu (P3)
lsp_menu = menu_bar.addMenu("&LSP")
act_lsp_def = QAction("&Go to Definition (F12)", self)
act_lsp_def.setShortcut(QKeySequence("F12"))
act_lsp_def.triggered.connect(self.action_lsp_definition)
lsp_menu.addAction(act_lsp_def)
act_lsp_comp = QAction("Trigger &Completion (Ctrl+Space)", self)
act_lsp_comp.setShortcut(QKeySequence("Ctrl+Space"))
act_lsp_comp.triggered.connect(self.action_lsp_completion)
lsp_menu.addAction(act_lsp_comp)
# Git Menu (P5)
git_menu = menu_bar.addMenu("&Git")
act_git_status = QAction("Git &Status", self)
act_git_status.triggered.connect(self.action_git_status)
git_menu.addAction(act_git_status)
act_git_commit = QAction("Git Stage & Commit...", self)
act_git_commit.triggered.connect(self.action_git_commit)
git_menu.addAction(act_git_commit)
# Build Menu (P6 + Multi-Target)
build_menu = menu_bar.addMenu("&Build")
act_cfg_debug = QAction("Target: &Debug (-g -O0)", self)
act_cfg_debug.triggered.connect(lambda: self.set_active_build_target("Debug"))
build_menu.addAction(act_cfg_debug)
act_cfg_release = QAction("Target: &Release (-O2 -s)", self)
act_cfg_release.triggered.connect(lambda: self.set_active_build_target("Release"))
build_menu.addAction(act_cfg_release)
build_menu.addSeparator()
act_build_cfg = QAction("&Configure CMake", self)
act_build_cfg.triggered.connect(self.action_build_configure)
build_menu.addAction(act_build_cfg)
act_build_proj = QAction("&Build Project (Ctrl+Shift+B)", self)
act_build_proj.setShortcut(QKeySequence("Ctrl+Shift+B"))
act_build_proj.triggered.connect(self.action_build_project)
build_menu.addAction(act_build_proj)
# Tools Menu (v2)
tools_menu = menu_bar.addMenu("&Tools")
act_tc = QAction("&Toolchains && Run Settings…", self)
act_tc.triggered.connect(self.action_toolchains)
tools_menu.addAction(act_tc)
act_mod = QAction("&Modernize this code (Turbo → C11/C++17)…", self)
act_mod.setShortcut(QKeySequence("Ctrl+Alt+M"))
act_mod.triggered.connect(self.action_modernize)
tools_menu.addAction(act_mod)
self.act_turbo = QAction("T&urbo mode (graphics.h / conio.h / iostream.h)", self)
self.act_turbo.setCheckable(True)
self.act_turbo.setChecked(bool(settings.get("turbo_mode", True)))
self.act_turbo.toggled.connect(lambda on: settings.set("turbo_mode", on))
tools_menu.addAction(self.act_turbo)
self.act_hinglish = QAction("Explain errors in &Hinglish", self)
self.act_hinglish.setCheckable(True)
self.act_hinglish.setChecked(settings.get("explain_lang", "en") == "hi")
self.act_hinglish.toggled.connect(lambda on: settings.set("explain_lang", "hi" if on else "en"))
tools_menu.addAction(self.act_hinglish)
# Help Menu
help_menu = menu_bar.addMenu("&Help")
act_palette = QAction("&Command Palette…", self)
act_palette.setShortcut(QKeySequence("Ctrl+Shift+P"))
act_palette.triggered.connect(self.show_command_palette)
help_menu.addAction(act_palette)
act_keys = QAction("&Keyboard Shortcuts", self)
act_keys.triggered.connect(self.show_shortcuts)
help_menu.addAction(act_keys)
help_menu.addSeparator()
act_about = QAction("&About MEDHĀ IDE", self)
act_about.triggered.connect(self.show_about_dialog)
help_menu.addAction(act_about)
def arrange_menus(self):
from medha.navigation import SearchView, GitView
from PySide6.QtWidgets import QStyle, QPushButton
from medha.command_palette import collect_actions
self.legacy_actions = [action for _, action in collect_actions(self.menuBar())]
menus = {action.menu().title().replace('&', ''): action.menu()
for action in self.menuBar().actions()}
bar = self.menuBar()
for action in list(bar.actions()):
bar.removeAction(action)
# Reuse the very same QAction objects so shortcuts and connected slots survive.
selection = QMenu('Selection', self)
go = QMenu('Go', self)
terminal = QMenu('Terminal', self)
for menu in [menus['File'], menus['Edit'], selection, menus['View'], go,
menus['Run'], terminal, menus['Help']]:
bar.addMenu(menu)
menus['Run'].addMenu(menus['Debug'])
menus['Run'].addMenu(menus['Build'])
menus['Run'].addMenu(menus['Analyze'])
menus['Edit'].addMenu(menus['Tools'])
go.addMenu(menus['LSP'])
menus['View'].addMenu(menus['Git'])
def add(menu, title, shortcut, callback):
action = QAction(title, self)
if shortcut:
action.setShortcut(QKeySequence(shortcut))
action.triggered.connect(callback)
menu.addAction(action)
return action
add(selection, 'Select All', 'Ctrl+A', lambda: self.get_current_editor() and self.get_current_editor().selectAll())
add(menus['Help'], 'Welcome', None, self.show_welcome)
add(menus['File'], 'Quick Open…', 'Ctrl+P', self.show_quick_open)
add(go, 'Go to Line…', 'Ctrl+G', self.go_to_line)
add(terminal, 'Focus Terminal', 'Ctrl+`', self.focus_terminal)
add(terminal, 'Clear Terminal', None, self.terminal.output_edit.clear)
add(terminal, 'Stop Program', None, self.runner_stop)
self.search_view = SearchView(self)
search_index = self.workbench.add_view('Search', self.search_view, QStyle.StandardPixmap.SP_FileDialogContentsView)
self.git_view = GitView(self)
git_index = self.workbench.add_view('Git', self.git_view, QStyle.StandardPixmap.SP_DirLinkIcon)
order = ['Explorer', 'Search', 'Run and Debug', 'Git', 'Extensions', 'DSA', 'AI', 'Outline']
for position, title in enumerate(order):
index = self.workbench.selector.findText(title)
self.workbench.activity_layout.insertWidget(position, self.workbench.buttons[index])
add(menus['View'], 'Search Workspace', 'Ctrl+Shift+F', lambda: self.workbench.activate(search_index))
add(menus['View'], 'Source Control', 'Ctrl+Shift+G', lambda: self.workbench.activate(git_index))
add(menus['View'], 'Medhā Dark', None, lambda: self.apply_theme('dark'))
add(menus['View'], 'Medhā Light', None, lambda: self.apply_theme('light'))
self.command_centre = QPushButton('Search commands… Ctrl+Shift+P')
self.command_centre.setObjectName('commandCentre')
self.command_centre.clicked.connect(self.show_command_palette)
bar.setCornerWidget(self.command_centre, Qt.Corner.TopRightCorner)
def show_quick_open(self):
from medha.navigation import QuickOpen
QuickOpen(self.workspace_path, self.open_file_path, self).exec()
def go_to_line(self):
from PySide6.QtWidgets import QInputDialog
editor = self.get_current_editor()
if editor:
line, accepted = QInputDialog.getInt(self, 'Go to Line', 'Line:', 1, 1, editor.blockCount())
if accepted:
self.navigate_to_line(line)
def show_panel(self, widget):
self.bottom_tabs.show()
self.bottom_tabs.setCurrentWidget(widget)
self.workbench.restore_sizes()
# Build/debug/navigation handlers reveal their output even after Ctrl+J.
def focus_terminal(self):
self.dock_bottom.show()
self.show_panel(self.terminal)
self.terminal.input_line.setFocus()
def set_active_build_target(self, target):
self.active_build_config = target
self.lbl_status.setText(f"Active Build Target: {target}")
def create_status_bar(self):
from medha.status import StatusController
self.status_controller = StatusController(self)
def confirm_close(self, widget):
if not isinstance(widget, AdvancedCodeEditorWidget) or not widget.is_modified:
return True
name = os.path.basename(widget.file_path) if widget.file_path else 'Untitled'
choice = QMessageBox.question(self, 'Unsaved changes', f'Save changes to {name}?',
QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard |
QMessageBox.StandardButton.Cancel, QMessageBox.StandardButton.Save)
if choice == QMessageBox.StandardButton.Cancel:
return False
if choice == QMessageBox.StandardButton.Save:
self.tab_widget.setCurrentWidget(widget)
self.action_save_file()
return not widget.is_modified
return True
# Cancelled Save As must keep the document open just like Cancel does.
def close_tab(self, index):
if index < 0:
return
widget = self.tab_widget.widget(index)
if not self.confirm_close(widget):
return
self.tab_widget.removeTab(index)
widget.deleteLater()
if self.tab_widget.count() == 0:
self.show_welcome()
def on_tab_changed(self, index):
self.update_cursor_status()
editor = self.get_current_editor()
if editor and hasattr(editor, 'get_symbol_outline'):
symbols = editor.get_symbol_outline()
self.outline_panel.update_outline(symbols)
if editor.file_path:
self.asm_inspector.set_active_file(editor.file_path)
def update_tab_title(self, editor):
for i in range(self.tab_widget.count()):
if self.tab_widget.widget(i) == editor:
base = os.path.basename(editor.file_path) if editor.file_path else "untitled.c"
if getattr(editor, 'is_modified', False):
base += " •"
self.tab_widget.setTabText(i, base.replace("&", "&&"))
break
def update_cursor_status(self):
if hasattr(self, 'status_controller'):
self.status_controller.document_changed()
def apply_dark_theme(self):
self.apply_theme(self.workbench.prefs.value('theme', 'dark'))
def apply_theme(self, name):
from PySide6.QtWidgets import QApplication
from medha.theme import stylesheet, apply_editor
self.theme_name = name if name in ('dark', 'light') else 'dark'
self.workbench.prefs.setValue('theme', self.theme_name)
# Legacy tools supplied local dark styles. Clear those overrides so the
# shared QSS controls the whole workbench in both built-in themes.
from shiboken6 import isValid
for widget in self.findChildren(QWidget):
if isValid(widget) and widget.styleSheet():
widget.setStyleSheet('')
app = QApplication.instance()
qss = stylesheet(self.theme_name)
self.setStyleSheet(qss)
app.setProperty('medhaTheme', self.theme_name)
for index in range(self.tab_widget.count()):
editor = self.tab_widget.widget(index)
if isinstance(editor, AdvancedCodeEditorWidget):
apply_editor(editor, self.theme_name)
self.install_tab_close(editor)
from medha.workbench import activity_icon
from medha.theme import tokens
for index, button in self.workbench.buttons.items():
button.setIcon(activity_icon(self.workbench.selector.itemText(index), tokens(self.theme_name)['fg']))
if hasattr(self, 'lbl_theme'):
self.lbl_theme.setText('Medhā ' + self.theme_name.title())
def install_tab_close(self, widget):
from PySide6.QtWidgets import QTabBar, QToolButton
index = self.tab_widget.indexOf(widget)
button = QToolButton()
button.setObjectName('tabClose')
button.setText('×')
button.setAccessibleName('Close tab')
button.setFixedSize(18, 18)
button.clicked.connect(lambda: self.close_tab(self.tab_widget.indexOf(widget)))
self.tab_widget.tabBar().setTabButton(index, QTabBar.ButtonPosition.RightSide, button)
# Resolve the tab index at click time: closing earlier tabs shifts indices.
def get_current_editor(self):
widget = self.tab_widget.currentWidget()
if isinstance(widget, (CodeEditorWidget, AdvancedCodeEditorWidget)):
return widget
return None
def create_untitled_tab(self, title="untitled.c", content=""):
editor = AdvancedCodeEditorWidget(file_path=None, parent=self)
editor.lang = editor.detect_language(title)
editor.highlighter.language = editor.lang
editor.highlighter.rules.clear()
editor.highlighter.setup_rules()
editor.setPlainText(content)
editor.document().setModified(False)
editor.is_modified = False
editor.cursorPositionChanged.connect(self.update_cursor_status)
editor.textChanged.connect(lambda e=editor: self.update_tab_title(e))
editor.breakpoint_toggled.connect(self.on_breakpoint_toggled)
idx = self.tab_widget.addTab(editor, title.replace("&", "&&"))
self.install_tab_close(editor)
self.tab_widget.setCurrentIndex(idx)
self.update_cursor_status()
def open_file_path(self, path):
if not os.path.exists(path):
return
for i in range(self.tab_widget.count()):
widget = self.tab_widget.widget(i)
if isinstance(widget, (CodeEditorWidget, AdvancedCodeEditorWidget)) and widget.file_path == path:
self.tab_widget.setCurrentIndex(i)
return
try:
with open(path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
filename = os.path.basename(path)
editor = AdvancedCodeEditorWidget(file_path=path, parent=self)
editor.encoding_label = 'UTF-8 (replacement)' if '\ufffd' in content else 'UTF-8'
editor.setPlainText(content)
editor.document().setModified(False)
editor.is_modified = False
editor.cursorPositionChanged.connect(self.update_cursor_status)
editor.textChanged.connect(lambda e=editor: self.update_tab_title(e))
editor.breakpoint_toggled.connect(self.on_breakpoint_toggled)
idx = self.tab_widget.addTab(editor, filename.replace("&", "&&"))
self.install_tab_close(editor)
self.tab_widget.setCurrentIndex(idx)
recent = [path] + [old for old in settings.get('recent_files', []) if old != path]
settings.set('recent_files', recent[:20])
self.lbl_status.setText(f"Opened file: {path}")
self.update_cursor_status()
symbols = editor.get_symbol_outline()
self.outline_panel.update_outline(symbols)
self.asm_inspector.set_active_file(path)
except Exception as e:
QMessageBox.critical(self, "Error Opening File", str(e))
def on_breakpoint_toggled(self, file_path, line, is_set):
self.gdb_engine.toggle_breakpoint(file_path, line)
self.real_gdb_panel.refresh_breakpoints()
def on_project_config_changed(self, proj_name, cfg_name):
self.set_active_build_target(cfg_name)
def action_open_file(self):
path, _ = QFileDialog.getOpenFileName(self, "Open File", self.workspace_path, "All Files (*)")
if path:
self.open_file_path(path)
def action_open_folder(self):
folder = QFileDialog.getExistingDirectory(self, "Open Workspace Folder", self.workspace_path)
if folder:
self.workspace_path = folder
self.explorer.set_workspace(folder)
self.terminal.set_working_directory(folder)
self.workspace_ctrl = HybridWorkspaceController(folder)
self.status_controller.refresh()
self.lbl_status.setText(f"Opened workspace: {folder}")
def action_save_file(self):
editor = self.get_current_editor()
if not editor:
return
if not editor.file_path:
self.action_save_as_file()
else:
try:
with open(editor.file_path, 'w', encoding='utf-8') as f:
f.write(editor.toPlainText())
editor.document().setModified(False)
editor.is_modified = False
self.update_tab_title(editor)
self.lbl_status.setText(f"Saved: {editor.file_path}")
self.linter_engine.analyze_file(editor.file_path)
self.asm_inspector.set_active_file(editor.file_path)
except Exception as e:
QMessageBox.critical(self, "Error Saving File", str(e))
def action_save_as_file(self):
editor = self.get_current_editor()
if not editor:
return
path, _ = QFileDialog.getSaveFileName(self, "Save File As", self.workspace_path, "All Files (*)")
if path:
try:
with open(path, 'w', encoding='utf-8') as f:
f.write(editor.toPlainText())
editor.file_path = path
editor.lang = editor.detect_language(path)
editor.highlighter.language = editor.lang
editor.highlighter.rules.clear()
editor.highlighter.setup_rules()
editor.highlighter.rehighlight()
self.update_cursor_status()
editor.document().setModified(False)
editor.is_modified = False
self.update_tab_title(editor)
self.lbl_status.setText(f"Saved: {path}")
self.linter_engine.analyze_file(path)
self.asm_inspector.set_active_file(path)
except Exception as e:
QMessageBox.critical(self, "Error Saving File", str(e))
def action_run_active_file(self):
editor = self.get_current_editor()
if not editor:
return
self.action_save_file()
if not editor.file_path or not os.path.exists(editor.file_path):
QMessageBox.warning(self, "Run Error", "Please save scratchpad file to disk before compilation.")
return
self.show_panel(self.terminal)
self.lbl_status.setText(f"Scratchpad Running ({self.active_build_config}) {os.path.basename(editor.file_path)}...")
self.runner.run_file(editor.file_path)
def action_run_linter(self):
editor = self.get_current_editor()
if editor and editor.file_path:
self.show_panel(self.safety_panel)
self.linter_engine.analyze_file(editor.file_path)
def action_run_disassembly(self):
editor = self.get_current_editor()
if editor and editor.file_path:
self.dock_asm.show()
self.asm_inspector.set_active_file(editor.file_path)
# --- LSP Action Handlers ---
def action_lsp_definition(self):
editor = self.get_current_editor()
if not editor or not editor.file_path:
return
ext = os.path.splitext(editor.file_path)[1].lower()
lang = "c" if ext in ['.c', '.cpp', '.h', '.hpp'] else "python"
from medha.lsp import LspClient
client = LspClient(lang, self.workspace_path)
try:
client.start()
except OSError:
self.lbl_status.setText("Go to Definition needs clangd (C/C++) or pylsp (Python) — see Tools → Toolchains")
return
cursor = editor.textCursor()
line = cursor.blockNumber() + 1
col = cursor.columnNumber() + 1
res = client.definition(editor.file_path, line, col)
client.shutdown()
if res:
fpath, fline, fcol = res
self.navigate_to_problem(fpath, fline, fcol)
else:
self.lbl_status.setText("LSP: Definition not found")
def action_lsp_completion(self):
editor = self.get_current_editor()
if not editor or not editor.file_path:
return
ext = os.path.splitext(editor.file_path)[1].lower()
lang = "c" if ext in ['.c', '.cpp', '.h', '.hpp'] else "python"
from medha.lsp import LspClient
client = LspClient(lang, self.workspace_path)
try:
client.start()
except OSError:
self.lbl_status.setText("Completion needs clangd (C/C++) or pylsp (Python) — see Tools → Toolchains")
return
cursor = editor.textCursor()
line = cursor.blockNumber() + 1
col = cursor.columnNumber() + 1
items = client.completions(editor.file_path, line, col)
client.shutdown()
if items:
self.lbl_status.setText(f"LSP Completions: {', '.join(items[:5])}")
# --- Debugger Action Handlers ---
def action_start_debug(self):
editor = self.get_current_editor()
if not editor or not editor.file_path:
return
self.action_save_file()
ext = os.path.splitext(editor.file_path)[1].lower()
from medha.debugger import DebugSession
if ext in ['.c', '.cpp', '.cc', '.cxx']:
# v2: compile with the detected toolchain (bundled MinGW on Windows) into
# .medha_build/, with -g -O0 so every line can be stepped. v1 used
# os.system("gcc …"), which breaks on paths with spaces and on Windows.
import subprocess
from medha import toolchains
try:
cc = toolchains.require("g++" if ext != ".c" else "gcc")
except toolchains.ToolMissing as e:
QMessageBox.warning(self, "Debugger", str(e))
return
out_dir = os.path.join(os.path.dirname(editor.file_path), ".medha_build")
os.makedirs(out_dir, exist_ok=True)
bin_path = os.path.join(out_dir, os.path.splitext(os.path.basename(editor.file_path))[0] + platform_info.EXE)
r = subprocess.run([cc, "-g", "-O0", editor.file_path, "-o", bin_path] + (["-lm"] if ext == ".c" else []),
capture_output=True, text=True)
if r.returncode != 0:
self.terminal.append_output(r.stderr, color="#f85149")
self.lbl_status.setText("Debug build failed — fix the errors first")
return
s = DebugSession(bin_path, kind="gdb")
self.gdb_engine.start_debug(bin_path, kind="gdb")
else:
s = DebugSession(editor.file_path, kind="debugpy")
self.gdb_engine.start_debug(editor.file_path, kind="debugpy")
s.start()
cursor = editor.textCursor()
line = cursor.blockNumber() + 1
s.set_breakpoint(editor.file_path, line)
s.run()
if s.wait_for_stop(timeout=5.0):
self.lbl_status.setText(f"Debugger: Stopped at line {line}")
if hasattr(editor, 'set_execution_line'):
editor.set_execution_line(line)
s.terminate()
def on_gdb_stopped_at(self, file_path, line):
self.open_file_path(file_path)
editor = self.get_current_editor()
if editor and hasattr(editor, 'set_execution_line'):
editor.set_execution_line(line)
def on_gdb_variables_updated(self, variables):
stack_vars = []
heap_allocs = []
for name, val in variables:
# v1 showed a made-up address "0x7fffffff" for every local and guessed heap
# blocks from the value text. GDB's -stack-list-variables gives no address,
# so we show "—" instead of inventing one; pointers (0x… values) are listed
# as pointing to that address, size unknown.
stack_vars.append((name, val, "—"))
if val.strip().startswith("0x") and val.strip() != "0x0":
heap_allocs.append((name, val.strip().split()[0], "?"))
if stack_vars:
self.memory_view.update_memory_map(stack_vars, heap_allocs)
self.dsa_tracer.parse_gdb_variables(variables)
# --- Git Action Handlers ---
def action_git_status(self):
from medha.git_backend import GitBackend
git = GitBackend(self.workspace_path)
status_files = git.status()
self.show_panel(self.terminal)
self.terminal.append_output(f"[Git Status] Modified files: {status_files}\n", color="#79c0ff")
def action_git_commit(self):
from medha.git_backend import GitBackend
git = GitBackend(self.workspace_path)
status_files = git.status()
if status_files:
git.stage(status_files)
sha = git.commit("Updated from MEDHĀ IDE")
self.lbl_status.setText(f"Git Commit SHA: {sha[:7]}")
# --- Build System Action Handlers ---
def action_build_configure(self):
from medha.build import BuildSystem
bs = BuildSystem(self.workspace_path)
code, out = bs.configure()
self.show_panel(self.terminal)
self.terminal.append_output(f"[CMake Configure Exit {code}]\n{out}\n", color="#79c0ff")
def action_build_project(self):
from medha.build import BuildSystem
bs = BuildSystem(self.workspace_path)
code, out, artifact = bs.build()
self.show_panel(self.terminal)
self.terminal.append_output(f"[Build Exit {code}] Artifact: {artifact}\n{out}\n", color="#79c0ff")
def on_runner_output(self, text, stream_type):
self.output_log.insertPlainText(text)
color = "#f85149" if stream_type == 'stderr' else None
self.terminal.append_output(text, color=color)
def on_runner_finished(self, exit_code, diagnostics):
if self.runner.binary_to_run and getattr(self, "_turbo_active", False):
self.turbo_panel.on_finished(exit_code)
self._turbo_active = False
self.problems.set_diagnostics(diagnostics)
self.status_controller.set_diagnostics(diagnostics)
if diagnostics:
self.show_panel(self.problems)
self.lbl_status.setText(f"Build Finished with {len(diagnostics)} diagnostic error(s).")
else:
self.lbl_status.setText(f"Process Finished with exit code {exit_code}.")
def navigate_to_problem(self, fpath, line, col=1):
self.open_file_path(fpath)
editor = self.get_current_editor()
if editor:
block = editor.document().findBlockByLineNumber(max(0, line - 1))
cursor = editor.textCursor()
cursor.setPosition(block.position() + max(0, col - 1))
editor.setTextCursor(cursor)
editor.setFocus()
def navigate_to_line(self, line):
editor = self.get_current_editor()
if editor:
block = editor.document().findBlockByLineNumber(max(0, line - 1))