-
Notifications
You must be signed in to change notification settings - Fork 0
/
pikchr.go
85 lines (70 loc) · 1.34 KB
/
pikchr.go
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
package pikchr
// #cgo LDFLAGS: -lm
// #include "pikchr.h"
// #include <stdlib.h>
import "C"
import (
"unsafe"
)
// Render pikchr source as an SVG.
func Render(src string, in ...Option) (*RenderResult, bool) {
opts := &RenderOptions{}
for _, set := range in {
set(opts)
}
rflags := C.PIKCHR_PLAINTEXT_ERRORS
if opts.DarkMode {
rflags |= C.PIKCHR_DARK_MODE
}
if opts.HTMLTextError {
rflags &^= C.PIKCHR_PLAINTEXT_ERRORS
}
var cname *C.char
if opts.SVGClassName != "" {
cname = C.CString(opts.SVGClassName)
}
w, h := C.int(0), C.int(0)
csrc := C.CString(src)
cres := C.pikchr(
csrc,
cname,
C.uint(rflags),
&w,
&h,
)
C.free(unsafe.Pointer(csrc))
C.free(unsafe.Pointer(cname))
defer C.free(unsafe.Pointer(cres))
res := &RenderResult{
Data: C.GoString(cres),
Width: int(w),
Height: int(h),
}
return res, int(w) > 0
}
type RenderResult struct {
// svg or text of error
Data string
Width, Height int
}
type RenderOptions struct {
HTMLTextError bool
DarkMode bool
SVGClassName string
}
type Option func(*RenderOptions)
func SVGClass(name string) Option {
return func(opts *RenderOptions) {
opts.SVGClassName = name
}
}
func Dark() Option {
return func(opts *RenderOptions) {
opts.DarkMode = true
}
}
func HTMLError() Option {
return func(opts *RenderOptions) {
opts.HTMLTextError = true
}
}