content: package com.alphabugx.editor;
  
  
  import javafx.application.Platform;
  import javafx.concurrent.Task;
  import javafx.scene.input.KeyCode;
  import javafx.scene.input.KeyEvent;
  import org.fxmisc.richtext.CodeArea;
  import org.fxmisc.richtext.LineNumberFactory;
  import org.fxmisc.richtext.model.StyleSpans;
  import org.fxmisc.richtext.model.StyleSpansBuilder;
  
  import java.io.File;
  import java.time.Duration;
  import java.util.*;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  /**
   * 专业的Java代码编辑器
   * 支持语法高亮、行号、代码跳转、搜索等功能
   */
  public class JavaCodeEditor extends CodeArea {
      
      // Java关键字
      private static final String[] KEYWORDS = new String[] {
          "abstract", "assert", "boolean", "break", "byte",
          "case", "catch", "char", "class", "const",
          "continue", "default", "do", "double", "else",
          "enum", "extends", "final", "finally", "float",
          "for", "goto", "if", "implements", "import",
          "instanceof", "int", "interface", "long", "native",
          "new", "package", "private", "protected", "public",
          "return", "short", "static", "strictfp", "super",
          "switch", "synchronized", "this", "throw", "throws",
          "transient", "try", "void", "volatile", "while"
      };
  
      private static final String KEYWORD_PATTERN = "\\b(" + String.join("|", KEYWORDS) + ")\\b";
      private static final String PAREN_PATTERN = "\\(|\\)";
      private static final String BRACE_PATTERN = "\\{|\\}";
      private static final String BRACKET_PATTERN = "\\[|\\]";
      private static final String SEMICOLON_PATTERN = "\\;";
      private static final String STRING_PATTERN = "\"([^\"\\\\]|\\\\.)*\"";
      private static final String COMMENT_PATTERN = "//[^\n]*" + "|" + "/\\*(.|\\R)*?\\*/";
      private static final String ANNOTATION_PATTERN = "@\\w+";
      private static final String NUMBER_PATTERN = "\\b\\d+(\\.\\d+)?[fFdDlL]?\\b";
      
      private static final Pattern PATTERN = Pattern.compile(
              "(?<KEYWORD>" + KEYWORD_PATTERN + ")"
              + "|(?<PAREN>" + PAREN_PATTERN + ")"
              + "|(?<BRACE>" + BRACE_PATTERN + ")"
              + "|(?<BRACKET>" + BRACKET_PATTERN + ")"
              + "|(?<SEMICOLON>" + SEMICOLON_PATTERN + ")"
              + "|(?<STRING>" + STRING_PATTERN + ")"
              + "|(?<COMMENT>" + COMMENT_PATTERN + ")"
              + "|(?<ANNOTATION>" + ANNOTATION_PATTERN + ")"
              + "|(?<NUMBER>" + NUMBER_PATTERN + ")"
      );
  
      private ExecutorService executor;
      private File currentFile;
  
      private Runnable globalSearchCallback; // 全局搜索回调
      
      public JavaCodeEditor() {
          super();
          this.executor = Executors.newSingleThreadExecutor();
  
          
          initializeEditor();
          setupSyntaxHighlighting();
          setupCodeNavigation();
          setupKeyboardShortcuts();
      }
      
      /**
       * 初始化编辑器
       */
      private void initializeEditor() {
          // 添加行号
          setParagraphGraphicFactory(LineNumberFactory.get(this));
          
          // 设置基本字体
          setStyle("-fx-font-family: 'Consolas', 'Monaco', 'Courier New', monospace; -fx-font-size: 14px;");
          
          // 固定使用IntelliJ Light主题
          applyLightTheme();
      }
      
      /**
       * 应用IntelliJ Light主题
       */
      private void applyLightTheme() {
          try {
              String cssUrl = getClass().getResource("/com/alphabugx/editor/themes/intellij-light.css").toExternalForm();
              getStylesheets().clear();
              getStylesheets().add(cssUrl);
          } catch (Exception e) {
              System.err.println("无法加载IntelliJ Light主题CSS文件，使用默认样式");
              // 使用内联样式作为备用
              setStyle(getStyle() + "; -fx-background-color: #ffffff; -fx-text-fill: #000000;");
          }
          
          // 重新应用语法高亮
          if (!getText().isEmpty()) {
              setStyleSpans(0, computeHighlighting(getText()));
          }
      }
      
      /**
       * 设置语法高亮
       */
      private void setupSyntaxHighlighting() {
          // 当文本改变时，延迟高亮以提高性能
          richChanges()
              .filter(ch -> !ch.getInserted().equals(ch.getRemoved()))
              .successionEnds(Duration.ofMillis(500))
              .subscribe(ignore -> {
                  Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {
                      @Override
                      protected StyleSpans<Collection<String>> call() throws Exception {
                          return computeHighlighting(getText());
                      }
                  };
                  
                  task.setOnSucceeded(e -> {
                                              setStyleSpans(0, task.getValue());
                  });
                  
                  executor.execute(task);
              });
      }
      
      /**
       * 计算语法高亮
       */
      private static StyleSpans<Collection<String>> computeHighlighting(String text) {
          Matcher matcher = PATTERN.matcher(text);
          StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
          int lastKwEnd = 0;
          
          while(matcher.find()) {
              String styleClass =
                  matcher.group("KEYWORD") != null ? "keyword" :
                  matcher.group("PAREN") != null ? "paren" :
                  matcher.group("BRACE") != null ? "brace" :
                  matcher.group("BRACKET") != null ? "bracket" :
                  matcher.group("SEMICOLON") != null ? "semicolon" :
                  matcher.group("STRING") != null ? "string" :
                  matcher.group("COMMENT") != null ? "comment" :
                  matcher.group("ANNOTATION") != null ? "annotation" :
                  matcher.group("NUMBER") != null ? "number" :
                  null;
              
              assert styleClass != null;
              spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
              spansBuilder.add(Collections.singleton(styleClass), matcher.end() - matcher.start());
              lastKwEnd = matcher.end();
          }
          spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
          return spansBuilder.create();
      }
      
      /**
       * 设置代码导航功能 (已禁用，体验不佳)
       */
      private void setupCodeNavigation() {
          // 代码导航功能已移除，体验不佳
          // 用户可以通过全局搜索功能查找相关代码
      }
      
      /**
       * 设置键盘快捷键
       */
      private void setupKeyboardShortcuts() {
          addEventFilter(KeyEvent.KEY_PRESSED, event -> {
              if (event.isControlDown()) {
                  switch (event.getCode()) {
                                      case F:
                      // Ctrl+F 打开全局搜索
                      if (globalSearchCallback != null) {
                          globalSearchCallback.run();
                      }
                      event.consume();
                      break;
                      case G:
                          // Ctrl+G 跳转到行
                          openGoToLineDialog();
                          event.consume();
                          break;
                      case SPACE:
                          // Ctrl+Space 代码补全
                          showCodeCompletion();
                          event.consume();
                          break;
                  }
              }
          });
      }
      
  
      
      /**
       * 搜索文本
       */
      public void searchText(String searchText, boolean useRegex, boolean caseSensitive) {
          String text = getText();
          Pattern pattern;
          
          try {
              if (useRegex) {
                  int flags = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
                  pattern = Pattern.compile(searchText, flags);
              } else {
                  String escaped = Pattern.quote(searchText);
                  int flags = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
                  pattern = Pattern.compile(escaped, flags);
              }
              
              Matcher matcher = pattern.matcher(text);
              
              // 清除之前的高亮
              clearSearchHighlight();
              
              // 添加搜索结果高亮
              while (matcher.find()) {
                  setStyle(matcher.start(), matcher.end(), Collections.singleton("search-highlight"));
              }
              
              // 跳转到第一个匹配
              matcher.reset();
              if (matcher.find()) {
                  selectRange(matcher.start(), matcher.end());
                  requestFollowCaret();
              }
              
          } catch (Exception e) {
              // 正则表达式错误
              System.err.println("搜索表达式错误: " + e.getMessage());
          }
      }
      
      /**
       * 清除搜索高亮
       */
      private void clearSearchHighlight() {
          clearStyle(0, getLength());
          // 重新应用语法高亮
          setStyleSpans(0, computeHighlighting(getText()));
      }
      
      /**
       * 打开搜索对话框
       */
      private void openSearchDialog() {
          // TODO: 实现搜索对话框
          System.out.println("打开搜索对话框");
      }
      
      /**
       * 打开跳转到行对话框
       */
      private void openGoToLineDialog() {
          // TODO: 实现跳转到行对话框
          System.out.println("打开跳转到行对话框");
      }
      
      /**
       * 显示代码补全
       */
      private void showCodeCompletion() {
          // TODO: 实现代码补全
          System.out.println("显示代码补全");
      }
      
      /**
       * 设置当前文件
       */
      public void setCurrentFile(File file) {
          this.currentFile = file;
      }
      
      /**
       * 设置全局搜索回调
       */
      public void setGlobalSearchCallback(Runnable callback) {
          this.globalSearchCallback = callback;
      }
      
      /**
       * 获取当前文件
       */
      public File getCurrentFile() {
          return currentFile;
      }
      
      /**
       * 清理资源
       */
      public void cleanup() {
          if (executor != null && !executor.isShutdown()) {
              executor.shutdown();
          }
      }
      
  } 