手写 Python 实现的 C++ 编译器

· · 科技·工程

import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog
import subprocess
import threading
import tempfile
import os

class CppCompilerIDE(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("C++ IDE Pro")
        self.geometry("1000x800")

        self.current_file = None
        self.indent_spaces = 4
        self.font = ('Consolas', 12)
        self.bracket_pairs = {'(': ')', '[': ']', '{': '}', '"': '"', "'": "'"}

        self.create_widgets()
        self.create_menu()
        self.bind_events()

    def create_widgets(self):
        main_panel = ttk.PanedWindow(self, orient=tk.VERTICAL)
        main_panel.pack(fill=tk.BOTH, expand=True)

        code_frame = ttk.Frame(main_panel)
        self.code_editor = scrolledtext.ScrolledText(
            code_frame,
            wrap=tk.WORD,
            font=self.font,
            undo=True,
            tabs=(f'{self.indent_spaces}c',),
            padx=5,
            pady=5
        )
        self.code_editor.pack(fill=tk.BOTH, expand=True)
        main_panel.add(code_frame, weight=3)

        io_frame = ttk.Frame(main_panel)

        input_panel = ttk.LabelFrame(io_frame, text="输入")
        self.input_area = scrolledtext.ScrolledText(
            input_panel,
            height=8,
            font=self.font
        )
        self.input_area.pack(fill=tk.BOTH, expand=True)
        input_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5)

        output_panel = ttk.LabelFrame(io_frame, text="输出")
        self.output_area = scrolledtext.ScrolledText(
            output_panel,
            height=15,
            font=self.font,
            state='disabled'
        )
        self.output_area.pack(fill=tk.BOTH, expand=True)
        output_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)

        main_panel.add(io_frame, weight=1)

        self.status_bar = ttk.Label(self, text="就绪")
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def create_menu(self):
        menu_bar = tk.Menu(self)

        file_menu = tk.Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="新建", command=self.new_file, accelerator="Ctrl+N")
        file_menu.add_command(label="打开", command=self.open_file, accelerator="Ctrl+O")
        file_menu.add_command(label="保存", command=self.save_file, accelerator="Ctrl+S")
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.quit)
        menu_bar.add_cascade(label="文件", menu=file_menu)

        edit_menu = tk.Menu(menu_bar, tearoff=0)
        edit_menu.add_command(label="撤销", command=self.code_editor.edit_undo, accelerator="Ctrl+Z")
        edit_menu.add_command(label="重做", command=self.code_editor.edit_redo, accelerator="Ctrl+Y")
        edit_menu.add_separator()
        edit_menu.add_command(label="剪切", command=lambda: self.code_editor.event_generate("<<Cut>>"))
        edit_menu.add_command(label="复制", command=lambda: self.code_editor.event_generate("<<Copy>>"))
        edit_menu.add_command(label="粘贴", command=lambda: self.code_editor.event_generate("<<Paste>>"))
        menu_bar.add_cascade(label="编辑", menu=edit_menu)

        run_menu = tk.Menu(menu_bar, tearoff=0)
        run_menu.add_command(label="运行", command=self.compile_and_run, accelerator="F5")
        menu_bar.add_cascade(label="运行", menu=run_menu)

        self.config(menu=menu_bar)

    def bind_events(self):
        self.code_editor.bind("<Return>", self.auto_indent)
        self.code_editor.bind("<Tab>", self.increase_indent)
        self.code_editor.bind("<Shift-Tab>", self.decrease_indent)
        self.code_editor.bind("<KeyRelease>", self.auto_complete)
        self.code_editor.bind("<BackSpace>", self.handle_backspace)
        self.bind("<F5>", lambda e: self.compile_and_run())
        self.bind("<Control-n>", lambda e: self.new_file())
        self.bind("<Control-o>", lambda e: self.open_file())
        self.bind("<Control-s>", lambda e: self.save_file())

    def new_file(self):
        self.code_editor.delete(1.0, tk.END)
        self.current_file = None
        self.status_bar.config(text="新文件已创建")

    def open_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("C++ Files", "*.cpp")])
        if file_path:
            with open(file_path, "r") as f:
                self.code_editor.delete(1.0, tk.END)
                self.code_editor.insert(tk.END, f.read())
            self.current_file = file_path
            self.status_bar.config(text=f"已打开: {file_path}")

    def save_file(self):
        if self.current_file:
            content = self.code_editor.get(1.0, tk.END)
            with open(self.current_file, "w") as f:
                f.write(content)
            self.status_bar.config(text=f"已保存: {self.current_file}")
        else:
            self.save_as_file()

    def save_as_file(self):
        file_path = filedialog.asksaveasfilename(defaultextension=".cpp", filetypes=[("C++ Files", "*.cpp")])
        if file_path:
            self.current_file = file_path
            self.save_file()

    def compile_and_run(self):
        code = self.code_editor.get(1.0, tk.END)
        user_input = self.input_area.get(1.0, tk.END)

        with tempfile.NamedTemporaryFile(mode='w', suffix='.cpp', delete=False) as f:
            f.write(code)
            cpp_file = f.name
            exe_file = cpp_file.replace('.cpp', '.exe' if os.name == 'nt' else '')

        def compile_thread():
            try:
                self.update_output("编译中...\n", clear=True)
                compile_cmd = f"g++ {cpp_file} -o {exe_file}"
                compile_proc = subprocess.run(compile_cmd, shell=True, capture_output=True, text=True)

                if compile_proc.returncode != 0:
                    self.update_output(f"编译错误:\n{compile_proc.stderr}")
                    return

                self.update_output("执行中...\n")
                run_proc = subprocess.Popen(exe_file, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                stdout, stderr = run_proc.communicate(input=user_input)
                self.update_output(f"输出:\n{stdout}\n错误:\n{stderr}")

            except Exception as e:
                self.update_output(f"系统错误: {str(e)}")
            finally:
                os.remove(cpp_file)
                if os.path.exists(exe_file):
                    os.remove(exe_file)

        threading.Thread(target=compile_thread).start()

    def auto_indent(self, event):
        current_line = self.code_editor.get("insert linestart", "insert lineend")
        leading_spaces = len(current_line) - len(current_line.lstrip())

        if current_line.strip().endswith("{"):
            leading_spaces += self.indent_spaces
        elif current_line.strip().startswith("}"):
            leading_spaces = max(0, leading_spaces - self.indent_spaces)

        self.code_editor.insert("insert", "\n" + " " * leading_spaces)
        return "break"

    def increase_indent(self, event):
        sel_start, sel_end = self.get_selected_lines()
        for line_num in range(sel_start, sel_end+1):
            self.modify_line_indent(line_num, self.indent_spaces)
        return "break"

    def decrease_indent(self, event):
        sel_start, sel_end = self.get_selected_lines()
        for line_num in range(sel_start, sel_end+1):
            self.modify_line_indent(line_num, -self.indent_spaces)
        return "break"

    def auto_complete(self, event):
        char = event.char
        if char in self.bracket_pairs:
            cursor_pos = self.code_editor.index(tk.INSERT)
            self.code_editor.insert(tk.INSERT, self.bracket_pairs[char])
            self.code_editor.mark_set(tk.INSERT, cursor_pos)
            return "break"

    def handle_backspace(self, event):
        current_index = self.code_editor.index(tk.INSERT)
        prev_char = self.code_editor.get(f"{current_index} - 1c", current_index)
        next_char = self.code_editor.get(current_index, f"{current_index} + 1c")

        if prev_char in self.bracket_pairs and next_char == self.bracket_pairs[prev_char]:
            self.code_editor.delete(f"{current_index} - 1c", current_index)
            self.code_editor.delete(current_index, f"{current_index} + 1c")
            return "break"

    def get_selected_lines(self):
        try:
            first_line = int(self.code_editor.index("sel.first").split(".")[0])
            last_line = int(self.code_editor.index("sel.last").split(".")[0])
            return (first_line, last_line)
        except tk.TclError:
            current_line = int(self.code_editor.index("insert").split(".")[0])
            return (current_line, current_line)

    def modify_line_indent(self, line_num, delta):
        line_start = f"{line_num}.0"
        line_end = f"{line_num}.end"
        line_content = self.code_editor.get(line_start, line_end)
        existing_spaces = len(line_content) - len(line_content.lstrip())
        new_spaces = max(0, existing_spaces + delta)
        self.code_editor.replace(line_start, line_end, " " * new_spaces + line_content.lstrip())

    def update_output(self, text, clear=False):
        self.output_area.config(state='normal')
        if clear:
            self.output_area.delete(1.0, tk.END)
        self.output_area.insert(tk.END, text)
        self.output_area.see(tk.END)
        self.output_area.config(state='disabled')

if __name__ == "__main__":
    app = CppCompilerIDE()
    app.mainloop()