🐉 CNSH 剪贴板翻译 · 鸿蒙原子化服务

DNA: #龍芯⚡️2026-07-08-HARMONYOS-CLIPBOARD-v1.0
支持 HarmonyOS 3.0+ / OpenHarmony 4.0+
可作为原子化服务卡片、快应用、或系统级扩展


项目结构

clipboard-cnsh/
├── entry/
│   └── src/
│       └── main/
│           ├── ets/
│           │   ├── entryability/
│           │   │   └── EntryAbility.ets       # 主入口
│           │   ├── pages/
│           │   │   └── Index.ets              # 主页面
│           │   ├── widget/
│           │   │   └── pages/
│           │   │       └── ClipboardWidget.ets # 服务卡片
│           │   └── common/
│           │       └── CnshAPI.ets            # API调用封装
│           ├── module.json5                    # 模块配置
│           └── resources/
│               └── base/
│                   ├── element/
│                   │   └── string.json
│                   └── media/
│                       └── icon.png
├── oh-package.json5
├── hvigorfile.ts
└── build-profile.json5

核心代码

1. CnshAPI.ets — API调用封装

// CNSH 剪贴板翻译 API 封装
import http from '@ohos.net.http';
import pasteboard from '@ohos.pasteboard';

const API_BASE: string = 'http://192.168.1.100:8777'; // 替换为实际服务器地址

export interface CnshResult {
  状态: string
  DNA: string
  时间戳: { ISO8601: string, 北京时间: string, Unix: number, 锁定: boolean }
  内容指纹: string
  CNSH关键字: Array<{ 关键字: string, 英文: string, 类别: string }>
  完整性哈希: string
  完整性组件: object
  原文: string
  CNSH标注: stringDNA: string[]
  验证指令: string
}

export class CnshAPI {
  // 读取剪贴板
  static async getClipboard(): Promise<string> {
    const systemPasteboard = pasteboard.getSystemPasteboard();
    const data = await systemPasteboard.getData();
    return data.getPrimaryText() ?? '';
  }

  // 调用CNSH翻译API
  static async translate(text: string, parentDna: string = ''): Promise<CnshResult> {
    const httpRequest = http.createHttp();
    const response = await httpRequest.request(
      `${API_BASE}/api/cnsh/clipboard-translate`,
      {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify({
          text: text,
          parent_dna: parentDna
        }),
        connectTimeout: 10000,
        readTimeout: 15000
      }
    );
    httpRequest.destroy();
    return JSON.parse(response.result as string) as CnshResult;
  }

  // 验证完整性
  static async verify(components: object): Promise<{完整: boolean, 说明: string}> {
    const httpRequest = http.createHttp();
    const response = await httpRequest.request(
      `${API_BASE}/api/cnsh/clipboard-verify`,
      {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify({ 完整性组件: components }),
        connectTimeout: 8000,
        readTimeout: 10000
      }
    );
    httpRequest.destroy();
    return JSON.parse(response.result as string);
  }

  // 写入剪贴板
  static async setClipboard(text: string): Promise<void> {
    const systemPasteboard = pasteboard.getSystemPasteboard();
    const pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
    await systemPasteboard.setData(pasteData);
  }
}

2. Index.ets — 主页面

// CNSH 剪贴板翻译 · 主页面
import { CnshAPI, CnshResult } from '../common/CnshAPI';
import promptAction from '@ohos.promptAction';
import pasteboard from '@ohos.pasteboard';

@Entry
@Component
struct CnshClipboardPage {
  @State inputText: string = '';
  @State resultDNA: string = '';
  @State keywords: string = '';
  @State integrityHash: string = '';
  @State timestamp: string = '';
  @State isLoading: boolean = false;
  @State verifyStatus: string = '';
  @State parentDna: string = '';
  private fullResult: CnshResult | null = null;

  // 页面显示时自动读取剪贴板
  async onPageShow() {
    const text = await CnshAPI.getClipboard();
    if (text) {
      this.inputText = text;
    }
  }

  // 执行翻译
  async translate() {
    if (!this.inputText) {
      promptAction.showToast({ message: '请先贴入内容', duration: 2000 });
      return;
    }
    this.isLoading = true;
    try {
      const result = await CnshAPI.translate(this.inputText, this.parentDna);
      this.fullResult = result;
      this.resultDNA = result.DNA;
      this.keywords = `${result.CNSH关键字.length}个关键字`;
      this.integrityHash = result.完整性哈希.substring(0, 16);
      this.timestamp = result.时间戳.北京时间;
      this.verifyStatus = '';

      // 自动复制DNA到剪贴板
      await CnshAPI.setClipboard(result.DNA);
      promptAction.showToast({ message: '✅ CNSH翻译完成·DNA已复制', duration: 2000 });
    } catch (e) {
      promptAction.showToast({ message: `🔴 翻译失败: ${JSON.stringify(e)}`, duration: 3000 });
    } finally {
      this.isLoading = false;
    }
  }

