smooth-frame 0.2.0

Generate Sketch-like smooth corner and smooth frame cubic Bezier paths.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use smooth_frame::{PathCommand, Point, SmoothRect};
use std::env;
use std::path::{Path, PathBuf};

const SKETCHTOOL_TOLERANCE: f64 = 1.0e-5;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SvgCommand {
    MoveTo(Point),
    LineTo(Point),
    CubicTo {
        ctrl1: Point,
        ctrl2: Point,
        to: Point,
    },
    Close,
}

#[derive(Debug)]
pub struct SketchtoolCase {
    name: String,
    width: f64,
    height: f64,
    radius: f64,
    smoothing: f64,
    path: String,
}

#[derive(Debug)]
pub struct CaseResult {
    suite: String,
    width: f64,
    height: f64,
    smoothing: f64,
    radius: f64,
    command_shape: String,
    max_diff: f64,
}

#[derive(Debug)]
struct SummaryRow {
    suite: String,
    size: String,
    smoothing: String,
    radii: Vec<f64>,
    command_shape: String,
    max_diff: f64,
}

impl From<PathCommand> for SvgCommand {
    // 将库路径命令转换成测试侧 SVG 命令表示。
    fn from(command: PathCommand) -> Self {
        match command {
            PathCommand::MoveTo(point) => SvgCommand::MoveTo(point),
            PathCommand::LineTo(point) => SvgCommand::LineTo(point),
            PathCommand::CubicTo { ctrl1, ctrl2, to } => SvgCommand::CubicTo { ctrl1, ctrl2, to },
            PathCommand::Close => SvgCommand::Close,
        }
    }
}

// 查找本机可用的 SketchTool 可执行文件。
pub fn find_sketchtool() -> Option<PathBuf> {
    if let Some(path) = env::var_os("SMOOTH_FRAME_SKETCHTOOL").map(PathBuf::from) {
        return path.exists().then_some(path);
    }

    let bundled = PathBuf::from("/Applications/Sketch.app/Contents/MacOS/sketchtool");
    if bundled.exists() {
        return Some(bundled);
    }

    env::var_os("PATH")?
        .to_string_lossy()
        .split(':')
        .map(|path| Path::new(path).join("sketchtool"))
        .find(|path| path.exists())
}

// 生成用于批量导出 Sketch smooth rect 的 JavaScript 脚本。
pub fn sketchtool_script() -> String {
    r#"
var api=require('sketch');

function attrValue(svg, tagName, attrName) {
  var tagStart = svg.indexOf('<' + tagName + ' ');
  if (tagStart < 0) return null;
  var attrStart = svg.indexOf(' ' + attrName + '="', tagStart);
  if (attrStart < 0) return null;
  attrStart += attrName.length + 3;
  var attrEnd = svg.indexOf('"', attrStart);
  return svg.slice(attrStart, attrEnd);
}

function extractPathData(svg) {
  var path = attrValue(svg, 'path', 'd');
  if (path) return path;

  var points = attrValue(svg, 'polygon', 'points');
  if (points) {
    var nums = points.trim().split(/[ ,]+/).filter(Boolean);
    var d = '';
    for (var i = 0; i < nums.length; i += 2) {
      d += (i === 0 ? 'M' : ' L') + nums[i] + ',' + nums[i + 1];
    }
    return d + ' Z';
  }

  return 'NO_PATH';
}

function emit(name, width, height, radius, smoothing) {
  var shape=new api.ShapePath({
    name:name,
    frame:new api.Rectangle(0,0,width,height)
  });
  shape.style.fills=[{color:'#000000FF'}];
  shape.style.borders=[];
  shape.style.corners={
    style:api.Style.CornerStyle.Smooth,
    radii:[radius,radius,radius,radius],
    smoothing:smoothing
  };
  page.layers.push(shape);
  var svg=String(api.export(shape,{formats:['svg'], output:null}));
  var d=extractPathData(svg);
  console.log(['SFCASE', name, width, height, radius, smoothing, d].join('\t'));
  shape.remove();
}

var doc=new api.Document();
var page=doc.selectedPage;

for (var radius=0; radius<=500; radius++) {
  emit('square_r_'+radius, 1000, 1000, radius, 0.6);
}

var smoothings=[0,0.3,0.6,0.8,1.0];
var smoothingRadii=[0,1,100,250,400,500];
for (var si=0; si<smoothings.length; si++) {
  for (var ri=0; ri<smoothingRadii.length; ri++) {
    emit(
      'smoothing_'+smoothings[si]+'_r_'+smoothingRadii[ri],
      1000,
      1000,
      smoothingRadii[ri],
      smoothings[si]
    );
  }
}

var rects=[
  [1000,500,250],
  [500,1000,250],
  [1200,300,150],
  [300,1200,150],
  [1024,768,384]
];
for (var di=0; di<rects.length; di++) {
  var item=rects[di];
  for (var rr=0; rr<=item[2]; rr++) {
    emit('rect_'+item[0]+'x'+item[1]+'_r_'+rr, item[0], item[1], rr, 0.6);
  }
}

try { doc.close(); } catch(e) {}
"#
    .to_owned()
}

