多窗体:新建 / 删除窗体,项目 1 登录示例;标识符支持中文
- 新建窗体:生成与 VS 新建窗体相同的 X.cs 和 X.Designer.cs,沿用工程命名空间; 删除窗体(启动窗体不能删) - 标签页按窗体分组,启动窗体排在最前并默认打开 - 运行时点哪个窗口哪个到最前;消息框始终在所有窗口之上 - 示例:项目 1 任务 1 登录与增加用户,两个窗体的 Designer.cs 由设计器引擎生成; 修正书上未声明的 change 变量、关闭后重复 Show 已释放窗体的问题 - 设计器的正则支持中文控件名、类名、命名空间 - 修正:切换窗体时属性窗口的名称没有刷新 - 测试:多窗体端到端测试;新窗体模板测试 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
02d2f0eabc
commit
8feda289de
19 files changed
+739
-36
No files matched your search
@@ -44,7 +44,8 @@ function reset(prop: PropDef) {
|
||||
// ---------- 名称 ----------
|
||||
const nameDraft = ref('')
|
||||
const nameError = ref<string | null>(null)
|
||||
watch(() => props.selected, () => {
|
||||
// 切换选中的控件或切换到另一个窗体时刷新
|
||||
watch([() => props.selected, () => props.doc.formName], () => {
|
||||
nameDraft.value = props.selected || props.doc.formName
|
||||
nameError.value = null
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -39,7 +39,7 @@ function lineOf(text: string, index: number) {
|
||||
|
||||
/** 找到 class className 的类体结束 "}" 的位置(跳过字符串、字符和注释) */
|
||||
export function classClosingBrace(code: string, className: string): number {
|
||||
const decl = new RegExp(`\\bclass\\s+${className}\\b`).exec(code)
|
||||
const decl = new RegExp(`(?<![\\p{L}\\p{N}_])class\\s+${className}(?![\\p{L}\\p{N}_])`, 'u').exec(code)
|
||||
if (!decl) return -1
|
||||
let i = code.indexOf('{', decl.index)
|
||||
if (i < 0) return -1
|
||||
|
||||
@@ -123,17 +123,17 @@ function skipVerbatim(text: string, i: number) {
|
||||
|
||||
// ---------- 解析 ----------
|
||||
|
||||
const CREATE = /^this\.(\w+) = new ([\w.]+)\(([^()]*)\);$/
|
||||
const LAYOUT = /^this\.(?:(\w+)\.)?(SuspendLayout|ResumeLayout|PerformLayout)\((?:false)?\);$/
|
||||
const INIT = /^\(\(System\.ComponentModel\.ISupportInitialize\)\(this\.(\w+)\)\)\.(BeginInit|EndInit)\(\);$/
|
||||
const EVENT = /^this\.(?:(\w+)\.)?(\w+) \+= new ([\w.]+)\(this\.(\w+)\);$/
|
||||
const ADD = /^this\.(?:(\w+)\.)?Controls\.Add\(this\.(\w+)\);$/
|
||||
const ITEMS = /^this\.(\w+)\.Items\.AddRange\(new object\[\] \{([\s\S]*)\}\);$/
|
||||
const PROP = /^this\.([\w.]+) = ([\s\S]+);$/
|
||||
const CREATE = /^this\.([\p{L}\p{N}_]+) = new ([\p{L}\p{N}_.]+)\(([^()]*)\);$/u
|
||||
const LAYOUT = /^this\.(?:([\p{L}\p{N}_]+)\.)?(SuspendLayout|ResumeLayout|PerformLayout)\((?:false)?\);$/u
|
||||
const INIT = /^\(\(System\.ComponentModel\.ISupportInitialize\)\(this\.([\p{L}\p{N}_]+)\)\)\.(BeginInit|EndInit)\(\);$/u
|
||||
const EVENT = /^this\.(?:([\p{L}\p{N}_]+)\.)?([\p{L}\p{N}_]+) \+= new ([\p{L}\p{N}_.]+)\(this\.([\p{L}\p{N}_]+)\);$/u
|
||||
const ADD = /^this\.(?:([\p{L}\p{N}_]+)\.)?Controls\.Add\(this\.([\p{L}\p{N}_]+)\);$/u
|
||||
const ITEMS = /^this\.([\p{L}\p{N}_]+)\.Items\.AddRange\(new object\[\] \{([\s\S]*)\}\);$/u
|
||||
const PROP = /^this\.([\p{L}\p{N}_.]+) = ([\s\S]+);$/u
|
||||
|
||||
/** 一个 Designer.cs 文件里窗体类的名字:partial class 后面的标识符 */
|
||||
function findFormName(text: string) {
|
||||
const match = /partial\s+class\s+(\w+)/.exec(text)
|
||||
const match = /partial\s+class\s+([\p{L}\p{N}_]+)/u.exec(text)
|
||||
if (!match) throw new DesignerParseError('找不到 partial class 声明')
|
||||
return match[1]
|
||||
}
|
||||
@@ -157,7 +157,7 @@ export function parseDesigner(text: string): DesignerDocument {
|
||||
|
||||
// 第一遍:找出所有创建的控件。只有声明了字段的才算控件——
|
||||
// 窗体属性也可能写成 this.ClientSize = new System.Drawing.Size(...),形式和创建控件一样
|
||||
const fields = new Set([...text.matchAll(/^\s*private\s+[\w.]+\s+(\w+)\s*;/gm)].map((m) => m[1]))
|
||||
const fields = new Set([...text.matchAll(/^\s*private\s+[\p{L}\p{N}_.]+\s+([\p{L}\p{N}_]+)\s*;/gmu)].map((m) => m[1]))
|
||||
const controls = new Set<string>()
|
||||
for (const piece of pieces) {
|
||||
const m = piece.kind === 'stmt' ? CREATE.exec(piece.text) : null
|
||||
@@ -173,7 +173,7 @@ export function parseDesigner(text: string): DesignerDocument {
|
||||
headerLines.push(piece.text)
|
||||
// VS 的块头是三行注释:"// "、"// 名字"、"// "
|
||||
if (headerLines.length === 3) {
|
||||
const name = /^\/\/ (\w+)$/.exec(headerLines[1])?.[1]
|
||||
const name = /^\/\/ ([\p{L}\p{N}_]+)$/u.exec(headerLines[1])?.[1]
|
||||
if (!name || headerLines[0].trim() !== '//' || headerLines[2].trim() !== '//') {
|
||||
throw new DesignerParseError(`无法识别的注释:${headerLines.join(' ')}`)
|
||||
}
|
||||
|
||||
@@ -236,7 +236,7 @@ export function renameControl(doc: DesignerDocument, from: string, to: string):
|
||||
case 'layout':
|
||||
return s.target === from ? { ...s, target: to, text: undefined } : s
|
||||
case 'raw':
|
||||
return s.text.includes(`this.${from}`) ? { kind: 'raw', text: s.text.replace(new RegExp(`\\bthis\\.${from}\\b`, 'g'), `this.${to}`) } : s
|
||||
return s.text.includes(`this.${from}`) ? { kind: 'raw', text: s.text.replace(new RegExp(`(?<![\\p{L}\\p{N}_])this\\.${from}(?![\\p{L}\\p{N}_])`, 'gu'), `this.${to}`) } : s
|
||||
}
|
||||
}
|
||||
next.prologue = next.prologue.map(fix)
|
||||
@@ -245,7 +245,7 @@ export function renameControl(doc: DesignerDocument, from: string, to: string):
|
||||
if (block.name === from) block.name = to
|
||||
block.stmts = block.stmts.map(fix)
|
||||
}
|
||||
next.tail = next.tail.replace(new RegExp(`(private [\\w.]+ )${from};`), `$1${to};`)
|
||||
next.tail = next.tail.replace(new RegExp(`(private [\\p{L}\\p{N}_.]+ )${from};`, 'u'), `$1${to};`)
|
||||
return next
|
||||
}
|
||||
|
||||
@@ -336,7 +336,7 @@ function ensureLayout(doc: DesignerDocument, target: string, op: 'SuspendLayout'
|
||||
|
||||
// ---------- 字段声明 ----------
|
||||
|
||||
const FIELD = /^([ \t]*)private ([\w.]+) (\w+);[ \t]*$/gm
|
||||
const FIELD = /^([ \t]*)private ([\p{L}\p{N}_.]+) ([\p{L}\p{N}_]+);[ \t]*$/gmu
|
||||
|
||||
function addField(tail: string, type: string, name: string, eol: string) {
|
||||
const fields = [...tail.matchAll(FIELD)]
|
||||
@@ -354,7 +354,7 @@ function addField(tail: string, type: string, name: string, eol: string) {
|
||||
}
|
||||
|
||||
function removeField(tail: string, name: string) {
|
||||
return tail.replace(new RegExp(`^[ \\t]*private [\\w.]+ ${name};[ \\t]*\\r?\\n`, 'm'), '')
|
||||
return tail.replace(new RegExp(`^[ \\t]*private [\\p{L}\\p{N}_.]+ ${name};[ \\t]*\\r?\\n`, 'mu'), '')
|
||||
}
|
||||
|
||||
/** 窗体或控件的显示名:窗体用类名 */
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/// <reference types="bun" />
|
||||
import { expect, test } from 'bun:test'
|
||||
import { generateDesigner, parseDesigner } from './document'
|
||||
import { addControl } from './edit'
|
||||
import { controlDef } from './catalog'
|
||||
import { formNameTaken, newFormFiles, nextFormName, projectNamespace, startupForm } from './templates'
|
||||
|
||||
const files = [
|
||||
{ path: 'Program.cs', content: 'namespace 登录\n{\n static class Program\n {\n static void Main()\n {\n Application.Run(new Login());\n }\n }\n}\n' },
|
||||
{ path: 'Login.cs', content: 'namespace 登录\n{\n public partial class Login : Form\n {\n }\n}\n' },
|
||||
]
|
||||
|
||||
test('新窗体沿用工程的命名空间,名字不与已有窗体重复', () => {
|
||||
expect(projectNamespace(files)).toBe('登录')
|
||||
expect(nextFormName(files)).toBe('Form2')
|
||||
expect(formNameTaken(files, 'Login')).toBe(true)
|
||||
expect(startupForm(files)).toBe('Login')
|
||||
})
|
||||
|
||||
test('新窗体的 Designer.cs 能被设计器打开,添加控件后格式正确', () => {
|
||||
const [, designer] = newFormFiles('登录', 'AddUser')
|
||||
const doc = parseDesigner(designer.content)
|
||||
expect(generateDesigner(doc)).toBe(designer.content)
|
||||
expect(doc.formName).toBe('AddUser')
|
||||
const text = generateDesigner(addControl(doc, controlDef('System.Windows.Forms.Button'), '', { x: 10, y: 10 }).doc)
|
||||
expect(text).toContain(' this.button1 = new System.Windows.Forms.Button();\n this.SuspendLayout();')
|
||||
expect(text).toContain(' this.Controls.Add(this.button1);\n this.Name = "AddUser";')
|
||||
expect(text).toContain(' #endregion\n\n private System.Windows.Forms.Button button1;\n }')
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
// 新建窗体:生成与 VS(中文版、.NET Framework 4.5)新建窗体并保存一次后相同的两个文件。
|
||||
import type { SourceFile } from '@iot/shared'
|
||||
|
||||
/** 工程的命名空间:取 Program.cs(没有就取任意 .cs)里的 namespace */
|
||||
export function projectNamespace(files: SourceFile[]): string {
|
||||
const ordered = [...files].sort((a, b) => Number(b.path === 'Program.cs') - Number(a.path === 'Program.cs'))
|
||||
for (const file of ordered) {
|
||||
const m = /^\s*namespace\s+([\p{L}\p{N}_.]+)/mu.exec(file.content)
|
||||
if (m) return m[1]
|
||||
}
|
||||
return 'WindowsFormsApplication1'
|
||||
}
|
||||
|
||||
/** 下一个可用的窗体名:Form2、Form3…… */
|
||||
export function nextFormName(files: SourceFile[]): string {
|
||||
for (let n = 2; ; n++) if (!formNameTaken(files, `Form${n}`)) return `Form${n}`
|
||||
}
|
||||
|
||||
/** 窗体名是否已被使用(同名文件或同名类) */
|
||||
export function formNameTaken(files: SourceFile[], name: string): boolean {
|
||||
return files.some((f) => f.path === `${name}.cs` || f.path === `${name}.Designer.cs` || new RegExp(`(?<![\\p{L}\\p{N}_])class\\s+${name}(?![\\p{L}\\p{N}_])`, 'u').test(f.content))
|
||||
}
|
||||
|
||||
/** Program.cs 里 Application.Run(new X()) 启动的窗体类名 */
|
||||
export function startupForm(files: SourceFile[]): string | undefined {
|
||||
const program = files.find((f) => f.path === 'Program.cs')
|
||||
return program && /Application\.Run\(\s*new\s+([\p{L}\p{N}_]+)\s*\(/u.exec(program.content)?.[1]
|
||||
}
|
||||
|
||||
/** VS 的属性块头:三行注释,第一、三行是 "// "(末尾带空格) */
|
||||
function blockHeader(name: string) {
|
||||
return [' // ', ` // ${name}`, ' // '].join('\n')
|
||||
}
|
||||
|
||||
export function newFormFiles(namespace: string, name: string): SourceFile[] {
|
||||
const code = `using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ${namespace}
|
||||
{
|
||||
public partial class ${name} : Form
|
||||
{
|
||||
public ${name}()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
const designer = `namespace ${namespace}
|
||||
{
|
||||
partial class ${name}
|
||||
{
|
||||
/// <summary>
|
||||
/// 必需的设计器变量。
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// 清理所有正在使用的资源。
|
||||
/// </summary>
|
||||
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows 窗体设计器生成的代码
|
||||
|
||||
/// <summary>
|
||||
/// 设计器支持所需的方法 - 不要
|
||||
/// 使用代码编辑器修改此方法的内容。
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.SuspendLayout();
|
||||
${blockHeader(name)}
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(284, 261);
|
||||
this.Name = "${name}";
|
||||
this.Text = "${name}";
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
`
|
||||
return [
|
||||
{ path: `${name}.cs`, content: code },
|
||||
{ path: `${name}.Designer.cs`, content: designer },
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user