parser.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. package mvg
  2. import "encoding/hex"
  3. import "fmt"
  4. import "strconv"
  5. import "strings"
  6. import "golang.org/x/image/colornames"
  7. /* LL(1) syntax.
  8. COMMANDS -> COMMAND COMMANDS | .
  9. COMMAND -> word PARAMS .
  10. PARAMS -> ws PARAM PARAMS | PARAM.
  11. PARAM -> LIST | ELEM | string | id | word | url.
  12. LIST -> ELEM comma LIST | ELEM .
  13. ELEM -> var | number.
  14. */
  15. type Parser struct {
  16. Name string
  17. Buffer []rune
  18. Index int
  19. Line int
  20. }
  21. func (p *Parser) Error(msg string, extra ...interface{}) Error {
  22. form := "%s:%d:" + msg
  23. args := []interface{}{}
  24. args = append(args, p.Name, p.Line)
  25. args = append(args, extra...)
  26. return Error{fmt.Errorf(form, args...)}
  27. }
  28. func (p *Parser) Peek() rune {
  29. if p.Index > len(p.Buffer) {
  30. return -1
  31. }
  32. ru := p.Buffer[p.Index]
  33. return ru
  34. }
  35. func (p *Parser) Next() rune {
  36. ru := p.Peek()
  37. if ru == -1 {
  38. return ru
  39. }
  40. if ru == '\n' {
  41. p.Line++
  42. }
  43. p.Index++
  44. return ru
  45. }
  46. func (p *Parser) ParseWhile(ok func(r rune, i int) bool, found func(string) Value) Value {
  47. var ru rune
  48. val := []rune{}
  49. start := p.Index
  50. ru = p.Next()
  51. if !ok(ru, p.Index-start) {
  52. return nil
  53. }
  54. val = append(val, ru)
  55. for ; ok(ru, p.Index-start); ru = p.Next() {
  56. val = append(val, ru)
  57. }
  58. if ru == -1 {
  59. return p.Error("Unexpected EOF")
  60. }
  61. return found(string(val))
  62. }
  63. func IsID(r rune, i int) bool {
  64. if (i == 0) && (r == '%') {
  65. return true
  66. }
  67. return IsWord(r, i)
  68. }
  69. func IsWord(r rune, i int) bool {
  70. return (r >= 'a' && r <= 'z') ||
  71. (r >= 'A' && r <= 'Z') ||
  72. r == '_' || r == '-'
  73. }
  74. func IsNumber(r rune, i int) bool {
  75. return (r >= '0' && r <= '9') ||
  76. r == '.'
  77. }
  78. type Value interface {
  79. Eval(gc *GraphicContext) Value
  80. }
  81. type Error struct {
  82. error
  83. }
  84. func (e Error) Eval(gc *GraphicContext) Value {
  85. return e
  86. }
  87. type Word string
  88. func (w Word) Eval(gc *GraphicContext) Value {
  89. return w
  90. }
  91. type ID string
  92. func (i ID) Eval(gc *GraphicContext) Value {
  93. return i
  94. }
  95. func (p *Parser) ParseID() Value {
  96. return p.ParseWhile(IsID, func(res string) Value {
  97. return ID(res[1:len(res)]) // chop off the %
  98. })
  99. }
  100. type Variable string
  101. func IsVariable(r rune, i int) bool {
  102. if (i == 0) && (r == '$') {
  103. return true
  104. }
  105. return IsWord(r, i)
  106. }
  107. func (v Variable) Eval(gc *GraphicContext) Value {
  108. var ok bool
  109. var val Value
  110. for val, ok = gc.Variables[string(v)]; !ok; val, ok = gc.Variables[string(v)] {
  111. if gc.Parent == nil {
  112. return Error{fmt.Errorf("Could not evaluate variable: %s", string(v))}
  113. }
  114. gc = gc.Parent
  115. }
  116. return val
  117. }
  118. func (p *Parser) ParseVariable() Value {
  119. return p.ParseWhile(IsVariable, func(res string) Value {
  120. return Variable(res[1:len(res)]) // chop off the $
  121. })
  122. }
  123. type Number float32
  124. func (n Number) Eval(gc *GraphicContext) Value {
  125. return n
  126. }
  127. func (p *Parser) ParseWord() Value {
  128. return p.ParseWhile(IsWord, func(res string) Value {
  129. return Word(res)
  130. })
  131. }
  132. func (p *Parser) ParseNumber() Value {
  133. return p.ParseWhile(IsNumber, func(res string) Value {
  134. f, err := strconv.ParseFloat(res, 32)
  135. if err != nil {
  136. return p.Error("Cannot convert to number: %s, %s", res, err)
  137. }
  138. return Number(f)
  139. })
  140. }
  141. type Ref string
  142. func IsRef(r rune, i int) bool {
  143. if (i == 0) && (r == 'u') {
  144. return true
  145. } else if (i == 1) && (r == 'r') {
  146. return true
  147. } else if (i == 2) && (r == 'l') {
  148. return true
  149. } else if (i == 3) && (r == '(') {
  150. return true
  151. } else if (i == 4) && (r == '#') {
  152. return true
  153. } else if (i > 5) && (r == ')') {
  154. return true
  155. }
  156. return IsWord(r, i)
  157. }
  158. func (p *Parser) ParseRef() Value {
  159. prefix := string(p.Buffer[p.Index : p.Index+4])
  160. if prefix != "url(#" {
  161. return nil
  162. }
  163. return p.ParseWhile(IsRef, func(res string) Value {
  164. return Variable(res[5 : len(res)-1]) // chop off the url(#)
  165. })
  166. }
  167. func (r Ref) Eval(gc *GraphicContext) Value {
  168. var ok bool
  169. var val DefValue
  170. for val, ok = gc.Defs[string(r)]; !ok; val, ok = gc.Defs[string(r)] {
  171. if gc.Parent == nil {
  172. return Error{fmt.Errorf("Could not evaluate reference: %s", string(r))}
  173. }
  174. gc = gc.Parent
  175. }
  176. return val
  177. }
  178. type String string
  179. func IsStringFor(p Parser, between rune) func(r rune, i int) bool {
  180. return func(r rune, i int) bool {
  181. if (i == 0) && (r == between) {
  182. return true
  183. } else if r == between {
  184. return p.Buffer[p.Index+i-1] != '\\'
  185. } else {
  186. return true
  187. }
  188. }
  189. }
  190. var StringEscaper = strings.NewReplacer(
  191. "\\\\", "\\",
  192. "\\n", "\n",
  193. "\\r", "\r",
  194. "\\t", "\t",
  195. )
  196. func (s String) Eval(gc *GraphicContext) Value {
  197. return s
  198. }
  199. func (p *Parser) ParseString() Value {
  200. between := p.Peek()
  201. if between != '\'' && between != '"' && between != '`' {
  202. return nil
  203. }
  204. return p.ParseWhile(IsStringFor(*p, between), func(res string) Value {
  205. mid := res[1:(len(res) - 2)]
  206. return String(StringEscaper.Replace(mid))
  207. })
  208. }
  209. func IsColor(r rune, i int) bool {
  210. if (i == 0) && (r == '#') {
  211. return true
  212. }
  213. return (r >= '0' && r <= '9') ||
  214. (r >= 'a' && r <= 'f') ||
  215. (r >= 'A' && r <= 'F')
  216. }
  217. func StringToColor(str string) (Color, error) {
  218. if str[0] == '#' {
  219. sub := str[1:len(str)]
  220. switch len(sub) {
  221. case 3:
  222. sub = sub[0:0] + sub[0:0] + sub[1:1] + sub[1:1] + sub[2:2] + sub[2:2] + "00"
  223. case 4:
  224. sub = sub[0:0] + sub[0:0] + sub[1:1] + sub[1:1] + sub[2:2] + sub[2:2] + sub[3:3] + sub[3:3]
  225. case 6:
  226. sub = sub + "00"
  227. case 8:
  228. sub = sub
  229. default:
  230. return Color{}, fmt.Errorf("Length of color hex must be 3,4, 6, or 8")
  231. }
  232. b, err := hex.DecodeString(sub)
  233. if err != nil {
  234. return Color{}, err
  235. }
  236. return Color{b[0], b[1], b[2], b[3]}, nil
  237. } else {
  238. col, ok := colornames.Map[str]
  239. var err error = nil
  240. if !ok {
  241. err = fmt.Errorf("Unknown color name: %s", col)
  242. }
  243. return Color(col), err
  244. }
  245. }
  246. func (p *Parser) ParseColor() Value {
  247. return p.ParseWhile(IsColor, func(res string) Value {
  248. col, err := StringToColor(res)
  249. if err != nil {
  250. return p.Error("Could not parse color: %s: %s", res, err)
  251. }
  252. return col
  253. })
  254. }
  255. type ParserFunc func() Value
  256. type ParserList []ParserFunc
  257. func (pl ParserList) OneOf() Value {
  258. for _, parser := range pl {
  259. val := parser()
  260. if val != nil {
  261. return val
  262. }
  263. }
  264. return nil
  265. }
  266. func (p Parser) ParseSeparatedList(parseElem, parseSep ParserFunc) Value {
  267. list := List{}
  268. for elem := parseElem(); elem != nil; elem = parseElem() {
  269. list = append(list, elem)
  270. sep := parseSep()
  271. if sep == nil {
  272. break
  273. }
  274. }
  275. return list
  276. }
  277. type List []Value
  278. func (l List) Eval(gc *GraphicContext) Value {
  279. return l
  280. }
  281. func (p *Parser) ParseElem() Value {
  282. l := ParserList{p.ParseVariable, p.ParseNumber}
  283. return l.OneOf()
  284. }
  285. func (p *Parser) ParseList() Value {
  286. }
  287. /*
  288. COMMANDS -> COMMAND COMMANDS | .
  289. COMMAND -> word PARAMS .
  290. PARAMS -> ws PARAM PARAMS | PARAM.
  291. PARAM -> LIST | ELEM | string | id | word | ref.
  292. LIST -> ELEM comma LIST | ELEM .
  293. ELEM -> var | number.
  294. Drawing Primitives
  295. Here is a complete description of the MVG drawing primitives:
  296. Primitive Description
  297. affine sx,rx,ry,sy,tx,ty
  298. arc x0,y0 x1,y1 a0,a1
  299. bezier x0,y0 ... xn,yn Bezier (spline) requires three or more x,y coordinates
  300. to define its shape. The first and last points are the knots
  301. (preserved coordinates) and any intermediate coordinates are the control points.
  302. If two control points are specified, the line between each end knot and its
  303. sequentially respective control point determines the tangent direction of the
  304. curve at that end. If one control point is specified, the lines from the end
  305. knots to the one control point determines the tangent directions of the curve
  306. at each end. If more than two control points are specified, then the
  307. additional control points act in combination to determine the intermediate
  308. shape of the curve. In order to draw complex curves, it is highly recommended
  309. either to use the Path primitive or to draw multiple four-point bezier segments
  310. with the start and end knots of each successive segment repeated.
  311. border-color color
  312. circle originx,originy perimeterx,perimetery
  313. clip-path url(name)
  314. clip-rule rule Choose from these rule types:
  315. evenodd
  316. nonzero
  317. clip-units units Choose from these unit types:
  318. userSpace
  319. userSpaceOnUse
  320. objectBoundingBox
  321. color x,y method Choose from these method types:
  322. point
  323. replace
  324. floodfill
  325. filltoborder
  326. reset
  327. compliance type Choose from these compliance types: MVG or SVG
  328. decorate type Choose from these types of decorations:
  329. none
  330. line-through
  331. overline
  332. underline
  333. ellipse centerx,centery radiusx,radiusy arcstart,arcstop
  334. fill color Choose from any of these colors.
  335. fill-opacity opacity The opacity ranges from 0.0 (fully transparent) to 1.0
  336. (fully opaque) or as a percentage (e.g. 50%).
  337. fill-rule rule Choose from these rule types:
  338. evenodd
  339. nonzero
  340. font name
  341. font-family family
  342. font-size point-size
  343. font-stretch type Choose from these stretch types:
  344. all
  345. normal
  346. ultra-condensed
  347. extra-condensed
  348. condensed
  349. semi-condensed
  350. semi-expanded
  351. expanded
  352. extra-expanded
  353. ultra-expanded
  354. font-style style Choose from these styles:
  355. all
  356. normal
  357. italic
  358. oblique
  359. font-weight weight Choose from these weights:
  360. all
  361. normal
  362. bold
  363. 100
  364. 200
  365. 300
  366. 400
  367. 500
  368. 600
  369. 700
  370. 800
  371. 900
  372. gradient-units units Choose from these units:
  373. userSpace
  374. userSpaceOnUse
  375. objectBoundingBox
  376. gravity type Choose from these gravity types:
  377. NorthWest
  378. North
  379. NorthEast
  380. West
  381. Center
  382. East
  383. SouthWest
  384. South
  385. SouthEast
  386. image compose x,y width,height 'filename' Choose from these compose operations:
  387. Method Description
  388. clear Both the color and the alpha of the destination are cleared. Neither the source nor the destination are used as input.
  389. src The source is copied to the destination. The destination is not used as input.
  390. dst The destination is left untouched.
  391. src-over The source is composited over the destination.
  392. dst-over The destination is composited over the source and the result replaces the destination.
  393. src-in The part of the source lying inside of the destination replaces the destination.
  394. dst-in The part of the destination lying inside of the source replaces the destination.
  395. src-out The part of the source lying outside of the destination replaces the destination.
  396. dst-out The part of the destination lying outside of the source replaces the destination.
  397. src-atop The part of the source lying inside of the destination is composited onto the destination.
  398. dst-atop The part of the destination lying inside of the source is composited over the source and replaces the destination.
  399. multiply The source is multiplied by the destination and replaces the destination. The resultant color is always at least as dark as either of the two constituent colors. Multiplying any color with black produces black. Multiplying any color with white leaves the original color unchanged.
  400. screen The source and destination are complemented and then multiplied and then replace the destination. The resultant color is always at least as light as either of the two constituent colors. Screening any color with white produces white. Screening any color with black leaves the original color unchanged.
  401. overlay Multiplies or screens the colors, dependent on the destination color. Source colors overlay the destination whilst preserving its highlights and shadows. The destination color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the destination.
  402. darken Selects the darker of the destination and source colors. The destination is replaced with the source when the source is darker, otherwise it is left unchanged.
  403. lighten Selects the lighter of the destination and source colors. The destination is replaced with the source when the source is lighter, otherwise it is left unchanged.
  404. linear-light Increase contrast slightly with an impact on the foreground's tonal values.
  405. color-dodge Brightens the destination color to reflect the source color. Painting with black produces no change.
  406. color-burn Darkens the destination color to reflect the source color. Painting with white produces no change.
  407. hard-light Multiplies or screens the colors, dependent on the source color value. If the source color is lighter than 0.5, the destination is lightened as if it were screened. If the source color is darker than 0.5, the destination is darkened, as if it were multiplied. The degree of lightening or darkening is proportional to the difference between the source color and 0.5. If it is equal to 0.5 the destination is unchanged. Painting with pure black or white produces black or white.
  408. soft-light Darkens or lightens the colors, dependent on the source color value. If the source color is lighter than 0.5, the destination is lightened. If the source color is darker than 0.5, the destination is darkened, as if it were burned in. The degree of darkening or lightening is proportional to the difference between the source color and 0.5. If it is equal to 0.5, the destination is unchanged. Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
  409. plus The source is added to the destination and replaces the destination. This operator is useful for animating a dissolve between two images.
  410. add As per 'plus' but transparency data is treated as matte values. As such any transparent areas in either image remain transparent.
  411. minus Subtract the colors in the source image from the destination image. When transparency is involved, Opaque areas will be subtracted from any destination opaque areas.
  412. subtract Subtract the colors in the source image from the destination image. When transparency is involved transparent areas are subtracted, so only the opaque areas in the source remain opaque in the destination image.
  413. difference Subtracts the darker of the two constituent colors from the lighter. Painting with white inverts the destination color. Painting with black produces no change.
  414. exclusion Produces an effect similar to that of 'difference', but appears as lower contrast. Painting with white inverts the destination color. Painting with black produces no change.
  415. xor The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source.
  416. copy-* Copy the specified channel in the source image to the same channel in the destination image. If the channel specified in the source image does not exist, (which can only happen for methods, 'copy-opacity' or 'copy-black') then it is assumed that the source image is a special grayscale channel image of the values to be copied.
  417. change-mask Replace any destination pixel that is the similar to the source images pixel (as defined by the current -fuzz factor), with transparency.
  418. interline-spacing pixels
  419. interword-spacing pixels
  420. kerning pixels
  421. line x,y x1,y1
  422. matte x,y method Choose from these methods:
  423. point
  424. replace
  425. floodfill
  426. filltoborder
  427. reset
  428. offset offset
  429. opacity opacity Use percent (e.g. 50%).
  430. path path
  431. point x,y
  432. polygon x,y x1,y1, ..., xn,yn
  433. polyline x,y x1,y1, ..., xn,yn
  434. pop clip-path
  435. pop defs
  436. pop gradient
  437. pop graphic-context
  438. pop pattern
  439. push clip-path "name"
  440. push defs
  441. push gradient id linear x,y x1,y1
  442. push gradient id radial xc,cy xf,yf radius
  443. push graphic-context { "id" } the id is optional
  444. push pattern id radial x,y width,height
  445. rectangle x,y x1,y1
  446. rotate angle
  447. roundrectangle x,y x1,y1 width,height
  448. scale x,y
  449. skewX angle
  450. skewX angle
  451. stop-color color offset
  452. stroke color
  453. stroke-antialias 0 • 1
  454. stroke-dasharray none • numeric-list
  455. stroke-dashoffset offset
  456. stroke-linecap type Choose from these cap types:
  457. butt
  458. round
  459. square
  460. stroke-linejoin type Choose from these join types:
  461. bevel
  462. miter
  463. round
  464. stroke-miterlimit limit
  465. stroke-opacity opacity The opacity ranges from 0.0 (fully transparent) to 1.0 (fully opaque) or as a percentage (e.g. 50%).
  466. stroke-width width
  467. text "text"
  468. text-antialias 0 • 1
  469. text-undercolor color
  470. translate x,y
  471. use "url(#id)"
  472. viewbox x,y x1,y1
  473. */