  // 验证完整性
  async verify() {
    if (!this.fullResult?.完整性组件) {
      promptAction.showToast({ message: '请先执行翻译', duration: 2000 });
      return;
    }
    try {
      const v = await CnshAPI.verify(this.fullResult.完整性组件);
      this.verifyStatus = v.完整 ? '✅ 完整性通过' : '🔴 完整性断裂·不可使用';
    } catch (e) {
      this.verifyStatus = `验证失败: ${JSON.stringify(e)}`;
    }
  }

  build() {
    Column() {
      // 标题栏
      Row() {
        Text('🏦 CNSH 剪贴板翻译')
          .fontSize(18)
          .fontWeight(600)
          .fontColor('#d4a574')
      }
      .width('100%')
      .padding(16)
      .backgroundColor('#1a1a2e')

      // 内容区
      Scroll() {
        Column({ space: 12 }) {
          // 贴入提示
          Button('📋 从剪贴板读取')
            .width('100%')
            .height(48)
            .fontSize(15)
            .backgroundColor('#2a2a3e')
            .fontColor('#e0d6c2')
            .borderRadius(12)
            .onClick(async () => {
              const t = await CnshAPI.getClipboard();
              if (t) this.inputText = t;
            })

          // 父DNA输入
          TextInput({ placeholder: '父DNA码(可选·链式协作)', text: this.parentDna })
            .width('100%')
            .height(40)
            .fontSize(13)
            .backgroundColor('#16213e')
            .fontColor('#e0d6c2')
            .borderRadius(8)
            .placeholderColor('#8a8a9a')
            .onChange((v: string) => { this.parentDna = v; })

          // 文本预览
          if (this.inputText) {
            Text(this.inputText)
              .maxLines(5)
              .textOverflow({ overflow: TextOverflow.Ellipsis })
              .fontSize(13)
              .fontColor('#8a8a9a')
              .padding(12)
              .backgroundColor('#2a2a3e')
              .borderRadius(8)
              .width('100%')
          }

          // 翻译按钮
          Button(this.isLoading ? '⏳ 翻译中...' : '🔮 翻译·注入DNA')
            .width('100%')
            .height(52)
            .fontSize(16)
            .fontWeight(600)
            .backgroundColor('#d4a574')
            .fontColor('#1a1a2e')
            .borderRadius(12)
            .enabled(!this.isLoading)
            .onClick(() => { this.translate(); })

          // 结果展示
          if (this.resultDNA) {
            Column({ space: 8 }) {
              Text('📦 翻译结果')
                .fontSize(14)
                .fontWeight(500)
                .fontColor('#d4a574')
                .width('100%')

              // DNA码
              Row() {
                Text('🧬 DNA')
                  .fontSize(11)
                  .fontColor('#8a8a9a')
                  .width(70)
                Text(this.resultDNA)
                  .fontSize(11)
                  .fontColor('#d4a574')
                  .fontFamily('monospace')
                  .layoutWeight(1)
                  .textOverflow({ overflow: TextOverflow.Ellipsis })
              }

              // 时间戳
              Row() {
                Text('🔒 时间戳')
                  .fontSize(11)
                  .fontColor('#8a8a9a')
                  .width(70)
                Text(this.timestamp)
                  .fontSize(11)
                  .fontColor('#e0d6c2')
              }

              // 关键字
              Row() {
                Text('🏷 关键字')
                  .fontSize(11)
                  .fontColor('#8a8a9a')
                  .width(70)
                Text(this.keywords)
                  .fontSize(11)
                  .fontColor('#0ff')
              }

              // 完整性哈希
              Row() {
                Text('🧬 完整性')
                  .fontSize(11)
                  .fontColor('#8a8a9a')
                  .width(70)
                Text(`${this.integrityHash}...`)
                  .fontSize(11)
                  .fontColor('#2ecc71')
                  .fontFamily('monospace')
              }

              Divider().color('#2a2a3e')

              // 验证按钮
              Row({ space: 8 }) {
                Button('🔍 验证完整性')
                  .fontSize(12)
                  .backgroundColor('#2a2a3e')
                  .fontColor('#e0d6c2')
                  .borderRadius(8)
                  .height(36)
                  .onClick(() => { this.verify(); })

                Button('📋 复制JSON包')
                  .fontSize(12)
                  .backgroundColor('#2a2a3e')
                  .fontColor('#e0d6c2')
                  .borderRadius(8)
                  .height(36)
                  .onClick(async () => {
                    if (this.fullResult) {
                      await CnshAPI.setClipboard(JSON.stringify(this.fullResult, null, 2));
                      promptAction.showToast({ message: '✅ JSON包已复制', duration: 2000 });
                    }
                  })
              }
              .width('100%')
              .justifyContent(FlexAlign.SpaceEvenly)

              // 验证结果
              if (this.verifyStatus) {
                Text(this.verifyStatus)
                  .fontSize(12)
                  .fontColor(this.verifyStatus.startsWith('✅') ? '#2ecc71' : '#e74c3c')
                  .padding(8)
                  .borderRadius(6)
                  .backgroundColor(this.verifyStatus.startsWith('✅') ? 'rgba(46,204,113,0.1)' : 'rgba(231,76,60,0.1)')
                  .width('100%')
                  .textAlign(TextAlign.Center)
              }
            }
            .padding(16)
            .backgroundColor('#1a1a2e')
            .borderRadius(12)
            .border({ width: 1, color: '#d4a574' })
            .width('100%')
          }
        }
        .padding(16)
      }
      .layoutWeight(1)
      .scrollBar(BarState.Auto)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#0f0f1a')
  }
}

3. ClipboardWidget.ets — 服务卡片(桌面小组件)

// CNSH 剪贴板翻译 · 2×2 服务卡片
import { CnshAPI } from '../../common/CnshAPI';
import promptAction from '@ohos.promptAction';

@Entry
@Component
struct ClipboardWidget {
  @LocalStorageProp('dnaText') dnaText: string = '点击翻译';
  private text: string = '';

