import sys
import os
import subprocess
import tempfile
import re
import threading
import webbrowser
import json
import shutil
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

# 快捷键配置文件
SHORTCUTS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'shortcuts.json')

# 默认快捷键
DEFAULT_SHORTCUTS = {
    'run': 'F5',
    'stop': 'F6',
    'compile': 'Ctrl+B',
    'format': 'Ctrl+Shift+F',
    'new_file': 'Ctrl+N',
    'open_file': 'Ctrl+O',
    'save_file': 'Ctrl+S',
    'save_as': 'Ctrl+Shift+S',
    'clear_output': 'Ctrl+L',
    'clear_all': 'Ctrl+Shift+L',
    'exit': 'Ctrl+Q',
    'send_input': 'Enter',
}

class CodeEditor(QPlainTextEdit):
    """纯 Python 实现的代码编辑器，支持高亮和补全"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.current_theme = "梦幻紫"
        self.setFont(QFont('Consolas', 12))
        self.setTabStopWidth(4 * 10)
        
        # 初始样式
        self.apply_theme(self.current_theme)
        
        self.highlighter = GoHighlighter(self.document(), self.current_theme)
        
        # 自动补全
        self.completion_list = QListWidget()
        self.completion_list.setWindowFlags(Qt.Popup)
        self.completion_list.hide()
        self.completion_list.itemClicked.connect(self.insert_completion)
        
        # 按使用频率和重要性排序的关键词
        self.go_keywords = [
            'func', 'if', 'else', 'for', 'range', 'return', 'var', 'const',
            'type', 'struct', 'interface', 'package', 'import', 'defer', 'go',
            'switch', 'case', 'default', 'break', 'continue', 'goto', 'select',
            'chan', 'map', 'make', 'new', 'len', 'cap', 'append', 'copy',
            'delete', 'close', 'panic', 'recover', 'print', 'println',
            'int', 'string', 'bool', 'byte', 'rune', 'float64', 'float32',
            'int64', 'int32', 'int16', 'int8', 'uint64', 'uint32', 'uint16',
            'uint8', 'uint', 'uintptr', 'complex64', 'complex128', 'error',
            'fmt', 'io', 'os', 'strings', 'strconv', 'time', 'math', 'rand',
            'net', 'http', 'json', 'ioutil', 'bufio', 'regexp', 'sync',
            'Print', 'Println', 'Printf', 'Scan', 'Scanln', 'Scanf',
            'Errorf', 'Fprint', 'Fprintf', 'Sprint', 'Sprintf',
        ]
        
        self.completion_timer = QTimer()
        self.completion_timer.setSingleShot(True)
        self.completion_timer.timeout.connect(self.show_completions)
        
        self.textChanged.connect(self.on_text_changed)
        self.last_completion_word = ""
    
    def apply_theme(self, theme_name):
        """应用主题"""
        self.current_theme = theme_name
        themes = get_themes()
        theme = themes.get(theme_name, themes["梦幻紫"])
        
        # 应用编辑器样式
        bg_color = theme['bg']
        text_color = theme['text']
        selection_bg = theme['selection_bg']
        selection_color = theme['selection_color']
        border_color = theme.get('border', '#3c3c3c')
        
        self.setStyleSheet(f"""
            QPlainTextEdit {{
                background-color: {bg_color};
                color: {text_color};
                selection-background-color: {selection_bg};
                selection-color: {selection_color};
                border: 1px solid {border_color};
                border-radius: 5px;
                padding: 5px;
            }}
        """)
        
        # 更新高亮器
        if hasattr(self, 'highlighter'):
            self.highlighter.update_theme(theme_name)
            self.highlighter.rehighlight()
    
    def on_text_changed(self):
        cursor = self.textCursor()
        cursor.select(QTextCursor.WordUnderCursor)
        word = cursor.selectedText()
        
        if len(word) >= 2:
            if self.is_in_string_or_comment():
                self.completion_list.hide()
                return
            self.completion_timer.start(300)
        else:
            self.completion_list.hide()
            
    def is_in_string_or_comment(self):
        """检查光标是否在字符串或注释中"""
        cursor = self.textCursor()
        pos = cursor.position()
        text = self.toPlainText()
        
        before_text = text[:pos]
        
        in_string = False
        in_backtick = False
        in_single_quote = False
        in_line_comment = False
        in_block_comment = False
        
        i = 0
        while i < len(before_text):
            char = before_text[i]
            
            if char == '/' and i + 1 < len(before_text) and before_text[i+1] == '/':
                in_line_comment = True
                while i < len(before_text) and before_text[i] != '\n':
                    i += 1
                in_line_comment = False
                continue
                
            if char == '/' and i + 1 < len(before_text) and before_text[i+1] == '*':
                in_block_comment = True
                while i + 1 < len(before_text):
                    if before_text[i] == '*' and before_text[i+1] == '/':
                        in_block_comment = False
                        i += 2
                        break
                    i += 1
                continue
                
            if char == '"' and not in_single_quote and not in_backtick:
                in_string = not in_string
            elif char == '`' and not in_string and not in_single_quote:
                in_backtick = not in_backtick
            elif char == "'" and not in_string and not in_backtick:
                in_single_quote = not in_single_quote
                
            i += 1
            
        return in_string or in_backtick or in_single_quote or in_line_comment or in_block_comment
            
    def show_completions(self):
        cursor = self.textCursor()
        cursor.select(QTextCursor.WordUnderCursor)
        word = cursor.selectedText().lower()
        
        if not word or len(word) < 2:
            self.completion_list.hide()
            return
            
        if word == self.last_completion_word:
            return
        self.last_completion_word = word
            
        matches = []
        for kw in self.go_keywords:
            if kw.lower().startswith(word) and kw.lower() != word:
                matches.append(kw)
        
        matches = matches[:15]
        
        if not matches:
            self.completion_list.hide()
            return
            
        self.completion_list.clear()
        self.completion_list.addItems(matches)
        
        rect = self.cursorRect(cursor)
        pos = self.mapToGlobal(rect.bottomRight())
        
        screen_geometry = QApplication.primaryScreen().geometry()
        list_width = 250
        list_height = min(300, len(matches) * 25)
        
        if pos.x() + list_width > screen_geometry.width():
            pos.setX(screen_geometry.width() - list_width - 10)
        if pos.y() + list_height > screen_geometry.height():
            pos.setY(pos.y() - list_height - rect.height())
            
        self.completion_list.setGeometry(pos.x(), pos.y(), list_width, list_height)
        self.completion_list.show()
        
    def insert_completion(self, item):
        cursor = self.textCursor()
        cursor.select(QTextCursor.WordUnderCursor)
        cursor.removeSelectedText()
        cursor.insertText(item.text())
        self.setTextCursor(cursor)
        self.completion_list.hide()
        self.last_completion_word = ""
        
    def keyPressEvent(self, event):
        if self.completion_list.isVisible():
            if event.key() == Qt.Key_Down:
                current = self.completion_list.currentRow()
                if current < self.completion_list.count() - 1:
                    self.completion_list.setCurrentRow(current + 1)
                return
            elif event.key() == Qt.Key_Up:
                current = self.completion_list.currentRow()
                if current > 0:
                    self.completion_list.setCurrentRow(current - 1)
                return
            elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
                if self.completion_list.currentItem():
                    self.insert_completion(self.completion_list.currentItem())
                return
            elif event.key() == Qt.Key_Tab:
                if self.completion_list.currentItem():
                    self.insert_completion(self.completion_list.currentItem())
                return
            elif event.key() == Qt.Key_Escape:
                self.completion_list.hide()
                self.last_completion_word = ""
                return
            elif event.key() == Qt.Key_Space:
                self.completion_list.hide()
                self.last_completion_word = ""
                super().keyPressEvent(event)
                return
                
        super().keyPressEvent(event)
        
        if event.key() == Qt.Key_Space and event.modifiers() == Qt.ControlModifier:
            self.last_completion_word = ""
            self.show_completions()
            
    def get_text(self):
        return self.toPlainText()
        
    def set_text(self, text):
        self.setPlainText(text)
        
    def clear_text(self):
        self.clear()

class GoHighlighter(QSyntaxHighlighter):
    """Go 语法高亮器 - 支持主题切换"""
    def __init__(self, parent=None, theme_name="梦幻紫"):
        super().__init__(parent)
        self.theme_name = theme_name
        self.update_theme(theme_name)
        
    def update_theme(self, theme_name):
        """更新主题"""
        self.theme_name = theme_name
        themes = get_themes()
        theme = themes.get(theme_name, themes["梦幻紫"])
        self.colors = theme['colors']
        self.rules = []
        self.setup_rules()
        
    def setup_rules(self):
        """设置高亮规则"""
        colors = self.colors
        
        # 关键字
        keyword_format = QTextCharFormat()
        keyword_format.setForeground(QColor(colors['keyword']))
        keyword_format.setFontWeight(QFont.Bold)
        keywords = [
            'break', 'case', 'chan', 'const', 'continue', 'default', 'defer',
            'else', 'fallthrough', 'for', 'func', 'go', 'goto', 'if', 'import',
            'interface', 'map', 'package', 'range', 'return', 'select', 'struct',
            'switch', 'type', 'var'
        ]
        for word in keywords:
            self.rules.append((QRegExp(f'\\b{word}\\b'), keyword_format))
        
        # 类型
        type_format = QTextCharFormat()
        type_format.setForeground(QColor(colors['type']))
        types = ['bool', 'byte', 'complex64', 'complex128', 'error', 'float32', 
                'float64', 'int', 'int8', 'int16', 'int32', 'int64', 'rune', 
                'string', 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'uintptr']
        for word in types:
            self.rules.append((QRegExp(f'\\b{word}\\b'), type_format))
        
        # 内置函数
        builtin_format = QTextCharFormat()
        builtin_format.setForeground(QColor(colors['builtin']))
        builtins = ['append', 'cap', 'close', 'complex', 'copy', 'delete', 'imag',
                   'len', 'make', 'new', 'panic', 'print', 'println', 'real', 'recover']
        for word in builtins:
            self.rules.append((QRegExp(f'\\b{word}\\b'), builtin_format))
        
        # 字符串
        string_format = QTextCharFormat()
        string_format.setForeground(QColor(colors['string']))
        self.rules.append((QRegExp('".*"'), string_format))
        self.rules.append((QRegExp('`.*`'), string_format))
        
        # 字符
        char_format = QTextCharFormat()
        char_format.setForeground(QColor(colors['string']))
        self.rules.append((QRegExp("'.'"), char_format))
        
        # 注释
        comment_format = QTextCharFormat()
        comment_format.setForeground(QColor(colors['comment']))
        self.rules.append((QRegExp('//[^\n]*'), comment_format))
        self.multiline_comment_format = comment_format
        
        # 数字
        number_format = QTextCharFormat()
        number_format.setForeground(QColor(colors['number']))
        self.rules.append((QRegExp('\\b[0-9]+\\b'), number_format))
        self.rules.append((QRegExp('\\b0x[0-9a-fA-F]+\\b'), number_format))
        self.rules.append((QRegExp('\\b[0-9]+\\.[0-9]+\\b'), number_format))
        
        # 函数调用
        function_format = QTextCharFormat()
        function_format.setForeground(QColor(colors['function']))
        self.rules.append((QRegExp('\\b[a-zA-Z_][a-zA-Z0-9_]*\\s*\\('), function_format))
        
        # package 和 import
        package_format = QTextCharFormat()
        package_format.setForeground(QColor(colors['package']))
        package_format.setFontWeight(QFont.Bold)
        self.rules.append((QRegExp('\\bpackage\\b'), package_format))
        self.rules.append((QRegExp('\\bimport\\b'), package_format))
        
        # 操作符
        operator_format = QTextCharFormat()
        operator_format.setForeground(QColor(colors['operator']))
        operators = ['\\+', '-', '\\*', '/', '%', '&', '\\|', '\\^', '<', '>', '=', '!']
        for op in operators:
            self.rules.append((QRegExp(op), operator_format))
            
    def highlightBlock(self, text):
        for pattern, format in self.rules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)
        
        self.setCurrentBlockState(0)
        
        start_index = 0
        if self.previousBlockState() != 1:
            start_index = text.find('/*')
            
        while start_index >= 0:
            end_index = text.find('*/', start_index + 2)
            if end_index == -1:
                self.setCurrentBlockState(1)
                comment_len = len(text) - start_index
            else:
                comment_len = end_index - start_index + 2
                
            self.setFormat(start_index, comment_len, self.multiline_comment_format)
            start_index = text.find('/*', start_index + comment_len)

def get_themes():
    """获取所有主题配置 - 完整界面配色"""
    return {
        "梦幻紫": {
            'name': '梦幻紫',
            'bg': '#1a1025',
            'text': '#e8d5f5',
            'selection_bg': '#4a1a6b',
            'selection_color': '#ffffff',
            'border': '#4a2a6b',
            'menu_bg': '#2a1a3a',
            'menu_text': '#e8d5f5',
            'menu_hover': '#4a1a6b',
            'toolbar_bg': '#2a1a3a',
            'status_bg': '#1a1025',
            'status_text': '#e8d5f5',
            'button_bg': '#6a3a8a',
            'button_hover': '#8a4aaa',
            'button_text': '#ffffff',
            'input_bg': '#2a1a3a',
            'input_text': '#e8d5f5',
            'output_bg': '#1a1025',
            'output_text': '#e8d5f5',
            'splitter': '#3a2a4a',
            'colors': {
                'keyword': '#c792ea',
                'type': '#7c4dff',
                'builtin': '#f78c6c',
                'string': '#ffcb6b',
                'comment': '#676e95',
                'number': '#c3e88d',
                'function': '#82aaff',
                'package': '#ffcb6b',
                'operator': '#89ddff',
            }
        },
        "樱花粉": {
            'name': '樱花粉',
            'bg': '#1e1218',
            'text': '#f5d5e0',
            'selection_bg': '#5a2a3a',
            'selection_color': '#ffffff',
            'border': '#4a2a3a',
            'menu_bg': '#2e1a22',
            'menu_text': '#f5d5e0',
            'menu_hover': '#5a2a3a',
            'toolbar_bg': '#2e1a22',
            'status_bg': '#1e1218',
            'status_text': '#f5d5e0',
            'button_bg': '#8a3a5a',
            'button_hover': '#aa4a7a',
            'button_text': '#ffffff',
            'input_bg': '#2e1a22',
            'input_text': '#f5d5e0',
            'output_bg': '#1e1218',
            'output_text': '#f5d5e0',
            'splitter': '#3a2a3a',
            'colors': {
                'keyword': '#ff8aae',
                'type': '#ff6b8a',
                'builtin': '#ffb3c6',
                'string': '#ffd1dc',
                'comment': '#6a4a5a',
                'number': '#ffb3c6',
                'function': '#ff8aae',
                'package': '#ffd1dc',
                'operator': '#ffb3c6',
            }
        },
        "薄荷绿": {
            'name': '薄荷绿',
            'bg': '#0f1e16',
            'text': '#d5f5e0',
            'selection_bg': '#2a5a3a',
            'selection_color': '#ffffff',
            'border': '#2a4a3a',
            'menu_bg': '#1a2e22',
            'menu_text': '#d5f5e0',
            'menu_hover': '#2a5a3a',
            'toolbar_bg': '#1a2e22',
            'status_bg': '#0f1e16',
            'status_text': '#d5f5e0',
            'button_bg': '#3a8a5a',
            'button_hover': '#4aaa6a',
            'button_text': '#ffffff',
            'input_bg': '#1a2e22',
            'input_text': '#d5f5e0',
            'output_bg': '#0f1e16',
            'output_text': '#d5f5e0',
            'splitter': '#2a3a3a',
            'colors': {
                'keyword': '#69db7c',
                'type': '#20c997',
                'builtin': '#63e6be',
                'string': '#ffd43b',
                'comment': '#5a6a6a',
                'number': '#8ce99a',
                'function': '#4dabf7',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        },
        "天空蓝": {
            'name': '天空蓝',
            'bg': '#0f1a2e',
            'text': '#d5e5f5',
            'selection_bg': '#2a4a6a',
            'selection_color': '#ffffff',
            'border': '#2a3a5a',
            'menu_bg': '#1a2a3e',
            'menu_text': '#d5e5f5',
            'menu_hover': '#2a4a6a',
            'toolbar_bg': '#1a2a3e',
            'status_bg': '#0f1a2e',
            'status_text': '#d5e5f5',
            'button_bg': '#3a6a8a',
            'button_hover': '#4a8aaa',
            'button_text': '#ffffff',
            'input_bg': '#1a2a3e',
            'input_text': '#d5e5f5',
            'output_bg': '#0f1a2e',
            'output_text': '#d5e5f5',
            'splitter': '#2a3a4a',
            'colors': {
                'keyword': '#74c0fc',
                'type': '#4dabf7',
                'builtin': '#66d9e8',
                'string': '#ffd43b',
                'comment': '#5a6a7a',
                'number': '#8ce99a',
                'function': '#fcc419',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        },
        "珊瑚橙": {
            'name': '珊瑚橙',
            'bg': '#1e120f',
            'text': '#f5ddd5',
            'selection_bg': '#5a2a1a',
            'selection_color': '#ffffff',
            'border': '#4a2a1a',
            'menu_bg': '#2e1a12',
            'menu_text': '#f5ddd5',
            'menu_hover': '#5a2a1a',
            'toolbar_bg': '#2e1a12',
            'status_bg': '#1e120f',
            'status_text': '#f5ddd5',
            'button_bg': '#8a4a2a',
            'button_hover': '#aa5a3a',
            'button_text': '#ffffff',
            'input_bg': '#2e1a12',
            'input_text': '#f5ddd5',
            'output_bg': '#1e120f',
            'output_text': '#f5ddd5',
            'splitter': '#3a2a1a',
            'colors': {
                'keyword': '#ff8a6c',
                'type': '#ff6b4a',
                'builtin': '#ffb38a',
                'string': '#ffd1a8',
                'comment': '#6a4a3a',
                'number': '#ffb38a',
                'function': '#ff8a6c',
                'package': '#ffd1a8',
                'operator': '#ffb38a',
            }
        },
        "森林绿": {
            'name': '森林绿',
            'bg': '#0f1a0f',
            'text': '#d5e8d5',
            'selection_bg': '#2a4a2a',
            'selection_color': '#ffffff',
            'border': '#2a3a2a',
            'menu_bg': '#1a2a1a',
            'menu_text': '#d5e8d5',
            'menu_hover': '#2a4a2a',
            'toolbar_bg': '#1a2a1a',
            'status_bg': '#0f1a0f',
            'status_text': '#d5e8d5',
            'button_bg': '#3a6a3a',
            'button_hover': '#4a8a4a',
            'button_text': '#ffffff',
            'input_bg': '#1a2a1a',
            'input_text': '#d5e8d5',
            'output_bg': '#0f1a0f',
            'output_text': '#d5e8d5',
            'splitter': '#2a3a2a',
            'colors': {
                'keyword': '#69db7c',
                'type': '#2b8a3e',
                'builtin': '#8ce99a',
                'string': '#ffd43b',
                'comment': '#4a6a4a',
                'number': '#b2f2bb',
                'function': '#4dabf7',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        },
        "极光蓝": {
            'name': '极光蓝',
            'bg': '#0a0e1a',
            'text': '#d5e8f5',
            'selection_bg': '#1a3a5a',
            'selection_color': '#ffffff',
            'border': '#2a3a5a',
            'menu_bg': '#1a1a2e',
            'menu_text': '#d5e8f5',
            'menu_hover': '#1a3a5a',
            'toolbar_bg': '#1a1a2e',
            'status_bg': '#0a0e1a',
            'status_text': '#d5e8f5',
            'button_bg': '#2a5a7a',
            'button_hover': '#3a7a9a',
            'button_text': '#ffffff',
            'input_bg': '#1a1a2e',
            'input_text': '#d5e8f5',
            'output_bg': '#0a0e1a',
            'output_text': '#d5e8f5',
            'splitter': '#2a2a4a',
            'colors': {
                'keyword': '#4dabf7',
                'type': '#3b9ae1',
                'builtin': '#66d9e8',
                'string': '#ffd43b',
                'comment': '#5a6a7a',
                'number': '#8ce99a',
                'function': '#fcc419',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        },
        "薰衣草": {
            'name': '薰衣草',
            'bg': '#1a1020',
            'text': '#e5d5f5',
            'selection_bg': '#3a2a5a',
            'selection_color': '#ffffff',
            'border': '#3a2a5a',
            'menu_bg': '#2a1a3a',
            'menu_text': '#e5d5f5',
            'menu_hover': '#3a2a5a',
            'toolbar_bg': '#2a1a3a',
            'status_bg': '#1a1020',
            'status_text': '#e5d5f5',
            'button_bg': '#5a3a7a',
            'button_hover': '#7a4a9a',
            'button_text': '#ffffff',
            'input_bg': '#2a1a3a',
            'input_text': '#e5d5f5',
            'output_bg': '#1a1020',
            'output_text': '#e5d5f5',
            'splitter': '#3a2a4a',
            'colors': {
                'keyword': '#b197fc',
                'type': '#845ef7',
                'builtin': '#9775fa',
                'string': '#ffd43b',
                'comment': '#5a4a6a',
                'number': '#b2f2bb',
                'function': '#4dabf7',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        },
        "玫瑰金": {
            'name': '玫瑰金',
            'bg': '#1a1018',
            'text': '#f5dde8',
            'selection_bg': '#5a2a3a',
            'selection_color': '#ffffff',
            'border': '#4a2a3a',
            'menu_bg': '#2a1a22',
            'menu_text': '#f5dde8',
            'menu_hover': '#5a2a3a',
            'toolbar_bg': '#2a1a22',
            'status_bg': '#1a1018',
            'status_text': '#f5dde8',
            'button_bg': '#8a4a6a',
            'button_hover': '#aa5a8a',
            'button_text': '#ffffff',
            'input_bg': '#2a1a22',
            'input_text': '#f5dde8',
            'output_bg': '#1a1018',
            'output_text': '#f5dde8',
            'splitter': '#3a2a3a',
            'colors': {
                'keyword': '#ff6b8a',
                'type': '#ff8aae',
                'builtin': '#ffb3c6',
                'string': '#ffd1dc',
                'comment': '#6a4a5a',
                'number': '#ffb3c6',
                'function': '#ff6b8a',
                'package': '#ffd1dc',
                'operator': '#ffb3c6',
            }
        },
        "星辰黑": {
            'name': '星辰黑',
            'bg': '#0a0a0f',
            'text': '#e0e0f0',
            'selection_bg': '#2a2a4a',
            'selection_color': '#ffffff',
            'border': '#2a2a4a',
            'menu_bg': '#1a1a2a',
            'menu_text': '#e0e0f0',
            'menu_hover': '#2a2a4a',
            'toolbar_bg': '#1a1a2a',
            'status_bg': '#0a0a0f',
            'status_text': '#e0e0f0',
            'button_bg': '#4a4a6a',
            'button_hover': '#6a6a8a',
            'button_text': '#ffffff',
            'input_bg': '#1a1a2a',
            'input_text': '#e0e0f0',
            'output_bg': '#0a0a0f',
            'output_text': '#e0e0f0',
            'splitter': '#2a2a3a',
            'colors': {
                'keyword': '#7c7cf8',
                'type': '#5c5cf8',
                'builtin': '#9c9cf8',
                'string': '#ffd43b',
                'comment': '#5a5a6a',
                'number': '#8ce99a',
                'function': '#fcc419',
                'package': '#ffd43b',
                'operator': '#66d9e8',
            }
        }
    }

class CheckableListWidget(QListWidget):
    """支持复选框的列表"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSelectionMode(QListWidget.NoSelection)
        
    def addItem(self, item):
        """添加带复选框的项"""
        if isinstance(item, str):
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)
            list_item.setCheckState(Qt.Unchecked)
            super().addItem(list_item)
        else:
            super().addItem(item)
            
    def addItems(self, items):
        """批量添加带复选框的项"""
        for item in items:
            self.addItem(item)
            
    def get_checked_items(self):
        """获取所有选中的项"""
        checked = []
        for i in range(self.count()):
            item = self.item(i)
            if item.checkState() == Qt.Checked:
                checked.append(item.text())
        return checked
        
    def select_all(self, checked=True):
        """全选或取消全选"""
        state = Qt.Checked if checked else Qt.Unchecked
        for i in range(self.count()):
            self.item(i).setCheckState(state)

