GYscan Java Edition - 完整接口文档

← 返回文档导航

GYscan Java Edition - 完整接口文档

版本: 1.1.0
日期: 2026-07-10
描述: GYscan Java 版插件框架完整接口规范(基于 Swing/FlatLaf 的 GUI 完整支持)


目录

  1. SDK 与宿主概述
  2. 插件 API 层 (com.gyscan.plugin.api)
  3. AbstractPlugin 基类
  4. PluginLogger 日志工具类
  5. PluginHelper 助手工具类
  6. ParameterDefinition 参数定义
  7. 菜单 API (com.gyscan.plugin.api.menu)
  8. GUI API (com.gyscan.plugin.api.gui)
  9. FlatLaf 主题 API (com.gyscan.plugin.api)
  10. 插件图标 API (com.gyscan.plugin.api)
  11. Java 版本支持与核心依赖 (com.gyscan.plugin.api)
  12. 事件总线 API (com.gyscan.plugin.api.event)
  13. StartPlugin 独立启动 API (com.gyscan.plugin.api)
  14. 终端颜色工具 (com.gyscan.core.util.Color)
  15. 终端进度条工具 (com.gyscan.core.util.Progress)
  16. 命令行参数框架 (com.gyscan.core.help) ⭐ NEW
  17. 插件开发指南
  1. 实际插件参考

1. SDK 与宿主概述

GYscan Java Edition 由 宿主程序 和 插件 SDK 两部分组成:

组件 路径 说明
宿主 JAR build/libs/gyscan-1.0.0.jar 主程序,包含 Shell、插件管理器
SDK JAR build/libs/gyscan-sdk-1.0.0.jar 插件开发依赖,仅含 com.gyscan.plugin.api.*

SDK 包结构 (仅导出以下包):

com.gyscan.plugin.api/
├── AbstractPlugin.java              # 插件基类
├── LookAndFeelManager.java          # FlatLaf 主题管理器(含 7 种内置主题)
├── ParameterDefinition.java         # 参数定义
├── Plugin.java                      # 插件主接口
├── PluginContext.java               # 插件上下文(注册命令/菜单/GUI)
├── PluginHelper.java                # 助手工具类
├── PluginIconLoader.java            # 插件图标加载工具(含默认图标)
├── PluginLogger.java                # 日志工具
├── PluginTemplate.java              # 一键模板生成工具
├── StartPlugin.java                # 独立启动插件脚手架(无需宿主)
├── event/
│   ├── EventBus.java               # 事件总线
│   └── Subscribe.java               # 事件订阅注解
└── gui/
    └── GUIComponent.java           # GUI 组件(Swing/FlatLaf)

注意: FlatLaf 类 (com.formdev.flatlaf.*) 也已打包进 SDK JAR,插件可直接使用。

宿主内部包 (插件不可直接使用):

com.gyscan.core.plugin.*   # 插件管理器、全局注册表等内部实现
com.gyscan.host.*          # Shell、守护进程

2. 插件 API 层 (com.gyscan.plugin.api)

Plugin 主接口

所有插件必须实现此接口。实现方式有两种:直接 implements Plugin(完全控制)或继承 AbstractPlugin(推荐,减少样板代码)。

package com.gyscan.plugin.api;                              // 插件 SDK 的包路径,你的插件需要 import 此包

import java.util.List;                                       // 用于 getDependencies/getAliases 返回插件列表
import java.util.concurrent.CompletableFuture;               // 用于 submitTask 异步任务返回值

public interface Plugin {                                    // 所有插件的根接口,你的插件类必须实现它

    /** 插件唯一 ID — 宿主用它在插件表中索引你的插件,不可重复 */
    String getPluginId();                                    // → 返回如 "my_scanner",建议 snake_case

    /** 插件显示名称 — 在 help 列表、GUI 标题栏中展示 */
    String getName();                                        // → 返回如 "My Scanner"

    /** 插件版本号 — 用于升级检测和版本展示 */
    String getVersion();                                     // → 返回如 "1.0.0"

    /** 插件简介 — 一行描述插件功能 */
    String getDescription();                                 // → 返回如 "一个示例扫描器插件"

    default String getAuthor() { return "Unknown"; }         // → 作者名,在插件详情中显示,可选覆盖

    default String getWebsite() { return ""; }               // → 官网链接,可选覆盖

    default List<String> getDependencies() { return List.of(); } // → 依赖的其他插件 ID 列表,宿主会先加载它们

    default List<String> getAliases() { return List.of(); }  // → 命令别名,如 List.of("ms", "myscan")

    /**
     * 插件 Logo 资源路径(相对 JAR 根目录的 classpath 路径),
     * 推荐在 build.gradle 的 jar.manifest 中以 {@code Plugin-Logo} 字段声明,
     * 宿主会优先从 MANIFEST.MF 读取该字段加载 logo。
     */
    default String getLogo() { return null; }                // → 返回如 "images/logo.png",不设置则用默认图

    /** @deprecated 推荐使用 getLogo() 替代 */
    @Deprecated
    default String getIcon() { return getLogo(); }           // → 兼容旧版,直接委托给 getLogo()

    /**
     * 插件被加载后立即调用 — 这里是你的「主入口」。
     * 在此方法中注册命令(registerCommand)、菜单、GUI 组件、事件订阅。
     * 宿主或 StartPlugin 在创建你的插件实例后,第一件事就是调用这个方法。
     */
    void onLoad(PluginContext context);                      // → 核心方法!必须实现,context 提供所有注册能力

    /**
     * 插件激活后回调 — onLoad 执行完毕、注册到全局注册表后调用。
     * 适用于在所有注册完成后执行初始化操作(如注册定时任务)。
     */
    default void onLoaded() { }                              // → 可选,空实现意味着不执行额外初始化

    /** 插件启用回调 — 用户执行 plugin enable 时触发 */
    default void onEnable() { }                              // → 可选,用于恢复暂停的功能

    /** 插件禁用回调 — 用户执行 plugin disable 时触发 */
    default void onDisable() { }                             // → 可选,用于暂停功能但保留注册信息

    /** 插件被卸载时调用 — 清理所有资源 */
    void onUnload();                                         // → 必须实现!在此反注册命令、释放线程、关闭连接

    boolean isEnabled();                                     // → 查询插件是否处于启用状态
    void setEnabled(boolean enabled);                        // → 宿主调用此方法启用/禁用插件

    /** 向沙箱线程池提交异步任务,返回 CompletableFuture 可用于链式处理 */
    default <T> CompletableFuture<T> submitTask(java.util.function.Supplier<T> task) {
        throw new UnsupportedOperationException("Sandbox not available"); // → 独立运行时不可用,宿主中由 PluginManager 提供实现
    }

    /** 带超时的异步任务提交 */
    default <T> CompletableFuture<T> submitTask(long timeoutSeconds, java.util.function.Supplier<T> task) {
        throw new UnsupportedOperationException("Sandbox not available");
    }
}

新人上手:只需关心 4 个必须实现的方法 — getPluginId()、getName()、getVersion()、getDescription() 提供元信息;onLoad(context) 注册命令;onUnload() 清理资源。其余 default 方法可以完全不碰。


3. AbstractPlugin 基类

AbstractPlugin 提供了 Plugin 接口的默认实现,插件直接继承即可。推荐所有插件继承此类而不是直接实现 Plugin 接口,可以减少大量样板代码(如 isEnabled/setEnabled 的状态管理)。

package com.gyscan.plugin.api;                               // SDK 包路径

public abstract class AbstractPlugin implements Plugin {     // 继承此类 = 声明这是一个 GYscan 插件

    protected PluginContext context;                         // → 宿主注入的上下文对象,在 onLoad 时赋值
    //                                                         调用 getContext() 获取它,用于注册命令/菜单/GUI

    protected PluginContext getContext() { return context; } // → 在你的插件代码中通过此方法拿到 context
    //                                                         典型用法: getContext().registerCommand(...)

    @Override public void onLoad(PluginContext context);     // → 你必须覆盖!宿主在此传入 context 供你注册资源
    @Override public void onLoaded();                        // → 可选覆盖,所有注册完成后的回调
    @Override public void onEnable();                        // → 可选覆盖,插件被启用时回调
    @Override public void onDisable();                       // → 可选覆盖,插件被禁用时回调
    @Override public void onUnload();                        // → 必须覆盖!在此反注册所有资源
    @Override public boolean isEnabled();                    // → 基类已管理 enabled 状态,一般无需覆盖
    @Override public void setEnabled(boolean enabled);       // → 基类已管理,一般无需覆盖
}

实际使用:在你的插件类中写 public class MyPlugin extends AbstractPlugin { ... },然后只需覆盖 onLoad 和 onUnload 即可。基类自动处理 isEnabled/setEnabled 的状态维护。

生命周期流程:

插件加载
  ├─ Class.forName() 加载插件类
  ├─ newInstance() 创建实例
  ├─ constructor.onLoad(context)          ← 插件注册命令/菜单/GUI
  ├─ eventBus.register(plugin)
  ├─ 全局注册表注册
  ├─ 状态: LOADING → INITIALIZING → ACTIVE
  └─ plugin.onLoaded()                  ← 插件激活后回调

插件卸载
  ├─ setEnabled(false)
  ├─ plugin.onDisable()                  ← 暂停功能
  └─ plugin.onUnload()                   ← 释放资源
方法 调用时机 用途
onLoad(context) 插件被加载后立即调用 注册命令、菜单、GUI、事件订阅、读取配置
onLoaded() onLoad 完成后、注册到 GlobalRegistry 后 在所有注册完成后执行初始化操作(如注册定时任务)
onEnable() 调用 setEnabled(true) 时 恢复插件功能 (如重新启用心跳定时器)
onDisable() 调用 setEnabled(false) 时 暂停插件功能 (但保留注册信息)
onUnload() 插件被卸载时 反注册所有资源、释放线程/连接、保存状态

4. PluginLogger 日志工具类

package com.gyscan.plugin.api;                                // SDK 包路径

public class PluginLogger {                                   // 插件专用日志工具,输出会携带插件标识

    public PluginLogger(PluginContext context);               // → 构造时需要传入 context(用于获取插件 ID 作为日志前缀)

    public void info(String message);                         // → 打印 INFO 级别日志
    public void warn(String message);                         // → 打印 WARN 级别日志
    public void error(String message);                        // → 打印 ERROR 级别日志
    public void error(String message, Throwable t);           // → 打印 ERROR + 异常堆栈
    public void debug(String message);                        // → 打印 DEBUG 级别日志(仅调试模式输出)

    public void log(String level, String format, Object... args); // → 通用日志方法,支持格式化字符串
}

使用示例:

public class MyPlugin extends AbstractPlugin {                 // 继承 AbstractPlugin

    private PluginLogger logger;                               // → 声明日志工具字段

    @Override
    public void onLoad(PluginContext context) {                // 宿主调用的入口
        super.onLoad(context);                                 // → 必须先调用父类,让基类保存 context
        this.logger = new PluginLogger(context);               // → 用 context 创建 logger(日志输出会带插件标识)
        logger.info("插件正在加载...");                          // → 输出: [MyPlugin] 插件正在加载...
    }

    // 在任意方法中使用:
    // logger.warn("配置项缺失,使用默认值");
    // logger.error("连接失败", exception);
}

注意:必须在 super.onLoad(context) 之后再创建 PluginLogger,因为父类的 onLoad 会保存 context,而 PluginLogger 依赖 context 获取插件 ID。


5. PluginHelper 助手工具类

package com.gyscan.plugin.api;                                // SDK 包路径

public class PluginHelper {                                   // 资源读写助手,统一处理文件 IO

    public PluginHelper(PluginContext context);               // → 构造时需要传入 context

    /** 加载插件内置资源文件 (classpath 下) — 读取 JAR 内 resources 目录中的文件 */
    public InputStream getResourceAsStream(String path);      // → path 如 "images/logo.png",返回输入流

    /** 加载插件内置资源为字符串 (UTF-8) */
    public String readResourceString(String path) throws IOException; // → 一次性将资源文件读为字符串

    /** 读取插件配置文件 (pluginDataDir 下的 JSON/YAML/TXT) */
    public String readConfigString(String filename) throws IOException; // → 从数据目录读取持久化配置

