Skip to content

API 开发规范

本文说明 Native API 的开发规范,涵盖 IPC 通信、原生模块封装与渲染进程调用方式。

概述

Native API 连接渲染进程与主进程的原生能力,采用 Renderer → IPC → Controller → Bean → Rust 的分层调用链。


架构概览

text
┌─────────────────────────────────────────────────────────────────┐
│                      Renderer Process                           │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  apiService.ts                                           │   │
│  │  - execNativeCommand(commandName, args)                  │   │
│  │  - execWindowsCommand(commandName, args)                 │   │
│  └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
                              │ IPC

┌─────────────────────────────────────────────────────────────────┐
│                       Main Process                               │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  NativeApiController.ts                                  │   │
│  │  - @IpcHandler() 装饰的方法                               │   │
│  │  - 调用 DesktopNative 服务                                │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                   │
│                              ▼                                   │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  DesktopNative.ts (Bean)                                 │   │
│  │  - 封装原生模块调用                                       │   │
│  │  - 提供 fallback 实现                                     │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                   │
│                              ▼                                   │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │  desktop-selection-native (Rust)                         │   │
│  │  - 原生功能实现                                           │   │
│  └─────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

目录结构

text
src/
├── main/
│   ├── beans/
│   │   └── DesktopNative.ts      # 原生模块封装
│   └── controller/
│       ├── NativeApiController.ts # IPC 控制器
│       └── NativeApiTypes.ts      # API 类型定义
├── renderer/
│   └── common/
│       └── apiService.ts          # 渲染进程 API 服务
└── native/desktop_selection/
    └── src/
        └── lib.rs                 # Rust 原生模块

添加新 API 步骤

1. 定义类型(可选)

NativeApiTypes.ts 中定义参数和返回值类型:

typescript
/** 新功能参数接口 */
export interface NewFeatureParams {
  /** 参数1 */
  param1: string;
  /** 参数2 */
  param2?: number;
}

/** 新功能返回值接口 */
export interface NewFeatureResult {
  /** 结果字段 */
  success: boolean;
  /** 数据 */
  data?: any;
}

2. 在 DesktopNative 中添加方法

typescript
// src/main/beans/DesktopNative.ts

/**
 * 新功能方法
 * @param param1 - 参数1说明
 * @param param2 - 参数2说明
 * @returns 返回值说明
 */
public newFeature(param1: string, param2?: number): NewFeatureResult {
  if (this.native) {
    return this.native.newFeature(param1, param2);
  }
  // Fallback 实现
  return { success: false, data: null };
}

3. 在 NativeApiController 中暴露 IPC 方法

typescript
// src/main/controller/NativeApiController.ts

import type { NewFeatureParams, NewFeatureResult } from './NativeApiTypes';

/**
 * 新功能 API
 * @param params - 新功能参数
 * @returns 操作结果
 */
public newFeatureApi(params: NewFeatureParams): ApiResultType<NewFeatureResult> {
  return this.wrapAsync(() => 
    this.desktopNative.newFeature(params.param1, params.param2)
  );
}

4. 在渲染进程中调用

typescript
// 在 Vue 组件或其他渲染进程代码中
import { execNativeCommand } from '@renderer/common/apiService';

const result = await execNativeCommand('newFeatureApi', {
  param1: 'value1',
  param2: 123,
});

if (result.success) {
  console.log('成功:', result.data);
}

API 命名规范

类型命名规则示例
获取数据getXxxApigetInstalledAppsApi
执行操作xxxApimoveMouseApi, pressKeyApi
启动功能startXxxApistartScreenshotApi
停止功能stopXxxApistopHighlightApi
检查状态isXxxRunningApiisScreenshotRunningApi

已有 API 列表

截图相关

API 名称说明
startScreenshotApi启动交互式框选截图
captureAreaApi截取指定区域
isScreenshotRunningApi检查截图是否运行中

鼠标控制

API 名称说明
moveMouseApi移动鼠标到指定位置
getMousePositionApi获取当前鼠标位置
clickMouseApi点击鼠标按钮
doubleClickMouseApi双击鼠标
smoothMoveMouseApi平滑移动鼠标
humanMoveMouseApi模拟人类移动鼠标
scrollMouseApi滚动鼠标滚轮
dragMouseApi拖拽鼠标

键盘控制

API 名称说明
typeStringApi输入字符串
pressKeyApi按下按键
keyDownApi按下并保持按键
keyUpApi释放按键

图像处理

API 名称说明
findImageInDesktopApi在桌面查找图像
findImageApi在图像中查找子图像
findColorApi在图像中查找颜色
cropImageApi裁剪图像
resizeImageApi缩放图像

高亮标注

API 名称说明
highlightAreaApi高亮屏幕区域
highlightRegionsApi高亮多个区域
stopHighlightApi停止所有高亮

Accessibility

API 名称说明
checkAccessibilityPermissionApi检查权限
requestAccessibilityPermissionApi请求权限
getElementAtPositionApi获取指定位置元素
getElementUnderMouseApi获取鼠标下元素
locateElementApi定位元素

元素拾取

API 名称说明
startElementPickerApi启动元素拾取
stopElementPickerApi停止元素拾取
confirmElementPickerApi确认选择
cancelElementPickerApi取消选择

应用管理

API 名称说明
getInstalledAppsApi获取已安装应用列表

错误处理

所有 API 都使用 wrapAsync 包装,自动处理错误:

typescript
private async wrapAsync<T>(fn: () => Promise<T> | T): ApiResultType<T> {
  const result = new CommonResult<T>();
  try {
    result.data = await fn();
  } catch (error: any) {
    result.setError(error.message || '操作失败');
  }
  return result;
}

渲染进程调用时检查结果:

typescript
const result = await execNativeCommand('someApi', params);
if (result.error) {
  console.error('API 调用失败:', result.error);
  return;
}
// 使用 result.data

最佳实践

  1. 类型安全:为所有参数和返回值定义 TypeScript 类型
  2. 错误处理:使用 wrapAsync 统一处理异常
  3. Fallback:在 DesktopNative 中提供原生模块不可用时的 fallback 实现
  4. JSDoc 注释:为所有公开方法添加完整的 JSDoc 注释
  5. 命名一致性:遵循 API 命名规范,方法名以 Api 结尾

企业级桌面 RPA 自动化平台