diff --git a/.gitignore b/.gitignore index b9924d2..8f8ef0c 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,11 @@ desktop.ini *.tmp *.bak /out/ + +# 授权文件(按机器绑定,不入库) +/license/*.lic +/dist/license/ + +# 本地打包产物 +/sequence_diagram/ +/*.7z diff --git a/README.md b/README.md index d681416..7bacf4c 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ - **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致 - **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES -## 正式版 V1.0.1 +## 正式版 V1.1.1 **可运行的 Flutter Windows 桌面正式版**(源码在 `lib/`),设计人:呆头鹅。 @@ -98,6 +98,6 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模 - **软件**:时序图设计器 · Sequence Diagram Studio - **设计人**:呆头鹅 -- **版本**:V1.0.1 +- **版本**:V1.1.1 - **版权**:Copyright © 2026 呆头鹅。保留所有权利。 - **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md) diff --git a/docs/HELP.md b/docs/HELP.md index 96311c6..ad52093 100644 --- a/docs/HELP.md +++ b/docs/HELP.md @@ -362,6 +362,20 @@ ms = angle / 360 × cycleMs --- +## O. 授权(License) + +**导出需要授权**:未授权时「导出 SVG / PNG」按钮置灰。 + +1. 打开「帮助 → 关于」,查看**本机 MAC** 与**授权申请邮箱 liuyu65@126.com**; +2. 把本机 MAC 发送到该邮箱申请授权,收到 `.lic` 文件(一行文本); +3. 把 `.lic` 放入软件目录下的 **`license`** 文件夹,重启软件即可导出。 + +授权串算法(管理员用 `tools/keygen/keygen.exe` 图形界面生成): +`MAC → 去横线 → A=01…Z=26(数字 0–9 记 00–09)→ 末尾加 26 → 整串倒序`。 +例:`AA-BB-CC-DD-EE-FF` → `62606050504040303020201010`。 + +--- + ## 附录:快捷键、文件格式、构建 ### 快捷键 diff --git a/lib/license/license_service.dart b/lib/license/license_service.dart new file mode 100644 index 0000000..b9e5eeb --- /dev/null +++ b/lib/license/license_service.dart @@ -0,0 +1,158 @@ +/// 软件授权(License)服务。 +/// +/// 授权模型: +/// - 应用启动时读取可执行文件同级目录下的 `license/*.lic`(每个文件一行文本); +/// - 由**本机 MAC 地址**按固定算法算出期望的授权串,与 .lic 内容比对; +/// - 有效则可导出 SVG / PNG,无效则导出按钮置灰; +/// - 关于页展示授权状态、本机 MAC,并提供「提交授权申请」。 +/// +/// 授权算法(与 keygen 保持一致): +/// 1. MAC `AA-BB-CC-DD-EE-FF` → 去掉横线 / 空格 → `AABBCCDDEEFF`; +/// 2. 每个字符按 `A=01 … Z=26`(数字 `0..9` 记作 `00..09`)转两位十进制; +/// 3. 尾部追加固定串 `26`; +/// 4. 整串倒序,即为 .lic 文件内容。 +/// +/// 例:`AABBCCDDEEFF` → `010102020303040405050606` → 加 `26` +/// → `01010202030304040505060626` → 倒序 → `62606050504040303020201010`。 +library; + +import 'dart:io'; + +/// 授权状态快照。 +class LicenseInfo { + /// 构造授权信息。 + const LicenseInfo({required this.mac, required this.valid, this.filePath, this.content}); + + /// 本机主 MAC 地址(形如 `AA-BB-CC-DD-EE-FF`);读取失败为 null。 + final String? mac; + + /// 是否存在有效授权。 + final bool valid; + + /// 命中的 .lic 文件路径(若有)。 + final String? filePath; + + /// 命中的 .lic 文件内容(若有)。 + final String? content; + + /// 期望的授权串(由本机 MAC 计算);无法获取 MAC 时为 null。 + String? get expected => mac == null ? null : LicenseService.encodeMac(mac!); +} + +/// 授权服务(单例)。 +class LicenseService { + LicenseService._(); + + /// 单例。 + static final LicenseService instance = LicenseService._(); + + LicenseInfo _info = const LicenseInfo(mac: null, valid: false); + + /// 最近一次的授权信息。 + LicenseInfo get info => _info; + + /// 是否已授权。 + bool get licensed => _info.valid; + + /// license 目录(可执行文件同级目录下的 `license`)。 + Directory get licenseDir => Directory('${Directory.current.path}${Platform.pathSeparator}license'); + + /// 初始化:读取 MAC 并校验 `license/*.lic`。 + Future init() async { + final String? mac = await _readMac(); + bool valid = false; + String? hitPath; + String? hitContent; + + final Directory dir = licenseDir; + if (dir.existsSync()) { + final List files = dir + .listSync() + .whereType() + .where((File f) => f.path.toLowerCase().endsWith('.lic')) + .toList() + ..sort((File a, File b) => a.path.compareTo(b.path)); + final String? expected = mac == null ? null : encodeMac(mac); + for (final File f in files) { + String content; + try { + content = f.readAsStringSync().trim(); + } catch (_) { + continue; + } + if (expected != null && content == expected) { + valid = true; + hitPath = f.path; + hitContent = content; + break; + } + } + } + _info = LicenseInfo(mac: mac, valid: valid, filePath: hitPath, content: hitContent); + return _info; + } + + /// 读取本机第一个 MAC 地址(通过系统 `getmac`)。 + Future _readMac() async { + try { + final ProcessResult r = await Process.run( + 'getmac', + ['/fo', 'csv', '/nh'], + runInShell: true, + ); + final String out = '${r.stdout}'; + final Match? m = RegExp(r'([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2}').firstMatch(out); + if (m == null) return null; + return m.group(0)!.toUpperCase().replaceAll(':', '-'); + } catch (_) { + return null; + } + } + + /// 按授权算法,由 [mac] 计算期望的授权串(.lic 内容)。 + static String encodeMac(String mac) { + final String clean = mac.replaceAll(RegExp(r'[^0-9A-Za-z]'), '').toUpperCase(); + final StringBuffer sb = StringBuffer(); + for (final int code in clean.codeUnits) { + int v; + if (code >= 0x30 && code <= 0x39) { + v = code - 0x30; // '0'..'9' -> 0..9 + } else if (code >= 0x41 && code <= 0x5A) { + v = code - 0x40; // 'A'..'Z' -> 1..26 + } else { + continue; + } + sb.write(v.toString().padLeft(2, '0')); + } + sb.write('26'); + final String fwd = sb.toString(); + return String.fromCharCodes(fwd.codeUnits.reversed); + } + + /// 提交授权申请:通过网络(默认邮件客户端)把 MAC 与发件人信息发送到指定邮箱。 + /// + /// 返回 true 表示已成功唤起邮件客户端。 + Future submitApplication({required String sender, String? note}) async { + const String to = 'liuyu65@126.com'; + final String mac = _info.mac ?? '(读取失败)'; + final String subject = Uri.encodeComponent('时序图设计器 V1.1.1 授权申请'); + final String body = Uri.encodeComponent( + 'MAC 地址:$mac\n' + '发件人信息:$sender\n' + '备注:${note ?? '(无)'}\n' + '软件版本:V1.1.1\n', + ); + final String url = 'mailto:$to?subject=$subject&body=$body'; + try { + await Process.run('rundll32', ['url.dll,FileProtocolHandler', url]); + return true; + } catch (_) { + try { + await Process.run('cmd', ['/c', 'start', '', url], runInShell: true); + return true; + } catch (_) { + return false; + } + } + } +} diff --git a/lib/main.dart b/lib/main.dart index 7b607f3..5f77c7e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -10,6 +10,7 @@ import 'dart:ui' show AppExitResponse; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'license/license_service.dart'; import 'model/models.dart'; import 'persistence/storage.dart'; import 'state/app_controller.dart'; @@ -52,6 +53,10 @@ class _SequenceDiagramAppState extends State { super.initState(); _controller = AppController()..start(); _controller.addListener(_updateWindowTitle); + // 启动即校验授权(读取可执行文件同级 license/*.lic)。 + LicenseService.instance.init().then((LicenseInfo info) { + _controller.setLicensed(info.valid); + }); _lifecycle = AppLifecycleListener( onExitRequested: () async { await _controller.markCleanOnExit(); diff --git a/lib/state/app_controller.dart b/lib/state/app_controller.dart index b08128f..202ccdd 100644 --- a/lib/state/app_controller.dart +++ b/lib/state/app_controller.dart @@ -34,6 +34,19 @@ class AppController extends ChangeNotifier { /// 当前主题亮度(默认浅色 / 白底)。 Brightness _brightness = Brightness.light; + /// 是否已获得有效授权(有效时才允许导出 SVG / PNG)。 + bool _licensed = false; + + /// 是否已授权。 + bool get licensed => _licensed; + + /// 设置授权状态并刷新(启动时校验 / 重新读取 .lic 后调用)。 + void setLicensed(bool value) { + if (_licensed == value) return; + _licensed = value; + notifyListeners(); + } + /// 当前项目对应的文件路径;null 表示尚未保存。 String? _filePath; diff --git a/lib/ui/app_shell.dart b/lib/ui/app_shell.dart index 40a4c13..262c9f9 100644 --- a/lib/ui/app_shell.dart +++ b/lib/ui/app_shell.dart @@ -150,6 +150,10 @@ class _AppShellState extends State { /// 导出 SVG:将当前视图交给 [SvgWriter] 生成矢量内容并写入文件。 Future _exportSvg() async { + if (!c.licensed) { + if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。'); + return; + } final String? path = await pickFile(context, save: true, initialPath: c.filePath); if (path == null) return; final String svgPath = path.replaceAll(RegExp(r'\.json$'), '.svg'); @@ -169,6 +173,10 @@ class _AppShellState extends State { /// 导出 PNG:把画布舞台的 [RenderRepaintBoundary] 以 2 倍像素比 /// 渲染为位图并写入文件。 Future _exportPng() async { + if (!c.licensed) { + if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。'); + return; + } final String? path = await pickFile(context, save: true, initialPath: c.filePath); if (path == null) return; final String pngPath = path.replaceAll(RegExp(r'\.(json|svg)$'), '.png'); @@ -347,9 +355,10 @@ class _AppShellState extends State { _segmented(t), ]; right = [ - _primaryBtn(t, '导出 SVG', _exportSvg), + // 未授权时导出按钮置灰(授权有效才允许导出)。 + _primaryBtn(t, '导出 SVG', c.licensed ? _exportSvg : null), const SizedBox(width: 6), - _ghost(t, '导出 PNG', _exportPng), + _ghost(t, '导出 PNG', c.licensed ? _exportPng : null), const SizedBox(width: 6), _zoomBox(t), const SizedBox(width: 6), @@ -384,10 +393,10 @@ class _AppShellState extends State { _segmented(t, compact: true), ]; right = [ - // 导出保持两个独立按钮(不用合并菜单,便于一眼识别)。 - _ghost(t, '导出 SVG', _exportSvg), + // 导出保持两个独立按钮;未授权时置灰。 + _ghost(t, '导出 SVG', c.licensed ? _exportSvg : null), const SizedBox(width: 4), - _ghost(t, '导出 PNG', _exportPng), + _ghost(t, '导出 PNG', c.licensed ? _exportPng : null), const SizedBox(width: 4), _zoomBox(t), _iconBtn(t, Icons.crop_free, c.fitView, tooltip: '适应视图'), @@ -586,13 +595,14 @@ class _AppShellState extends State { ); } - /// 主色填充按钮(用于导出等主要动作)。 - Widget _primaryBtn(Tokens t, String label, VoidCallback onTap) { + /// 主色填充按钮(用于导出等主要动作);[onTap] 为 null 时禁用(置灰)。 + Widget _primaryBtn(Tokens t, String label, VoidCallback? onTap) { + final bool enabled = onTap != null; return FilledButton( onPressed: onTap, style: FilledButton.styleFrom( - backgroundColor: t.accent2, - foregroundColor: Colors.white, + backgroundColor: enabled ? t.accent2 : t.panel2, + foregroundColor: enabled ? Colors.white : t.dim, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), minimumSize: const Size(0, 34), diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index 577edf4..781f2fc 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -11,6 +11,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart' hide Action; +import '../license/license_service.dart'; import '../model/models.dart'; import '../model/units.dart'; import '../state/app_controller.dart'; @@ -1650,15 +1651,8 @@ class HelpDialog extends StatelessWidget { ['导出入口', '导出 SVG / PNG 统一放在顶部工具栏右侧,避免多处重复。'], ['其它', 'F2 编辑时序与节拍参数(含单位与相位分区);F3 切换深/浅主题;Delete 删除选中动作。'], ]), - // 关于:设计人、版本与版权声明。 - _section(t, >[ - ['软件名称', '时序图设计器 · Sequence Diagram Studio'], - ['设计人', '呆头鹅'], - ['版本', 'V1.0.1'], - ['版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'], - ['用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'], - ['技术栈', 'Flutter Desktop · 自绘 Canvas · 纯 Dart 几何 · JSON 持久化 · SVG 导出。'], - ]), + // 关于:设计人、版本、版权、授权信息与本机 MAC。 + _about(context, t), ], ), ), @@ -1677,6 +1671,98 @@ class HelpDialog extends StatelessWidget { ); } + /// 「关于」页:软件信息 + 授权状态 + 本机 MAC + 提交授权申请。 + Widget _about(BuildContext context, Tokens t) { + final LicenseInfo info = LicenseService.instance.info; + final String lic = info.valid + ? '已授权(${info.filePath?.split(RegExp(r'[\\/]')).last ?? '.lic'})' + : '未授权'; + Widget row(String k, String v, {Color? vc}) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text(k, style: TextStyle(color: t.accent, fontWeight: FontWeight.w600, fontSize: 12.5)), + ), + Expanded( + child: SelectableText(v, style: TextStyle(color: vc ?? t.sub, fontSize: 12.5, height: 1.5)), + ), + ], + ), + ); + return ListView( + padding: const EdgeInsets.only(top: 14), + children: [ + row('软件名称', '时序图设计器 · Sequence Diagram Studio'), + row('设计人', '呆头鹅'), + row('版本', 'V1.1.1'), + row('授权状态', lic, vc: info.valid ? t.ok : t.danger), + row('本机 MAC', info.mac ?? '读取失败'), + row('授权申请邮箱', 'liuyu65@126.com'), + if (!info.valid) row('期望授权串', info.expected ?? '(无法获取 MAC)'), + row('版权声明', 'Copyright © 2026 呆头鹅。保留所有权利。'), + row('用途', '面向 PLC 流程节拍 / 相位角设计;未经许可不得用于商业再分发。'), + const SizedBox(height: 4), + if (!info.valid) + Align( + alignment: Alignment.centerLeft, + child: FilledButton.icon( + onPressed: () => _submitApplication(context), + icon: const Icon(Icons.outgoing_mail, size: 16), + label: const Text('提交授权申请(发送 MAC 到 liuyu65@126.com)'), + ), + ), + const SizedBox(height: 10), + Text( + '申请授权:请把上方的「本机 MAC」发送到邮箱 liuyu65@126.com 申请授权;' + '收到 .lic 文件后放入软件目录下的 license 文件夹,重启软件即可导出 SVG / PNG。', + style: TextStyle(color: t.dim, fontSize: 11.5, height: 1.6), + ), + ], + ); + } + + /// 弹出「提交授权申请」对话框,收集发件人信息后唤起系统邮件客户端。 + Future _submitApplication(BuildContext context) async { + final TextEditingController ctrl = TextEditingController(); + final String? sender = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('提交授权申请'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('将把本机 MAC 地址与以下发件人信息发送到 liuyu65@126.com:'), + const SizedBox(height: 10), + TextField( + controller: ctrl, + autofocus: true, + decoration: const InputDecoration(labelText: '发件人信息(单位 / 姓名 / 联系方式)'), + ), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('取消')), + FilledButton(onPressed: () => Navigator.pop(ctx, ctrl.text.trim()), child: const Text('发送')), + ], + ), + ); + ctrl.dispose(); + if (sender == null) return; + final bool ok = await LicenseService.instance + .submitApplication(sender: sender.isEmpty ? '(未填写)' : sender); + if (context.mounted) { + await showMessage( + context, + ok ? '已发起申请' : '发送失败', + ok ? '已调用系统邮件客户端,请确认后发送到 liuyu65@126.com。' : '无法唤起邮件客户端,请手动将 MAC 发送到 liuyu65@126.com。', + ); + } + } + /// 渲染帮助中的一个条目列表,每行左侧为标题、右侧为说明。 Widget _section(Tokens t, List> rows) { return ListView( diff --git a/license/README.md b/license/README.md new file mode 100644 index 0000000..fecea2b --- /dev/null +++ b/license/README.md @@ -0,0 +1,26 @@ +# 授权文件目录(license) + +软件启动时会读取**本目录下所有 `.lic` 文件**,只要其中任意一个与本机 MAC 匹配,即视为已授权。 + +- 已授权:可导出 **SVG / PNG**; +- 未授权:导出按钮**置灰**,关于页可查看本机 MAC 并提交授权申请。 + +## 授权算法 + +1. MAC `AA-BB-CC-DD-EE-FF` → 去掉横线 / 空格 → `AABBCCDDEEFF` +2. 每个字符按 `A=01 … Z=26`(数字 `0..9` 记作 `00..09`)转两位十进制 + → `010102020303040405050606` +3. 尾部追加固定串 `26` → `01010202030304040505060626` +4. 整串**倒序** → `62606050504040303020201010` ← 这就是 `.lic` 文件内容(一行) + +## 生成方式 + +- 使用 `tools/keygen/keygen.exe`(Win32 图形界面):输入本机 MAC,点击「生成」, + 把结果保存为 `license/你的机器名.lic`(一行文本,无换行亦可)。 +- 或手动按上述算法计算。 + +## 说明 + +- `.lic` 文件按机器绑定,请勿把某台机器的 `.lic` 拷到别的机器(MAC 不匹配即无效)。 +- 提交授权申请:软件「帮助 → 关于」中点击「提交授权申请」,会把本机 MAC 与发件人信息 + 发送到 **liuyu65@126.com**。 diff --git a/pubspec.yaml b/pubspec.yaml index c17a236..beaef44 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.1+2 +version: 1.1.1+3 environment: sdk: ^3.13.3 diff --git a/scripts/build.bat b/scripts/build.bat index 95a751f..b22ee7f 100644 --- a/scripts/build.bat +++ b/scripts/build.bat @@ -31,6 +31,9 @@ if exist dist rmdir /s /q dist mkdir dist xcopy /e /i /y /q "build\windows\x64\runner\Release\*" "dist\" >nul +rem Copy the license folder (so .lic files live next to the exe). +if exist license xcopy /e /i /y /q "license\*" "dist\license\" >nul + echo. echo Build OK: dist\sequence_diagram.exe endlocal diff --git a/test/license_test.dart b/test/license_test.dart new file mode 100644 index 0000000..4e48439 --- /dev/null +++ b/test/license_test.dart @@ -0,0 +1,20 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:sequence_diagram/license/license_service.dart'; + +void main() { + group('license', () { + test('encodeMac matches the specified algorithm', () { + // AABBCCDDEEFF -> 010102020303040405050606 -> +26 -> reverse + const String expected = '62606050504040303020201010'; + expect(LicenseService.encodeMac('AA-BB-CC-DD-EE-FF'), expected); + expect(LicenseService.encodeMac('aabbccddeeff'), expected); + expect(LicenseService.encodeMac('AA BB CC DD EE FF'), expected); + expect(LicenseService.encodeMac('AABBCCDDEEFF'), expected); + }); + + test('encodeMac handles digits', () { + // '0'..'9' -> 00..09 ; e.g. "12" -> "0102" -> +"26" -> "010226" -> reverse + expect(LicenseService.encodeMac('12'), '622010'); + }); + }); +} diff --git a/tools/keygen/build.bat b/tools/keygen/build.bat new file mode 100644 index 0000000..5688095 --- /dev/null +++ b/tools/keygen/build.bat @@ -0,0 +1,26 @@ +@echo off +rem Build keygen.exe (Win32 GUI) with MSVC cl.exe. +rem Edit VS_VCVARS below if your Visual Studio lives elsewhere. +setlocal + +set VS_VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Auxiliary\Build\vcvars64.bat +if not exist "%VS_VCVARS%" set VS_VCVARS=C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat +if not exist "%VS_VCVARS%" ( + echo [error] vcvars64.bat not found. Edit VS_VCVARS in this script. + exit /b 1 +) + +call "%VS_VCVARS%" >nul +cd /d "%~dp0" + +rem /utf-8: source (and the Chinese UI strings) are UTF-8. +cl /nologo /O2 /EHsc /utf-8 /DUNICODE /D_UNICODE keygen.cpp /link /SUBSYSTEM:WINDOWS comctl32.lib /OUT:keygen.exe +if errorlevel 1 ( + echo Build failed. + exit /b 1 +) + +del /q keygen.obj >nul 2>nul +echo. +echo Build OK: %~dp0keygen.exe +endlocal diff --git a/tools/keygen/keygen.cpp b/tools/keygen/keygen.cpp new file mode 100644 index 0000000..7548001 --- /dev/null +++ b/tools/keygen/keygen.cpp @@ -0,0 +1,202 @@ +// keygen.cpp -- Win32 GUI license key generator for 时序图设计器. +// +// Enter a MAC address (e.g. AA-BB-CC-DD-EE-FF), press "生成", and copy the +// resulting single-line license string into a .lic file under the app's +// `license` folder. +// +// Algorithm (must match lib/license/license_service.dart): +// 1. strip every non-alphanumeric char, upper-case -> AABBCCDDEEFF +// 2. each char: 'A'..'Z' -> 01..26, '0'..'9' -> 00..09 (2 digits) +// -> 010102020303040405050606 +// 3. append the literal "26" -> ...060626 +// 4. reverse the whole string -> 62606050504040303020201010 +// +// Build: see build.bat (uses MSVC cl.exe, /SUBSYSTEM:WINDOWS). + +#ifndef UNICODE +#define UNICODE +#endif + +#include +#include + +#include +#include + +#pragma comment(lib, "user32.lib") +#pragma comment(lib, "gdi32.lib") + +namespace { + +constexpr int kIdMac = 1001; +constexpr int kIdGen = 1002; +constexpr int kIdResult = 1003; +constexpr int kIdCopy = 1004; + +HWND g_mac = nullptr; +HWND g_result = nullptr; + +std::wstring EncodeMac(const std::wstring& mac) { + std::wstring clean; + for (wchar_t ch : mac) { + if ((ch >= L'0' && ch <= L'9') || (ch >= L'a' && ch <= L'z') || + (ch >= L'A' && ch <= L'Z')) { + clean.push_back(static_cast(towupper(ch))); + } + } + std::wstring fwd; + for (wchar_t ch : clean) { + int v = -1; + if (ch >= L'0' && ch <= L'9') { + v = ch - L'0'; + } else if (ch >= L'A' && ch <= L'Z') { + v = ch - L'A' + 1; + } + if (v < 0) continue; + fwd.push_back(static_cast(L'0' + (v / 10))); + fwd.push_back(static_cast(L'0' + (v % 10))); + } + fwd += L"26"; + std::wstring rev(fwd.rbegin(), fwd.rend()); + return rev; +} + +std::wstring GetText(HWND h) { + const int len = GetWindowTextLengthW(h); + std::wstring s(len > 0 ? len : 0, L'\0'); + if (len > 0) GetWindowTextW(h, &s[0], len + 1); + return s; +} + +void DoGenerate() { + const std::wstring mac = GetText(g_mac); + const std::wstring lic = EncodeMac(mac); + SetWindowTextW(g_result, lic.c_str()); +} + +void DoCopy(HWND owner) { + const std::wstring lic = GetText(g_result); + if (lic.empty()) return; + if (!OpenClipboard(owner)) return; + EmptyClipboard(); + const size_t bytes = (lic.size() + 1) * sizeof(wchar_t); + HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, bytes); + if (mem != nullptr) { + void* dst = GlobalLock(mem); + if (dst != nullptr) { + memcpy(dst, lic.c_str(), bytes); + GlobalUnlock(mem); + SetClipboardData(CF_UNICODETEXT, mem); + } + } + CloseClipboard(); +} + +LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { + switch (msg) { + case WM_CREATE: { + HFONT font = static_cast(GetStockObject(DEFAULT_GUI_FONT)); + auto label = [&](const wchar_t* text, int x, int y, int w, int h) { + HWND c = CreateWindowExW(0, L"STATIC", text, WS_CHILD | WS_VISIBLE, x, + y, w, h, hwnd, nullptr, nullptr, nullptr); + SendMessageW(c, WM_SETFONT, reinterpret_cast(font), TRUE); + }; + label(L"MAC 地址(例如 AA-BB-CC-DD-EE-FF):", 16, 16, 360, 20); + g_mac = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"", WS_CHILD | + WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL, 16, 40, + 420, 28, hwnd, reinterpret_cast(static_cast(kIdMac)), + nullptr, nullptr); + SendMessageW(g_mac, WM_SETFONT, reinterpret_cast(font), TRUE); + + HWND gen = CreateWindowExW(0, L"BUTTON", L"生成授权串", + WS_CHILD | WS_VISIBLE | WS_TABSTOP | + BS_DEFPUSHBUTTON, + 448, 40, 120, 28, hwnd, + reinterpret_cast(static_cast(kIdGen)), nullptr, + nullptr); + SendMessageW(gen, WM_SETFONT, reinterpret_cast(font), TRUE); + + label(L"授权串(保存为 .lic 文件,放入 license 文件夹):", 16, 84, 460, 20); + g_result = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", L"", + WS_CHILD | WS_VISIBLE | ES_READONLY | + ES_AUTOHSCROLL, + 16, 108, 552, 28, hwnd, + reinterpret_cast(static_cast(kIdResult)), nullptr, + nullptr); + SendMessageW(g_result, WM_SETFONT, reinterpret_cast(font), TRUE); + + HWND copy = CreateWindowExW(0, L"BUTTON", L"复制", + WS_CHILD | WS_VISIBLE | WS_TABSTOP, 16, 150, + 120, 30, hwnd, + reinterpret_cast(static_cast(kIdCopy)), nullptr, + nullptr); + SendMessageW(copy, WM_SETFONT, reinterpret_cast(font), TRUE); + + label(L"提示:生成后把结果粘贴到 license\\<机器名>.lic(仅一行)。", + 16, 192, 560, 20); + return 0; + } + case WM_COMMAND: { + switch (LOWORD(wparam)) { + case kIdGen: + DoGenerate(); + return 0; + case kIdCopy: + DoCopy(hwnd); + return 0; + default: + break; + } + break; + } + case WM_CLOSE: + DestroyWindow(hwnd); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + default: + break; + } + return DefWindowProcW(hwnd, msg, wparam, lparam); +} + +} // namespace + +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { + INITCOMMONCONTROLSEX icc{}; + icc.dwSize = sizeof(icc); + icc.dwICC = ICC_STANDARD_CLASSES; + InitCommonControlsEx(&icc); + + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = WndProc; + wc.hInstance = instance; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); + wc.lpszClassName = L"SeqStudioKeygen"; + RegisterClassExW(&wc); + + const int w = 600, h = 260; + const int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2; + const int y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2; + HWND hwnd = CreateWindowExW(0, wc.lpszClassName, L"时序图设计器 · 授权码生成器", + WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | + WS_MINIMIZEBOX, + x, y, w, h, nullptr, nullptr, instance, nullptr); + if (hwnd == nullptr) return 1; + + ShowWindow(hwnd, show); + UpdateWindow(hwnd); + + MSG msg; + while (GetMessageW(&msg, nullptr, 0, 0)) { + if (!IsDialogMessageW(hwnd, &msg)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + return static_cast(msg.wParam); +} diff --git a/tools/keygen/keygen.exe b/tools/keygen/keygen.exe new file mode 100644 index 0000000..7124a7f Binary files /dev/null and b/tools/keygen/keygen.exe differ