    /** 写入插件配置文件 — 持久化保存配置 */
    public void writeConfigString(String filename, String content) throws IOException; // → 写入数据目录

    /** 获取插件数据目录路径 — 位于宿主的 plugin-data 目录下,用于存放配置文件 */
    public Path getPluginDataDir();                           // → 返回如 /path/to/plugin-data/my_plugin/
}

区别:getResourceAsStream/readResourceString 从 JAR 包内的 classpath 读取(只读);readConfigString/writeConfigString 从外部数据目录读写(可写,用于保存用户配置)。


6. ParameterDefinition 参数定义

用于 registerCommand 时声明该命令接受哪些参数,帮助用户理解命令用法。

package com.gyscan.plugin.api;                                // SDK 包路径

public class ParameterDefinition {                            // 参数元信息定义

    /** 完整构造 — 含默认值 */
    public ParameterDefinition(String name, String type, String description,
                              boolean required, String defaultValue);
    // → 示例: new ParameterDefinition("target", "String", "目标 URL", true, "")
    //   name="target"     — 参数名,在 help 中显示
    //   type="String"     — 类型标签(目前仅用于文档展示,不做强制校验)
    //   description="目标" — 参数描述
    //   required=true     — 是否必填 (true→尖括号<target>显示, false→方括号[target]显示)
    //   defaultValue=""   — 默认值(无默认值传 null 或 "")

    /** 简化构造 — 无默认值 */
    public ParameterDefinition(String name, String type, String description, boolean required);

    public String getName();                                  // → 获取参数名
    public String getType();                                  // → 获取类型标签
    public String getDescription();                           // → 获取描述
    public boolean isRequired();                              // → 是否必填
    public String getDefaultValue();                          // → 获取默认值

    @Override public String toString();                       // → 输出格式: <name: type> 或 [name: type]
}

重要:ParameterDefinition 是元信息声明,用于 help 命令展示和参数校验提示。它不会自动解析命令行参数,真正的参数解析需要在你的 handleCommand 方法中自己实现。


7. 菜单 API (com.gyscan.plugin.api.menu)

package com.gyscan.plugin.api.menu;                           // 菜单 API 包路径

public class MenuItem {                                        // 菜单项定义 — 会在 GYscan GUI 菜单栏中添加一项

    /** 完整构造 — 所有字段必填 */
    public MenuItem(String id, String label, String parentId,
                    String pluginId, String pluginName,
                    Runnable action, int order);
    // → 参数说明:
    //   id="my_menu_item"  — 菜单项唯一 ID,用于反注册
    //   label="我的菜单"     — GUI 菜单栏上显示的文字
    //   parentId=null       — 父菜单 ID,null 表示顶层菜单
    //   pluginId=getPluginId() — 所属插件 ID(用于归属显示)
    //   pluginName=getName()   — 所属插件名称
    //   action=() -> {...}     — 点击菜单时执行的回调(Runnable)
    //   order=10               — 排序序号,数字越小越靠前

    public String getId();                                    // → 获取菜单项 ID
    public String getLabel();                                 // → 获取显示标签
    public String getParentId();                              // → 获取父菜单 ID
    public String getPluginId();                              // → 获取所属插件 ID
    public String getPluginName();                            // → 获取所属插件名
    public Runnable getAction();                              // → 获取点击回调
    public int getOrder();                                    // → 获取排序序号
}

在 PluginContext 中注册 — 放在 onLoad 中调用:

context.registerMenuItem(                                     // → 通过 context 注册菜单项
    new MenuItem(
        "my_menu_item",                                      // → ① 菜单项唯一 ID(用于后续 unregister)
        "我的菜单",                                           // → ② GUI 菜单栏显示文字
        null,                                                // → ③ 父菜单 ID,null=顶层菜单
        getPluginId(),                                       // → ④ 所属插件 ID(AbstractPlugin 自带方法)
        getName(),                                           // → ⑤ 所属插件名称(AbstractPlugin 自带方法)
        () -> { /* 点击行为 */ },                             // → ⑥ lambda 回调,用户点击菜单时执行
        10                                                   // → ⑦ 排序序号,越小越靠前
    )
);

实际使用:在 onLoad 中调用 registerMenuItem,在 onUnload 中调用 context.unregisterMenuItem("my_menu_item") 清理。action 回调中通常写入 context.showGUI(...) 来打开窗口。


8. GUI API (com.gyscan.plugin.api.gui)

GUIComponent

用于注册 Swing/FlatLaf GUI 窗口组件:

package com.gyscan.plugin.api.gui;                            // GUI API 包路径

public class GUIComponent {                                    // GUI 窗口组件定义 — 用于宿主管理插件的 Swing 窗口

    /** 基础构造函数 (无 launcher) — 宿主通过 component 引用来显示窗口 */
    public GUIComponent(String id, String type, String title,
                        String pluginId, String pluginName,
                        Object component, int order);
    // → 无 launcher 时,宿主通过 component 字段直接操作(如 setVisible(true))

    /** 完整构造函数 (带 launcher) — 推荐使用,launcher 定义了如何打开此窗口 */
    public GUIComponent(String id, String type, String title,
                        String pluginId, String pluginName,
                        Object component, Runnable launcher, int order);
    // → 参数说明:
    //   id="hello_window"          — GUI 组件唯一 ID,用于后续 showGUI
    //   type="flatlaf"             — GUI 类型: "swing"/"flatlaf"/"console"
    //   title="我的窗口"            — 窗口标题栏文字
    //   pluginId=getPluginId()     — 所属插件 ID
    //   pluginName=getName()       — 所属插件名
    //   component=window           — 实际的 Swing 组件对象 (JFrame/JPanel 等)
    //   launcher=() -> {...}        — 打开窗口的回调(推荐始终设置)
    //   order=10                   — 排序序号

    public String getId();                                    // → 获取组件 ID
    public String getType();                                  // → 获取 GUI 类型
    public String getTitle();                                 // → 获取窗口标题
    public String getPluginId();                              // → 获取所属插件 ID
    public String getPluginName();                            // → 获取所属插件名
    public Object getComponent();                             // → 获取实际的 Swing 组件,可强转为 JFrame 等
    public Runnable getLauncher();                            // → 获取启动器,调用 run() 即可打开窗口
    public boolean hasLauncher();                             // → 是否设置了 launcher
    public int getOrder();                                    // → 获取排序序号
}

type 取值建议: "swing" / "flatlaf" / "console"

在 PluginContext 中注册 — 放在 onLoad 中调用:

// 1. 先创建你的 Swing 窗口对象
JFrame window = new MyPluginWindow();                           // → 你的自定义 JFrame 子类

// 2. 通过 context 注册 GUI 组件
context.registerGUIComponent(                                   // → 注册到宿主,宿主可统一管理
    new GUIComponent(
        "my_plugin_window",                                    // → ① 组件唯一 ID(用于后续 showGUI)
        "flatlaf",                                             // → ② GUI 类型: "flatlaf" 使用 FlatLaf 主题
        "我的窗口",                                             // → ③ 窗口标题栏文字
        getPluginId(),                                         // → ④ 所属插件 ID
        getName(),                                             // → ⑤ 所属插件名
        window,                                                // → ⑥ 实际的 JFrame 对象
        () -> window.setVisible(true),                         // → ⑦ launcher: 定义如何打开窗口
        10                                                     // → ⑧ 排序序号
    )
);

显示 GUI — 两种方式:

// 方式1: 通过 showGUI 触发 (推荐) — 放在命令 handler 或菜单 action 中
context.showGUI("my_plugin_window");                           // → 宿主找到组件并调用其 launcher.run()

// 方式2: 直接操作组件引用 — 适用于需要精细控制的场景
context.listGUIComponents().stream()                           // → 获取所有已注册的 GUI 组件
    .filter(g -> "my_plugin_window".equals(g.getId()))         // → 按 ID 过滤出目标组件
    .findFirst()                                               // → 取第一个匹配
    .ifPresent(g -> {                                          // → 如果找到
        if (g.hasLauncher()) g.getLauncher().run();            // → 有 launcher 就调用 launcher
        else if (g.getComponent() instanceof JFrame f)         // → 否则尝试直接 setVisible
            f.setVisible(true);
    });

9. FlatLaf 主题 API (com.gyscan.plugin.api)

LookAndFeelManager

提供 FlatLaf 主题管理功能,支持 7 种内置主题,支持与宿主程序主题同步:

package com.gyscan.plugin.api;                                // SDK 包路径

public class LookAndFeelManager {                             // FlatLaf 主题管理器,统一控制插件窗口外观

    public enum Theme {                                       // 7 种内置主题枚举
        LIGHT("Flat Light", "com.formdev.flatlaf.FlatLightLaf"),
        DARK("Flat Dark", "com.formdev.flatlaf.FlatDarkLaf"),
        ARC("Arc Dark (IntelliJ)", "...FlatArcDarkIJTheme"),
        ONEDARK("One Dark (IntelliJ)", "...FlatOneDarkIJTheme"),
        MATERIAL_DESIGN_DARK("Material Design Dark", "...FlatMaterialDesignDarkIJTheme"),
        IDEA("IntelliJ Light", "...FlatIntelliJLightIJTheme"),
        DRACULA("Dracula (IntelliJ)", "...FlatDraculaIJTheme");

        private final String displayName;                     // → 主题显示名称
        private final String className;                       // → FlatLaf 主题类全限定名
        public String getDisplayName();                       // → 获取显示名称(用于 UI 展示)
        public String getClassName();                         // → 获取类名(用于反射加载)
    }

    public static void initialize();                          // → 初始化:用当前/默认主题
    public static void initialize(Theme theme);               // → 初始化:用指定主题
    public static void setTheme(Theme theme);                 // → 运行时切换主题
    public static Theme getCurrentTheme();                    // → 获取当前主题
    public static boolean isInitialized();                    // → 是否已完成初始化
    public static boolean isHostDelegated();                  // → 是否委托宿主管理(插件在宿主中运行时为 true)
    public static void listAvailableThemes();                 // → 列出所有可用主题(打印到控制台)
    public static void initializeFromProperty();              // → 从 -Dgyscan.laf=THEME 系统属性初始化
    public static void applyToWindow(Window window);          // → 将当前主题应用到指定窗口
    public static void applyToComponent(Component c);         // → 将当前主题应用到指定组件
}

运行机制:

  • 当插件在 GYscan 宿主中运行时,自动委托宿主 LookAndFeelManager 管理主题(通过反射)
  • 当插件独立运行时,使用 SDK 内置的 FlatLaf 类(com.formdev.flatlaf.* 已打包进 SDK JAR)
  • 宿主主题切换时,插件窗口会自动跟随更新

使用示例:

public class MyFlatLafPlugin extends AbstractPlugin {          // 继承 AbstractPlugin

    @Override
    public void onLoad(PluginContext context) {                // 宿主入口
        super.onLoad(context);                                 // → 必须先调用父类保存 context

        LookAndFeelManager.initialize();                       // → 初始化 FlatLaf(自动检测宿主委托)

        JFrame frame = new JFrame("FlatLaf 窗口");             // → 创建 Swing 窗口
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // → 关闭时只销毁窗口,不退出程序
        frame.setSize(400, 300);                               // → 设置窗口大小 400x300

        JButton toggleBtn = new JButton("切换主题");            // → 创建「切换主题」按钮
        toggleBtn.addActionListener(e -> {                     // → 添加点击事件
            Theme current = LookAndFeelManager.getCurrentTheme(); // → 获取当前主题
            Theme next = (current == Theme.DARK)               // → 在 DARK 和 LIGHT 之间切换
                ? Theme.LIGHT : Theme.DARK;
            LookAndFeelManager.setTheme(next);                 // → 应用新主题(窗口自动刷新)
        });

        frame.add(toggleBtn, BorderLayout.NORTH);              // → 按钮放在窗口顶部
        frame.setLocationRelativeTo(null);                     // → 窗口居中显示
        frame.setVisible(true);                                // → 显示窗口
    }
}

FlatLaf 常用组件美化:

// 使用 FlatClientProperties 美化 Swing 组件 — 需要 import com.formdev.flatlaf.FlatClientProperties

JTextField field = new JTextField();                           // → 创建文本输入框
field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "输入内容..."); // → 设置占位文字
field.putClientProperty(FlatClientProperties.CLEAR_BUTTON, true);              // → 显示清除按钮