// 从 SketchTool stdout 中解析所有对齐用例。
pub fn parse_sketchtool_cases(stdout: &str) -> Vec<SketchtoolCase> {
    stdout
        .lines()
        .filter_map(|line| {
            let line = clean_sketch_console_line(line);
            let line = line.get(line.find("SFCASE")?..)?;
            let line = line.replace("\\t", "\t");
            let mut parts = line.splitn(7, '\t');
            if parts.next()? != "SFCASE" {
                return None;
            }

            Some(SketchtoolCase {
                name: parts.next()?.to_owned(),
                width: parts.next()?.parse().expect("width 解析失败"),
                height: parts.next()?.parse().expect("height 解析失败"),
                radius: parts.next()?.parse().expect("radius 解析失败"),
                smoothing: parts.next()?.parse().expect("smoothing 解析失败"),
                path: parts.next()?.to_owned(),
            })
        })
        .collect()
}

// 断言单个 SketchTool 用例与本库输出一致。
pub fn assert_case_matches(case: SketchtoolCase) -> CaseResult {
    let sketch_commands = parse_svg_path(&case.path);
    let ours = SmoothRect::new(case.width, case.height)
        .with_radius(case.radius)
        .with_smoothing(case.smoothing)
        .to_path();
    let our_commands = ours
        .commands()
        .iter()
        .copied()
        .map(SvgCommand::from)
        .collect::<Vec<_>>();

    assert_eq!(
        sketch_commands.len(),
        our_commands.len(),
        "case={} width={} height={} radius={} smoothing={} sketch={:?} ours={:?}",
        case.name,
        case.width,
        case.height,
        case.radius,
        case.smoothing,
        sketch_commands,
        our_commands
    );

    let mut max_diff: f64 = 0.0;
    for (index, (actual, expected)) in sketch_commands.iter().zip(our_commands.iter()).enumerate() {
        max_diff = max_diff.max(assert_svg_command_close(
            *actual, *expected, &case.name, index,
        ));
    }

    CaseResult {
        suite: case_suite(&case.name),
        width: case.width,
        height: case.height,
        smoothing: case.smoothing,
        radius: case.radius,
        command_shape: command_shape(&sketch_commands),
        max_diff,
    }
}