  async aboutToAppear() {
    // 卡片加载时读取剪贴板
    this.text = await CnshAPI.getClipboard();
  }

  build() {
    Stack() {
      Column({ space: 6 }) {
        Text('🏦')
          .fontSize(24)
        Text('CNSH翻译')
          .fontSize(13)
          .fontWeight(500)
          .fontColor('#d4a574')
        Text(this.dnaText)
          .fontSize(10)
          .fontColor('#8a8a9a')
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Center)
      .alignItems(HorizontalAlign.Center)
      .backgroundColor('#1a1a2e')
      .borderRadius(12)
      .onClick(async () => {
        try {
          const result = await CnshAPI.translate(this.text);
          await CnshAPI.setClipboard(result.DNA);
          promptAction.showToast({ message: '✅ 已注入DNA', duration: 1500 });
          postCardAction(this, {
            action: 'router',
            abilityName: 'EntryAbility',
            params: { result: JSON.stringify(result) }
          });
        } catch (e) {
          promptAction.showToast({ message: '🔴 翻译失败', duration: 1500 });
        }
      })
    }
    .width('100%')
    .height('100%')
  }
}

4. module.json5 — 模块配置

{
  "module": {
    "name": "entry",
    "type": "entry",
    "srcEntry": "./ets/entryability/EntryAbility.ets",
    "description": "CNSH 剪贴板翻译·DNA注入·时间戳锁定",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet", "2in1"],
    "deliveryWithInstall": true,
    "installationFree": true,
    "pages": "$profile:main_pages",
    "abilities": [{
      "name": "EntryAbility",
      "srcEntry": "./ets/entryability/EntryAbility.ets",
      "launchType": "standard",
      "visible": true
    }],
    "extensionAbilities": [{
      "name": "ClipboardWidget",
      "srcEntry": "./ets/widget/pages/ClipboardWidget.ets",
      "type": "form",
      "metadata": [{
        "name": "ohos.extension.form",
        "resource": "$profile:form_config"
      }]
    }],
    "requestPermissions": [
      { "name": "ohos.permission.READ_PASTEBOARD" },
      { "name": "ohos.permission.INTERNET" }
    ]
  }
}

安装方法

方法1:DevEco Studio 编译安装

# 在 DevEco Studio 中打开此项目
# 连接鸿蒙设备 → 点击运行

方法2:HAP 包侧载

hdc install entry-default-signed.hap

方法3:原子化服务上架

  • 在 AppGallery Connect 提交为原子化服务
  • 用户无需安装,即点即用

使用方式

方式 说明
桌面服务卡片 2×2卡片·点击即翻译剪贴板
快应用入口 即点即用·无需安装
全局搜索 搜索"CNSH"直接触发
智慧语音 说"翻译剪贴板CNSH"即可
负一屏 添加到负一屏快速访问

中国国产系统拓展

系统 实现方式 说明
鸿蒙 3.0+ 原子化服务卡片 本方案
鸿蒙 Next ArkUI + 原生权限 API 完全兼容
OpenHarmony 同上 开源鸿蒙编译运行
统信UOS Deepin .deb 包 系统托盘 + 全局快捷键
麒麟OS .deb/.rpm 系统托盘 + 剪贴板守护
深度OS Deepin Widget 与鸿蒙服务卡片同设计

所有国产系统统一使用同一套 API 后端,客户端只负责剪贴板读取+展示。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