JButton button = new JButton("提交");                          // → 创建按钮
button.putClientProperty(FlatClientProperties.STYLE,           // → 设置 FlatLaf 样式属性
    "background: @accentColor; foreground: white");             // → 背景用主题强调色,文字白色

JTable table = new JTable();                                   // → 创建表格
table.putClientProperty(FlatClientProperties.STYLE,            // → 设置行高 30px
    "rowHeight:30");
table.getTableHeader().putClientProperty(                      // → 设置表头底部粗线
    FlatClientProperties.STYLE, "bottomBorderThick:true");

启动参数:

java -Dgyscan.laf=DARK -jar gyscan.jar          # 强制使用深色主题
java -Dgyscan.laf=LIGHT -jar gyscan.jar         # 强制使用浅色主题
java -Dgyscan.laf=ARC -jar gyscan.jar            # 使用 Arc Dark 主题

10. 插件图标 API (com.gyscan.plugin.api)

PluginIconLoader

插件 Logo / 图标加载工具。加载规则:

  1. 优先从 MANIFEST.MF 读取:宿主在解析插件时优先读取 Plugin-Logo 字段。
  2. 向后兼容:未声明 Plugin-Logo 时回退到 Plugin-Icon;都没有时使用 SDK 内置默认占位图。
  3. 支持格式:png / jpg / jpeg,大小写不敏感;其它格式被拒绝并回退到默认图。
  4. 路径安全校验:拒绝绝对路径、.. 穿越、反斜杠不规范路径,统一回退到默认图。
  5. 资源缺失兜底:JAR 资源不存在 / 加载失败时回退到 SDK 默认占位图,插件列表界面永远有一张可显示的图片。
package com.gyscan.plugin.api;                                // SDK 包路径

import java.awt.Image;                                        // → AWT 图片类
import java.awt.image.BufferedImage;                          // → 缓冲图片(可转为 JavaFX Image)
import java.nio.file.Path;                                    // → 文件路径
import javax.swing.Icon;                                      // → Swing 图标接口
import javax.swing.ImageIcon;                                 // → Swing 图片图标

public class PluginIconLoader {                               // 统一管理插件 Logo/图标的加载

    /** SDK 内置默认 logo 路径 */
    public static final String DEFAULT_ICON_PATH = "images/plugin_default.jpg";

    // ----- ClassLoader 模式:插件独立运行时从 classpath 加载 -----
    public static Image   loadPluginIcon(ClassLoader cl, String iconPath);  // → 指定类加载器加载
    public static Icon    loadPluginIconAsIcon(ClassLoader cl, String path); // → 以 Icon 形式返回
    public static Image   loadPluginIcon(String iconPath);                   // → 用当前类加载器加载
    public static Icon    loadPluginIconAsIcon(String iconPath);             // → 以 Icon 形式返回

    // ----- JAR 模式:宿主从已加载的插件 JAR 中加载 -----
    public static Image   loadPluginIconFromJar(Path jarPath, String iconPath); // → 直接从 JAR 文件读
    public static Icon    loadPluginIconFromJarAsIcon(Path jarPath, String path);

    // ----- 默认占位图 -----
    public static Image   getDefaultIconImage();               // → 获取默认占位图(Image 格式)
    public static Icon    getDefaultIcon();                    // → 获取默认占位图(Icon 格式)
    public static void    preloadDefaultIcon();                // → 预加载默认图到内存

    // ----- 缩放便捷方法 -----
    public static ImageIcon createIconImageIcon(ClassLoader cl, String path, int w, int h);
    // → 加载并缩放到指定宽高,返回 ImageIcon 可直接放入 JButton
    public static ImageIcon createIconImageIcon(String path, int w, int h);
    // → 使用当前类加载器的便捷版本

    // ----- 工具方法 -----
    /** 判断路径是否为 png / jpg / jpeg 图片(大小写不敏感) */
    public static boolean isSupportedImagePath(String path);   // → 校验图片格式是否支持
}

使用示例(插件中加载自己的 Logo 并放到按钮上):

public class MyPlugin extends AbstractPlugin {                 // 继承 AbstractPlugin

    @Override
    public void onLoad(PluginContext context) {                // 宿主入口
        Image pluginLogo = PluginIconLoader.loadPluginIcon(getLogo()); // → 加载 setLogo() 返回的图片路径
        System.out.println("插件 Logo: " + pluginLogo);        // → 打印 Logo 对象信息

        ImageIcon sizedIcon = PluginIconLoader.createIconImageIcon( // → 加载并缩放到 48x48
            getLogo(), 48, 48                                  // → logo 路径 + 目标尺寸
        );
        JButton button = new JButton("我的插件", sizedIcon);    // → 创建带图标的按钮
    }

    @Override
    public String getLogo() {                                  // → 声明 logo 资源路径
        return "images/my-plugin-logo.png";                    // → 相对 classpath 的资源路径
    }
}

使用示例(宿主从插件 JAR 中加载):

// 宿主侧代码 — 插件开发者无需关心此部分
String logoPath = descriptor.getIcon();                        // → 从 PluginDescriptor 读取 Logo 路径
Image logo = PluginIconLoader.loadPluginIconFromJar(           // → 直接从插件 JAR 文件加载
    descriptor.getJarPath(), logoPath);                        // → JAR 路径 + 资源路径
if (logo instanceof BufferedImage img) {                       // → 如果是 BufferedImage 类型
    ImageView view = new ImageView(SwingFXUtils.toFXImage(img, null)); // → 转为 JavaFX Image 显示
    // ...
}

Plugin-Logo 字段声明(build.gradle)

插件在开发阶段,在项目的 build.gradle 中以 ext.logoFile 声明 logo 资源的相对路径
(相对 src/main/resources/)。该值会作为 Plugin-Logo 属性写入 JAR 的 MANIFEST.MF,
宿主在解析插件时优先读取该字段加载 logo。

// ============================================================
// 插件 Logo 配置
// ------------------------------------------------------------
// 1) logoFile: 资源在 src/main/resources/ 下的相对路径
//    支持 png / jpg / jpeg 格式
// 2) 该值会作为 Plugin-Logo 写入 MANIFEST.MF,宿主优先读取
// 3) 留空或 '-' 时,宿主将回退到 SDK 内置默认 logo
// 4) 可通过命令行覆盖:gradle jar -PlogoFile=images/other.png
// ============================================================
ext {
    logoFile = 'images/port-scan-logo.png'                    // → 指定 Logo 资源路径
}

jar {
    manifest {
        def logoProperty = project.findProperty('logoFile')     // → 尝试从命令行 -PlogoFile=xxx 读取
        def resolvedLogo = (logoProperty != null               // → 解析 Logo 路径
                            && !logoProperty.toString().isEmpty()
                            && logoProperty.toString() != '-')
            ? logoProperty.toString()                            // → 命令行传参优先
            : (ext.has('logoFile') ? ext.logoFile?.toString() : '') // → 否则用 ext.logoFile

        attributes(
            'Plugin-Id':          'my_plugin',                 // → 插件唯一 ID
            'Plugin-Name':        'MyPlugin',                  // → 插件显示名称
            'Plugin-Version':     project.version,             // → 插件版本
            'Plugin-Author':      'GYscan Team',               // → 作者
            'Plugin-Main-Class':  'com.gyscan.plugin.myplugin.MyPlugin', // → 主类全限定名
            'Plugin-Description': '插件描述',                    // → 描述
            'Plugin-Logo':        resolvedLogo ?: ''            // → Logo 路径(推荐用 Plugin-Logo)
            // 'Plugin-Icon':     '...'                         // → 兼容旧字段
        )
    }
}

推荐:始终使用 ext.logoFile 声明 Logo,配合 Plugin-Logo manifest 属性。宿主的加载优先级为 Plugin-Logo > Plugin-Icon > getLogo()。

字段优先级

宿主按以下顺序解析 logo 路径:

优先级 来源 说明
1(最高) Plugin-Logo 字段 推荐字段,新插件必须使用
2 Plugin-Icon 字段 向后兼容字段,旧插件可继续使用
3 Plugin.getLogo() 运行时返回 插件代码未显式覆盖时为 null
4 Plugin.getIcon() 运行时返回 已 @Deprecated,委托给 getLogo
5(兜底) PluginIconLoader.DEFAULT_ICON_PATH SDK 内置 images/plugin_default.jpg

图片格式支持

扩展名 是否支持 备注
png 是 推荐(支持透明通道)
jpg 是 推荐
jpeg 是 与 .jpg 等价
gif / bmp / svg / webp 否 加载时会被拒绝并回退到默认图

格式校验由 PluginIconLoader.isSupportedImagePath(String) 统一执行,不区分大小写。

错误处理