// 打印 SketchTool 对齐结果的汇总表。
pub fn print_alignment_table(results: &[CaseResult]) {
    let mut rows: Vec<SummaryRow> = Vec::new();

    for result in results {
        let size = format_number(result.width, 0) + "x" + &format_number(result.height, 0);
        let smoothing = format_number(result.smoothing, 3);
        if let Some(row) = rows.iter_mut().find(|row| {
            row.suite == result.suite
                && row.size == size
                && row.smoothing == smoothing
                && row.command_shape == result.command_shape
        }) {
            row.radii.push(result.radius);
            row.max_diff = row.max_diff.max(result.max_diff);
        } else {
            rows.push(SummaryRow {
                suite: result.suite.clone(),
                size,
                smoothing,
                radii: vec![result.radius],
                command_shape: result.command_shape.clone(),
                max_diff: result.max_diff,
            });
        }
    }

    rows.sort_by(|a, b| {
        a.suite
            .cmp(&b.suite)
            .then(a.size.cmp(&b.size))
            .then(a.smoothing.cmp(&b.smoothing))
            .then(
                a.radii
                    .first()
                    .partial_cmp(&b.radii.first())
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
            .then(a.command_shape.cmp(&b.command_shape))
    });

    println!();
    println!("SketchTool 对齐结果表");
    println!("| 用例组 | 尺寸 | smoothing | radius | 命令结构 | 用例数 | 最大误差 | 结果 |");
    println!("|---|---:|---:|---:|---:|---:|---:|---|");
    for row in rows {
        println!(
            "| {} | {} | {} | {} | {} | {} | {:.9} | 通过 |",
            row.suite,
            row.size,
            row.smoothing,
            format_radii(&row.radii),
            row.command_shape,
            row.radii.len(),
            row.max_diff
        );
    }
}

// 清理 Sketch 控制台输出中可能包裹的引号。
fn clean_sketch_console_line(line: &str) -> &str {
    let line = line.trim();
    if line.len() >= 2 && line.starts_with('\'') && line.ends_with('\'') {
        &line[1..line.len() - 1]
    } else {
        line
    }
}

// 根据用例名称判断所属测试矩阵。
fn case_suite(name: &str) -> String {
    if name.starts_with("square_r_") {
        "square-radius-sweep".to_owned()
    } else if name.starts_with("smoothing_") {
        "smoothing-matrix".to_owned()
    } else if name.starts_with("rect_") {
        "rect-ratio-sweep".to_owned()
    } else {
        "other".to_owned()
    }
}

// 统计 SVG 命令序列中的命令结构。
fn command_shape(commands: &[SvgCommand]) -> String {
    let mut moves = 0;
    let mut lines = 0;
    let mut cubics = 0;
    let mut closes = 0;
    for command in commands {
        match command {
            SvgCommand::MoveTo(_) => moves += 1,
            SvgCommand::LineTo(_) => lines += 1,
            SvgCommand::CubicTo { .. } => cubics += 1,
            SvgCommand::Close => closes += 1,
        }
    }
    format!("M{moves} L{lines} C{cubics} Z{closes}")
}

// 将连续半径合并成便于阅读的区间字符串。
fn format_radii(radii: &[f64]) -> String {
    let mut radii = radii.to_vec();
    radii.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    radii.dedup_by(|a, b| (*a - *b).abs() <= f64::EPSILON);

    let mut ranges = Vec::new();
    let mut index = 0;
    while index < radii.len() {
        let start = radii[index] as i64;
        let mut end = start;
        index += 1;
        while index < radii.len() && radii[index] as i64 == end + 1 {
            end += 1;
            index += 1;
        }

        if start == end {
            ranges.push(start.to_string());
        } else {
            ranges.push(format!("{start}-{end}"));
        }
    }

    ranges.join(",")
}

// 解析 SketchTool 导出的 SVG path data。
fn parse_svg_path(path: &str) -> Vec<SvgCommand> {
    let tokens = tokenize_svg_path(path);
    let mut cursor = 0;
    let mut current_command = None;
    let mut commands = Vec::new();

    while cursor < tokens.len() {
        if let Token::Command(command) = tokens[cursor] {
            current_command = Some(command);
            cursor += 1;
        }

        match current_command.expect("SVG path 缺少命令") {
            'M' => {
                let point = read_point(&tokens, &mut cursor);
                commands.push(SvgCommand::MoveTo(point));
                current_command = Some('L');
            }
            'L' => {
                let point = read_point(&tokens, &mut cursor);
                commands.push(SvgCommand::LineTo(point));
            }
            'C' => {
                let ctrl1 = read_point(&tokens, &mut cursor);
                let ctrl2 = read_point(&tokens, &mut cursor);
                let to = read_point(&tokens, &mut cursor);
                commands.push(SvgCommand::CubicTo { ctrl1, ctrl2, to });
            }
            'Z' => {
                commands.push(SvgCommand::Close);
                current_command = None;
            }
            command => panic!("暂不支持的 SVG 命令:{command}"),
        }
    }

    commands
}

#[derive(Debug, Clone, Copy)]
enum Token {
    Command(char),
    Number(f64),
}

// 将 SVG path 字符串切分成命令和数字 token。
fn tokenize_svg_path(path: &str) -> Vec<Token> {
    let chars = path.chars().collect::<Vec<_>>();
    let mut cursor = 0;
    let mut tokens = Vec::new();

    while cursor < chars.len() {
        let ch = chars[cursor];
        if ch.is_ascii_whitespace() || ch == ',' {
            cursor += 1;
            continue;
        }
        if matches!(ch, 'M' | 'L' | 'C' | 'Z') {
            tokens.push(Token::Command(ch));
            cursor += 1;
            continue;
        }

        let start = cursor;
        cursor += 1;
        while cursor < chars.len() {
            let ch = chars[cursor];
            let prev = chars[cursor - 1];
            if ch.is_ascii_digit() || ch == '.' || ch == 'e' || ch == 'E' {
                cursor += 1;
            } else if (ch == '-' || ch == '+') && (prev == 'e' || prev == 'E') {
                cursor += 1;
            } else {
                break;
            }
        }

        let number = chars[start..cursor]
            .iter()
            .collect::<String>()
            .parse::<f64>()
            .expect("SVG path 数字解析失败");
        tokens.push(Token::Number(number));
    }

    tokens
}

// 从 token 流中读取一个二维点。
fn read_point(tokens: &[Token], cursor: &mut usize) -> Point {
    Point::new(read_number(tokens, cursor), read_number(tokens, cursor))
}

// 从 token 流中读取一个浮点数。
fn read_number(tokens: &[Token], cursor: &mut usize) -> f64 {
    let number = match tokens.get(*cursor) {
        Some(Token::Number(number)) => *number,
        other => panic!("期望 SVG 数字,实际为:{other:?}"),
    };
    *cursor += 1;
    number
}

// 断言两个 SVG 命令在容差内一致并返回最大误差。
fn assert_svg_command_close(
    actual: SvgCommand,
    expected: SvgCommand,
    case_name: &str,
    index: usize,
) -> f64 {
    match (actual, expected) {
        (SvgCommand::MoveTo(actual), SvgCommand::MoveTo(expected))
        | (SvgCommand::LineTo(actual), SvgCommand::LineTo(expected)) => {
            assert_point_close(actual, expected, case_name, index)
        }
        (
            SvgCommand::CubicTo {
                ctrl1: actual_ctrl1,
                ctrl2: actual_ctrl2,
                to: actual_to,
            },
            SvgCommand::CubicTo {
                ctrl1: expected_ctrl1,
                ctrl2: expected_ctrl2,
                to: expected_to,
            },
        ) => {
            let ctrl1_diff = assert_point_close(actual_ctrl1, expected_ctrl1, case_name, index);
            let ctrl2_diff = assert_point_close(actual_ctrl2, expected_ctrl2, case_name, index);
            let to_diff = assert_point_close(actual_to, expected_to, case_name, index);
            ctrl1_diff.max(ctrl2_diff).max(to_diff)
        }
        (SvgCommand::Close, SvgCommand::Close) => 0.0,
        _ => panic!(
            "case={case_name} 第 {index} 条 SVG 命令类型不匹配:actual={actual:?}, expected={expected:?}"
        ),
    }
}

// 断言两个点在 SketchTool 对齐容差内一致。
fn assert_point_close(actual: Point, expected: Point, case_name: &str, index: usize) -> f64 {
    let x_diff = assert_number_close(actual.x, expected.x, case_name, index);
    let y_diff = assert_number_close(actual.y, expected.y, case_name, index);
    x_diff.max(y_diff)
}

// 断言两个浮点数在 SketchTool 对齐容差内一致。
fn assert_number_close(actual: f64, expected: f64, case_name: &str, index: usize) -> f64 {
    let diff = (actual - expected).abs();
    assert!(
        diff <= SKETCHTOOL_TOLERANCE,
        "case={case_name} 第 {index} 条命令数值不匹配:actual={actual}, expected={expected}, diff={}",
        diff
    );
    diff
}

// 按指定精度格式化测试汇总中的数字。
fn format_number(value: f64, precision: usize) -> String {
    let mut text = format!("{value:.precision$}");
    if text.contains('.') {
        while text.ends_with('0') {
            text.pop();
        }
        if text.ends_with('.') {
            text.pop();
        }
    }
    text
}