content: package com.alphabugx.search;
  
  import javafx.application.Platform;
  import javafx.concurrent.Task;
  import javafx.geometry.Insets;
  import javafx.scene.Scene;
  import javafx.scene.control.*;
  import javafx.scene.control.cell.PropertyValueFactory;
  import javafx.scene.layout.BorderPane;
  import javafx.scene.layout.HBox;
  import javafx.scene.layout.VBox;
  import javafx.stage.Modality;
  import javafx.stage.Stage;
  
  import java.io.File;
  import java.io.IOException;
  import java.nio.file.Files;
  import java.util.ArrayList;
  import java.util.List;
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  /**
   * 全局搜索对话框
   * 支持在所有Java文件中搜索关键字，支持正则表达式
   */
  public class GlobalSearchDialog {
      
      private Stage dialog;
      private TextField searchField;
      private CheckBox regexCheckBox;
      private CheckBox caseSensitiveCheckBox;
      private CheckBox wholeWordCheckBox;
      private TableView<SearchResult> resultsTable;
      private Label statusLabel;
      private Button searchButton;
      private File searchDirectory;
      private SearchResultHandler resultHandler;
      
      public interface SearchResultHandler {
          void onResultSelected(SearchResult result);
      }
      
      public GlobalSearchDialog(Stage owner, File searchDirectory) {
          this.searchDirectory = searchDirectory;
          initializeDialog(owner);
      }
      
      /**
       * 初始化对话框
       */
      private void initializeDialog(Stage owner) {
          dialog = new Stage();
          dialog.initModality(Modality.NONE);  // 改为非模态窗口，允许同时编辑
          dialog.initOwner(owner);
          dialog.setTitle("全局搜索 - 在所有Java文件中查找");
          dialog.setResizable(true);
          
          // 创建UI组件
          createSearchControls();
          createResultsTable();
          createLayout();
          
          // 设置场景
          Scene scene = new Scene(createMainLayout(), 800, 600);
          dialog.setScene(scene);
      }
      
      /**
       * 创建搜索控件
       */
      private void createSearchControls() {
          searchField = new TextField();
          searchField.setPromptText("输入搜索关键字...");
          searchField.setPrefWidth(300);
          
          regexCheckBox = new CheckBox("正则表达式");
          caseSensitiveCheckBox = new CheckBox("区分大小写");
          wholeWordCheckBox = new CheckBox("全词匹配");
          
          searchButton = new Button("搜索");
          searchButton.setDefaultButton(true);
          searchButton.setOnAction(e -> performSearch());
          
          Button clearButton = new Button("清空");
          clearButton.setOnAction(e -> clearResults());
          
          // 回车键搜索
          searchField.setOnAction(e -> performSearch());
          
          statusLabel = new Label("请输入搜索关键字");
      }
      
      /**
       * 创建结果表格
       */
      private void createResultsTable() {
          resultsTable = new TableView<>();
          
          // 文件名列
          TableColumn<SearchResult, String> fileColumn = new TableColumn<>("文件");
          fileColumn.setCellValueFactory(new PropertyValueFactory<>("fileName"));
          fileColumn.setPrefWidth(150);
          
          // 行号列
          TableColumn<SearchResult, Integer> lineColumn = new TableColumn<>("行号");
          lineColumn.setCellValueFactory(new PropertyValueFactory<>("lineNumber"));
          lineColumn.setPrefWidth(60);
          
          // 匹配内容列
          TableColumn<SearchResult, String> contentColumn = new TableColumn<>("匹配内容");
          contentColumn.setCellValueFactory(new PropertyValueFactory<>("matchedLine"));
          contentColumn.setPrefWidth(500);
          
          // 文件路径列
          TableColumn<SearchResult, String> pathColumn = new TableColumn<>("路径");
          pathColumn.setCellValueFactory(new PropertyValueFactory<>("filePath"));
          pathColumn.setPrefWidth(200);
          
          resultsTable.getColumns().addAll(fileColumn, lineColumn, contentColumn, pathColumn);
          
          // 双击跳转到文件
          resultsTable.setOnMouseClicked(event -> {
              if (event.getClickCount() == 2 && resultHandler != null) {
                  SearchResult selected = resultsTable.getSelectionModel().getSelectedItem();
                  if (selected != null) {
                      resultHandler.onResultSelected(selected);
                  }
              }
          });
      }
      
      /**
       * 创建布局
       */
      private BorderPane createMainLayout() {
          BorderPane mainLayout = new BorderPane();
          
          // 顶部搜索区域
          VBox topArea = new VBox(10);
          topArea.setPadding(new Insets(10));
          
          HBox searchBox = new HBox(10);
          searchBox.getChildren().addAll(
              new Label("搜索:"), searchField, searchButton, new Button("清空")
          );
          
          HBox optionsBox = new HBox(15);
          optionsBox.getChildren().addAll(regexCheckBox, caseSensitiveCheckBox, wholeWordCheckBox);
          
          topArea.getChildren().addAll(searchBox, optionsBox, statusLabel);
          mainLayout.setTop(topArea);
          
          // 中间结果区域
          mainLayout.setCenter(resultsTable);
          
          // 底部按钮区域
          HBox bottomArea = new HBox(10);
          bottomArea.setPadding(new Insets(10));
          Button closeButton = new Button("关闭");
          closeButton.setOnAction(e -> dialog.close());
          bottomArea.getChildren().add(closeButton);
          mainLayout.setBottom(bottomArea);
          
          return mainLayout;
      }
      
      /**
       * 创建布局
       */
      private void createLayout() {
          // 此方法保持空白，布局在createMainLayout中处理
      }
      
      /**
       * 执行搜索
       */
      private void performSearch() {
          String searchText = searchField.getText().trim();
          if (searchText.isEmpty()) {
              showStatus("请输入搜索关键字");
              return;
          }
          
          // 禁用搜索按钮
          searchButton.setDisable(true);
          showStatus("搜索中...");
          clearResults();
          
          // 在后台线程中执行搜索
          Task<List<SearchResult>> searchTask = new Task<List<SearchResult>>() {
              @Override
              protected List<SearchResult> call() throws Exception {
                  return searchInFiles(searchText);
              }
          };
          
          searchTask.setOnSucceeded(e -> {
              List<SearchResult> results = searchTask.getValue();
              Platform.runLater(() -> {
                  resultsTable.getItems().addAll(results);
                  showStatus("找到 " + results.size() + " 个匹配项");
                  searchButton.setDisable(false);
              });
          });
          
          searchTask.setOnFailed(e -> {
              Platform.runLater(() -> {
                  showStatus("搜索失败: " + searchTask.getException().getMessage());
                  searchButton.setDisable(false);
              });
          });
          
          Thread searchThread = new Thread(searchTask);
          searchThread.setDaemon(true);
          searchThread.start();
      }
      
      /**
       * 在文件中搜索
       */
      private List<SearchResult> searchInFiles(String searchText) {
          List<SearchResult> results = new ArrayList<>();
          List<File> javaFiles = findJavaFiles(searchDirectory);
          
          try {
              Pattern pattern = createSearchPattern(searchText);
              
              for (File file : javaFiles) {
                  searchInFile(file, pattern, results);
              }
          } catch (Exception e) {
              throw new RuntimeException("搜索过程中发生错误", e);
          }
          
          return results;
      }
      
      /**
       * 创建搜索模式
       */
      private Pattern createSearchPattern(String searchText) {
          int flags = 0;
          
          if (!caseSensitiveCheckBox.isSelected()) {
              flags |= Pattern.CASE_INSENSITIVE;
          }
          
          String patternString;
          if (regexCheckBox.isSelected()) {
              patternString = searchText;
          } else {
              patternString = Pattern.quote(searchText);
              if (wholeWordCheckBox.isSelected()) {
                  patternString = "\\b" + patternString + "\\b";
              }
          }
          
          return Pattern.compile(patternString, flags);
      }
      
      /**
       * 在单个文件中搜索
       */
      private void searchInFile(File file, Pattern pattern, List<SearchResult> results) {
          try {
              List<String> lines = Files.readAllLines(file.toPath());
              
              for (int i = 0; i < lines.size(); i++) {
                  String line = lines.get(i);
                  Matcher matcher = pattern.matcher(line);
                  
                  if (matcher.find()) {
                      SearchResult result = new SearchResult(
                          file.getName(),
                          file.getAbsolutePath(),
                          i + 1,
                          line.trim(),
                          matcher.start(),
                          matcher.end()
                      );
                      results.add(result);
                  }
              }
          } catch (IOException e) {
              System.err.println("读取文件失败: " + file.getAbsolutePath() + " - " + e.getMessage());
          }
      }
      
      /**
       * 查找所有Java文件
       */
      private List<File> findJavaFiles(File directory) {
          List<File> javaFiles = new ArrayList<>();
          findJavaFilesRecursive(directory, javaFiles);
          return javaFiles;
      }
      
      /**
       * 递归查找Java文件
       */
      private void findJavaFilesRecursive(File directory, List<File> javaFiles) {
          if (!directory.exists() || !directory.isDirectory()) {
              return;
          }
          
          File[] files = directory.listFiles();
          if (files != null) {
              for (File file : files) {
                  if (file.isDirectory()) {
                      findJavaFilesRecursive(file, javaFiles);
                  } else if (file.getName().endsWith(".java")) {
                      javaFiles.add(file);
                  }
              }
          }
      }
      
      /**
       * 清空结果
       */
      private void clearResults() {
          resultsTable.getItems().clear();
      }
      
      /**
       * 显示状态信息
       */
      private void showStatus(String message) {
          statusLabel.setText(message);
      }
      
      /**
       * 设置结果处理器
       */
      public void setResultHandler(SearchResultHandler handler) {
          this.resultHandler = handler;
      }
      
      /**
       * 显示对话框
       */
      public void showDialog() {
          dialog.show();
      }
      
      /**
       * 设置搜索文本
       */
      public void setSearchText(String text) {
          searchField.setText(text);
      }
      
      /**
       * 搜索结果类
       */
      public static class SearchResult {
          private final String fileName;
          private final String filePath;
          private final int lineNumber;
          private final String matchedLine;
          private final int startPos;
          private final int endPos;
          
          public SearchResult(String fileName, String filePath, int lineNumber, 
                            String matchedLine, int startPos, int endPos) {
              this.fileName = fileName;
              this.filePath = filePath;
              this.lineNumber = lineNumber;
              this.matchedLine = matchedLine;
              this.startPos = startPos;
              this.endPos = endPos;
          }
          
          // Getters
          public String getFileName() { return fileName; }
          public String getFilePath() { return filePath; }
          public int getLineNumber() { return lineNumber; }
          public String getMatchedLine() { return matchedLine; }
          public int getStartPos() { return startPos; }
          public int getEndPos() { return endPos; }
      }
  } 