异常情况 处理方式 日志
Plugin-Logo 字段缺失 回退到 Plugin-Icon → 默认图 无
Plugin-Logo 字段为空 回退到 Plugin-Icon → 默认图 无
路径为绝对路径(含盘符、//\ 起始) 拒绝并回退到默认图 [PluginDescriptor] 忽略非法的 logo 路径
路径含 ..(路径穿越) 拒绝并回退到默认图 [PluginDescriptor] 忽略非法的 logo 路径
路径扩展名不在白名单内 拒绝并回退到默认图 [PluginDescriptor] logo 扩展名不支持
JAR 中找不到对应资源 回退到默认图 [PluginIconLoader] 未找到 logo 资源
图片解码失败 回退到默认图 [PluginIconLoader] 加载图标失败

图标路径约定

路径 说明
images/plugin_default.jpg SDK 内置默认占位图
images/<name>-logo.png 推荐自定义 logo 命名规范
images/<name>-logo.jpg JPG 格式
images/icon.png 常用简写

像素画 (Pixel Art) Logo 支持

GYscan 宿主在插件列表界面 (Swing 端) 启用了像素画优化渲染管线,
插件 logo 推荐按以下规范制作以获得最佳显示效果。

v1.1 变更: 取消 1024 px 上限,宿主对任意尺寸的 logo 都会加载并按目标尺寸
做最近邻缩放;仅当 logo 宽 / 高小于 8 px 时才回退到 SDK 内置默认占位图。
这意味着 2K / 4K 视网膜大图可直接打包到插件 JAR 中。

像素尺寸规范

维度 最小支持像素 最大支持像素 推荐尺寸
宽 (Width) 8 px 无上限 64 / 128 / 256 / 512 / 1024 / 2048 (2 的幂)
高 (Height) 8 px 无上限 同上
宽高比 1:1 (正方形) 最佳 — 宽 == 高

小于 8×8 的 logo 会被宿主静默回退到 SDK 内置默认占位图;超出此最小值的
任意尺寸都会被接受, 渲染时按目标尺寸用最近邻插值缩放。

推荐尺寸 (2 的幂, 自上而下阶梯式)

用途场景 像素尺寸 备注
紧凑列表 (Swing 列表行) 64×64 较小体积首选
列表行高分辨率 (HiDPI 屏) 128×128 2x
详情面板图标 256×256 4x
大图 / 启动闪屏 512×512 8x
原始资源 (兼容 HiDPI) 1024×1024 16x
视网膜大图 (新增) 2048×2048 32x, 任意更大尺寸也可

渲染优化 (Nearest Neighbor)

宿主在缩放像素画时使用 **最近邻插值 (Nearest Neighbor)**,避免 SCALE_SMOOTH
默认的双线性插值导致的边缘模糊,保证像素硬边锐利:

// AWT (Swing) 端:  PluginIconLoader 内置 NEAREST_NEIGHBOR 缩放
ImageIcon icon = PluginIconLoader.loadPixelArtIconAsImageIcon( // → 像素画专用加载方法
    descriptor.getJarPath(), descriptor.getIcon(), 48, 48       // → JAR路径 + 图标路径 + 目标尺寸 48×48
);

像素画校验 API

// 校验返回枚举 (TOO_LARGE 仍保留枚举值但不会触发, 仅 TOO_SMALL 触发回退)
public enum PixelArtValidation {
    VALID,        // → 任意 >= 8 px 的合法尺寸,可正常加载
    TOO_SMALL,    // → 任意边 < 8 px, 触发回退到默认图
    TOO_LARGE,    // → 保留枚举值, 校验函数不再返回此值
    NOT_SQUARE    // → 在合法范围但宽 != 高
}

// 单图校验 — 在加载前先验证尺寸是否合格
PluginArtValidation v = PluginIconLoader.validatePixelArtSize(image); // → 返回校验结果枚举
if (v == PixelArtValidation.VALID) { /* OK, 可加载 */ }
if (v == PixelArtValidation.TOO_SMALL) { /* 会被回退到默认图 */ }

像素画 Logo 制作建议

  1. 画布:正方形 (64×64 / 128×128 / 256×256 / 512×512 / 1024×1024 / 2048×2048)
  2. 格式:png (推荐,支持透明通道);避免 jpg (像素画需要硬边与透明)
  3. **不抗锯齿 (No Anti-Aliasing)**:禁用 AI 抗锯齿,保留硬边
  4. 限制调色板:调色板越少,文件越小、显示越干净
  5. 不要内嵌缩略图:让宿主按目标尺寸做 NEAREST_NEIGHBOR 缩放
  6. 可直接使用高分辨率原图:无需预先缩放到 1024 px 以内, 2K/4K 大图同样可用

11. Java 版本支持与核心依赖 (com.gyscan.plugin.api)

11.1 Plugin 接口新增方法

public interface Plugin {
    // ... 原有方法 ...

    default String getMinJavaVersion() {                       // → 本插件需要的最低 Java 版本
        return null;                                            // → 返回 null 表示不限制
    }

    default String getMaxJavaVersion() {                       // → 本插件支持的最高 Java 版本
        return null;                                            // → 返回 null 表示不限制
    }

    default List<String> getCoreDependencies() {               // → 核心依赖插件 ID 列表
        return List.of();                                       // → 如果依赖未加载,宿主会阻止本插件启动
    }
}

用途:如果你插件的代码使用了 Java 17+ 的特性(如 record),覆盖 getMinJavaVersion() 返回 "17",宿主在 Java 11 环境下会拒绝加载并给出提示。

11.2 插件描述符 (PluginDescriptor)

插件 JAR 的 MANIFEST.MF 中新增属性:

Manifest 属性 说明 示例
Plugin-Min-Java-Version 插件最低支持的 Java 版本 11、17、21
Plugin-Max-Java-Version 插件最高支持的 Java 版本(留空表示不限制) 21、25 或留空
Plugin-Core-Dependencies 核心依赖插件 ID 列表(逗号分隔),必须加载,提供核心功能组合能力 security_core,、gyscan_core
Plugin-Exec 可选。加载完成后自动执行的命令(仅一条,必须是本插件注册的命令),留空或不声明则不执行 starx-gui、sqlexp -t all http://...

SDK 工具类 PluginDescriptor 新增 API:

package com.gyscan.core.plugin;                               // 注意:这是宿主内部包,插件不能直接依赖

public class PluginDescriptor {                               // 插件 JAR 描述信息 — 宿主从 MANIFEST.MF 读取
    public String getMinJavaVersion();                        // → 读取 Plugin-Min-Java-Version
    public String getMaxJavaVersion();                        // → 读取 Plugin-Max-Java-Version
    public List<String> getCoreDependencies();                // → 读取 Plugin-Core-Dependencies(逗号分隔的 ID 列表)
}

插件开发者视角:你不需要操作 PluginDescriptor。这些值通过 build.gradle 的 manifest 属性声明,宿主自动读取。

11.3 PluginManager 加载流程

加载插件时按以下顺序校验:

  1. Java 版本校验:检测当前 JVM 是否在插件声明的 [min, max] 范围内,不匹配则抛出异常阻止加载
  2. 核心依赖校验:检查 Plugin-Core-Dependencies 声明的插件是否已加载,未加载则抛出异常
  3. 普通依赖校验:原有 Plugin-Dependencies 的依赖检查

支持的版本格式:1.8、8、11、17、21、25

11.4 核心依赖 vs 普通依赖的区别

属性 核心依赖 (Plugin-Core-Dependencies) 普通依赖 (Plugin-Dependencies)
作用 提供核心/基础功能组合的插件组合 一般模块间的功能依赖
示例 安全扫描核心库 + 针对该库的扩展扫描插件 报告插件依赖日志插件
未加载处理 强制阻止当前插件加载 强制阻止当前插件加载
加载顺序 影响依赖拓扑排序(先于当前插件加载) 影响依赖拓扑排序(先于当前插件加载)

11.5 MANIFEST.MF 完整示例

Plugin-Id: ssh_audit
Plugin-Name: SSHAuditPlugin
Plugin-Version: 1.0.0
Plugin-Author: GYscan Team
Plugin-Main-Class: com.gyscan.plugin.sshaudit.SshAuditPlugin
Plugin-Description: SSH 配置安全审计插件 - 基于行业合规标准检查 SSH 服务配置
Plugin-Website: https://github.com/GYscan
Plugin-Aliases: sshaudit
Plugin-Min-Java-Version: 11
Plugin-Max-Java-Version:
Plugin-Core-Dependencies: gyscan_core
Plugin-Exec:

12. 事件总线 API (com.gyscan.plugin.api.event)

EventBus

订阅者模式的事件分发:

package com.gyscan.plugin.api.event;                          // 事件 API 包路径

public interface EventBus {                                   // 事件总线 — 订阅者模式的事件分发中心
    void register(Object subscriber);                         // → 注册订阅者(你的插件实例)
    //                                                          注册后,@Subscribe 标注的方法会自动收到事件
    void unregister(Object subscriber);                       // → 取消注册(onUnload 时必须调用)
    void post(Object event);                                  // → 发布事件 — 所有匹配的 @Subscribe 方法都会被调用
}

@Subscribe 注解

标注订阅者的回调方法 — 宿主通过反射找到标注了此注解的方法并调用。

package com.gyscan.plugin.api.event;                          // 事件 API 包路径

@Retention(RetentionPolicy.RUNTIME)                           // → 运行时保留,反射可用
@Target(ElementType.METHOD)                                   // → 只能标注在方法上
public @interface Subscribe {                                 // → 事件订阅注解
}

使用示例 — 完整流程:

public class MyPlugin extends AbstractPlugin {                 // 继承 AbstractPlugin

    @Override
    public void onLoad(PluginContext context) {               // 宿主入口
        getContext().getEventBus().register(this);             // → 注册本插件为事件订阅者(关键步骤!)
    }

    @Subscribe                                                 // → 标注此方法为事件处理器
    public void onSomeEvent(MyEvent event) {                   // → 方法名随意,参数类型决定监听的 事件类型
        System.out.println("收到事件: " + event.getMessage()); // → 处理事件逻辑
    }

    @Override
    public void onUnload() {                                   // 卸载时清理
        getContext().getEventBus().unregister(this);           // → 必须取消注册,防止内存泄漏
    }
}

public record MyEvent(String message) {}                      // → 定义一个事件类型(推荐用 record)

关键规则:register(this) 后,宿主会扫描你插件类中所有带 @Subscribe 注解的方法。当有人调用 eventBus.post(new MyEvent("hello")) 时,参数类型匹配的方法就会被自动调用。


13. StartPlugin 独立启动 API (com.gyscan.plugin.api)

StartPlugin

提供无需 GYscan 宿主即可独立运行插件的脚手架。内置独立的 PluginContext 实现,
在 main() 中调用后自动接管命令注册、EventBus、GUI、异步任务等功能。

package com.gyscan.plugin.api;

public final class StartPlugin {

    private StartPlugin() {}

    /** 纯 CLI 模式启动插件 (无任何 GUI 依赖)。 */
    public static void start(Plugin plugin, String[] args);

    /** 带 GUI 支持的启动模式 (会初始化 FlatLaf 主题)。 */
    public static void startWithGui(Plugin plugin, String[] args);

    /** 自动检测模式: 若参数中包含 --gui 则启用 GUI,否则纯 CLI。 */
    public static void auto(Plugin plugin, String[] args);
}

三种启动模式:

方法 GUI 依赖 FlatLaf 初始化 适用场景
start(plugin, args) 无 否 Termux / Docker / CI / 纯 CLI 工具
startWithGui(plugin, args) 需要 是 带 Swing 窗口的桌面工具
auto(plugin, args) 按需 --gui 时是 同一份代码兼容 CLI 和 GUI

内建独立上下文 (StandaloneContext)

StartPlugin 内部实现了一个完整的 PluginContext 实现,插件无需感知差异:

功能 实现方式
命令注册/分发 LinkedHashMap 收集 registerCommand,按子命令名路由
EventBus SimpleEventBus 支持 @Subscribe 注解事件分发
GUI 组件 支持 registerGUIComponent / showGUI,--gui 时自动启动首个窗口
异步任务 ScheduledExecutorService 线程池 (2 线程)
数据目录 /tmp/gyscan-standalone-{pluginId}
资源加载 从插件的 ClassLoader 加载 classpath 资源

命令行约定

java <MainClass> [--gui] <子命令> [参数...]
java <MainClass> help                 # 显示可用命令列表
java <MainClass> --gui                # 启动 GUI 窗口 (仅注册了 GUI 时)
java <MainClass> <子命令> <参数>       # 执行注册的 CLI 命令

使用示例

StartPlugin 的三个启动方法签名完全相同,都接收两个参数:

参数位置 类型 含义 说明
第 1 个 Plugin 你的插件实例 必须实现 Plugin 接口,在其 onLoad() 中用 context.registerCommand() 注册命令
第 2 个 String[] args 命令行参数 直接从 main(String[] args) 原样透传,StartPlugin 会自动解析第一个参数为子命令名

参数是如何被使用的:

用户执行: java MyTool greet Yiqiu --verbose
                          └──┬──┘ └─┬─┘ └───┬───┘
                    args[0]="greet" │        │
                    → 被识别为子命令名  │        │
                                    └── args 传递给 handler ──┘
                    执行: handler.accept(["Yiqiu", "--verbose"])

也就是说,args 的第一个不包含 -- 的 token 会被当作子命令名来路由,剩余的全部参数会作为子命令参数传递给你在 onLoad 中注册的 handler。


纯 CLI 插件 (完整示例):

import com.gyscan.plugin.api.Plugin;
import com.gyscan.plugin.api.PluginContext;
import com.gyscan.plugin.api.StartPlugin;
import java.util.List;

// 1. 实现 Plugin 接口 —— 这就是你传给 start() 的第一个参数
public class MyPlugin implements Plugin {

    @Override public String getPluginId()   { return "my_tool"; }
    @Override public String getName()       { return "My Tool"; }
    @Override public String getVersion()    { return "1.0.0"; }
    @Override public String getDescription(){ return "一个示例 CLI 工具"; }
    @Override public boolean isEnabled()    { return true; }
    @Override public void setEnabled(boolean b) {}
    @Override public void onUnload() {}

    // 2. 在这里注册你的命令 —— StartPlugin 会收集这些注册
    @Override
    public void onLoad(PluginContext ctx) {
        ctx.registerCommand("greet", "打招呼", args -> {
            // ↑ args 就是从命令行传入的剩余参数
            //   例如 java MyTool greet Yiqiu → args = ["Yiqiu"]
            String name = args.length > 0 ? args[0] : "陌生人";
            System.out.println("你好, " + name + "!");
        });

        ctx.registerCommand("version", "显示版本号", args -> {
            System.out.println(getName() + " v" + getVersion());
        });
    }

    // 3. 入口 —— 只需一行
    public static void main(String[] args) {
        StartPlugin.start(new MyPlugin(), args);
        //       参数1: 你的插件实例 ──────┘       └── 参数2: main 的 args 原样透传
    }
}

// 运行:
//   java MyPlugin greet Yiqiu     →  你好, Yiqiu!
//   java MyPlugin version         →  My Tool v1.0.0
//   java MyPlugin help            →  打印可用命令列表
//   java MyPlugin greet Yiqiu --verbose  →  handler 收到 ["Yiqiu", "--verbose"]

关键理解:new MyPlugin() 是你自己写的实现了 Plugin 接口的类的实例。StartPlugin.start() 内部会调用这个实例的 onLoad() 来收集你注册的命令,然后用 args 中的第一个参数去匹配并执行对应的命令 handler。每个 registerCommand 的 handler 接收的 args 是命令行中去除子命令名之后的剩余参数。


带 GUI 支持的插件:

public class MyGuiTool {                                        // 入口类
    public static void main(String[] args) {                    // main 方法
        StartPlugin.startWithGui(new MyPlugin(), args);         // → startWithGui 会初始化 FlatLaf 主题
    }
}

// 运行:
//   java MyGuiTool --gui          → 打开 GUI 窗口
//   java MyGuiTool <command> ...  → 执行 CLI 命令

自动检测模式 (推荐) — 同一份代码即可 CLI 也可 GUI:

public class MyTool {                                           // 入口类
    public static void main(String[] args) {                    // main 方法
        StartPlugin.auto(new MyPlugin(), args);                 // → auto 检测 --gui 标志自动切换模式
    }
}

// 运行:
//   java MyTool --gui                 → 检测到 --gui,启动 GUI
//   java MyTool <command> ...         → 没有 --gui,执行 CLI 命令

三种模式的选择建议:纯 CLI 工具选 start;肯定需要 GUI 的桌面工具选 startWithGui;一份代码两种都用选 auto(最推荐)。

生命周期

StartPlugin.start(plugin, args)
  ├─ 初始化 FlatLaf (仅 startWithGui / auto --gui)
  ├─ new StandaloneContext(plugin)
  ├─ plugin.onLoad(context)     ← 插件注册命令/菜单/GUI
  ├─ plugin.onLoaded()          ← 所有注册完成
  ├─ 命令分发 (CLI 模式)
  │   ├─ help / 无参数 → 打印可用命令列表
  │   ├─ <子命令>      → 执行对应的 handler
  │   └─ 未知命令      → 打印错误 + 帮助
  ├─ 启动 GUI (--gui 模式)
  │   └─ 找到首个注册的 GUIComponent → 调用 launcher
  └─ ctx.shutdown()

14. 终端颜色工具 (com.gyscan.core.util.Color)

SDK 可用: 此工具类已导出到 gyscan-sdk-1.0.0.jar,插件可直接 import com.gyscan.core.util.Color 使用,无需额外依赖。

概述

Color 提供统一的终端 ANSI 颜色处理能力,支持预定义颜色名和 RGB 真彩色两种上色方式。核心函数为 terColor,同时提供 red()、bold() 等便捷方法,并内置 TTY 自动检测,在非终端环境(管道/Docker/CI)自动跳过 ANSI 码。

Color 类 API

package com.gyscan.core.util;                                // SDK 导出包路径,插件 import 即可使用

public final class Color {                                    // 终端 ANSI 颜色工具

    // ===== TTY 检测 =====
    public static boolean isEnabled();                       // → 当前是否启用颜色输出
    public static boolean isTty();                           // → 原始 TTY 检测结果(不受 forceEnabled 影响)
    public static void setForceEnabled(boolean v);           // → 强制启用颜色,即使非 TTY 也输出 ANSI 码

    // ===== 样式常量 =====
    static final String RESET;                               // → 重置所有样式 (\u001B[0m)
    static final String BOLD;                                // → 加粗
    static final String DIM;                                 // → 暗淡
    static final String ITALIC;                              // → 斜体
    static final String UNDERLINE;                           // → 下划线
    static final String BLINK;                               // → 闪烁
    static final String REVERSE;                             // → 反色
    static final String HIDDEN;                              // → 隐藏
    static final String STRIKE;                              // → 删除线

    // ===== 标准前景色 (8 色) =====
    static final String BLACK, RED, GREEN, YELLOW;           // → 黑/红/绿/黄
    static final String BLUE, MAGENTA, CYAN, WHITE;          // → 蓝/品红/青/白

    // ===== 亮色前景色 (8 色) =====
    static final String BRIGHT_BLACK, BRIGHT_RED;             // → 亮黑(灰)/亮红
    static final String BRIGHT_GREEN, BRIGHT_YELLOW;          // → 亮绿/亮黄
    static final String BRIGHT_BLUE, BRIGHT_MAGENTA;          // → 亮蓝/亮品红
    static final String BRIGHT_CYAN, BRIGHT_WHITE;            // → 亮青/亮白

    // ===== 标准背景色 (8 色) =====
    static final String BG_BLACK, BG_RED, BG_GREEN, BG_YELLOW;
    static final String BG_BLUE, BG_MAGENTA, BG_CYAN, BG_WHITE;

    // ===== 亮色背景色 (8 色) =====
    static final String BG_BRIGHT_BLACK, BG_BRIGHT_RED;
    static final String BG_BRIGHT_GREEN, BG_BRIGHT_YELLOW;
    static final String BG_BRIGHT_BLUE, BG_BRIGHT_MAGENTA;
    static final String BG_BRIGHT_CYAN, BG_BRIGHT_WHITE;
}

terColor — 核心着色方法

terColor 是本类的核心方法,提供 两个维度 × 两种模式 = 4 种重载:

维度 方法签名 说明
预定义前景色 terColor(String text, String colorName) 用颜色名(如 “red”)给文字上色
预定义背景色 terColor(String text, String colorName, boolean bg) 第三个参数 true = 背景色
RGB 前景色 terColor(String text, int r, int g, int b) 用 RGB 数值(0-255)上色
RGB 背景色 terColor(String text, int r, int g, int b, boolean bg) 第四个参数 true = RGB 背景色
// ====== terColor 预定义颜色名重载 ======

/** 使用预定义颜色名为文字上色 (前景色) */
public static String terColor(String text, String colorName);
// → text="hello", colorName="red"
// → 返回: "\u001B[31mhello\u001B[0m"  (TTY可用时)
//   或  "hello"                      (TTY不可用时)

/** 使用预定义颜色名为文字上色, 指定前景/背景 */
public static String terColor(String text, String colorName, boolean background);
// → text="warn", colorName="yellow", background=true
// → 返回: "\u001B[43mwarn\u001B[0m"  (黄色背景)


// ====== terColor RGB 真彩色重载 ======

/** 使用 RGB 真彩色为文字上色 (24bit 前景色) */
public static String terColor(String text, int r, int g, int b);
// → r=0-255 红色分量, g=0-255 绿色分量, b=0-255 蓝色分量
// → 返回: "\u001B[38;2;r;g;bmtext\u001B[0m"

/** 使用 RGB 真彩色为文字上色, 指定前景/背景 */
public static String terColor(String text, int r, int g, int b, boolean background);
// → background=true: "\u001B[48;2;r;g;bmtext\u001B[0m" (RGB背景)

返回值类型: 始终返回 String。TTY 不可用时返回与 text 相同的纯文本;text 为 null 时返回 ""。

参数规范:

  • colorName: 大小写不敏感,支持 “grey”/“gray” 别名(映射到 bright_black)
  • r, g, b: 必须为 0-255 的整数,超出范围抛出 IllegalArgumentException

预定义颜色名完整列表

类别 颜色名 对应常量 说明
标准色 black BLACK 黑色
标准色 red RED 红色
标准色 green GREEN 绿色
标准色 yellow YELLOW 黄色
标准色 blue BLUE 蓝色
标准色 magenta MAGENTA 品红
标准色 cyan CYAN 青色
标准色 white WHITE 白色
亮色 bright_black BRIGHT_BLACK 亮黑 (灰色)
亮色 bright_red BRIGHT_RED 亮红
亮色 bright_green BRIGHT_GREEN 亮绿
亮色 bright_yellow BRIGHT_YELLOW 亮黄
亮色 bright_blue BRIGHT_BLUE 亮蓝
亮色 bright_magenta BRIGHT_MAGENTA 亮品红
亮色 bright_cyan BRIGHT_CYAN 亮青
亮色 bright_white BRIGHT_WHITE 亮白

便捷方法

// ===== 样式便捷方法 =====
public static String bold(String text);      // → 加粗文字
public static String dim(String text);       // → 暗淡文字
public static String italic(String text);    // → 斜体文字
public static String underline(String text); // → 下划线文字
public static String strike(String text);    // → 删除线文字

// ===== 颜色便捷方法 =====
public static String red(String text);           // → 红色文字
public static String green(String text);         // → 绿色文字
public static String yellow(String text);        // → 黄色文字
public static String blue(String text);          // → 蓝色文字
public static String magenta(String text);       // → 品红文字
public static String cyan(String text);          // → 青色文字
public static String white(String text);         // → 白色文字

public static String brightRed(String text);     // → 亮红文字
public static String brightGreen(String text);   // → 亮绿文字
public static String brightYellow(String text);  // → 亮黄文字
public static String brightBlue(String text);    // → 亮蓝文字
public static String brightMagenta(String text); // → 亮品红文字
public static String brightCyan(String text);    // → 亮青文字

// ===== 多码组合方法 =====
public static String colorize(String text, String... codes);
// → 传入多个样式/颜色码组合, 如: colorize("text", Color.BOLD, Color.RED)

使用示例

插件中使用 terColor (推荐方式):

import com.gyscan.core.util.Color;                            // → SDK 已导出,插件直接 import

public class MyPlugin extends AbstractPlugin {

    @Override
    public void onLoad(PluginContext context) {
        super.onLoad(context);

        // ① 预定义颜色名上色 — 最常用
        System.out.println(Color.terColor("扫描完成", "green"));   // → 绿色文字
        System.out.println(Color.terColor("发现 3 个漏洞", "red")); // → 红色文字
        System.out.println(Color.terColor("进度 50%", "yellow"));   // → 黄色文字

        // ② RGB 真彩色上色 — 自定义颜色
        System.out.println(Color.terColor("橙色文字", 255, 128, 0)); // → RGB(255,128,0)

        // ③ 便捷方法 — 更简洁
        System.out.println(Color.green("[+] 成功"));             // → 等价于 terColor("[+] 成功", "green")
        System.out.println(Color.red("[-] 失败"));               // → 等价于 terColor("[-] 失败", "red")
        System.out.println(Color.bold("重要提醒"));               // → 等价于 colorize("重要提醒", BOLD)

        // ④ 多码组合 — 加粗红色
        System.out.println(Color.colorize("严重警告!",
            Color.BOLD, Color.RED));                             // → 加粗 + 红色
    }
}

三种使用方式对比:

// 方式一: 使用 terColor(推荐 — 最直观)
String msg = Color.terColor("hello", "green");

// 方式二: 使用便捷方法(最简洁)
String msg = Color.green("hello");

// 方式三: 使用颜色常量拼接(灵活但易忘 RESET)
String msg = Color.GREEN + "hello" + Color.RESET;

强制启用颜色 (在管道/CI 中也需要彩色输出时):

public static void main(String[] args) {
    Color.setForceEnabled(true);                               // → 强制启用 ANSI 颜色
    System.out.println(Color.red("即使在管道中也会显示颜色"));
    System.out.println(Color.terColor("自定义", 100, 200, 50));
    Color.setForceEnabled(false);                              // → 恢复自动检测
}

注意: 在 com.gyscan.plugin.recon.AnsiColor 等第三方插件中已有类似的局部颜色实现。推荐新插件统一使用 SDK 内置的 Color 类,避免每个插件重复定义颜色常量。


15. 终端进度条工具 (com.gyscan.core.util.Progress)

SDK 可用: 此工具类已导出到 gyscan-sdk-1.0.0.jar,插件可直接 import com.gyscan.core.util.Progress 使用。

概述

Progress 提供终端进度条绘制能力,支持 11 种预定义样式(LINE/HASH/DOT/BLOCK/AT/STAR/EQ/PIPE/PLUS/CIRCLE/BRAILLE)、自定义字符、Unicode 细腻进度、旋转指示器,以及 Builder 模式灵活配置。配合 Color 类可实现彩色进度条。

预定义样式一览

样式 枚举值 效果示例 说明
短线 + 箭头 Style.LINE [----------->] [50%] 短线填充,> 作为头部
井号 + 箭头 Style.HASH [##########>] [50%] 井号填充,最常用
点号 + 箭头 Style.DOT [..........>] [50%] 低调风格
Unicode 方块 — [██████████▌] [50%] 8 段精度方块
@ 符号 Style.AT [@@@@@@@@@@>] [50%] 醒目粗体
等号 + 箭头 Style.EQ [==========>] [50%] 简洁风格
星号 + 箭头 Style.STAR [**********>] [50%] 装饰风格
竖线 + 箭头 Style.PIPE `[
加号 + 箭头 Style.PLUS [++++++++++>] [50%] 十字风格
短线 + 圆头 Style.CIRCLE [----------C] [50%] 完成时 C 变 @
盲文细腻 — [⣿⣿⣿⣿⣿⣿⣀⣀] [50%] 每字符 8 段精度

Progress 类 API

package com.gyscan.core.util;                                // SDK 导出包路径

public final class Progress {                                 // 终端进度条工具

    // ===== 预定义样式枚举 =====
    public enum Style {                                       // 11 种内置样式
        LINE,   HASH,   DOT,   AT,   EQ,                      // → 标准字符 + 箭头头
        STAR,   PIPE,   PLUS,                                  // → 更多字符变体
        CIRCLE, SPARSE;                                        // → 特殊头/块填充
    }

    // ===== 常量 =====
    public static final int DEFAULT_WIDTH = 20;               // → 默认进度条宽度 (不含括号)
}

render — 核心渲染方法

// ====== 预定义样式渲染 ======

/** 渲染进度条字符串 (预定义样式, 含百分比) */
public static String render(int current, int total, Style style, int width);
// → current=50, total=100, style=Style.HASH, width=20
// → 返回: "[##########>     ] [50%]"

// ====== 自定义字符渲染 (最大灵活度) ======

/** 渲染进度条字符串 (自定义填充/头部/完成字符) */
public static String render(int current, int total,
                             char fillChar, char headChar, char doneHead,
                             int width, boolean showPercent);
// → fillChar='█' 已填充区域字符
// → headChar='>' 进度未满时的头部
// → doneHead='✓' 100% 时的头部
// → showPercent=false 隐藏百分比

参数规范:

  • current: 当前进度值,范围 0 ~ total
  • total: 总量,必须 > 0
  • width: 进度条宽度(不含括号和百分比),最小 5
  • 返回值: 始终返回 String,如 [######>] [50%]
/** 在同一行打印进度条 (TTY 环境使用 \\r 覆盖) */
public static void print(int current, int total, Style style, int width);
// → 输出: \r[######>] [50%]

/** 打印进度条并追加额外信息 (如文件名) */
public static void print(int current, int total, Style style, int width, String extra);
// → 输出: \r[######>] [50%] 正在处理: data.txt

/** 打印进度条到指定输出流 */
public static void printTo(PrintStream out, int current, int total, Style style, int width);

/** 进度完成, 换行 */
public static void done();

/** 进度完成, 换行并打印完成消息 (先发 \\r 清除进度条行) */
public static void done(String message);
// → 输出: \r              (清除当前行)
//         扫描完成! 共处理 100 个文件

预设样式快捷方法

// 每种预定义样式都有对应的快捷方法, 使用默认宽度 20
public static String line(int current, int total);           // → [------>] [50%]
public static String hash(int current, int total);           // → [######>] [50%]
public static String dot(int current, int total);            // → [......>] [50%]
public static String at(int current, int total);             // → [@@@@@@>] [50%]
public static String block(int current, int total);          // → [██████▌] [50%] (8段精度)
public static String braille(int current, int total);        // → [⣿⣿⣿⣿⣀] [50%] (盲文)
public static String circle(int current, int total);         // → [------C] [50%]

/** 旋转指示器进度条 */
public static String spinner(int current, int total, int tick);
// → tick 用于旋转: | / - \ 循环
// → 返回: [######>] [50%] |

Builder 模式

/** 创建构建器 — 链式配置, 一次 build 后重复使用 */
public static Builder builder();

public static final class Builder {
    public Builder style(Style s);                           // → 设置样式
    public Builder width(int w);                             // → 设置宽度
    public Builder color(String name);                       // → 设置预定义颜色
    public Builder color(int r, int g, int b);               // → 设置 RGB 颜色
    public Builder showPercent(boolean v);                   // → 是否显示百分比
    public Builder prefix(String p);                         // → 左侧前缀
    public Builder suffix(String s);                         // → 右侧后缀
    public Builder output(PrintStream o);                    // → 输出流
    public Instance build();                                 // → 构建可复用实例
}

使用示例

基础用法 — render 渲染后自行输出:

import com.gyscan.core.util.Progress;                         // → SDK 已导出,插件直接 import

// 渲染多种样式, 一次性打印
System.out.println(Progress.line(50, 100));                   // → [---------->] [50%]
System.out.println(Progress.hash(50, 100));                   // → [##########>] [50%]
System.out.println(Progress.at(50, 100));                     // → [@@@@@@@@@@>] [50%]
System.out.println(Progress.block(50, 100));                  // → [██████████▌] [50%]
System.out.println(Progress.circle(50, 100));                 // → [----------C] [50%]
System.out.println(Progress.braille(50, 100));                // → [⣿⣿⣿⣿⣿⣿⣀⣀] [50%]

实时进度 — print + \r 原地更新 (最常用):

int total = 100;
for (int i = 0; i <= total; i++) {
    Progress.print(i, total, Progress.Style.HASH, 30, "处理中...");
    // → 输出: \r[##########>                ] [33%] 处理中...
    Thread.sleep(50);
}
Progress.done(Color.green("处理完成! 共 " + total + " 项"));
// → 先发 \r 清行, 再打印绿色完成消息

Builder 模式 — 彩色进度条:

// 一次配置, 多次使用
Progress.Instance bar = Progress.builder()
    .style(Progress.Style.BLOCK)
    .width(30)
    .color("green")                                          // → 绿色进度条
    .prefix("扫描中")
    .build();

for (int i = 0; i <= 100; i++) {
    bar.print(i, 100);
    Thread.sleep(50);
}
bar.done(Color.green("完成!"));

自定义字符 — 完全自由的进度条:

// 使用任意字符组合
String bar = Progress.render(50, 100,
    '█',   // 填充字符: 实心方块
    '▌',   // 头部字符: 半方块
    '✓',   // 完成字符: 对勾
    20,    // 宽度
    true   // 显示百分比
);
System.out.println(bar);
// → [██████████▌         ] [50%]

旋转指示器:

for (int i = 0; i <= 100; i++) {
    String bar = Progress.spinner(i, 100, i, 20);
    System.out.print("\r" + bar);                             // → [##########>] [50%] |
    Thread.sleep(50);
}

注意: 非 TTY 环境(Docker/CI/管道)中 print 自动降级为每行一个进度条(\n 换行),避免 \r 乱码。可通过 Color.setForceEnabled(true) 强制 TTY 行为。


16. 命令行参数框架 (com.gyscan.core.help)

SDK 可用: 自 1.0.0 起, 命令行参数框架已统一放置在 com.gyscan.core.help 包,
并在 gyscan-sdk-1.0.0.jar 中导出 (即 15 个类全部包含).
主程序 (com.gyscan.host) 与 GYscanSDK (com.gyscan.plugin.api) 共享同一份框架代码,
命令注册、补全、帮助生成统一走本框架.

16.1 框架总览

类 职责
SchemaParser 把 usage 字符串解析为 Schema (选项 + 位置参数列表)
OptionSpec / PositionalSpec 选项 / 位置参数规范 (短名 / 长名 / 参数名 / 多选值)
ArgumentParser 按 Schema 解析命令行 token 序列
ArgumentValidator 验证解析结果 (必填 / 整数 / 多选)
HelpGenerator 生成 text / markdown / json 帮助
CompletionProvider 生成 bash / zsh / fish 补全脚本, 以及 jline 3 候选值
CommandSpec 命令元信息 (名称 / 别名 / 描述 / usage), 暴露统一 API
HelpCommandRegistry 全局命令注册表, 框架内单例

16.2 SchemaParser — usage 字符串解析

import com.gyscan.core.help.SchemaParser;

String usage = "Usage: webapiscan <target_url> [-d depth] [-n threads] " +
               "[--format txt|json|md] [--no-rest]";
SchemaParser.Schema schema = SchemaParser.parse(usage);

for (OptionSpec o : schema.options) {
    System.out.println("短: " + o.displayShort() + " 长: " + o.displayLong() + " 参数: " + o.argName);
}
for (PositionalSpec p : schema.positionals) {
    System.out.println("位置: " + p.name + " 必填: " + p.required);
}

支持的语法:

语法 含义 示例
-x VAL 短选项 -d 2
--long VAL 长选项 --depth 2
--key=VAL 等号形式 --depth=2
--no-rest 标志 (无值) --no-rest
--format a|b|c 多选值 --format txt|json|md
<name> 必填位置参数 <target_url>
[name] 可选位置参数 [output]
Usage: <name> 装饰前缀自动跳过 Usage: webapiscan ...

16.3 ArgumentParser — 解析 token 序列

import com.gyscan.core.help.ArgumentParser;

String[] argv = {"--depth", "3", "https://example.com", "--no-rest", "--format", "json"};
ArgumentParser.Result r = ArgumentParser.parse(schema, argv);

int depth = Integer.parseInt(r.get("depth"));   // 3
String target = r.positional(0);               // https://example.com
boolean noRest = r.has("no-rest");             // true
List<String> formats = r.getAll("format");     // [json]

支持:

  • 短选项 + 空格值 (-d 2)
  • 短选项 + 粘连值 (-d2)
  • 合并短选项 (-dv → 两个标志)
  • 长选项 + 等号 (--depth=2)
  • 重复选项 (--include A --include B)
  • 位置参数 + 终止符 (-- 之后全是位置参数)
  • 未知选项 / 多选值不匹配时记录到 r.warnings, 不抛异常

16.4 ArgumentValidator — 验证

import com.gyscan.core.help.ArgumentValidator;

ArgumentValidator v = new ArgumentValidator().strictUnknown(true);
List<ArgumentValidator.Issue> issues = v.validate(schema, r);
for (ArgumentValidator.Issue i : issues) {
    System.out.println(i.severity + ": " + i.message);
}

验证规则:

  • 必填选项 / 必填位置参数 (<> 包裹的)
  • 整数类型 (匹配常见参数名 depth/threads/max/ms/port/retry/...)
  • 多选值 (choices)
  • 严格模式: 未知选项也报错

16.5 HelpGenerator — 多格式帮助

import com.gyscan.core.help.HelpGenerator;

System.out.println(HelpGenerator.text(schema));     // 纯文本
System.out.println(HelpGenerator.markdown(schema)); // Markdown 表格
System.out.println(HelpGenerator.json(schema));     // JSON (供外部 API 消费)

16.6 CompletionProvider — 智能补全

16.6.1 静态脚本生成 (Bash / Zsh / Fish)

import com.gyscan.core.help.CompletionProvider;

String bash = CompletionProvider.bash(schema);
String zsh  = CompletionProvider.zsh(schema);
String fish = CompletionProvider.fish(schema);

Bash:

# Bash completion for webapiscan
_webapiscan() {
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="-d --depth -n --threads --format --no-rest "
    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
    COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
}
complete -F _webapiscan webapiscan

Zsh: 使用 #compdef webapiscan + _arguments.

Fish: 使用 complete -c webapiscan -f + 每选项一行.

16.6.2 运行时补全 (JLine 3)

import com.gyscan.core.help.CompletionProvider;

List<String> candidates = CompletionProvider.jlineCandidates(schema, prevWord, currentWord);

返回符合当前 word 的候选 value 列表, 供 JLine 3 的 Candidate 包装使用.

16.7 CommandSpec — 命令元信息

import com.gyscan.core.help.CommandSpec;

CommandSpec spec = CommandSpec.builder("webapiscan")
        .description("Web API 扫描器")
        .category("扫描")
        .plugin("webapiscan", "Web API 扫描")
        .usage("Usage: webapiscan <target_url> [-d depth] [--no-rest]")
        .alias("ws", "web")
        .build();

spec.help();                    // 文本帮助
spec.helpMarkdown();            // Markdown 帮助
spec.helpJson();                // JSON 帮助
spec.bashCompletion();          // Bash 补全脚本
spec.zshCompletion();           // Zsh 补全脚本
spec.fishCompletion();          // Fish 补全脚本

ArgumentParser.Result r = spec.parse(argv);
List<ArgumentValidator.Issue> issues = spec.validate(r);

CommandSpec 是 主程序命令 与 插件命令 的统一抽象, 所有命令都通过它注册,
--help / --generate-completion 走主程序入口, 插件命令走 help <command> 子命令.

16.8 HelpCommandRegistry — 全局命令注册表

import com.gyscan.core.help.HelpCommandRegistry;

// 注册
HelpCommandRegistry.register(spec);

// 查询
CommandSpec found = HelpCommandRegistry.get("webapiscan");
Collection<CommandSpec> all = HelpCommandRegistry.all();

// 按类别
List<CommandSpec> cli = HelpCommandRegistry.cliCommands();
List<CommandSpec> gui = HelpCommandRegistry.guiCommands();

// 注销
HelpCommandRegistry.unregister("webapiscan");

主程序自身命令 (gyscan --help 等) 在 GYscanApplication 构造时注册一次;
插件命令在 PluginContextImpl.registerCommand 时同步注册,
unregisterCommand 时同步注销.

16.9 主程序 --help / --generate-completion

gyscan 主程序支持:

命令 功能
gyscan --help / -h 打印主程序帮助 (走 HelpGenerator)
gyscan --version / -v 显示版本号
gyscan --no-daemon 不启动守护进程
gyscan --plugin-dir <DIR> 指定插件目录
gyscan --load-plugin <JAR> 启动时加载指定 JAR 插件
gyscan --generate-completion <bash|zsh|fish|json|md> 输出补全脚本 / 帮助

例如:

# 安装 bash 补全
source <(gyscan --generate-completion bash)
echo 'source <(gyscan --generate-completion bash)' >> ~/.bashrc

# 安装 zsh 补全
gyscan --generate-completion zsh > "${fpath[1]}/_gyscan"

16.10 插件使用示例

插件在 registerCommand 时只需提供 usage, 框架自动完成:

  • help <command> 子命令的输出
  • 交互式 shell (JLine) 内的 Tab 补全 (选项 / 选项值 / 位置参数)
  • --generate-completion 输出插件自身补全脚本
// 插件 PluginImpl.java
public class WebAPIScanPlugin extends AbstractPlugin {
    @Override
    public void start(PluginContext ctx) {
        ctx.registerCommand(
            "webapiscan",
            "Web API 扫描器",
            "Usage: webapiscan <target_url> [-d depth] [-n threads] " +
            "[--format txt|json|md] [--no-rest] [--no-graphql] [--no-ws]",
            this::onRun
        );
    }

    private void onRun(String[] args) {
        // args 是 GYscan 解析后的剩余 token, 框架会负责:
        //   - help <command> 输出
        //   - 交互式补全候选
        // 这里直接使用业务逻辑即可
    }
}

PluginContextImpl.registerCommand 内部会构造一个对应的 CommandSpec
并通过 HelpCommandRegistry.register(spec) 同步注册; 卸载时同步注销.

16.11 编译与发布

build.gradle 中 sdkJar 已包含 com/gyscan/core/help/**, 即 SDK 默认导出整个框架:

tasks.register('sdkJar', Jar) {
    from(sourceSets.main.output) {
        include 'com/gyscan/plugin/api/**'
        include 'com/gyscan/core/util/Color*.class'
        include 'com/gyscan/core/util/Progress*.class'
        include 'com/gyscan/core/help/**'   // 命令行参数框架 — 插件可使用 help / 补全 / 验证
    }
}

unzip -l gyscan-sdk-1.0.0.jar | grep core/help 应当输出 15 行 (含目录条目), 表示框架已全部打包.

16.12 交互式 Shell 的 Tab 智能补全 (JLine 3)

进入 gyscan 交互式 shell (JLine 3) 后, 框架会接管 Tab 键,
打出主体命令 后按 Tab 即可:

  • 显示该命令所有可用的短选项 / 长选项作为候选
  • 已输入 - 开头时, 进一步按 Tab 显示该命令的所有选项
  • 已输入 -- 开头时, 仅显示长选项
  • 选中”带值”的选项 (如 --depth <N>) 后再按 Tab:
    • 整数参数 → 显示 1, 2, 4, 5, 8, 10, 16, … 等常用数值
    • 多选参数 → 显示该选项的所有 choices
    • URL 参数 → 显示 URL 协议前缀 (https://, http://)
    • 文件参数 → 显示文件路径
  • 位置参数 (<target_url>) 同样能按 Tab 补全

示例:

gyscan> webap<TAB>
  webapiscan          -- Web API 端点扫描
  webapiscan-gui      -- 打开 Web API 扫描 GUI 界面

gyscan> webapiscan -<TAB>
  -d  [-d N]   -- 短选项/同 --depth
  -m  [-m N]   -- 短选项/同 --max-urls
  -n  [-n N]   -- 短选项/同 --threads
  -t  [-t MS]  -- 短选项/同 --timeout
  -H  [-H SPEC]-- 短选项/同 --header
  -o  [-o FILE]-- 短选项/同 --output
  -v  [-v]     -- 短选项/同 --verbose
  -h  [-h]     -- 短选项/同 --help
  ...

gyscan> webapiscan --<TAB>
  --depth  -- --depth N
  --max-urls -- --max-urls N
  --format -- --format FMT
  ...

gyscan> webapiscan --depth <TAB>
  1  2  4  5  8  10  16  20  30  50  100  200  500  ...

gyscan> webapiscan --format <TAB>
  txt  json  md

实现位置: com.gyscan.host.shell.ShellCompleter + com.gyscan.core.help.SchemaParser.
框架无侵入, 插件只需在 registerCommand 时提供 usage 字符串, 补全自动可用.


17. 插件开发指南

16.1 一键模板生成 (PluginTemplate)

SDK 提供 PluginTemplate 工具类,可一键生成符合 GYscan 插件开发规范的完整模板项目。

核心特性: 用户可自由选择是否生成 GUI 注册代码 / 菜单项,避免生成冗余代码或不必要的依赖。

16.1.1 模板选项 (Options)

package com.gyscan.plugin.api;                                // SDK 包路径

public final class PluginTemplate {                           // 一键模板生成工具

    /**
     * 模板生成选项 - 控制模板是否携带 GUI / 菜单等可选代码块.
     */
    public static final class Options {                       // 生成选项配置
        /** 是否生成 GUI 注册代码 (GUI 启动命令 + registerGUIComponent + showGUI) */
        public Options withGui(boolean v);                    // → true=生成 GUI 代码,false=纯 CLI
        /** 是否生成菜单项 (依赖 withGui, withGui=false 时强制为 false) */
        public Options withMenu(boolean v);                   // → true=在模板中包含 registerMenuItem 代码

        public boolean isWithGui();                           // → 查询是否配置了 GUI
        public boolean isWithMenu();                          // → 查询是否配置了菜单

        /** 默认: GUI + 菜单 (与历史行为兼容) */
        public static Options defaults();                     // → 生成 GUI + 菜单,适用于桌面工具插件
        /** 纯 CLI: 不生成 GUI/菜单/相关命令, 仅含主命令骨架, 不引入 flatlaf 依赖 */
        public static Options cliOnly();                      // → 不生成 GUI,适用于纯命令行插件
    }

    /** 一键生成完整插件模板项目 (默认含 GUI + 菜单,向后兼容). */
    public static List<Path> generate(Path outputDir, String pluginId,
                                       String pluginName, String mainClass,
                                       String description) throws IOException;
    // → 参数: outputDir=输出目录, pluginId=插件ID(snake_case), pluginName=显示名,
    //         mainClass=主类全限定名, description=插件描述

    /** 一键生成完整插件模板项目 (Options 模式,自由控制 GUI/菜单). */
    public static List<Path> generate(Path outputDir, String pluginId,
                                       String pluginName, String mainClass,
                                       String description,
                                       Options options) throws IOException;
    // → 多一个 Options 参数,可自由控制是否生成 GUI/菜单代码
}

两种预设组合:

预设 GUI 启动命令 GUI 窗口 菜单项 flatlaf 依赖 适用场景
Options.defaults() ✅ ✅ ✅ ✅ 普通插件 (默认)
Options.cliOnly() ❌ ❌ ❌ ❌ 纯 CLI 工具/脚本/扫描器

16.1.2 程序化 API 使用

// 1) 默认: 含 GUI + 菜单 (向后兼容) — 在你的 main 或其他启动代码中调用
PluginTemplate.generate(                                    // → 调用 SDK 的模板生成方法
    Paths.get("./my-scan-plugin"),                           // → 输出目录(相对或绝对路径)
    "my_scan",                                              // → 插件 ID(snake_case)
    "MyScanPlugin",                                         // → 插件显示名称(PascalCase)
    "com.gyscan.plugin.myscan.MyScanPlugin",                 // → 主类全限定名
    "我的扫描插件"                                            // → 插件描述
);

// 2) 纯 CLI 模板: 无 GUI 无菜单, 不引入 flatlaf — 适合命令行工具
PluginTemplate.generate(
    Paths.get("./cli-tool"),                                 // → 输出目录
    "cli_tool", "CliTool",
    "com.gyscan.plugin.cli_tool.CliTool",
    "纯 CLI 工具",
    PluginTemplate.Options.cliOnly()                          // → 关键:使用 cliOnly 预设
);

// 3) 自定义组合 — 精细控制每个选项
PluginTemplate.Options opts = new PluginTemplate.Options()   // → 创建 Options 对象
    .withGui(true)                                            // → 需要 GUI
    .withMenu(true);                                          // → 需要菜单
PluginTemplate.generate(Paths.get("./custom"), "custom", "Custom",
    "com.gyscan.plugin.custom.Custom", "自定义", opts);       // → 传入自定义 Options

16.1.3 命令行一键生成(推荐)

sdk.jar 已设置 Main-Class: com.gyscan.plugin.api.PluginTemplate,可直接通过 java -jar 运行:

# 完整用法: 指定 pluginId + 显示名称
java -jar gyscan-sdk-1.0.0.jar --example my_scan --name MyScanPlugin

# 简写: 仅传 --example, name 自动衍生 (my_scan -> MyScan)
java -jar gyscan-sdk-1.0.0.jar --example my_scan

# 纯 CLI 插件 (无 GUI/菜单, 不依赖 flatlaf)
java -jar gyscan-sdk-1.0.0.jar --example my_cli --no-gui

# 纯 CLI + 不生成菜单 (no-gui 已隐含 no-menu)
java -jar gyscan-sdk-1.0.0.jar --example my_cli --no-gui --no-menu

# 查看帮助
java -jar gyscan-sdk-1.0.0.jar --help

参数说明:

参数 必选 说明
--example <pluginId> 是 snake_case 格式(如 my_scan),同时作为输出目录、包名、类名前缀
--name <pluginName> 否 PascalCase 显示名,缺省时由 pluginId 自动衍生
--no-gui 否 不生成 GUI 注册代码(无 GUI 启动命令, 无 registerGUIComponent),不引入 flatlaf 依赖
--no-menu 否 不生成菜单项(仍保留 GUI 窗口, 但不出现菜单栏)

默认输出目录为当前工作目录下的 <pluginId>/,主类包为 com.gyscan.plugin.<pluginId>。

16.1.4 生成的模板项目结构

my-scan-plugin/
├── build.gradle          # 含 Plugin-Logo 声明、完整 manifest 属性
├── settings.gradle
└── src/main/
    ├── java/com/gyscan/plugin/myscan/
    │   └── MyScanPlugin.java   # 标准骨架(按 Options 注入 GUI/菜单代码块)
    └── resources/images/
        └── my-scan-logo.png    # 默认 32x32 占位 logo

不同 Options 下生成的主类差异:

模板 registerCommands registerExtras build.gradle 依赖
defaults() 主命令 + GUI 启动命令 GUI 窗口 + 菜单项 flatlaf + sdk
cliOnly() 仅主命令 (无) sdk only

模板生成的 build.gradle 特性:

  • ext.logoFile 声明 logo 路径,写入 Plugin-Logo manifest 属性
  • 完整的 manifest 属性(Id/Name/Version/Author/Main-Class/Description/Website/Aliases/Min-Java-Version/Max-Java-Version/Core-Dependencies)
  • GUI 关闭时自动移除 flatlaf 依赖(减小 jar 体积)
  • archiveBaseName 自动命名为 <pluginId>-plugin

模板生成的主类骨架:

  • 实现 AbstractPlugin,含标准 getPluginId() / getName() / getVersion() / getDescription()
  • registerCommands() 注册 1 个主命令(示例含 --help 参数)+ 可选 GUI 启动命令
  • registerExtras() 按 Options 注册 GUI 窗口和菜单项
  • onUnload() 完整反注册所有命令、菜单、GUI

16.2 项目结构

my-plugin/
├── build.gradle
├── settings.gradle
└── src/main/java/com/gyscan/plugin/myplugin/
    └── MyPlugin.java

16.3 build.gradle 示例

plugins {
    id 'java'                                                  // → Gradle Java 插件,提供 compileJava、jar 等任务
}

group = 'com.gyscan.plugin'                                    // → Maven groupId,一般固定为 com.gyscan.plugin
version = '1.0.0'                                              // → 插件版本号,最终写入 JAR 的 Plugin-Version

java {
    sourceCompatibility = JavaVersion.VERSION_17                // → 源码兼容 Java 17
    targetCompatibility = JavaVersion.VERSION_17                // → 编译产物目标 Java 17
}

repositories {
    mavenCentral()                                             // → Maven 中央仓库,下载依赖需要
}

dependencies {
    compileOnly files('../../Java-GYscan/build/libs/gyscan-sdk-1.0.0.jar') // → 编译期依赖 SDK JAR
    //                                                                         compileOnly: 不打入最终 JAR,宿主提供
}

// ============================================================
// 插件 Logo 配置
// ------------------------------------------------------------
// logoFile: 资源在 src/main/resources/ 下的相对路径 (png/jpg/jpeg)
// 该值会作为 Plugin-Logo 写入 MANIFEST.MF,宿主优先读取
// 留空或 '-' 时回退到 SDK 默认占位图
// ============================================================
ext {
    logoFile = 'images/my-plugin-logo.png'                     // → 指定 Logo 资源路径
}

jar {
    manifest {
        def logoProperty = project.findProperty('logoFile')     // → 尝试从命令行 -PlogoFile=xxx 读取
        def resolvedLogo = (logoProperty != null               // → 解析 Logo 路径
                            && !logoProperty.toString().isEmpty()
                            && logoProperty.toString() != '-')
            ? logoProperty.toString()                            // → 命令行传参优先
            : (ext.has('logoFile') ? ext.logoFile?.toString() : '') // → 否则用 ext.logoFile

        attributes(
            'Plugin-Id':          'my_plugin',                 // → 插件唯一 ID (snake_case)
            'Plugin-Name':        'MyPlugin',                  // → 插件显示名称 (PascalCase)
            'Plugin-Version':     project.version,             // → 引用上面定义的 version
            'Plugin-Author':      'GYscan Team',               // → 作者名
            'Plugin-Main-Class':  'com.gyscan.plugin.myplugin.MyPlugin', // → 插件主类全限定名
            'Plugin-Description': '我的第一个插件',              // → 插件简介(一行)
            'Plugin-Website':     'https://gyscan.space',      // → 官网(可选)
            'Plugin-Aliases':     'myplugin',                  // → 别名(逗号分隔)
            'Plugin-Min-Java-Version': '11',                   // → 最低 Java 版本(可选)
            'Plugin-Max-Java-Version': '',                     // → 最高 Java 版本(留空=不限制)
            'Plugin-Core-Dependencies': '',                     // → 核心依赖插件 ID(逗号分隔)
            'Plugin-Exec':        '',                           // → 可选: 加载后自动执行的命令
            'Plugin-Logo':        resolvedLogo ?: ''            // → Logo 路径(写入 MANIFEST.MF)
        )
    }
}

关键:manifest 块中的所有 Plugin-* 属性都会被宿主在加载插件时读取。Plugin-Main-Class 是最重要的,宿主用它来反射加载你的插件类。Plugin-Logo 让宿主能找到你的 Logo 图片。

17.4 命名与命令注册规范

插件开发必须遵守以下规范:

规范 说明 示例
主命令唯一 每个插件仅注册 1 个 CLI 主命令 port-scan、ssh-audit
GUI 命令唯一 每个插件可注册 1 个专用 GUI 启动命令 port-scan-gui、ssh-audit-gui
CLI 参数格式 仅允许 -x、--xx、-xx 三种格式 -p、--ports、-Pn
插件 ID 格式 snake_case 小写下划线 port_scan、ssh_audit
命令名格式 kebab-case 小写连字符或插件 ID 前缀 port-scan、ssh-audit

不推荐的示例(违反规范):

// ❌ 注册了多个主命令 — 每个插件应该只有一个主命令
registerCommand("scan");
registerCommand("scan-host");
registerCommand("scan-ports");

// ❌ CLI 参数使用了不合规格式 — 不支持 --port=<value> 带等号的格式
// 正确格式: -p 80, -p 80, -P n, --port 80, --timeout 5

推荐的示例(符合规范):

private void registerCommands() {                              // → 在 onLoad 中调用此方法
    // ✅ 唯一主命令,所有功能通过参数 (-x / --xx / -xx) 区分
    getContext().registerCommand(                              // → 通过 context 注册
        "port-scan",                                           // → 命令名 (kebab-case)
        "端口扫描",                                             // → 简短描述
        "port-scan <target> [-p ports] [-n threads] [-T0~5] [--quick] [--open]", // → usage 帮助文本
        this::handleScan,                                      // → 命令执行回调
        List.of(                                               // → 参数定义列表
            new ParameterDefinition("target", "String", "扫描目标", true, "")
            // → 名为 target 的 String 型必填参数
        )
    );

    // ✅ 专用 GUI 命令 — 一键打开图形界面
    getContext().registerCommand(
        "port-scan-gui",                                       // → GUI 命令名(主命令名 + -gui 后缀)
        "打开 GUI 界面",                                        // → 简短描述
        args -> getContext().showGUI("port_scan_window")        // → lambda 直接打开窗口
    );
}

16.5 完整插件示例

package com.gyscan.plugin.myplugin;                            // → 插件主类的包路径

import com.gyscan.plugin.api.*;                                // → 导入 SDK 核心 API
import com.gyscan.plugin.api.gui.GUIComponent;                 // → GUI 组件定义
import com.gyscan.plugin.api.menu.MenuItem;                    // → 菜单项定义

import javax.swing.*;                                          // → Swing GUI 组件(JFrame 等)
import java.util.List;                                         // → List 集合类

public class MyPlugin extends AbstractPlugin {                 // → 继承 AbstractPlugin(推荐)

    private PluginLogger logger;                               // → 日志工具字段

    // ===== 插件元信息 =====
    @Override public String getPluginId() { return "my_plugin"; }       // → 唯一 ID (snake_case)
    @Override public String getName() { return "MyPlugin"; }            // → 显示名称
    @Override public String getVersion() { return "1.0.0"; }            // → 版本号
    @Override public String getDescription() { return "我的第一个插件"; } // → 简介

    // ===== 生命周期: 加载入口 =====
    @Override
    public void onLoad(PluginContext context) {                // 宿主/StartPlugin 调用此方法
        super.onLoad(context);                                 // → 必须先调用父类,保存 context
        this.logger = new PluginLogger(context);               // → 创建日志工具
        registerCommands();                                    // → 注册 CLI 命令
        registerMenuItems();                                   // → 注册 GUI 菜单项
        logger.info("插件已加载");                               // → 记录日志
    }

    @Override
    public void onLoaded() {                                   // 所有注册完成后的回调
        logger.info("插件所有资源注册完成");                      // → 此时可安全执行初始化任务
    }

    // ===== 注册命令 =====
    private void registerCommands() {
        // ① 注册唯一主命令
        getContext().registerCommand(                          // → 通过 context 注册
            "hello",                                           // → 命令名: 用户输入 hello xxx 时触发
            "打招呼命令",                                        // → 简短描述(help 列表中显示)
            "hello [name] [--uppercase] [--times N]",           // → usage 帮助文本
            this::handleHello,                                 // → 回调方法引用(相当于 args -> handleHello(args))
            List.of(new ParameterDefinition("name", "String", "名字", false, "World"))
            // → 参数定义: 名为 name 的可选 String 参数,默认值 "World"
        );

        // ② 注册 GUI 专用命令
        getContext().registerCommand(
            "hello-gui",                                       // → GUI 命令名 (主命令 + -gui 后缀)
            "打开 GUI 界面",                                     // → 简短描述
            args -> getContext().showGUI("hello_window")        // → lambda: 直接打开窗口
        );
    }

    // ===== 命令处理 =====
    private void handleHello(String[] args) {                  // → 宿主传入去除命令名后的参数
        String name = "World";                                 // → 默认名字
        boolean upper = false;                                 // → 是否大写
        int times = 1;                                         // → 重复次数,默认 1
        for (int i = 0; i < args.length; i++) {                // → 遍历参数
            if ("--uppercase".equals(args[i])) upper = true;   // → 匹配 --uppercase 标志
            else if ("--times".equals(args[i]) && i + 1 < args.length) // → 匹配 --times 标志
                try { times = Integer.parseInt(args[++i]); }   // → 取下一个参数作为次数
                catch (Exception ignored) {}                   // → 解析失败则忽略,使用默认值
            else if (!args[i].startsWith("-")) name = args[i]; // → 不以 - 开头的视为名字
        }
        String msg = "Hello, " + name + "!";                   // → 构造问候语
        if (upper) msg = msg.toUpperCase();                    // → 如果指定了大写,转为大写
        for (int i = 0; i < times; i++)                        // → 按次数输出
            System.out.println(msg);                           // → 打印到标准输出
    }

    // ===== 注册菜单项 =====
    private void registerMenuItems() {
        getContext().registerMenuItem(new MenuItem(            // → 在 GUI 菜单栏添加一项
            "hello_menu",                                      // → ① 菜单项唯一 ID
            "我的插件",                                         // → ② 菜单显示文字
            null,                                              // → ③ 父菜单 ID,null=顶层菜单
            getPluginId(),                                     // → ④ 所属插件 ID
            getName(),                                         // → ⑤ 所属插件名称
            () -> getContext().showGUI("hello_window"),         // → ⑥ 点击回调: 打开 GUI 窗口
            50                                                 // → ⑦ 排序序号
        ));
    }

    // ===== 生命周期: 卸载清理 =====
    @Override
    public void onUnload() {                                   // 宿主调用此方法卸载插件
        getContext().unregisterCommand("hello");               // → 反注册主命令
        getContext().unregisterCommand("hello-gui");           // → 反注册 GUI 命令
        getContext().unregisterMenuItem("hello_menu");          // → 反注册菜单项
        logger.info("插件已卸载");                               // → 记录日志
    }
}

这个示例展示了完整插件的所有关键模式:在 onLoad 注册命令和菜单 → onLoaded 做初始化 → handleHello 手工解析参数 → onUnload 清理注册。不需要 GUI 的插件可以直接删除 registerMenuItems 部分。

17.6 生命周期总结

┌─────────────────────────────────────────────┐
│              插件生命周期                     │
├─────────────────────────────────────────────┤
│ 1. 加载 JAR                                 │
│ 2. new MyPlugin()                           │
│ 3. onLoad(context)  ← 注册命令/菜单/GUI     │
│ 4. onLoaded()       ← 所有注册完成后         │
│                                             │
│ 5. setEnabled(false) → onDisable()         │
│ 6. setEnabled(true)  → onEnable()          │
│                                             │
│ 7. 卸载                                     │
│ 8. onUnload()        ← 清理所有注册          │
└─────────────────────────────────────────────┘

18. 实际插件参考

参考 /home/yiqiu/projects/GYscan/projet_plugin/ 下的示例插件源码:

插件 主命令 GUI 命令 说明
scan port-scan port-scan-gui 端口扫描插件,Nmap 兼容参数
ssh_audit ssh-audit ssh-audit-gui SSH 配置安全审计插件

各插件均遵循以下规范:

  • 1 个 CLI 主命令 (port-scan / ssh-audit),功能通过 -x / --xx / -xx 参数区分
  • 1 个专用 GUI 启动命令 (port-scan-gui / ssh-audit-gui)
  • 插件 ID 为 snake_case,命令名为 kebab-case
  • 插件支持 FlatLaf 主题切换

本文档与 gyscan-sdk-1.0.0.jar 对应. 若代码版本升级, 请以最新 JAR 中实际 API 为准.