class BuildExeDialog(QDialog):
    """打包exe对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.setWindowTitle('📦 打包 EXE')
        self.setGeometry(300, 300, 650, 550)
        self.is_building = False
        
        # 默认值
        self.app_name = 'myapp'
        self.output_dir = os.path.join(os.getcwd(), 'dist')
        self.goos = 'windows'
        self.goarch = 'amd64'
        self.hide_console = False
        
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setSpacing(12)
        
        # 标题
        title_label = QLabel('📦 Go 代码打包器')
        title_label.setStyleSheet("""
            font-size: 20px;
            font-weight: bold;
            padding: 10px 0;
            color: #e8d5f5;
        """)
        layout.addWidget(title_label)
        
        # 源码目录（自动使用当前程序目录）
        src_layout = QHBoxLayout()
        src_label = QLabel('📂 源码目录：')
        src_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        src_layout.addWidget(src_label)
        
        self.src_path = QLineEdit()
        self.src_path.setText(os.path.dirname(os.path.abspath(__file__)))
        self.src_path.setReadOnly(True)
        self.src_path.setStyleSheet("""
            QLineEdit {
                padding: 8px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
        """)
        src_layout.addWidget(self.src_path)
        layout.addLayout(src_layout)
        
        # 应用名称
        name_layout = QHBoxLayout()
        name_label = QLabel('🏷️ 应用名称：')
        name_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        name_layout.addWidget(name_label)
        
        self.name_input = QLineEdit()
        self.name_input.setText('myapp')
        self.name_input.setPlaceholderText('输入应用名称（不含.exe）')
        self.name_input.setStyleSheet("""
            QLineEdit {
                padding: 8px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        name_layout.addWidget(self.name_input)
        layout.addLayout(name_layout)
        
        # 输出目录
        out_layout = QHBoxLayout()
        out_label = QLabel('📁 输出目录：')
        out_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        out_layout.addWidget(out_label)
        
        self.out_path = QLineEdit()
        self.out_path.setText(self.output_dir)
        self.out_path.setStyleSheet("""
            QLineEdit {
                padding: 8px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        out_layout.addWidget(self.out_path)
        
        out_browse_btn = QPushButton('浏览...')
        out_browse_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 18px;
                border-radius: 6px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        out_browse_btn.clicked.connect(self.browse_output)
        out_layout.addWidget(out_browse_btn)
        layout.addLayout(out_layout)
        
        # 图标选择
        icon_layout = QHBoxLayout()
        icon_label = QLabel('🖼️ 应用图标：')
        icon_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        icon_layout.addWidget(icon_label)
        
        self.icon_path = QLineEdit()
        self.icon_path.setPlaceholderText('可选，选择 .ico 文件')
        self.icon_path.setStyleSheet("""
            QLineEdit {
                padding: 8px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        icon_layout.addWidget(self.icon_path)
        
        icon_browse_btn = QPushButton('选择图标')
        icon_browse_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 18px;
                border-radius: 6px;
                background-color: #6d6d6d;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        icon_browse_btn.clicked.connect(self.browse_icon)
        icon_layout.addWidget(icon_browse_btn)
        layout.addLayout(icon_layout)
        
        # 构建选项分组
        options_group = QGroupBox('⚙️ 构建选项')
        options_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #3c3c3c;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 10px;
            }
        """)
        options_layout = QGridLayout()
        options_group.setLayout(options_layout)
        
        # 目标系统
        options_layout.addWidget(QLabel('目标系统：'), 0, 0)
        self.os_combo = QComboBox()
        self.os_combo.addItems(['windows', 'linux', 'darwin'])
        self.os_combo.setStyleSheet("""
            QComboBox {
                padding: 6px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QComboBox::drop-down {
                border: none;
                padding-right: 10px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #d4d4d4;
                margin-right: 5px;
            }
            QComboBox:hover {
                border-color: #0e639c;
            }
            QComboBox QAbstractItemView {
                background-color: #1a1a1a;
                color: #d4d4d4;
                border: 1px solid #3c3c3c;
                selection-background-color: #0e639c;
                padding: 5px;
            }
        """)
        options_layout.addWidget(self.os_combo, 0, 1)
        
        # 架构
        options_layout.addWidget(QLabel('架构：'), 0, 2)
        self.arch_combo = QComboBox()
        self.arch_combo.addItems(['amd64', '386', 'arm64', 'arm'])
        self.arch_combo.setStyleSheet("""
            QComboBox {
                padding: 6px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QComboBox::drop-down {
                border: none;
                padding-right: 10px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #d4d4d4;
                margin-right: 5px;
            }
            QComboBox:hover {
                border-color: #0e639c;
            }
            QComboBox QAbstractItemView {
                background-color: #1a1a1a;
                color: #d4d4d4;
                border: 1px solid #3c3c3c;
                selection-background-color: #0e639c;
                padding: 5px;
            }
        """)
        options_layout.addWidget(self.arch_combo, 0, 3)
        
        # 隐藏控制台
        self.hide_console_check = QCheckBox('隐藏控制台窗口（GUI程序）')
        self.hide_console_check.setStyleSheet("""
            QCheckBox {
                font-size: 13px;
                padding: 5px 0;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
            }
        """)
        options_layout.addWidget(self.hide_console_check, 1, 0, 1, 4)
        
        layout.addWidget(options_group)
        
        # 日志输出
        log_group = QGroupBox('📋 构建日志')
        log_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #3c3c3c;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 10px;
            }
        """)
        log_layout = QVBoxLayout()
        log_group.setLayout(log_layout)
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setFont(QFont('Consolas', 11))
        self.log_text.setStyleSheet("""
            QTextEdit {
                background-color: #0a0a0a;
                font-family: 'Consolas', monospace;
                font-size: 12px;
                padding: 10px;
                border-radius: 6px;
                border: 1px solid #2a2a2a;
                color: #d4d4d4;
            }
        """)
        log_layout.addWidget(self.log_text)
        layout.addWidget(log_group)
        
        # 状态栏和按钮
        bottom_layout = QHBoxLayout()
        
        self.status_label = QLabel('就绪')
        self.status_label.setStyleSheet("color: #888; font-size: 13px;")
        bottom_layout.addWidget(self.status_label)
        
        bottom_layout.addStretch()
        
        self.build_btn = QPushButton('🚀 开始打包')
        self.build_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 35px;
                font-weight: bold;
                font-size: 14px;
                border-radius: 6px;
                background-color: #388a34;
                color: white;
            }
            QPushButton:hover {
                background-color: #45a341;
            }
            QPushButton:disabled {
                background-color: #6d6d6d;
            }
        """)
        self.build_btn.clicked.connect(self.start_build)
        bottom_layout.addWidget(self.build_btn)
        
        close_btn = QPushButton('关闭')
        close_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 25px;
                font-weight: bold;
                font-size: 14px;
                border-radius: 6px;
                background-color: #6d6d6d;
                color: white;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        close_btn.clicked.connect(self.close)
        bottom_layout.addWidget(close_btn)
        
        layout.addLayout(bottom_layout)
        
    def browse_output(self):
        """选择输出目录"""
        directory = QFileDialog.getExistingDirectory(self, '选择输出目录', self.out_path.text())
        if directory:
            self.out_path.setText(directory)
            
    def browse_icon(self):
        """选择图标文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, '选择图标文件', '', '图标文件 (*.ico);;所有文件 (*)'
        )
        if file_path:
            self.icon_path.setText(file_path)
            
    def log_message(self, message):
        """添加日志"""
        self.log_text.append(message)
        # 滚动到底部
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.log_text.setTextCursor(cursor)
        QApplication.processEvents()
        
    def start_build(self):
        """开始打包"""
        if self.is_building:
            return
            
        # 获取参数
        app_name = self.name_input.text().strip()
        if not app_name:
            QMessageBox.warning(self, '警告', '请输入应用名称！')
            return
            
        output_dir = self.out_path.text().strip()
        if not output_dir:
            QMessageBox.warning(self, '警告', '请选择输出目录！')
            return
            
        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)
        
        # 确定输出文件名
        goos = self.os_combo.currentText()
        if goos == 'windows' and not app_name.endswith('.exe'):
            app_name += '.exe'
            
        output_path = os.path.join(output_dir, app_name)
        source_dir = self.src_path.text()
        icon_path = self.icon_path.text().strip() if self.icon_path.text().strip() else None
        
        # 检查源码目录中的 .go 文件
        go_files = [f for f in os.listdir(source_dir) if f.endswith('.go')]
        if not go_files:
            QMessageBox.warning(self, '警告', '源码目录中没有找到 .go 文件！')
            return
            
        # 禁用按钮
        self.is_building = True
        self.build_btn.setEnabled(False)
        self.build_btn.setText('⏳ 打包中...')
        self.status_label.setText('正在打包...')
        self.log_text.clear()
        
        # 在后台线程中执行打包
        thread = threading.Thread(
            target=self.build_go,
            args=(source_dir, output_path, output_dir, icon_path),
            daemon=True
        )
        thread.start()
        
    def build_go(self, source_dir, output_path, output_dir, icon_path=None):
        """执行Go打包"""
        try:
            self.log_message('=' * 60)
            self.log_message(f'📦 开始打包：{os.path.basename(output_path)}')
            self.log_message(f'📂 源码目录：{source_dir}')
            self.log_message(f'📁 输出目录：{output_dir}')
            self.log_message(f'🖥️  目标平台：{self.os_combo.currentText()}/{self.arch_combo.currentText()}')
            self.log_message('=' * 60)
            
            # 构建命令
            cmd = ['go', 'build']
            
            # 设置环境变量（交叉编译）
            env = os.environ.copy()
            env['GOOS'] = self.os_combo.currentText()
            env['GOARCH'] = self.arch_combo.currentText()
            
            # 如果是 Windows 且需要隐藏控制台
            if self.os_combo.currentText() == 'windows' and self.hide_console_check.isChecked():
                cmd.extend(['-ldflags', '-H windowsgui'])
                self.log_message('🔧 启用隐藏控制台模式')
                
            # 处理图标（仅 Windows）
            if icon_path and os.path.exists(icon_path) and self.os_combo.currentText() == 'windows':
                # 复制图标到输出目录
                try:
                    shutil.copy2(icon_path, output_dir)
                    self.log_message(f'✅ 图标已复制到输出目录')
                    self.log_message('⚠️ 注意：图标嵌入需要使用 go-winres 或 rsrc 工具')
                except Exception as e:
                    self.log_message(f'⚠️ 图标复制失败：{e}')
            
            cmd.extend(['-o', output_path])
            cmd.append('.')
            
            self.log_message(f'🔨 执行命令：{" ".join(cmd)}')
            self.log_message('⏳ 正在编译，请稍候...')
            
            # 执行构建
            process = subprocess.Popen(
                cmd,
                cwd=source_dir,
                env=env,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8',
                errors='replace'
            )
            
            # 实时输出日志
            for line in process.stdout:
                if line.strip():
                    self.log_message(f'  {line.strip()}')
                    
            for line in process.stderr:
                if line.strip():
                    self.log_message(f'  ⚠️ {line.strip()}')
                    
            process.wait()
            
            # 检查结果
            if process.returncode == 0:
                self.log_message('=' * 60)
                self.log_message('✅ 打包成功！')
                self.log_message(f'📁 文件位置：{output_path}')
                
                if os.path.exists(output_path):
                    size = os.path.getsize(output_path) / (1024 * 1024)
                    self.log_message(f'📊 文件大小：{size:.2f} MB')
                    
                self.status_label.setText('✅ 打包完成')
                QMessageBox.information(self, '成功', f'打包完成！\n文件保存在：{output_path}')
            else:
                self.log_message('=' * 60)
                self.log_message('❌ 打包失败！请检查上面的错误信息')
                self.status_label.setText('❌ 打包失败')
                QMessageBox.warning(self, '失败', '打包失败，请查看日志详情')
                
        except FileNotFoundError:
            self.log_message('❌ 错误：未找到 Go 编译器')
            self.log_message('请确保 Go 已安装并添加到系统 PATH 中')
            self.status_label.setText('❌ 未找到 Go')
            QMessageBox.critical(self, '错误', '未找到 Go 编译器\n请安装 Go 并配置环境变量')
            
        except Exception as e:
            self.log_message(f'❌ 异常错误：{str(e)}')
            self.status_label.setText('❌ 发生错误')
            QMessageBox.critical(self, '错误', f'发生异常：{str(e)}')
            
        finally:
            # 恢复按钮
            self.is_building = False
            self.build_btn.setEnabled(True)
            self.build_btn.setText('🚀 开始打包')

class ShortcutManager(QDialog):
    """快捷键设置对话框 - 优化样式"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.setWindowTitle('⌨️ 快捷键设置')
        self.setGeometry(300, 300, 600, 500)
        self.shortcuts = self.load_shortcuts()
        self.recording_action = None
        self.shortcut_inputs = {}
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setSpacing(15)
        
        # 标题
        title_label = QLabel('⌨️ 快捷键设置')
        title_label.setStyleSheet("""
            font-size: 20px;
            font-weight: bold;
            padding: 10px 0;
            color: #e8d5f5;
        """)
        layout.addWidget(title_label)
        
        # 说明
        info_label = QLabel('💡 点击输入框后按下新的组合键进行设置')
        info_label.setStyleSheet("""
            color: #888;
            padding: 8px 12px;
            background-color: rgba(255,255,255,0.05);
            border-radius: 6px;
            font-size: 13px;
        """)
        layout.addWidget(info_label)
        
        # 快捷键列表 - 使用表格样式
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: transparent;
            }
        """)
        
        container = QWidget()
        container.setStyleSheet("""
            QWidget {
                background-color: rgba(255,255,255,0.02);
                border-radius: 8px;
            }
        """)
        container_layout = QVBoxLayout()
        container.setLayout(container_layout)
        container_layout.setSpacing(5)
        container_layout.setContentsMargins(10, 10, 10, 10)
        
        # 功能列表 - 分两列显示
        actions = [
            ('run', '▶ 运行代码'),
            ('stop', '⏹ 停止运行'),
            ('compile', '🔨 编译代码'),
            ('format', '📝 格式化代码'),
            ('new_file', '📄 新建文件'),
            ('open_file', '📂 打开文件'),
            ('save_file', '💾 保存文件'),
            ('save_as', '📋 另存为'),
            ('clear_output', '🗑 清除输出'),
            ('clear_all', '🧹 清除全部'),
            ('exit', '🚪 退出程序'),
            ('send_input', '📤 发送输入'),
        ]
        
        # 创建网格布局
        grid_layout = QGridLayout()
        grid_layout.setSpacing(8)
        grid_layout.setHorizontalSpacing(15)
        
        for idx, (action_id, action_name) in enumerate(actions):
            row = idx // 2
            col = (idx % 2) * 2
            
            # 功能名称标签
            label = QLabel(action_name)
            label.setStyleSheet("""
                QLabel {
                    font-size: 13px;
                    padding: 5px 10px;
                    color: #d4d4d4;
                }
            """)
            label.setMinimumWidth(100)
            grid_layout.addWidget(label, row, col)
            
            # 快捷键输入框
            input_box = QLineEdit()
            input_box.setReadOnly(True)
            input_box.setText(self.shortcuts.get(action_id, ''))
            input_box.setStyleSheet("""
                QLineEdit {
                    padding: 6px 12px;
                    border: 2px solid #3c3c3c;
                    border-radius: 6px;
                    background-color: #1a1a1a;
                    color: #d4d4d4;
                    font-weight: bold;
                    font-size: 13px;
                    font-family: 'Consolas', monospace;
                }
                QLineEdit:hover {
                    border-color: #0e639c;
                }
                QLineEdit:focus {
                    border-color: #ff6b6b;
                    background-color: #2a1a1a;
                }
            """)
            input_box.mousePressEvent = lambda e, id=action_id: self.start_recording(id)
            input_box.setMinimumWidth(120)
            grid_layout.addWidget(input_box, row, col + 1)
            
            # 保存到字典
            self.shortcut_inputs[action_id] = input_box
            
            # 重置按钮
            reset_btn = QPushButton('↺')
            reset_btn.setToolTip('重置为默认')
            reset_btn.setStyleSheet("""
                QPushButton {
                    padding: 4px 8px;
                    border-radius: 4px;
                    background-color: #6d6d6d;
                    color: white;
                    font-weight: bold;
                    font-size: 14px;
                    min-width: 30px;
                }
                QPushButton:hover {
                    background-color: #808080;
                }
            """)
            reset_btn.clicked.connect(lambda checked, id=action_id: self.reset_shortcut(id))
            grid_layout.addWidget(reset_btn, row, col + 2)
        
        container_layout.addLayout(grid_layout)
        container_layout.addStretch()
        
        scroll.setWidget(container)
        layout.addWidget(scroll)
        
        # 底部按钮
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(10)
        
        reset_all_btn = QPushButton('🔄 重置所有')
        reset_all_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 25px;
                border-radius: 6px;
                background-color: #c0392b;
                color: white;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #e74c3c;
            }
        """)
        reset_all_btn.clicked.connect(self.reset_all)
        btn_layout.addWidget(reset_all_btn)
        
        btn_layout.addStretch()
        
        save_btn = QPushButton('💾 保存')
        save_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 30px;
                border-radius: 6px;
                background-color: #388a34;
                color: white;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a341;
            }
        """)
        save_btn.clicked.connect(self.save_shortcuts)
        btn_layout.addWidget(save_btn)
        
        close_btn = QPushButton('✕ 关闭')
        close_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 25px;
                border-radius: 6px;
                background-color: #6d6d6d;
                color: white;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        close_btn.clicked.connect(self.close)
        btn_layout.addWidget(close_btn)
        
        layout.addLayout(btn_layout)
        
    def start_recording(self, action_id):
        """开始录制快捷键"""
        # 如果已经在录制其他快捷键，先取消
        if self.recording_action and self.recording_action != action_id:
            old_input = self.shortcut_inputs.get(self.recording_action)
            if old_input:
                old_text = self.shortcuts.get(self.recording_action, '')
                old_input.setText(old_text)
                old_input.setStyleSheet("""
                    QLineEdit {
                        padding: 6px 12px;
                        border: 2px solid #3c3c3c;
                        border-radius: 6px;
                        background-color: #1a1a1a;
                        color: #d4d4d4;
                        font-weight: bold;
                        font-size: 13px;
                        font-family: 'Consolas', monospace;
                    }
                    QLineEdit:hover {
                        border-color: #0e639c;
                    }
                """)
        
        self.recording_action = action_id
        input_box = self.shortcut_inputs.get(action_id)
        if input_box:
            input_box.setText('按下组合键...')
            input_box.setStyleSheet("""
                QLineEdit {
                    padding: 6px 12px;
                    border: 2px solid #ff6b6b;
                    border-radius: 6px;
                    background-color: #2a1a1a;
                    color: #ff6b6b;
                    font-weight: bold;
                    font-size: 13px;
                    font-family: 'Consolas', monospace;
                }
            """)
            input_box.setFocus()
        
    def keyPressEvent(self, event):
        """捕获键盘事件"""
        # 如果正在录制
        if hasattr(self, 'recording_action') and self.recording_action:
            key = event.key()
            modifiers = event.modifiers()
            
            # 忽略单独的修饰键
            if key in (Qt.Key_Control, Qt.Key_Shift, Qt.Key_Alt, Qt.Key_Meta):
                event.accept()
                return
            
            # Escape 取消录制
            if key == Qt.Key_Escape:
                input_box = self.shortcut_inputs.get(self.recording_action)
                if input_box:
                    current_text = self.shortcuts.get(self.recording_action, '')
                    input_box.setText(current_text)
                    input_box.setStyleSheet("""
                        QLineEdit {
                            padding: 6px 12px;
                            border: 2px solid #3c3c3c;
                            border-radius: 6px;
                            background-color: #1a1a1a;
                            color: #d4d4d4;
                            font-weight: bold;
                            font-size: 13px;
                            font-family: 'Consolas', monospace;
                        }
                        QLineEdit:hover {
                            border-color: #0e639c;
                        }
                    """)
                self.recording_action = None
                event.accept()
                return
            
            # 构建快捷键字符串
            keys = []
            if modifiers & Qt.ControlModifier:
                keys.append('Ctrl')
            if modifiers & Qt.ShiftModifier:
                keys.append('Shift')
            if modifiers & Qt.AltModifier:
                keys.append('Alt')
            if modifiers & Qt.MetaModifier:
                keys.append('Win')
            
            # 特殊按键映射
            key_map = {
                Qt.Key_F1: 'F1', Qt.Key_F2: 'F2', Qt.Key_F3: 'F3',
                Qt.Key_F4: 'F4', Qt.Key_F5: 'F5', Qt.Key_F6: 'F6',
                Qt.Key_F7: 'F7', Qt.Key_F8: 'F8', Qt.Key_F9: 'F9',
                Qt.Key_F10: 'F10', Qt.Key_F11: 'F11', Qt.Key_F12: 'F12',
                Qt.Key_Escape: 'Esc',
                Qt.Key_Return: 'Enter',
                Qt.Key_Enter: 'Enter',
                Qt.Key_Tab: 'Tab',
                Qt.Key_Backspace: 'Backspace',
                Qt.Key_Delete: 'Delete',
                Qt.Key_Insert: 'Insert',
                Qt.Key_Home: 'Home',
                Qt.Key_End: 'End',
                Qt.Key_PageUp: 'PageUp',
                Qt.Key_PageDown: 'PageDown',
                Qt.Key_Up: 'Up',
                Qt.Key_Down: 'Down',
                Qt.Key_Left: 'Left',
                Qt.Key_Right: 'Right',
                Qt.Key_Space: 'Space',
            }
            
            if key in key_map:
                keys.append(key_map[key])
            elif key >= Qt.Key_A and key <= Qt.Key_Z:
                keys.append(chr(key))
            elif key >= Qt.Key_0 and key <= Qt.Key_9:
                keys.append(chr(key))
            else:
                # 不支持的按键，忽略
                event.accept()
                return
            
            if keys:
                shortcut = '+'.join(keys)
                
                # 检查是否已被其他功能使用（排除自身）
                conflict = None
                for action_id, input_box in self.shortcut_inputs.items():
                    if input_box.text() == shortcut and action_id != self.recording_action:
                        conflict = action_id
                        break
                
                if conflict:
                    QMessageBox.warning(self, '⚠️ 冲突', 
                        f'快捷键 "{shortcut}" 已被 "{self.get_action_name(conflict)}" 使用\n请选择其他组合键。')
                    event.accept()
                    return
                
                # 更新显示
                input_box = self.shortcut_inputs.get(self.recording_action)
                if input_box:
                    input_box.setText(shortcut)
                    input_box.setStyleSheet("""
                        QLineEdit {
                            padding: 6px 12px;
                            border: 2px solid #3c3c3c;
                            border-radius: 6px;
                            background-color: #1a1a1a;
                            color: #d4d4d4;
                            font-weight: bold;
                            font-size: 13px;
                            font-family: 'Consolas', monospace;
                        }
                        QLineEdit:hover {
                            border-color: #0e639c;
                        }
                    """)
                    self.shortcuts[self.recording_action] = shortcut
                self.recording_action = None
                event.accept()
                return
            
            event.accept()
        else:
            # 不在录制状态时，正常处理事件
            super().keyPressEvent(event)
        
    def get_action_name(self, action_id):
        """获取功能名称"""
        names = {
            'run': '运行代码',
            'stop': '停止运行',
            'compile': '编译代码',
            'format': '格式化代码',
            'new_file': '新建文件',
            'open_file': '打开文件',
            'save_file': '保存文件',
            'save_as': '另存为',
            'clear_output': '清除输出',
            'clear_all': '清除全部',
            'exit': '退出程序',
            'send_input': '发送输入',
        }
        return names.get(action_id, action_id)
        
    def reset_shortcut(self, action_id):
        """重置单个快捷键"""
        default = DEFAULT_SHORTCUTS.get(action_id, '')
        if default:
            self.shortcuts[action_id] = default
            input_box = self.shortcut_inputs.get(action_id)
            if input_box:
                input_box.setText(default)
        
    def reset_all(self):
        """重置所有快捷键"""
        reply = QMessageBox.question(self, '确认重置', '确定要重置所有快捷键到默认设置吗？',
                                   QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            for action_id, default in DEFAULT_SHORTCUTS.items():
                self.shortcuts[action_id] = default
                if action_id in self.shortcut_inputs:
                    self.shortcut_inputs[action_id].setText(default)
                    
    def save_shortcuts(self):
        """保存快捷键设置"""
        try:
            with open(SHORTCUTS_FILE, 'w', encoding='utf-8') as f:
                json.dump(self.shortcuts, f, indent=4, ensure_ascii=False)
            QMessageBox.information(self, '✅ 成功', '快捷键设置已保存！')
            if self.parent:
                self.parent.update_shortcuts()
            self.close()
        except Exception as e:
            QMessageBox.critical(self, '❌ 错误', f'保存快捷键设置失败: {str(e)}')
            
    def load_shortcuts(self):
        """加载快捷键设置"""
        if os.path.exists(SHORTCUTS_FILE):
            try:
                with open(SHORTCUTS_FILE, 'r', encoding='utf-8') as f:
                    loaded = json.load(f)
                    shortcuts = DEFAULT_SHORTCUTS.copy()
                    shortcuts.update(loaded)
                    return shortcuts
            except:
                return DEFAULT_SHORTCUTS.copy()
        return DEFAULT_SHORTCUTS.copy()

class DependencyManager(QDialog):
    """依赖管理器对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.setWindowTitle('📦 Go 依赖管理')
        self.setGeometry(200, 200, 850, 650)
        self.current_proxy = None
        self.all_installed_packages = []  # 存储所有已安装的包
        self.all_popular_packages = []    # 存储所有热门包
        self.popular_packages_by_category = {}  # 按分类存储
        self.is_loading = False  # 防止递归加载
        self.initUI()
        # 先加载热门包，再加载已安装包
        self.load_popular_packages()
        self.load_installed_packages()
        
    def initUI(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title_label = QLabel('📦 Go 依赖管理')
        title_label.setStyleSheet("font-size: 20px; font-weight: bold; padding: 10px;")
        layout.addWidget(title_label)
        
        # 选项卡
        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet("""
            QTabWidget::pane {
                border: 1px solid #3c3c3c;
                border-radius: 5px;
                background: transparent;
            }
            QTabBar::tab {
                padding: 10px 20px;
                margin: 2px;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                font-weight: bold;
                font-size: 13px;
            }
            QTabBar::tab:selected {
                background: #0e639c;
                color: white;
            }
            QTabBar::tab:hover:!selected {
                background: #3c3c3c;
            }
        """)
        layout.addWidget(self.tab_widget)
        
        # === 安装依赖选项卡 ===
        install_tab = QWidget()
        install_layout = QVBoxLayout()
        install_tab.setLayout(install_layout)
        install_layout.setContentsMargins(10, 10, 10, 10)
        install_layout.setSpacing(10)
        
        # 安装输入区域
        input_container = QWidget()
        input_container.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.03);
                border-radius: 8px;
                padding: 5px;
            }
        """)
        input_layout = QHBoxLayout()
        input_container.setLayout(input_layout)
        
        self.package_input = QLineEdit()
        self.package_input.setPlaceholderText('输入依赖包路径 (例如: github.com/gin-gonic/gin)')
        self.package_input.setStyleSheet("""
            QLineEdit {
                padding: 10px 15px;
                font-size: 14px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        input_layout.addWidget(self.package_input)
        
        install_btn = QPushButton('📥 安装')
        install_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 30px;
                font-weight: bold;
                font-size: 14px;
                background-color: #388a34;
                border-radius: 6px;
                color: white;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #45a341;
            }
            QPushButton:pressed {
                background-color: #2d7a2d;
            }
        """)
        install_btn.clicked.connect(self.install_package)
        input_layout.addWidget(install_btn)
        
        install_layout.addWidget(input_container)
        
        # 安装日志 - 带进度条
        log_container = QWidget()
        log_layout = QVBoxLayout()
        log_container.setLayout(log_layout)
        log_layout.setContentsMargins(0, 0, 0, 0)
        
        log_header = QWidget()
        log_header_layout = QHBoxLayout()
        log_header.setLayout(log_header_layout)
        log_header_layout.setContentsMargins(0, 5, 0, 5)
        
        log_label = QLabel('📋 安装日志')
        log_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        log_header_layout.addWidget(log_label)
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #3c3c3c;
                border-radius: 4px;
                text-align: center;
                height: 20px;
                background-color: #1a1a1a;
                color: #d4d4d4;
            }
            QProgressBar::chunk {
                background-color: #388a34;
                border-radius: 4px;
            }
        """)
        self.progress_bar.setVisible(False)
        log_header_layout.addWidget(self.progress_bar)
        
        log_layout.addWidget(log_header)
        
        self.install_log = QTextEdit()
        self.install_log.setReadOnly(True)
        self.install_log.setStyleSheet("""
            QTextEdit {
                background-color: #0a0a0a;
                font-family: 'Consolas', monospace;
                font-size: 12px;
                padding: 12px;
                border-radius: 6px;
                border: 1px solid #2a2a2a;
                color: #d4d4d4;
            }
        """)
        log_layout.addWidget(self.install_log)
        
        install_layout.addWidget(log_container, stretch=1)
        
        self.tab_widget.addTab(install_tab, '📥 安装依赖')
        
        # === 依赖包选项卡 ===
        popular_tab = QWidget()
        popular_layout = QVBoxLayout()
        popular_tab.setLayout(popular_layout)
        popular_layout.setContentsMargins(10, 10, 10, 10)
        popular_layout.setSpacing(10)
        
        top_container = QWidget()
        top_container.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.03);
                border-radius: 8px;
                padding: 8px;
            }
        """)
        top_layout = QHBoxLayout()
        top_container.setLayout(top_layout)
        
        category_label = QLabel('📂 分类:')
        category_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        top_layout.addWidget(category_label)
        
        self.category_combo = QComboBox()
        # 添加"未安装"选项到分类列表
        self.category_combo.addItems(['全部', '未安装', 'Web框架', '数据库', '工具库', '日志', '测试', '监控', '消息队列', '其他'])
        self.category_combo.currentTextChanged.connect(self.on_category_changed)
        self.category_combo.setStyleSheet("""
            QComboBox {
                padding: 6px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
                min-width: 120px;
            }
            QComboBox::drop-down {
                border: none;
                padding-right: 10px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #d4d4d4;
                margin-right: 5px;
            }
            QComboBox:hover {
                border-color: #0e639c;
            }
            QComboBox QAbstractItemView {
                background-color: #1a1a1a;
                color: #d4d4d4;
                border: 1px solid #3c3c3c;
                selection-background-color: #0e639c;
                padding: 5px;
            }
        """)
        top_layout.addWidget(self.category_combo)
        
        top_layout.addSpacing(20)
        
        search_label = QLabel('🔍 搜索:')
        search_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        top_layout.addWidget(search_label)
        
        self.popular_search = QLineEdit()
        self.popular_search.setPlaceholderText('输入关键词搜索...')
        self.popular_search.textChanged.connect(self.filter_popular_packages)
        self.popular_search.setStyleSheet("""
            QLineEdit {
                padding: 6px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        top_layout.addWidget(self.popular_search)
        
        top_layout.addStretch()
        popular_layout.addWidget(top_container)
        
        tool_container = QWidget()
        tool_container.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.02);
                border-radius: 6px;
                padding: 5px;
            }
        """)
        tool_layout = QHBoxLayout()
        tool_container.setLayout(tool_layout)
        
        select_all_btn = QPushButton('☑ 全选')
        select_all_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        select_all_btn.clicked.connect(lambda: self.popular_list.select_all(True))
        tool_layout.addWidget(select_all_btn)
        
        deselect_all_btn = QPushButton('☐ 取消全选')
        deselect_all_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #6d6d6d;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        deselect_all_btn.clicked.connect(lambda: self.popular_list.select_all(False))
        tool_layout.addWidget(deselect_all_btn)
        
        tool_layout.addSpacing(15)
        
        batch_install_btn = QPushButton('📥 批量安装选中')
        batch_install_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #388a34;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #45a341;
            }
        """)
        batch_install_btn.clicked.connect(self.batch_install_packages)
        tool_layout.addWidget(batch_install_btn)
        
        tool_layout.addStretch()
        
        count_label = QLabel('共 0 个包')
        count_label.setStyleSheet("font-size: 13px; font-weight: bold; color: #888;")
        self.popular_count_label = count_label
        tool_layout.addWidget(count_label)
        
        popular_layout.addWidget(tool_container)
        
        self.popular_list = CheckableListWidget()
        self.popular_list.setStyleSheet("""
            QListWidget {
                border: 1px solid #2a2a2a;
                border-radius: 6px;
                background-color: #0a0a0a;
                padding: 5px;
            }
            QListWidget::item {
                padding: 8px;
                border-radius: 4px;
            }
            QListWidget::item:hover {
                background-color: #2a2a3a;
            }
            QListWidget::item:selected {
                background-color: #0e639c;
            }
        """)
        self.popular_list.itemDoubleClicked.connect(self.install_single_from_popular)
        popular_layout.addWidget(self.popular_list)
        
        info_label = QLabel('💡 勾选依赖包后点击 "批量安装选中" 进行批量安装，双击单个包快速安装')
        info_label.setStyleSheet("color: #888; padding: 5px; font-size: 12px;")
        popular_layout.addWidget(info_label)
        
        self.tab_widget.addTab(popular_tab, '📦 依赖包')
        
        # === 已安装依赖选项卡 ===
        installed_tab = QWidget()
        installed_layout = QVBoxLayout()
        installed_tab.setLayout(installed_layout)
        installed_layout.setContentsMargins(10, 10, 10, 10)
        installed_layout.setSpacing(10)
        
        search_container = QWidget()
        search_container.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.03);
                border-radius: 8px;
                padding: 5px;
            }
        """)
        search_installed_layout = QHBoxLayout()
        search_container.setLayout(search_installed_layout)
        
        search_label2 = QLabel('🔍 搜索:')
        search_label2.setStyleSheet("font-weight: bold; font-size: 13px;")
        search_installed_layout.addWidget(search_label2)
        
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText('搜索已安装的依赖...')
        self.search_input.textChanged.connect(self.search_installed)
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 6px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #0e639c;
            }
        """)
        search_installed_layout.addWidget(self.search_input)
        
        refresh_btn = QPushButton('🔄 刷新')
        refresh_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        refresh_btn.clicked.connect(self.load_installed_packages)
        search_installed_layout.addWidget(refresh_btn)
        
        search_installed_layout.addStretch()
        installed_layout.addWidget(search_container)
        
        tool_container2 = QWidget()
        tool_container2.setStyleSheet("""
            QWidget {
                background-color: rgba(255, 255, 255, 0.02);
                border-radius: 6px;
                padding: 5px;
            }
        """)
        tool_layout2 = QHBoxLayout()
        tool_container2.setLayout(tool_layout2)
        
        select_all_btn2 = QPushButton('☑ 全选')
        select_all_btn2.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        select_all_btn2.clicked.connect(lambda: self.installed_list.select_all(True))
        tool_layout2.addWidget(select_all_btn2)
        
        deselect_all_btn2 = QPushButton('☐ 取消全选')
        deselect_all_btn2.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #6d6d6d;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        deselect_all_btn2.clicked.connect(lambda: self.installed_list.select_all(False))
        tool_layout2.addWidget(deselect_all_btn2)
        
        tool_layout2.addSpacing(15)
        
        batch_uninstall_btn = QPushButton('🗑 批量卸载选中')
        batch_uninstall_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #c0392b;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #e74c3c;
            }
        """)
        batch_uninstall_btn.clicked.connect(self.batch_uninstall_packages)
        tool_layout2.addWidget(batch_uninstall_btn)
        
        tool_layout2.addSpacing(10)
        
        update_all_btn = QPushButton('🔄 更新所有依赖')
        update_all_btn.setStyleSheet("""
            QPushButton {
                padding: 6px 18px;
                border-radius: 4px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        update_all_btn.clicked.connect(self.update_all_packages)
        tool_layout2.addWidget(update_all_btn)
        
        tool_layout2.addStretch()
        
        count_label2 = QLabel('共 0 个包')
        count_label2.setStyleSheet("font-size: 13px; font-weight: bold; color: #888;")
        self.installed_count_label = count_label2
        tool_layout2.addWidget(count_label2)
        
        installed_layout.addWidget(tool_container2)
        
        self.installed_list = CheckableListWidget()
        self.installed_list.setStyleSheet("""
            QListWidget {
                border: 1px solid #2a2a2a;
                border-radius: 6px;
                background-color: #0a0a0a;
                padding: 5px;
            }
            QListWidget::item {
                padding: 8px;
                border-radius: 4px;
            }
            QListWidget::item:hover {
                background-color: #2a2a3a;
            }
            QListWidget::item:selected {
                background-color: #0e639c;
            }
        """)
        installed_layout.addWidget(self.installed_list)
        
        self.tab_widget.addTab(installed_tab, '✅ 已安装依赖')
        
        # === 设置选项卡 ===
        settings_tab = QWidget()
        settings_layout = QVBoxLayout()
        settings_tab.setLayout(settings_layout)
        settings_layout.setContentsMargins(10, 10, 10, 10)
        settings_layout.setSpacing(15)
        
        proxy_group = QGroupBox('🌐 代理设置')
        proxy_group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #3c3c3c;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 10px;
            }
        """)
        proxy_layout = QVBoxLayout()
        proxy_group.setLayout(proxy_layout)
        
        proxy_select_layout = QHBoxLayout()
        proxy_label = QLabel('选择代理:')
        proxy_label.setStyleSheet("font-weight: bold;")
        proxy_select_layout.addWidget(proxy_label)
        
        self.proxy_combo = QComboBox()
        self.proxy_combo.addItems([
            '无代理',
            'https://proxy.golang.org',
            'https://goproxy.cn',
            'https://goproxy.io',
            'https://mirrors.aliyun.com/goproxy/',
            'https://proxy.golang.com.cn',
            'https://gocenter.io',
            'https://athens.azurefd.net',
        ])
        self.proxy_combo.currentTextChanged.connect(self.on_proxy_changed)
        self.proxy_combo.setStyleSheet("""
            QComboBox {
                padding: 8px 12px;
                border: 2px solid #3c3c3c;
                border-radius: 6px;
                background-color: #1a1a1a;
                color: #d4d4d4;
                font-size: 13px;
                min-width: 200px;
            }
            QComboBox::drop-down {
                border: none;
                padding-right: 10px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #d4d4d4;
                margin-right: 5px;
            }
            QComboBox:hover {
                border-color: #0e639c;
            }
            QComboBox QAbstractItemView {
                background-color: #1a1a1a;
                color: #d4d4d4;
                border: 1px solid #3c3c3c;
                selection-background-color: #0e639c;
                padding: 5px;
            }
        """)
        proxy_select_layout.addWidget(self.proxy_combo)
        
        proxy_select_layout.addStretch()
        proxy_layout.addLayout(proxy_select_layout)
        
        self.proxy_status_label = QLabel('当前代理: 无代理')
        self.proxy_status_label.setStyleSheet("color: #888; padding: 5px;")
        proxy_layout.addWidget(self.proxy_status_label)
        
        proxy_btn_layout = QHBoxLayout()
        
        apply_proxy_btn = QPushButton('应用代理')
        apply_proxy_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 20px;
                border-radius: 4px;
                background-color: #0e639c;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1177bb;
            }
        """)
        apply_proxy_btn.clicked.connect(self.apply_proxy)
        proxy_btn_layout.addWidget(apply_proxy_btn)
        
        clear_proxy_btn = QPushButton('清除代理')
        clear_proxy_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 20px;
                border-radius: 4px;
                background-color: #c0392b;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #e74c3c;
            }
        """)
        clear_proxy_btn.clicked.connect(self.clear_proxy)
        proxy_btn_layout.addWidget(clear_proxy_btn)
        
        proxy_btn_layout.addStretch()
        proxy_layout.addLayout(proxy_btn_layout)
        
        settings_layout.addWidget(proxy_group)
        settings_layout.addStretch()
        
        self.tab_widget.addTab(settings_tab, '⚙️ 设置')
        
        close_btn = QPushButton('关闭')
        close_btn.clicked.connect(self.close)
        close_btn.setStyleSheet("""
            QPushButton {
                padding: 8px 30px;
                font-weight: bold;
                font-size: 14px;
                border-radius: 6px;
                background-color: #6d6d6d;
                color: white;
            }
            QPushButton:hover {
                background-color: #808080;
            }
        """)
        layout.addWidget(close_btn, alignment=Qt.AlignRight)
        
        self.load_proxy_settings()
        
    def on_category_changed(self, category):
        """分类切换事件"""
        # 如果切换到"未安装"分类，先确保已安装列表已加载
        if category == '未安装' and not self.all_installed_packages:
            # 如果还没有加载已安装列表，先加载
            self.load_installed_packages()
        else:
            self.filter_popular_packages()
        
    def on_proxy_changed(self, text):
        """代理选择变化"""
        if text == '无代理':
            self.proxy_status_label.setText('当前代理: 无代理')
        else:
            self.proxy_status_label.setText(f'当前代理: {text}')
            
    def load_proxy_settings(self):
        """加载保存的代理设置"""
        try:
            proxy = os.environ.get('GOPROXY', '')
            if proxy:
                index = self.proxy_combo.findText(proxy)
                if index >= 0:
                    self.proxy_combo.setCurrentIndex(index)
                    self.proxy_status_label.setText(f'当前代理: {proxy}')
                else:
                    self.proxy_combo.setCurrentIndex(0)
                    self.proxy_status_label.setText('当前代理: 无代理')
        except:
            pass
            
    def apply_proxy(self):
        """应用代理"""
        proxy = self.proxy_combo.currentText()
        
        if proxy == '无代理':
            if 'GOPROXY' in os.environ:
                del os.environ['GOPROXY']
            self.proxy_status_label.setText('当前代理: 无代理')
            self.install_log.append('✅ 已清除代理设置')
        else:
            os.environ['GOPROXY'] = proxy
            self.proxy_status_label.setText(f'当前代理: {proxy}')
            self.install_log.append(f'✅ 已设置代理: {proxy}')
            
        self.install_log.append(f'📋 GOPROXY = {os.environ.get("GOPROXY", "未设置")}')
        
    def clear_proxy(self):
        """清除代理"""
        if 'GOPROXY' in os.environ:
            del os.environ['GOPROXY']
        self.proxy_combo.setCurrentIndex(0)
        self.proxy_status_label.setText('当前代理: 无代理')
        self.install_log.append('✅ 已清除代理设置')
        self.install_log.append('📋 GOPROXY = 未设置')
        
    def update_progress(self, value, text=""):
        """更新进度条"""
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(value)
        if text:
            self.install_log.append(text)
            
    def reset_progress(self):
        """重置进度条"""
        self.progress_bar.setValue(0)
        self.progress_bar.setVisible(False)
        
    def get_popular_packages_by_category(self):
        """获取按分类的热门依赖包"""
        return {
            'Web框架': [
                'github.com/gin-gonic/gin (Web框架)',
                'github.com/gofiber/fiber/v2 (Web框架)',
                'github.com/gorilla/mux (路由)',
                'github.com/gorilla/handlers (中间件)',
                'github.com/gorilla/sessions (Session管理)',
                'github.com/labstack/echo/v4 (Web框架)',
                'github.com/valyala/fasthttp (高性能HTTP)',
                'github.com/beego/beego/v2 (Web框架)',
                'github.com/revel/revel (Web框架)',
                'github.com/go-chi/chi/v5 (路由)',
            ],
            '数据库': [
                'github.com/jinzhu/gorm (ORM)',
                'gorm.io/gorm (ORM)',
                'github.com/go-sql-driver/mysql (MySQL驱动)',
                'github.com/lib/pq (PostgreSQL驱动)',
                'github.com/jackc/pgx/v4 (PostgreSQL驱动)',
                'github.com/go-redis/redis/v8 (Redis客户端)',
                'github.com/olivere/elastic/v7 (Elasticsearch)',
                'github.com/elastic/go-elasticsearch/v8 (Elasticsearch)',
                'github.com/mongodb/mongo-go-driver (MongoDB驱动)',
                'github.com/ClickHouse/clickhouse-go (ClickHouse驱动)',
            ],
            '工具库': [
                'github.com/spf13/viper (配置管理)',
                'github.com/fsnotify/fsnotify (文件监控)',
                'github.com/robfig/cron/v3 (定时任务)',
                'github.com/dgrijalva/jwt-go (JWT认证)',
                'github.com/golang-jwt/jwt/v4 (JWT认证)',
                'github.com/go-playground/validator/v10 (验证器)',
                'github.com/urfave/cli/v2 (命令行)',
                'github.com/spf13/cobra (命令行)',
                'github.com/google/wire (依赖注入)',
                'github.com/golang/mock (Mock测试)',
            ],
            '日志': [
                'github.com/sirupsen/logrus (日志)',
                'github.com/uber-go/zap (高性能日志)',
                'github.com/rs/zerolog (日志)',
                'github.com/natefinch/lumberjack (日志切割)',
            ],
            '测试': [
                'github.com/stretchr/testify (测试框架)',
                'github.com/onsi/ginkgo/v2 (BDD测试)',
                'github.com/onsi/gomega (Matcher)',
                'github.com/gavv/httpexpect/v2 (HTTP测试)',
            ],
            '监控': [
                'github.com/prometheus/client_golang (监控)',
                'github.com/rcrowley/go-metrics (指标)',
                'github.com/opentracing/opentracing-go (链路追踪)',
                'github.com/openzipkin/zipkin-go (链路追踪)',
            ],
            '消息队列': [
                'github.com/Shopify/sarama (Kafka)',
                'github.com/segmentio/kafka-go (Kafka)',
                'github.com/nats-io/nats.go (NATS)',
                'github.com/rabbitmq/amqp091-go (RabbitMQ)',
                'github.com/gocql/gocql (Cassandra)',
            ],
            '其他': [
                'github.com/gorilla/websocket (WebSocket)',
                'github.com/antchfx/htmlquery (HTML解析)',
                'github.com/gocolly/colly (爬虫)',
                'github.com/grpc/grpc-go (gRPC)',
                'github.com/golang/protobuf (Protobuf)',
                'github.com/uber/jaeger-client-go (链路追踪)',
                'github.com/aws/aws-sdk-go (AWS SDK)',
                'github.com/go-git/go-git/v5 (Git操作)',
                'github.com/gofrs/uuid (UUID生成)',
                'github.com/oklog/ulid (ULID生成)',
            ]
        }
        
    def load_popular_packages(self):
        """加载热门依赖包"""
        self.all_popular_packages = []
        self.popular_packages_by_category = self.get_popular_packages_by_category()
        
        for category, packages in self.popular_packages_by_category.items():
            for pkg in packages:
                self.all_popular_packages.append(pkg)
        
        # 直接显示所有包
        self.popular_list.addItems(self.all_popular_packages)
        self.popular_count_label.setText(f'共 {self.popular_list.count()} 个包')
        
    def filter_popular_packages(self):
        """过滤热门依赖包（支持"未安装"筛选）"""
        # 防止在加载过程中触发
        if self.is_loading:
            return
            
        category = self.category_combo.currentText()
        search_text = self.popular_search.text().lower()
        
        self.popular_list.clear()
        
        # 首先根据分类获取包列表
        if category == '全部':
            filtered_packages = self.all_popular_packages.copy()
        elif category == '未安装':
            # 筛选未安装的包
            filtered_packages = []
            for pkg in self.all_popular_packages:
                # 提取包名（去掉括号中的描述）
                pkg_name = pkg.split('(')[0].strip()
                # 检查是否已安装 - 精确匹配
                is_installed = False
                for installed in self.all_installed_packages:
                    # 检查包名是否匹配（支持带版本号的情况）
                    if installed == pkg_name or installed.startswith(pkg_name + '@') or installed.startswith(pkg_name + ' '):
                        is_installed = True
                        break
                    # 也检查包名是否包含在已安装列表中（部分匹配）
                    if pkg_name in installed or installed in pkg_name:
                        is_installed = True
                        break
                if not is_installed:
                    filtered_packages.append(pkg)
        else:
            filtered_packages = self.popular_packages_by_category.get(category, [])
        
        # 应用搜索过滤
        if search_text:
            filtered_packages = [pkg for pkg in filtered_packages if search_text in pkg.lower()]
        
        # 显示结果
        if filtered_packages:
            self.popular_list.addItems(filtered_packages)
        self.popular_count_label.setText(f'共 {self.popular_list.count()} 个包')
        
    def load_installed_packages(self):
        """加载已安装的依赖包"""
        self.is_loading = True  # 开始加载，防止触发过滤
        
        self.installed_list.clear()
        self.all_installed_packages = []  # 清空存储
        
        try:
            result = subprocess.run(['go', 'list', '-m', 'all'], 
                                  capture_output=True, 
                                  text=True,
                                  timeout=10)
            
            if result.returncode == 0:
                packages = result.stdout.strip().split('\n')
                for pkg in packages:
                    if pkg and not pkg.startswith('myproject'):
                        # 清理包名（去掉版本号）
                        clean_pkg = pkg.split(' ')[0].split('@')[0]
                        self.installed_list.addItem(pkg)
                        self.all_installed_packages.append(clean_pkg)
                self.installed_count_label.setText(f'共 {self.installed_list.count()} 个包')
                self.install_log.append(f'✅ 加载了 {self.installed_list.count()} 个依赖包')
            else:
                self.install_log.append(f'❌ 加载依赖失败: {result.stderr}')
                
        except subprocess.TimeoutExpired:
            self.install_log.append('❌ 加载依赖超时')
        except Exception as e:
            self.install_log.append(f'❌ 加载依赖失败: {str(e)}')
        
        self.is_loading = False  # 加载完成
        
        # 如果当前在"未安装"分类，刷新列表
        if self.category_combo.currentText() == '未安装':
            self.filter_popular_packages()
        
    def search_installed(self):
        """搜索已安装的依赖"""
        search_text = self.search_input.text().lower()
        
        # 重新加载所有已安装包
        self.installed_list.clear()
        
        for pkg in self.all_installed_packages:
            if not search_text or search_text in pkg.lower():
                self.installed_list.addItem(pkg)
        
        self.installed_count_label.setText(f'共 {self.installed_list.count()} 个包')
                    
    def install_package(self):
        """安装单个依赖包"""
        package = self.package_input.text().strip()
        if not package:
            QMessageBox.warning(self, '警告', '请输入要安装的依赖包路径！')
            return
            
        if '(' in package:
            package = package.split('(')[0].strip()
            
        self.install_log.append(f'🔨 正在安装: {package}')
        self.update_progress(10, f'开始安装 {package}...')
        
        def install_thread():
            try:
                self.update_progress(30, f'下载 {package}...')
                result = subprocess.run(['go', 'get', package], 
                                      capture_output=True, 
                                      text=True,
                                      timeout=60)
                
                if result.returncode == 0:
                    self.update_progress(100, f'✅ 安装成功: {package}')
                    self.load_installed_packages()
                    QTimer.singleShot(1000, self.reset_progress)
                else:
                    self.update_progress(0, f'❌ 安装失败: {result.stderr}')
                    QTimer.singleShot(1000, self.reset_progress)
                    
            except subprocess.TimeoutExpired:
                self.update_progress(0, '❌ 安装超时')
                QTimer.singleShot(1000, self.reset_progress)
            except Exception as e:
                self.update_progress(0, f'❌ 安装失败: {str(e)}')
                QTimer.singleShot(1000, self.reset_progress)
                
        thread = threading.Thread(target=install_thread)
        thread.daemon = True
        thread.start()
        
        self.package_input.clear()
        
    def batch_install_packages(self):
        """批量安装选中的依赖包"""
        checked = self.popular_list.get_checked_items()
        if not checked:
            QMessageBox.warning(self, '警告', '请先选择要安装的依赖包！')
            return
            
        reply = QMessageBox.question(self, '确认批量安装', 
                                   f'确定要安装 {len(checked)} 个依赖包吗？\n这将花费一些时间。',
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.install_log.append(f'🔨 开始批量安装 {len(checked)} 个依赖包...')
            self.update_progress(5, f'开始批量安装 {len(checked)} 个包...')
            
            def batch_install_thread():
                success_count = 0
                fail_count = 0
                total = len(checked)
                
                for idx, package in enumerate(checked):
                    if '(' in package:
                        pkg_name = package.split('(')[0].strip()
                    else:
                        pkg_name = package
                        
                    progress = int((idx + 1) / total * 90) + 5
                    self.update_progress(progress, f'安装: {pkg_name} ({idx+1}/{total})')
                    
                    try:
                        result = subprocess.run(['go', 'get', pkg_name], 
                                              capture_output=True, 
                                              text=True,
                                              timeout=60)
                        if result.returncode == 0:
                            success_count += 1
                            self.install_log.append(f'  ✅ {pkg_name}')
                        else:
                            fail_count += 1
                            self.install_log.append(f'  ❌ {pkg_name}: {result.stderr[:100]}')
                    except Exception as e:
                        fail_count += 1
                        self.install_log.append(f'  ❌ {pkg_name}: {str(e)[:100]}')
                
                self.update_progress(100, f'✅ 批量安装完成！成功: {success_count}, 失败: {fail_count}')
                self.load_installed_packages()
                QTimer.singleShot(2000, self.reset_progress)
                
            thread = threading.Thread(target=batch_install_thread)
            thread.daemon = True
            thread.start()
            
    def uninstall_package(self):
        """卸载单个依赖包"""
        selected = self.installed_list.currentItem()
        if not selected:
            QMessageBox.warning(self, '警告', '请先选择要卸载的依赖包！')
            return
            
        package = selected.text()
        self.perform_uninstall(package)
        
    def batch_uninstall_packages(self):
        """批量卸载选中的依赖包"""
        checked = self.installed_list.get_checked_items()
        if not checked:
            QMessageBox.warning(self, '警告', '请先选择要卸载的依赖包！')
            return
            
        reply = QMessageBox.question(self, '确认批量卸载', 
                                   f'确定要卸载 {len(checked)} 个依赖包吗？',
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.install_log.append(f'🔨 开始批量卸载 {len(checked)} 个依赖包...')
            self.update_progress(5, f'开始批量卸载 {len(checked)} 个包...')
            
            def batch_uninstall_thread():
                success_count = 0
                fail_count = 0
                total = len(checked)
                
                for idx, package in enumerate(checked):
                    progress = int((idx + 1) / total * 80) + 10
                    self.update_progress(progress, f'卸载: {package} ({idx+1}/{total})')
                    
                    try:
                        result = subprocess.run(['go', 'mod', 'edit', '-droprequire', package], 
                                              capture_output=True, 
                                              text=True,
                                              timeout=30)
                        if result.returncode == 0:
                            success_count += 1
                            self.install_log.append(f'  ✅ {package}')
                        else:
                            fail_count += 1
                            self.install_log.append(f'  ❌ {package}: {result.stderr[:100]}')
                    except Exception as e:
                        fail_count += 1
                        self.install_log.append(f'  ❌ {package}: {str(e)[:100]}')
                
                self.update_progress(95, '清理依赖...')
                tidy_result = subprocess.run(['go', 'mod', 'tidy'], 
                                           capture_output=True, 
                                           text=True,
                                           timeout=30)
                
                self.update_progress(100, f'✅ 批量卸载完成！成功: {success_count}, 失败: {fail_count}')
                self.load_installed_packages()
                QTimer.singleShot(2000, self.reset_progress)
                
            thread = threading.Thread(target=batch_uninstall_thread)
            thread.daemon = True
            thread.start()
            
    def perform_uninstall(self, package):
        """执行单个卸载"""
        reply = QMessageBox.question(self, '确认卸载', 
                                   f'确定要卸载依赖包: {package} 吗？',
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.install_log.append(f'🔨 正在卸载: {package}')
            self.update_progress(20, f'开始卸载 {package}...')
            
            def uninstall_thread():
                try:
                    self.update_progress(50, f'移除 {package}...')
                    result = subprocess.run(['go', 'mod', 'edit', '-droprequire', package], 
                                          capture_output=True, 
                                          text=True,
                                          timeout=30)
                    
                    if result.returncode == 0:
                        self.update_progress(80, '清理依赖...')
                        tidy_result = subprocess.run(['go', 'mod', 'tidy'], 
                                                   capture_output=True, 
                                                   text=True,
                                                   timeout=30)
                        if tidy_result.returncode == 0:
                            self.update_progress(100, f'✅ 卸载成功: {package}')
                            self.load_installed_packages()
                            QTimer.singleShot(1000, self.reset_progress)
                        else:
                            self.update_progress(0, f'❌ 清理依赖失败: {tidy_result.stderr}')
                            QTimer.singleShot(1000, self.reset_progress)
                    else:
                        self.update_progress(0, f'❌ 卸载失败: {result.stderr}')
                        QTimer.singleShot(1000, self.reset_progress)
                            
                except Exception as e:
                    self.update_progress(0, f'❌ 卸载失败: {str(e)}')
                    QTimer.singleShot(1000, self.reset_progress)
                    
            thread = threading.Thread(target=uninstall_thread)
            thread.daemon = True
            thread.start()
            
    def update_package(self):
        """更新选中的依赖包"""
        selected = self.installed_list.currentItem()
        if not selected:
            QMessageBox.warning(self, '警告', '请先选择要更新的依赖包！')
            return
            
        package = selected.text()
        self.install_log.append(f'🔨 正在更新: {package}')
        self.update_progress(10, f'开始更新 {package}...')
        
        def update_thread():
            try:
                self.update_progress(40, f'下载更新 {package}...')
                result = subprocess.run(['go', 'get', '-u', package], 
                                      capture_output=True, 
                                      text=True,
                                      timeout=60)
                
                if result.returncode == 0:
                    self.update_progress(100, f'✅ 更新成功: {package}')
                    self.load_installed_packages()
                    QTimer.singleShot(1000, self.reset_progress)
                else:
                    self.update_progress(0, f'❌ 更新失败: {result.stderr}')
                    QTimer.singleShot(1000, self.reset_progress)
                    
            except Exception as e:
                self.update_progress(0, f'❌ 更新失败: {str(e)}')
                QTimer.singleShot(1000, self.reset_progress)
                
        thread = threading.Thread(target=update_thread)
        thread.daemon = True
        thread.start()
        
    def update_all_packages(self):
        """更新所有依赖包"""
        reply = QMessageBox.question(self, '确认更新', 
                                   '确定要更新所有依赖包吗？这可能需要一些时间。',
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.install_log.append('🔨 正在更新所有依赖...')
            self.update_progress(5, '开始更新所有依赖...')
            
            def update_all_thread():
                try:
                    self.update_progress(30, '下载更新...')
                    result = subprocess.run(['go', 'get', '-u', './...'], 
                                          capture_output=True, 
                                          text=True,
                                          timeout=300)
                    
                    if result.returncode == 0:
                        self.update_progress(100, '✅ 所有依赖更新成功')
                        self.load_installed_packages()
                        QTimer.singleShot(1000, self.reset_progress)
                    else:
                        self.update_progress(0, f'❌ 更新失败: {result.stderr}')
                        QTimer.singleShot(1000, self.reset_progress)
                        
                except subprocess.TimeoutExpired:
                    self.update_progress(0, '❌ 更新超时')
                    QTimer.singleShot(1000, self.reset_progress)
                except Exception as e:
                    self.update_progress(0, f'❌ 更新失败: {str(e)}')
                    QTimer.singleShot(1000, self.reset_progress)
                    
            thread = threading.Thread(target=update_all_thread)
            thread.daemon = True
            thread.start()
    
    def install_single_from_popular(self, item):
        """双击从热门列表安装单个包"""
        if item:
            package = item.text()
            self.package_input.setText(package)
            self.install_package()

class GoCompiler(QMainWindow):
    def __init__(self):
        super().__init__()
        self.process = None
        self.temp_dir = None
        self.is_running = False
        self.skin_actions = []
        self.current_theme = "梦幻紫"
        self.action_map = {}
        self.shortcut_actions = []
        self.shortcuts = {}
        self.main_go_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'main.go')
        self.initUI()
        self.load_shortcuts()
        self.setup_shortcuts()
        self.load_main_go()
        
    def load_main_go(self):
        """加载或创建 main.go 文件"""
        if os.path.exists(self.main_go_file):
            try:
                with open(self.main_go_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                    self.code_editor.set_text(content)
                    self.statusBar.showMessage('已加载 main.go')
            except Exception as e:
                self.statusBar.showMessage(f'加载 main.go 失败: {str(e)}')
        else:
            default_content = '''package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, World!")
}'''
            try:
                with open(self.main_go_file, 'w', encoding='utf-8') as f:
                    f.write(default_content)
                self.code_editor.set_text(default_content)
                self.statusBar.showMessage('已创建 main.go')
            except Exception as e:
                self.statusBar.showMessage(f'创建 main.go 失败: {str(e)}')
                
    def save_main_go(self):
        """保存代码到 main.go"""
        try:
            content = self.code_editor.get_text()
            with open(self.main_go_file, 'w', encoding='utf-8') as f:
                f.write(content)
            return True
        except Exception as e:
            QMessageBox.critical(self, '错误', f'保存 main.go 失败: {str(e)}')
            return False
        
    def load_shortcuts(self):
        """加载快捷键设置"""
        if os.path.exists(SHORTCUTS_FILE):
            try:
                with open(SHORTCUTS_FILE, 'r', encoding='utf-8') as f:
                    loaded = json.load(f)
                    self.shortcuts = DEFAULT_SHORTCUTS.copy()
                    self.shortcuts.update(loaded)
            except:
                self.shortcuts = DEFAULT_SHORTCUTS.copy()
        else:
            self.shortcuts = DEFAULT_SHORTCUTS.copy()
            
    def setup_shortcuts(self):
        """设置快捷键"""
        for action_id, shortcut in self.shortcuts.items():
            if shortcut and action_id in self.action_map:
                try:
                    self.action_map[action_id].setShortcut(shortcut)
                except:
                    pass
                    
    def update_shortcuts(self):
        """更新快捷键"""
        self.load_shortcuts()
        self.setup_shortcuts()
        
    def initUI(self):
        self.setWindowTitle('Go 编译器')
        self.setGeometry(100, 100, 1200, 800)
        
        # 创建编辑器
        self.code_editor = CodeEditor()
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(5, 5, 5, 5)
        main_layout.setSpacing(5)
        central_widget.setLayout(main_layout)
        
        # 创建工具栏
        self.createToolBar()
        
        # 创建菜单栏
        self.createMenuBar()
        
        # 创建状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        
        h_splitter = QSplitter(Qt.Horizontal)
        
        # 左侧：编辑器
        editor_widget = QWidget()
        editor_layout = QVBoxLayout()
        editor_widget.setLayout(editor_layout)
        editor_layout.setContentsMargins(0, 0, 0, 0)
        editor_layout.addWidget(self.code_editor)
        
        # 右侧：输出区域
        output_widget = QWidget()
        output_layout = QVBoxLayout()
        output_widget.setLayout(output_layout)
        output_layout.setContentsMargins(0, 0, 0, 0)
        
        self.output_text = QTextEdit()
        self.output_text.setReadOnly(True)
        self.output_text.setFont(QFont('Consolas', 12))
        output_layout.addWidget(self.output_text)
        
        # 输入区域
        input_widget = QWidget()
        input_layout = QHBoxLayout()
        input_widget.setLayout(input_layout)
        input_layout.setContentsMargins(0, 5, 0, 0)
        
        input_label = QLabel('📥 输入:')
        input_label.setMaximumWidth(70)
        input_layout.addWidget(input_label)
        
        self.input_edit = QLineEdit()
        self.input_edit.setPlaceholderText('在此输入... (按 Enter 发送)')
        self.input_edit.returnPressed.connect(self.send_input)
        input_layout.addWidget(self.input_edit)
        
        self.send_btn = QPushButton('发送')
        self.send_btn.clicked.connect(self.send_input)
        self.send_btn.setEnabled(False)
        self.send_btn.setMaximumWidth(80)
        input_layout.addWidget(self.send_btn)
        
        output_layout.addWidget(input_widget)
        
        h_splitter.addWidget(editor_widget)
        h_splitter.addWidget(output_widget)
        h_splitter.setSizes([600, 600])
        
        main_layout.addWidget(h_splitter)
        
        # 应用初始主题
        self.apply_theme(self.current_theme)
        
        self.check_go_environment()
        
    def apply_theme(self, theme_name):
        """应用完整界面主题"""
        self.current_theme = theme_name
        themes = get_themes()
        theme = themes.get(theme_name, themes["梦幻紫"])
        
        self.code_editor.apply_theme(theme_name)
        
        bg = theme['bg']
        text = theme['text']
        menu_bg = theme['menu_bg']
        menu_text = theme['menu_text']
        menu_hover = theme['menu_hover']
        toolbar_bg = theme['toolbar_bg']
        status_bg = theme['status_bg']
        status_text = theme['status_text']
        button_bg = theme['button_bg']
        button_hover = theme['button_hover']
        button_text = theme['button_text']
        input_bg = theme['input_bg']
        input_text = theme['input_text']
        output_bg = theme['output_bg']
        output_text = theme['output_text']
        splitter = theme['splitter']
        border = theme['border']
        selection_bg = theme['selection_bg']
        selection_color = theme['selection_color']
        
        self.setStyleSheet(f"""
            QMainWindow {{
                background-color: {bg};
            }}
            QPlainTextEdit {{
                background-color: {bg};
                color: {text};
                selection-background-color: {selection_bg};
                selection-color: {selection_color};
                border: 1px solid {border};
                border-radius: 5px;
                padding: 5px;
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 14px;
            }}
            QPlainTextEdit:focus {{
                border: 1px solid {button_bg};
            }}
            QTextEdit {{
                background-color: {output_bg};
                color: {output_text};
                border: 1px solid {border};
                border-radius: 5px;
                padding: 10px;
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 14px;
            }}
            QTextEdit:focus {{
                border: 1px solid {button_bg};
            }}
            QPushButton {{
                background-color: {button_bg};
                color: {button_text};
                border: none;
                padding: 6px 12px;
                border-radius: 3px;
                font-size: 12px;
                font-weight: bold;
            }}
            QPushButton:hover {{
                background-color: {button_hover};
            }}
            QPushButton:pressed {{
                background-color: {selection_bg};
            }}
            QPushButton#runBtn {{
                background-color: #388a34;
            }}
            QPushButton#runBtn:hover {{
                background-color: #45a341;
            }}
            QPushButton#stopBtn {{
                background-color: #c0392b;
            }}
            QPushButton#stopBtn:hover {{
                background-color: #e74c3c;
            }}
            QLineEdit {{
                background-color: {input_bg};
                color: {input_text};
                border: 1px solid {border};
                border-radius: 4px;
                padding: 8px;
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 14px;
            }}
            QLineEdit:focus {{
                border: 1px solid {button_bg};
            }}
            QLabel {{
                color: {text};
                font-size: 13px;
                font-weight: bold;
            }}
            QStatusBar {{
                background-color: {status_bg};
                color: {status_text};
            }}
            QMenuBar {{
                background-color: {menu_bg};
                color: {menu_text};
                font-size: 13px;
            }}
            QMenuBar::item {{
                padding: 5px 10px;
                background-color: transparent;
            }}
            QMenuBar::item:selected {{
                background-color: {menu_hover};
            }}
            QMenu {{
                background-color: {menu_bg};
                color: {menu_text};
                border: 1px solid {border};
            }}
            QMenu::item {{
                padding: 6px 30px 6px 20px;
                background-color: transparent;
            }}
            QMenu::item:selected {{
                background-color: {menu_hover};
            }}
            QMenu::separator {{
                height: 1px;
                background-color: {border};
                margin: 5px 10px;
            }}
            QSplitter::handle {{
                background-color: {splitter};
            }}
            QSplitter::handle:horizontal {{
                width: 2px;
            }}
            QSplitter::handle:vertical {{
                height: 2px;
            }}
            QToolBar {{
                background-color: {toolbar_bg};
                border: none;
                spacing: 8px;
                padding: 5px 10px;
            }}
            QToolBar QPushButton {{
                font-size: 13px;
                padding: 6px 14px;
            }}
            QListWidget {{
                background-color: {menu_bg};
                color: {menu_text};
                border: 1px solid {border};
                font-family: 'Consolas', 'Courier New', monospace;
                font-size: 13px;
            }}
            QListWidget::item:selected {{
                background-color: {menu_hover};
            }}
            QDialog {{
                background-color: {menu_bg};
            }}
            QScrollBar:vertical {{
                background: {bg};
                width: 12px;
                border-radius: 6px;
            }}
            QScrollBar::handle:vertical {{
                background: {button_bg};
                border-radius: 6px;
                min-height: 20px;
            }}
            QScrollBar::handle:vertical:hover {{
                background: {button_hover};
            }}
            QScrollBar:horizontal {{
                background: {bg};
                height: 12px;
                border-radius: 6px;
            }}
            QScrollBar::handle:horizontal {{
                background: {button_bg};
                border-radius: 6px;
                min-width: 20px;
            }}
            QScrollBar::handle:horizontal:hover {{
                background: {button_hover};
            }}
            QScrollBar::add-line, QScrollBar::sub-line {{
                border: none;
                background: none;
            }}
        """)
        
        self.status_label.setText(f'🎨 {theme_name}')
        
    def createMenuBar(self):
        menubar = self.menuBar()
        
        file_menu = menubar.addMenu('文件')
        
        new_action = QAction('新建', self)
        new_action.triggered.connect(self.new_file)
        file_menu.addAction(new_action)
        self.action_map['new_file'] = new_action
        self.shortcut_actions.append(new_action)
        
        open_action = QAction('打开', self)
        open_action.triggered.connect(self.open_file)
        file_menu.addAction(open_action)
        self.action_map['open_file'] = open_action
        self.shortcut_actions.append(open_action)
        
        save_action = QAction('保存', self)
        save_action.triggered.connect(self.save_file)
        file_menu.addAction(save_action)
        self.action_map['save_file'] = save_action
        self.shortcut_actions.append(save_action)
        
        save_as_action = QAction('另存为', self)
        save_as_action.triggered.connect(self.save_file_as)
        file_menu.addAction(save_as_action)
        self.action_map['save_as'] = save_as_action
        self.shortcut_actions.append(save_as_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction('退出', self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        self.action_map['exit'] = exit_action
        self.shortcut_actions.append(exit_action)
        
        run_menu = menubar.addMenu('运行')
        
        run_action = QAction('运行', self)
        run_action.triggered.connect(self.run_code)
        run_menu.addAction(run_action)
        self.action_map['run'] = run_action
        self.shortcut_actions.append(run_action)
        
        stop_action = QAction('停止', self)
        stop_action.triggered.connect(self.stop_code)
        run_menu.addAction(stop_action)
        self.action_map['stop'] = stop_action
        self.shortcut_actions.append(stop_action)
        
        run_menu.addSeparator()
        
        compile_action = QAction('编译', self)
        compile_action.triggered.connect(self.compile_code)
        run_menu.addAction(compile_action)
        self.action_map['compile'] = compile_action
        self.shortcut_actions.append(compile_action)
        
        tools_menu = menubar.addMenu('工具')
        
        format_action = QAction('格式化代码', self)
        format_action.triggered.connect(self.format_code)
        tools_menu.addAction(format_action)
        self.action_map['format'] = format_action
        self.shortcut_actions.append(format_action)
        
        tools_menu.addSeparator()
        
        dep_action = QAction('📦 依赖管理', self)
        dep_action.triggered.connect(self.open_dependency_manager)
        tools_menu.addAction(dep_action)
        
        tools_menu.addSeparator()
        
        # 添加打包exe功能
        build_exe_action = QAction('📦 打包 EXE', self)
        build_exe_action.triggered.connect(self.open_build_exe_dialog)
        tools_menu.addAction(build_exe_action)
        
        tools_menu.addSeparator()
        
        shortcut_action = QAction('⌨️ 快捷键设置', self)
        shortcut_action.triggered.connect(self.open_shortcut_manager)
        tools_menu.addAction(shortcut_action)
        
        tools_menu.addSeparator()
        
        self.skin_menu = tools_menu.addMenu('🎨 皮肤')
        
        themes = get_themes()
        self.skin_actions = []
        for theme_name in themes.keys():
            action = QAction(theme_name, self)
            action.setCheckable(True)
            action.triggered.connect(lambda checked, t=theme_name: self.change_skin(t))
            self.skin_menu.addAction(action)
            self.skin_actions.append(action)
            if theme_name == self.current_theme:
                action.setChecked(True)
        
        tools_menu.addSeparator()
        
        clear_action = QAction('清除输出', self)
        clear_action.triggered.connect(self.clear_output)
        tools_menu.addAction(clear_action)
        self.action_map['clear_output'] = clear_action
        self.shortcut_actions.append(clear_action)
        
        clear_all_action = QAction('清除全部', self)
        clear_all_action.triggered.connect(self.clear_all)
        tools_menu.addAction(clear_all_action)
        self.action_map['clear_all'] = clear_all_action
        self.shortcut_actions.append(clear_all_action)
        
        tools_menu.addSeparator()
        
        go_env_action = QAction('检查 Go 环境', self)
        go_env_action.triggered.connect(self.check_go_environment)
        tools_menu.addAction(go_env_action)
        
        help_menu = menubar.addMenu('帮助')
        
        about_action = QAction('关于', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
        
        shortcuts_action = QAction('快捷键', self)
        shortcuts_action.triggered.connect(self.show_shortcuts)
        help_menu.addAction(shortcuts_action)
        
    def open_shortcut_manager(self):
        """打开快捷键设置"""
        dialog = ShortcutManager(self)
        dialog.exec_()
        
    def open_dependency_manager(self):
        """打开依赖管理器"""
        try:
            if not os.path.exists('go.mod'):
                reply = QMessageBox.question(self, '初始化项目', 
                                           '当前目录没有 go.mod 文件，是否初始化 Go 模块？',
                                           QMessageBox.Yes | QMessageBox.No)
                if reply == QMessageBox.Yes:
                    result = subprocess.run(['go', 'mod', 'init', 'myproject'], 
                                          capture_output=True, 
                                          text=True,
                                          timeout=10)
                    if result.returncode != 0:
                        QMessageBox.warning(self, '错误', f'初始化失败: {result.stderr}')
                        return
        except Exception as e:
            QMessageBox.warning(self, '错误', f'检查项目环境失败: {str(e)}')
            return
            
        dialog = DependencyManager(self)
        dialog.exec_()
        
    def open_build_exe_dialog(self):
        """打开打包EXE对话框"""
        dialog = BuildExeDialog(self)
        dialog.exec_()
        
    def change_skin(self, theme_name):
        """切换皮肤"""
        self.apply_theme(theme_name)
        
        for action in self.skin_actions:
            action.setChecked(action.text() == theme_name)
        
        self.statusBar.showMessage(f'已切换皮肤: {theme_name}')
        
    def createToolBar(self):
        toolbar = self.addToolBar('工具栏')
        toolbar.setMovable(False)
        
        self.run_btn = QPushButton('▶ 运行')
        self.run_btn.setObjectName('runBtn')
        self.run_btn.clicked.connect(self.run_code)
        self.run_btn.setToolTip('运行当前代码')
        toolbar.addWidget(self.run_btn)
        
        self.stop_btn = QPushButton('⏹ 停止')
        self.stop_btn.setObjectName('stopBtn')
        self.stop_btn.clicked.connect(self.stop_code)
        self.stop_btn.setToolTip('停止运行')
        self.stop_btn.setEnabled(False)
        toolbar.addWidget(self.stop_btn)
        
        toolbar.addSeparator()
        
        self.status_label = QLabel('就绪')
        self.status_label.setStyleSheet("font-size: 13px; padding: 5px;")
        toolbar.addWidget(self.status_label)
        
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        toolbar.addWidget(spacer)
        
        self.go_version_label = QLabel('')
        self.go_version_label.setStyleSheet("font-size: 12px; padding: 5px;")
        toolbar.addWidget(self.go_version_label)
        
    def check_go_environment(self):
        """检查 Go 环境"""
        try:
            result = subprocess.run(['go', 'version'], 
                                  capture_output=True, 
                                  text=True,
                                  timeout=5)
            if result.returncode == 0:
                version = result.stdout.strip().split('\n')[0]
                self.statusBar.showMessage(f'✅ Go 环境: {version}')
                self.status_label.setText('✅ Go 环境就绪')
                self.go_version_label.setText(version)
                return True
            else:
                self.statusBar.showMessage('❌ Go 环境未找到')
                self.status_label.setText('❌ Go 未安装')
                self.go_version_label.setText('')
                return False
        except (subprocess.TimeoutExpired, FileNotFoundError):
            self.statusBar.showMessage('❌ Go 环境未找到，请安装 Go')
            self.status_label.setText('❌ Go 未安装')
            self.go_version_label.setText('')
            return False
    
    def run_code(self):
        """运行 Go 代码 - 支持 Web 和 GUI 应用"""
        code = self.code_editor.get_text().strip()
        if not code:
            QMessageBox.warning(self, '警告', '请输入要运行的 Go 代码！')
            return
            
        if self.is_running:
            self.stop_code()
            
        try:
            self.temp_dir = tempfile.mkdtemp()
            temp_file = os.path.join(self.temp_dir, 'main.go')
            
            with open(temp_file, 'w', encoding='utf-8') as f:
                f.write(code)
            
            # 检查是否需要初始化 go.mod
            has_import = 'import' in code
            has_main = 'func main' in code
            
            # 如果是 Web 或 GUI 应用，初始化模块并下载依赖
            is_web_app = 'http.ListenAndServe' in code or 'http.Handle' in code
            is_gui_app = 'github.com/andlabs/ui' in code or 'fyne' in code
            
            if is_web_app or is_gui_app:
                self.output_text.append('🌐 检测到 Web/GUI 应用，正在初始化环境...')
                
                # 初始化 go.mod
                init_result = subprocess.run(['go', 'mod', 'init', 'tempapp'], 
                                           cwd=self.temp_dir,
                                           capture_output=True, 
                                           text=True,
                                           timeout=10)
                if init_result.returncode != 0:
                    self.output_text.append(f'⚠️ go mod init 警告: {init_result.stderr}')
                
                # 下载依赖
                tidy_result = subprocess.run(['go', 'mod', 'tidy'], 
                                           cwd=self.temp_dir,
                                           capture_output=True, 
                                           text=True,
                                           timeout=60)
                if tidy_result.returncode != 0:
                    self.output_text.append(f'⚠️ go mod tidy 警告: {tidy_result.stderr}')
                
                self.output_text.append('✅ 环境准备完成')
            
            self.output_text.append('🔨 正在编译并运行...\n')
            self.output_text.append('─' * 60)
            
            # 创建进程
            self.process = QProcess()
            self.process.setWorkingDirectory(self.temp_dir)
            self.process.setProcessChannelMode(QProcess.MergedChannels)
            
            # 连接信号
            self.process.readyReadStandardOutput.connect(self.handle_output)
            self.process.readyReadStandardError.connect(self.handle_error)
            self.process.finished.connect(self.handle_finished)
            self.process.stateChanged.connect(self.handle_state_changed)
            
            # 启动 Go run
            self.process.start('go', ['run', temp_file])
            
            self.is_running = True
            self.run_btn.setEnabled(False)
            self.stop_btn.setEnabled(True)
            
            # 如果是交互式应用，启用输入
            if 'Scan' in code or 'ReadString' in code:
                self.send_btn.setEnabled(True)
                self.input_edit.setEnabled(True)
                self.input_edit.clear()
                self.input_edit.setFocus()
            else:
                self.send_btn.setEnabled(False)
                self.input_edit.setEnabled(False)
            
            self.statusBar.showMessage('运行中...')
            self.status_label.setText('⏳ 运行中...')
            
            # 如果是 Web 应用，提示访问地址
            if is_web_app:
                self.output_text.append('\n🌐 Web 服务已启动！')
                self.output_text.append('📍 访问 http://localhost:8080')
                self.output_text.append('─' * 60)
            
        except Exception as e:
            self.output_text.append(f'❌ 错误: {str(e)}')
            self.statusBar.showMessage('运行失败')
            self.status_label.setText('❌ 运行失败')
    
    def stop_code(self):
        """停止运行中的代码"""
        if self.process and self.process.state() == QProcess.Running:
            self.process.terminate()
            if not self.process.waitForFinished(3000):
                self.process.kill()
            self.output_text.append('\n⏹ 程序已被用户停止')
            self.statusBar.showMessage('程序已停止')
            self.status_label.setText('⏹ 已停止')
            
        self.is_running = False
        self.run_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.send_btn.setEnabled(False)
        self.input_edit.setEnabled(False)
        
        if self.temp_dir and os.path.exists(self.temp_dir):
            import shutil
            shutil.rmtree(self.temp_dir, ignore_errors=True)
            self.temp_dir = None
    
    def handle_output(self):
        """处理标准输出"""
        if self.process:
            data = self.process.readAllStandardOutput()
            if data:
                text = data.data().decode('utf-8', errors='ignore')
                if text:
                    self.output_text.append(text)
                    self.output_text.verticalScrollBar().setValue(
                        self.output_text.verticalScrollBar().maximum()
                    )
    
    def handle_error(self):
        """处理错误输出"""
        if self.process:
            data = self.process.readAllStandardError()
            if data:
                text = data.data().decode('utf-8', errors='ignore')
                if text:
                    self.output_text.append(f'❌ {text}')
    
    def handle_finished(self, exit_code, exit_status):
        """处理运行完成"""
        self.is_running = False
        self.run_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.send_btn.setEnabled(False)
        self.input_edit.setEnabled(False)
        
        if exit_code == 0:
            self.output_text.append('─' * 60)
            self.output_text.append('✅ 程序执行完成')
            self.statusBar.showMessage('运行完成')
            self.status_label.setText('✅ 运行完成')
        elif exit_code == -1:
            pass
        else:
            self.output_text.append('─' * 60)
            self.output_text.append(f'⚠️ 程序退出 (退出码: {exit_code})')
            self.statusBar.showMessage(f'运行失败 (退出码: {exit_code})')
            self.status_label.setText('❌ 运行失败')
            
        self.process = None
        
        if self.temp_dir and os.path.exists(self.temp_dir):
            import shutil
            shutil.rmtree(self.temp_dir, ignore_errors=True)
            self.temp_dir = None
    
    def handle_state_changed(self, state):
        """处理进程状态变化"""
        if state == QProcess.NotRunning and self.is_running:
            self.is_running = False
            self.run_btn.setEnabled(True)
            self.stop_btn.setEnabled(False)
            self.send_btn.setEnabled(False)
            self.input_edit.setEnabled(False)
    
    def send_input(self):
        """发送输入到运行的进程"""
        if not self.process or self.process.state() != QProcess.Running:
            QMessageBox.warning(self, '警告', '程序没有在运行！')
            return
            
        input_text = self.input_edit.text()
        if not input_text:
            return
            
        input_bytes = (input_text + '\n').encode('utf-8')
        self.process.write(input_bytes)
        self.output_text.append(f'📥 {input_text}')
        self.input_edit.clear()
    
    def compile_code(self):
        """编译 Go 代码"""
        if not self.save_main_go():
            return
            
        self.output_text.clear()
        self.output_text.append('🔨 正在编译...\n')
        self.output_text.append('─' * 60)
        
        try:
            result = subprocess.run(['go', 'build', '-o', 'program', self.main_go_file],
                                  capture_output=True,
                                  text=True,
                                  timeout=30)
            
            if result.returncode == 0:
                self.output_text.append('✅ 编译成功！')
                self.output_text.append(f'📁 可执行文件: {os.path.join(os.path.dirname(self.main_go_file), "program")}')
                self.statusBar.showMessage('编译成功')
                self.status_label.setText('✅ 编译成功')
            else:
                self.output_text.append('❌ 编译失败：')
                self.output_text.append(result.stderr)
                self.statusBar.showMessage('编译失败')
                self.status_label.setText('❌ 编译失败')
                
        except subprocess.TimeoutExpired:
            self.output_text.append('❌ 编译超时')
            self.statusBar.showMessage('编译超时')
        except Exception as e:
            self.output_text.append(f'❌ 错误: {str(e)}')
            self.statusBar.showMessage('编译失败')
    
    def format_code(self):
        """格式化 Go 代码"""
        if not self.save_main_go():
            return
            
        try:
            result = subprocess.run(['go', 'fmt', self.main_go_file],
                                  capture_output=True,
                                  text=True,
                                  timeout=5)
            
            if result.returncode == 0:
                with open(self.main_go_file, 'r', encoding='utf-8') as f:
                    formatted_code = f.read()
                self.code_editor.set_text(formatted_code)
                self.statusBar.showMessage('代码格式化完成')
                self.status_label.setText('✅ 格式化完成')
                QMessageBox.information(self, '成功', '代码格式化完成！')
            else:
                self.statusBar.showMessage('格式化失败')
                QMessageBox.warning(self, '失败', '代码格式化失败，请检查代码语法')
            
        except Exception as e:
            self.statusBar.showMessage(f'格式化错误: {str(e)}')
            QMessageBox.critical(self, '错误', f'格式化错误: {str(e)}')
    
    def clear_output(self):
        """清除输出"""
        self.output_text.clear()
        self.statusBar.showMessage('已清除输出')
    
    def clear_all(self):
        """清除全部"""
        self.output_text.clear()
        self.input_edit.clear()
        self.statusBar.showMessage('已清除全部内容')
    
    def new_file(self):
        """新建文件"""
        if self.is_running:
            self.stop_code()
        self.code_editor.clear_text()
        self.output_text.clear()
        self.input_edit.clear()
        self.statusBar.showMessage('新建文件')
    
    def open_file(self):
        """打开文件"""
        if self.is_running:
            self.stop_code()
            
        file_path, _ = QFileDialog.getOpenFileName(
            self, '打开 Go 文件', '', 'Go 文件 (*.go);;所有文件 (*)'
        )
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                self.code_editor.set_text(content)
                with open(self.main_go_file, 'w', encoding='utf-8') as f:
                    f.write(content)
                self.statusBar.showMessage(f'已打开: {file_path}')
            except Exception as e:
                QMessageBox.critical(self, '错误', f'无法打开文件: {str(e)}')
    
    def save_file(self):
        """保存文件"""
        if self.save_main_go():
            self.statusBar.showMessage(f'已保存: {self.main_go_file}')
            QMessageBox.information(self, '成功', f'代码已保存到: {self.main_go_file}')
    
    def save_file_as(self):
        """另存为"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, '保存 Go 文件', '', 'Go 文件 (*.go);;所有文件 (*)'
        )
        if file_path:
            try:
                content = self.code_editor.get_text()
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                self.statusBar.showMessage(f'已保存: {file_path}')
            except Exception as e:
                QMessageBox.critical(self, '错误', f'无法保存文件: {str(e)}')
    
    def show_about(self):
        QMessageBox.about(
            self,
            '关于 Go 编译器',
            '''
            <h2>🚀 Go 编译器</h2>
            <p>版本 3.0 (纯PyQt5版本)</p>
            <p>基于 Python + PyQt5 的 Go 语言 IDE</p>
            <p>✨ 主要功能：</p>
            <ul>
                <li>10种可爱渐变色主题（完整界面换肤）</li>
                <li>📦 依赖管理（支持批量安装/卸载）</li>
                <li>⌨️ 自定义快捷键</li>
                <li>📄 自动保存到 main.go</li>
                <li>🌐 支持运行 Web 应用</li>
                <li>📊 安装进度条显示</li>
                <li>🌍 代理设置支持</li>
                <li>📦 打包 EXE（支持交叉编译）</li>
                <li>语法高亮显示</li>
                <li>智能自动补全</li>
                <li>交互式输入/输出</li>
                <li>编译和运行</li>
                <li>代码格式化</li>
                <li>文件管理</li>
            </ul>
            <p><b>特点：</b>纯 PyQt5 实现，无需任何第三方库</p>
            <p><b>🎨 主题：</b>梦幻紫、樱花粉、薄荷绿、天空蓝、珊瑚橙、森林绿、极光蓝、薰衣草、玫瑰金、星辰黑</p>
            '''
        )
    
    def show_shortcuts(self):
        shortcut_text = '''
        <h3>⌨️ 快捷键</h3>
        <table style="width:100%; border-collapse: collapse;">
        '''
        
        action_names = {
            'run': '运行代码',
            'stop': '停止运行',
            'compile': '编译代码',
            'format': '格式化代码',
            'new_file': '新建文件',
            'open_file': '打开文件',
            'save_file': '保存文件',
            'save_as': '另存为',
            'clear_output': '清除输出',
            'clear_all': '清除全部',
            'exit': '退出程序',
            'send_input': '发送输入',
        }
        
        for action_id, shortcut in self.shortcuts.items():
            if action_id in action_names:
                shortcut_text += f'<tr><td><b>{shortcut}</b></td><td>{action_names[action_id]}</td></tr>'
        
        shortcut_text += '</table><br><p>💡 在 "工具" → "快捷键设置" 中自定义快捷键</p>'
        
        QMessageBox.information(
            self,
            '快捷键列表',
            shortcut_text
        )
    
    def closeEvent(self, event):
        self.save_main_go()
        if self.is_running:
            self.stop_code()
        event.accept()

def main():
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    
    compiler = GoCompiler()
    compiler.show()
    
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()