metafile.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. package metafile
  2. /*
  3. metafile.go - Windows metafiles (WMF / EMF) as pictures a browser can show
  4. Decks and documents made with older Office versions often carry their
  5. pictures as Windows metafiles: a scanned figure pasted into PowerPoint
  6. 2003 is stored as a .wmf whose only drawing record stretches one DIB
  7. over the frame, and diagrams are .emf drawings. No browser decodes
  8. either format, so the editor showed an empty frame. The import plays
  9. the metafile into a raster image instead (wmf.go and
  10. emf.go read the records; this file holds the canvas they draw
  11. on and the DIB decoder both formats share).
  12. Supported: bitmap records (stretched, mirrored, the common raster ops),
  13. pens and brushes, lines, polylines, polygons, rectangles, rounded
  14. rectangles, ellipses, arcs / pies / chords, Bezier curves, EMF paths,
  15. world transforms and text. Clipping regions and EMF+ records (the dual
  16. EMF+ files carry a plain EMF fallback that is played instead) are not.
  17. A picture that is only bitmaps is rendered at the bitmap's own
  18. resolution so no detail is lost or invented; a drawing is rendered at
  19. twice its 96 DPI size so it stays sharp on a high density screen.
  20. */
  21. import (
  22. "bytes"
  23. "encoding/binary"
  24. "errors"
  25. "image"
  26. "image/color"
  27. "image/jpeg"
  28. "image/png"
  29. "math"
  30. "strings"
  31. "sync"
  32. xdraw "golang.org/x/image/draw"
  33. "golang.org/x/image/font"
  34. "golang.org/x/image/font/gofont/gobold"
  35. "golang.org/x/image/font/gofont/gobolditalic"
  36. "golang.org/x/image/font/gofont/goitalic"
  37. "golang.org/x/image/font/gofont/gomono"
  38. "golang.org/x/image/font/gofont/goregular"
  39. "golang.org/x/image/font/opentype"
  40. "golang.org/x/image/math/f64"
  41. "golang.org/x/image/math/fixed"
  42. "golang.org/x/image/vector"
  43. )
  44. const (
  45. // the largest picture a metafile is rendered to
  46. mfMaxSide = 4096
  47. mfMaxPixels = 16 << 20
  48. // the largest DIB decoded out of a metafile
  49. mfMaxDIBPixels = 64 << 20
  50. )
  51. var errNotMetafile = errors.New("not a WMF or EMF metafile")
  52. // metafileKind reports "wmf", "emf" or "" from the leading bytes
  53. func metafileKind(data []byte) string {
  54. if len(data) >= 44 && binary.LittleEndian.Uint32(data) == 1 && string(data[40:44]) == " EMF" {
  55. return "emf"
  56. }
  57. if len(data) >= 4 && binary.LittleEndian.Uint32(data) == 0x9AC6CDD7 {
  58. return "wmf"
  59. }
  60. if len(data) >= 18 {
  61. typ := binary.LittleEndian.Uint16(data)
  62. hs := binary.LittleEndian.Uint16(data[2:])
  63. ver := binary.LittleEndian.Uint16(data[4:])
  64. if (typ == 1 || typ == 2) && hs == 9 && (ver == 0x100 || ver == 0x300) {
  65. return "wmf"
  66. }
  67. }
  68. return ""
  69. }
  70. // BrowserPicture returns a picture in a format the browser can draw. A
  71. // Windows metafile is rendered to PNG (or JPEG for a photo) and a TIFF is
  72. // converted to PNG; any other picture comes back unchanged. ok is false
  73. // only for a metafile or TIFF that could not be converted.
  74. func BrowserPicture(data []byte, ext string) ([]byte, string, bool) {
  75. ext = strings.ToLower(ext)
  76. kind := metafileKind(data)
  77. if kind == "" && (ext == "tif" || ext == "tiff") {
  78. out, err := TIFFToPNG(data)
  79. if err != nil {
  80. return data, ext, false
  81. }
  82. return out, "png", true
  83. }
  84. if kind == "" && ext != "wmf" && ext != "emf" {
  85. return data, ext, true
  86. }
  87. out, outExt, err := metafileToImage(data)
  88. if err != nil {
  89. return data, ext, false
  90. }
  91. return out, outExt, true
  92. }
  93. // metafileToImage renders a WMF or EMF and encodes the result
  94. func metafileToImage(data []byte) ([]byte, string, error) {
  95. img, photo, err := renderMetafile(data)
  96. if err != nil {
  97. return nil, "", err
  98. }
  99. var buf bytes.Buffer
  100. if photo {
  101. if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
  102. return nil, "", err
  103. }
  104. return buf.Bytes(), "jpeg", nil
  105. }
  106. enc := png.Encoder{CompressionLevel: png.BestSpeed}
  107. if err := enc.Encode(&buf, img); err != nil {
  108. return nil, "", err
  109. }
  110. return buf.Bytes(), "png", nil
  111. }
  112. // mfPlayer is one metafile format's record reader
  113. type mfPlayer interface {
  114. // baseSize is the picture's size in CSS pixels (96 DPI)
  115. baseSize() (float64, float64)
  116. // play draws every record onto the canvas
  117. play(c *mfCanvas) error
  118. }
  119. // renderMetafile plays a metafile twice: once to measure the bitmaps it
  120. // holds (which decides the output resolution) and once to draw. photo
  121. // reports a picture that is only photographic bitmaps, best kept as JPEG.
  122. func renderMetafile(data []byte) (image.Image, bool, error) {
  123. var p mfPlayer
  124. var err error
  125. switch metafileKind(data) {
  126. case "wmf":
  127. p, err = newWmfPlayer(data)
  128. case "emf":
  129. p, err = newEmfPlayer(data)
  130. default:
  131. return nil, false, errNotMetafile
  132. }
  133. if err != nil {
  134. return nil, false, err
  135. }
  136. bw, bh := p.baseSize()
  137. if !(bw >= 1 && bh >= 1) || math.IsInf(bw, 0) || math.IsInf(bh, 0) {
  138. return nil, false, errors.New("metafile has no usable picture frame")
  139. }
  140. measure := newMfCanvas(bw, bh, 1, true)
  141. if err := p.play(measure); err != nil {
  142. return nil, false, err
  143. }
  144. if !measure.drewBitmap && !measure.drewVector {
  145. return nil, false, errors.New("metafile holds nothing that can be drawn")
  146. }
  147. scale := 2.0
  148. if !measure.drewVector && measure.maxRatio > 0 {
  149. scale = measure.maxRatio
  150. } else if measure.maxRatio > scale {
  151. scale = measure.maxRatio
  152. }
  153. scale = math.Min(scale, mfMaxSide/math.Max(bw, bh))
  154. scale = math.Min(scale, math.Sqrt(mfMaxPixels/(bw*bh)))
  155. if bw*scale < 1 || bh*scale < 1 {
  156. scale = math.Max(1/bw, 1/bh)
  157. }
  158. c := newMfCanvas(bw, bh, scale, false)
  159. if err := p.play(c); err != nil {
  160. return nil, false, err
  161. }
  162. photo := measure.photo && !measure.drewVector
  163. if photo {
  164. // a scan stretched over (nearly) the whole frame: GDI shows the
  165. // uncovered sliver as the white page, so flatten it for JPEG
  166. if transparentShare(c.img) > 0.02 {
  167. photo = false
  168. } else {
  169. flattenOnWhite(c.img)
  170. }
  171. }
  172. return c.img, photo, nil
  173. }
  174. // transparentShare is the fraction of pixels that are not fully opaque
  175. func transparentShare(img *image.RGBA) float64 {
  176. n, total := 0, 0
  177. for i := 3; i < len(img.Pix); i += 4 {
  178. total++
  179. if img.Pix[i] != 0xFF {
  180. n++
  181. }
  182. }
  183. if total == 0 {
  184. return 1
  185. }
  186. return float64(n) / float64(total)
  187. }
  188. // flattenOnWhite composites a premultiplied image over white in place
  189. func flattenOnWhite(img *image.RGBA) {
  190. p := img.Pix
  191. for i := 0; i+3 < len(p); i += 4 {
  192. inv := 255 - uint32(p[i+3])
  193. p[i] = uint8(uint32(p[i]) + inv)
  194. p[i+1] = uint8(uint32(p[i+1]) + inv)
  195. p[i+2] = uint8(uint32(p[i+2]) + inv)
  196. p[i+3] = 255
  197. }
  198. }
  199. /* ---------------- device context ---------------- */
  200. type mfPt struct{ X, Y float64 }
  201. type mfPen struct {
  202. col color.NRGBA
  203. width float64 // logical units; 0 is a one pixel cosmetic pen
  204. null bool
  205. }
  206. type mfBrush struct {
  207. col color.NRGBA
  208. null bool
  209. }
  210. type mfFont struct {
  211. height float64 // logical units; < 0 is the em height, > 0 the cell height
  212. weight int
  213. italic bool
  214. underline bool
  215. strike bool
  216. escapement float64 // tenths of a degree, counterclockwise
  217. face string
  218. }
  219. // mfObject is one slot of the metafile's object table; an object the
  220. // canvas cannot use (palette, region) is a slot with nothing set
  221. type mfObject struct {
  222. pen *mfPen
  223. brush *mfBrush
  224. font *mfFont
  225. }
  226. const (
  227. mmText = 1
  228. mmLoMetric = 2
  229. mmHiMetric = 3
  230. mmLoEnglish = 4
  231. mmHiEnglish = 5
  232. mmTwips = 6
  233. mmIsotropic = 7
  234. mmAnisotropic = 8
  235. )
  236. type mfDC struct {
  237. pen mfPen
  238. brush mfBrush
  239. font mfFont
  240. textColor color.NRGBA
  241. bkColor color.NRGBA
  242. bkOpaque bool
  243. textAlign uint32
  244. winding bool // polygon fill mode WINDING (else ALTERNATE)
  245. mapMode int
  246. winOrg, winExt mfPt
  247. vpOrg, vpExt mfPt
  248. winExtSet bool
  249. vpExtSet bool
  250. // EMF world transform: x' = a*x + c*y + e, y' = b*x + d*y + f
  251. xf [6]float64
  252. cur mfPt
  253. }
  254. func defaultMfDC() mfDC {
  255. black := color.NRGBA{A: 255}
  256. white := color.NRGBA{255, 255, 255, 255}
  257. return mfDC{
  258. pen: mfPen{col: black},
  259. brush: mfBrush{col: white},
  260. font: mfFont{height: -12, weight: 400},
  261. textColor: black,
  262. bkColor: white,
  263. bkOpaque: true,
  264. mapMode: mmText,
  265. winExt: mfPt{1, 1},
  266. vpExt: mfPt{1, 1},
  267. xf: [6]float64{1, 0, 0, 1, 0, 0},
  268. }
  269. }
  270. func colorRef(v uint32) color.NRGBA {
  271. return color.NRGBA{uint8(v), uint8(v >> 8), uint8(v >> 16), 255}
  272. }
  273. /* ---------------- canvas ---------------- */
  274. type mfCanvas struct {
  275. img *image.RGBA
  276. w, h int
  277. scale float64 // output pixels per CSS pixel
  278. measure bool
  279. // measure pass results
  280. maxRatio float64 // bitmap source pixels per CSS pixel, the largest seen
  281. drewBitmap bool
  282. drewVector bool
  283. photo bool // a bitmap of 16+ bits per pixel or a JPEG was drawn
  284. dc mfDC
  285. saved []mfDC
  286. objs map[uint32]*mfObject
  287. // toCSS maps a logical point to CSS pixels of the picture; set by the
  288. // player, it reads the current device context
  289. toCSS func(p mfPt) mfPt
  290. ras *vector.Rasterizer
  291. // EMF path bracket: subpaths in output pixels
  292. inPath bool
  293. path [][]mfPt
  294. pathOpen []bool
  295. }
  296. func newMfCanvas(bw, bh, scale float64, measure bool) *mfCanvas {
  297. c := &mfCanvas{
  298. scale: scale,
  299. measure: measure,
  300. dc: defaultMfDC(),
  301. objs: map[uint32]*mfObject{},
  302. }
  303. c.w = int(math.Round(bw * scale))
  304. c.h = int(math.Round(bh * scale))
  305. if c.w < 1 {
  306. c.w = 1
  307. }
  308. if c.h < 1 {
  309. c.h = 1
  310. }
  311. if !measure {
  312. c.img = image.NewRGBA(image.Rect(0, 0, c.w, c.h))
  313. c.ras = vector.NewRasterizer(c.w, c.h)
  314. }
  315. return c
  316. }
  317. // px maps a logical point to output pixels
  318. func (c *mfCanvas) px(p mfPt) mfPt {
  319. q := c.toCSS(p)
  320. return mfPt{q.X * c.scale, q.Y * c.scale}
  321. }
  322. // pxLen is the output length of a logical length along x and along y
  323. func (c *mfCanvas) pxLen(v float64) (float64, float64) {
  324. o := c.px(mfPt{0, 0})
  325. x := c.px(mfPt{v, 0})
  326. y := c.px(mfPt{0, v})
  327. return math.Hypot(x.X-o.X, x.Y-o.Y), math.Hypot(y.X-o.X, y.Y-o.Y)
  328. }
  329. func (c *mfCanvas) save() {
  330. c.saved = append(c.saved, c.dc)
  331. }
  332. // restore pops to a saved state; rel < 0 counts back from the newest
  333. func (c *mfCanvas) restore(rel int) {
  334. if rel >= 0 || len(c.saved) == 0 {
  335. rel = -1
  336. }
  337. i := len(c.saved) + rel
  338. if i < 0 {
  339. i = 0
  340. }
  341. c.dc = c.saved[i]
  342. c.saved = c.saved[:i]
  343. }
  344. func (c *mfCanvas) selectObject(o *mfObject) {
  345. if o == nil {
  346. return
  347. }
  348. switch {
  349. case o.pen != nil:
  350. c.dc.pen = *o.pen
  351. case o.brush != nil:
  352. c.dc.brush = *o.brush
  353. case o.font != nil:
  354. c.dc.font = *o.font
  355. }
  356. }
  357. // stockObject resolves GetStockObject handles (high bit set)
  358. func stockObject(h uint32) *mfObject {
  359. white := color.NRGBA{255, 255, 255, 255}
  360. gray := func(v uint8) color.NRGBA { return color.NRGBA{v, v, v, 255} }
  361. switch h & 0x7FFFFFFF {
  362. case 0:
  363. return &mfObject{brush: &mfBrush{col: white}}
  364. case 1:
  365. return &mfObject{brush: &mfBrush{col: gray(0xC0)}}
  366. case 2:
  367. return &mfObject{brush: &mfBrush{col: gray(0x80)}}
  368. case 3:
  369. return &mfObject{brush: &mfBrush{col: gray(0x40)}}
  370. case 4:
  371. return &mfObject{brush: &mfBrush{col: gray(0)}}
  372. case 5:
  373. return &mfObject{brush: &mfBrush{null: true}}
  374. case 6:
  375. return &mfObject{pen: &mfPen{col: white}}
  376. case 7:
  377. return &mfObject{pen: &mfPen{col: gray(0)}}
  378. case 8:
  379. return &mfObject{pen: &mfPen{null: true}}
  380. case 10, 11, 12, 13, 14, 16, 17:
  381. return &mfObject{font: &mfFont{height: -12, weight: 400}}
  382. }
  383. return nil
  384. }
  385. // penFromStyle builds a pen from a GDI pen style, width and colour
  386. func penFromStyle(style uint32, width float64, col uint32) *mfPen {
  387. if style&0x0F == 5 { // PS_NULL
  388. return &mfPen{null: true}
  389. }
  390. return &mfPen{col: colorRef(col), width: math.Abs(width)}
  391. }
  392. // brushFromStyle builds a brush from a GDI brush style and colour
  393. func brushFromStyle(style uint32, col uint32) *mfBrush {
  394. switch style {
  395. case 1: // BS_NULL
  396. return &mfBrush{null: true}
  397. case 2: // BS_HATCHED: the hatch lines cover about a third of the area
  398. cl := colorRef(col)
  399. cl.A = 90
  400. return &mfBrush{col: cl}
  401. case 0:
  402. return &mfBrush{col: colorRef(col)}
  403. }
  404. // pattern brushes: a neutral fill keeps the shape visible
  405. return &mfBrush{col: color.NRGBA{0xC0, 0xC0, 0xC0, 255}}
  406. }
  407. /* ---------------- drawing ---------------- */
  408. // shape fills (when closed) and outlines a set of logical polygons
  409. func (c *mfCanvas) shape(polys [][]mfPt, closed bool) {
  410. px := make([][]mfPt, 0, len(polys))
  411. for _, poly := range polys {
  412. if len(poly) < 2 {
  413. continue
  414. }
  415. q := make([]mfPt, len(poly))
  416. for i, p := range poly {
  417. q[i] = c.px(p)
  418. }
  419. px = append(px, q)
  420. }
  421. if len(px) == 0 {
  422. return
  423. }
  424. if c.inPath {
  425. for _, q := range px {
  426. c.path = append(c.path, q)
  427. c.pathOpen = append(c.pathOpen, !closed)
  428. }
  429. return
  430. }
  431. c.drawPx(px, closed, closed, true)
  432. }
  433. // drawPx fills and / or strokes polygons already in output pixels
  434. func (c *mfCanvas) drawPx(px [][]mfPt, fill, closed, stroke bool) {
  435. if fill && !c.dc.brush.null && c.dc.brush.col.A > 0 {
  436. c.drewVector = true
  437. if !c.measure {
  438. c.fillPolys(px, c.dc.brush.col)
  439. }
  440. }
  441. if stroke && !c.dc.pen.null {
  442. c.drewVector = true
  443. if !c.measure {
  444. wx, wy := c.pxLen(c.dc.pen.width)
  445. w := (wx + wy) / 2
  446. if c.dc.pen.width == 0 || w < 1 {
  447. w = 1
  448. }
  449. c.strokePolys(px, closed, w, c.dc.pen.col)
  450. }
  451. }
  452. }
  453. func (c *mfCanvas) fillPolys(px [][]mfPt, col color.NRGBA) {
  454. c.ras.Reset(c.w, c.h)
  455. for _, poly := range px {
  456. if len(poly) < 3 {
  457. continue
  458. }
  459. c.ras.MoveTo(float32(poly[0].X), float32(poly[0].Y))
  460. for _, p := range poly[1:] {
  461. c.ras.LineTo(float32(p.X), float32(p.Y))
  462. }
  463. c.ras.ClosePath()
  464. }
  465. c.ras.Draw(c.img, c.img.Bounds(), image.NewUniform(col), image.Point{})
  466. }
  467. // strokePolys outlines polylines as one coverage pass: a quad per segment
  468. // and a round-ish cap at every vertex, all wound the same way so the
  469. // overlaps do not cancel out
  470. func (c *mfCanvas) strokePolys(px [][]mfPt, closed bool, width float64, col color.NRGBA) {
  471. hw := width / 2
  472. c.ras.Reset(c.w, c.h)
  473. quad := func(a, b mfPt) {
  474. dx, dy := b.X-a.X, b.Y-a.Y
  475. l := math.Hypot(dx, dy)
  476. if l < 1e-9 {
  477. return
  478. }
  479. nx, ny := -dy/l*hw, dx/l*hw
  480. c.ras.MoveTo(float32(a.X+nx), float32(a.Y+ny))
  481. c.ras.LineTo(float32(b.X+nx), float32(b.Y+ny))
  482. c.ras.LineTo(float32(b.X-nx), float32(b.Y-ny))
  483. c.ras.LineTo(float32(a.X-nx), float32(a.Y-ny))
  484. c.ras.ClosePath()
  485. }
  486. join := func(p mfPt) {
  487. if hw <= 0.75 {
  488. return
  489. }
  490. const n = 10
  491. for i := 0; i <= n; i++ {
  492. t := -2 * math.Pi * float64(i) / n
  493. x, y := float32(p.X+hw*math.Cos(t)), float32(p.Y+hw*math.Sin(t))
  494. if i == 0 {
  495. c.ras.MoveTo(x, y)
  496. } else {
  497. c.ras.LineTo(x, y)
  498. }
  499. }
  500. c.ras.ClosePath()
  501. }
  502. for _, poly := range px {
  503. for i := 0; i+1 < len(poly); i++ {
  504. quad(poly[i], poly[i+1])
  505. join(poly[i])
  506. }
  507. if len(poly) > 0 {
  508. join(poly[len(poly)-1])
  509. }
  510. if closed && len(poly) > 2 {
  511. quad(poly[len(poly)-1], poly[0])
  512. }
  513. }
  514. c.ras.Draw(c.img, c.img.Bounds(), image.NewUniform(col), image.Point{})
  515. }
  516. /* ---------------- geometry helpers (logical space) ---------------- */
  517. func rectPoly(l, t, r, b float64) []mfPt {
  518. return []mfPt{{l, t}, {r, t}, {r, b}, {l, b}}
  519. }
  520. func ellipsePoly(l, t, r, b float64) []mfPt {
  521. cx, cy := (l+r)/2, (t+b)/2
  522. rx, ry := math.Abs(r-l)/2, math.Abs(b-t)/2
  523. n := 64
  524. pts := make([]mfPt, n)
  525. for i := range pts {
  526. a := 2 * math.Pi * float64(i) / float64(n)
  527. pts[i] = mfPt{cx + rx*math.Cos(a), cy + ry*math.Sin(a)}
  528. }
  529. return pts
  530. }
  531. func roundRectPoly(l, t, r, b, cw, ch float64) []mfPt {
  532. if r < l {
  533. l, r = r, l
  534. }
  535. if b < t {
  536. t, b = b, t
  537. }
  538. rx := math.Min(math.Abs(cw)/2, (r-l)/2)
  539. ry := math.Min(math.Abs(ch)/2, (b-t)/2)
  540. if rx <= 0 || ry <= 0 {
  541. return rectPoly(l, t, r, b)
  542. }
  543. var pts []mfPt
  544. corner := func(cx, cy, a0 float64) {
  545. for i := 0; i <= 8; i++ {
  546. a := a0 + math.Pi/2*float64(i)/8
  547. pts = append(pts, mfPt{cx + rx*math.Cos(a), cy + ry*math.Sin(a)})
  548. }
  549. }
  550. corner(r-rx, t+ry, -math.Pi/2)
  551. corner(r-rx, b-ry, 0)
  552. corner(l+rx, b-ry, math.Pi/2)
  553. corner(l+rx, t+ry, math.Pi)
  554. return pts
  555. }
  556. // arcPoly walks an ellipse counterclockwise (as seen on screen) from the
  557. // ray through start to the ray through end, as GDI's Arc / Pie / Chord do
  558. func arcPoly(l, t, r, b float64, start, end mfPt) []mfPt {
  559. cx, cy := (l+r)/2, (t+b)/2
  560. rx, ry := math.Abs(r-l)/2, math.Abs(b-t)/2
  561. if rx == 0 || ry == 0 {
  562. return nil
  563. }
  564. a0 := math.Atan2(-(start.Y-cy)/ry, (start.X-cx)/rx)
  565. a1 := math.Atan2(-(end.Y-cy)/ry, (end.X-cx)/rx)
  566. for a1 <= a0 {
  567. a1 += 2 * math.Pi
  568. }
  569. n := int(math.Ceil((a1-a0)/(2*math.Pi)*64)) + 1
  570. pts := make([]mfPt, 0, n+1)
  571. for i := 0; i <= n; i++ {
  572. a := a0 + (a1-a0)*float64(i)/float64(n)
  573. pts = append(pts, mfPt{cx + rx*math.Cos(a), cy - ry*math.Sin(a)})
  574. }
  575. return pts
  576. }
  577. // bezierPoly flattens cubic segments: pts is a start point followed by
  578. // (control, control, end) triples
  579. func bezierPoly(pts []mfPt) []mfPt {
  580. if len(pts) == 0 {
  581. return nil
  582. }
  583. out := []mfPt{pts[0]}
  584. for i := 1; i+2 < len(pts); i += 3 {
  585. p0, p1, p2, p3 := out[len(out)-1], pts[i], pts[i+1], pts[i+2]
  586. const n = 16
  587. for k := 1; k <= n; k++ {
  588. t := float64(k) / n
  589. u := 1 - t
  590. out = append(out, mfPt{
  591. u*u*u*p0.X + 3*u*u*t*p1.X + 3*u*t*t*p2.X + t*t*t*p3.X,
  592. u*u*u*p0.Y + 3*u*u*t*p1.Y + 3*u*t*t*p2.Y + t*t*t*p3.Y,
  593. })
  594. }
  595. }
  596. return out
  597. }
  598. /* ---------------- path bracket (EMF) ---------------- */
  599. func (c *mfCanvas) beginPath() {
  600. c.inPath = true
  601. c.path, c.pathOpen = nil, nil
  602. }
  603. // pathMoveTo starts a new subpath at a logical point
  604. func (c *mfCanvas) pathMoveTo(p mfPt) {
  605. c.path = append(c.path, []mfPt{c.px(p)})
  606. c.pathOpen = append(c.pathOpen, true)
  607. }
  608. // pathLineTo appends logical points to the open subpath
  609. func (c *mfCanvas) pathLineTo(pts ...mfPt) {
  610. if len(c.path) == 0 || !c.pathOpen[len(c.path)-1] {
  611. c.pathMoveTo(c.dc.cur)
  612. }
  613. i := len(c.path) - 1
  614. for _, p := range pts {
  615. c.path[i] = append(c.path[i], c.px(p))
  616. }
  617. }
  618. func (c *mfCanvas) closeFigure() {
  619. if n := len(c.path); n > 0 {
  620. c.pathOpen[n-1] = false
  621. }
  622. }
  623. func (c *mfCanvas) drawPath(fill, stroke bool) {
  624. if len(c.path) == 0 {
  625. return
  626. }
  627. var closed, open [][]mfPt
  628. for i, sp := range c.path {
  629. if fill || !c.pathOpen[i] {
  630. closed = append(closed, sp)
  631. } else {
  632. open = append(open, sp)
  633. }
  634. }
  635. if len(closed) > 0 {
  636. c.drawPx(closed, fill, true, stroke)
  637. }
  638. if len(open) > 0 {
  639. c.drawPx(open, false, false, stroke)
  640. }
  641. c.path, c.pathOpen = nil, nil
  642. }
  643. /* ---------------- bitmaps ---------------- */
  644. const (
  645. ropSrcCopy = 0x00CC0020
  646. ropSrcPaint = 0x00EE0086
  647. ropSrcAnd = 0x008800C6
  648. ropSrcInvert = 0x00660046
  649. ropSrcErase = 0x00440328
  650. ropNotSrcCopy = 0x00330008
  651. ropMergePaint = 0x00BB0226
  652. ropPatCopy = 0x00F00021
  653. ropBlackness = 0x00000042
  654. ropWhiteness = 0x00FF0062
  655. )
  656. // blit draws src (only srcRect of it) into the logical destination
  657. // rectangle at (x, y) with size (w, h); a negative size mirrors
  658. func (c *mfCanvas) blit(src image.Image, srcRect image.Rectangle, x, y, w, h float64, rop uint32, photo bool) {
  659. srcRect = srcRect.Canon()
  660. b := src.Bounds()
  661. if !srcRect.Overlaps(b) {
  662. return
  663. }
  664. // a source rectangle past the bitmap edge: keep the part that exists
  665. // and shrink the destination with it
  666. clip := srcRect.Intersect(b)
  667. if clip != srcRect {
  668. fx := w / float64(srcRect.Dx())
  669. fy := h / float64(srcRect.Dy())
  670. x += float64(clip.Min.X-srcRect.Min.X) * fx
  671. y += float64(clip.Min.Y-srcRect.Min.Y) * fy
  672. w = float64(clip.Dx()) * fx
  673. h = float64(clip.Dy()) * fy
  674. srcRect = clip
  675. }
  676. tl := c.px(mfPt{x, y})
  677. tr := c.px(mfPt{x + w, y})
  678. bl := c.px(mfPt{x, y + h})
  679. dw := math.Hypot(tr.X-tl.X, tr.Y-tl.Y)
  680. dh := math.Hypot(bl.X-tl.X, bl.Y-tl.Y)
  681. if dw < 0.5 || dh < 0.5 {
  682. return
  683. }
  684. c.drewBitmap = true
  685. if c.measure {
  686. // the CSS size the bitmap covers decides the output resolution
  687. r := math.Max(float64(srcRect.Dx())/dw, float64(srcRect.Dy())/dh)
  688. if r > c.maxRatio {
  689. c.maxRatio = r
  690. }
  691. if photo {
  692. c.photo = true
  693. }
  694. return
  695. }
  696. sw, sh := float64(srcRect.Dx()), float64(srcRect.Dy())
  697. s2d := f64.Aff3{
  698. (tr.X - tl.X) / sw, (bl.X - tl.X) / sh, 0,
  699. (tr.Y - tl.Y) / sw, (bl.Y - tl.Y) / sh, 0,
  700. }
  701. s2d[2] = tl.X - s2d[0]*float64(srcRect.Min.X) - s2d[1]*float64(srcRect.Min.Y)
  702. s2d[5] = tl.Y - s2d[3]*float64(srcRect.Min.X) - s2d[4]*float64(srcRect.Min.Y)
  703. var interp xdraw.Transformer = xdraw.BiLinear
  704. if sw/dw > 1.5 || sh/dh > 1.5 {
  705. interp = xdraw.CatmullRom
  706. }
  707. switch rop {
  708. case ropSrcCopy, 0:
  709. c.transform(interp, s2d, src, srcRect, c.img)
  710. return
  711. }
  712. // a bitwise raster op: render the source alone, then combine
  713. box := image.Rect(
  714. int(math.Floor(math.Min(math.Min(tl.X, tr.X), math.Min(bl.X, tr.X+bl.X-tl.X)))),
  715. int(math.Floor(math.Min(math.Min(tl.Y, tr.Y), math.Min(bl.Y, tr.Y+bl.Y-tl.Y)))),
  716. int(math.Ceil(math.Max(math.Max(tl.X, tr.X), math.Max(bl.X, tr.X+bl.X-tl.X)))),
  717. int(math.Ceil(math.Max(math.Max(tl.Y, tr.Y), math.Max(bl.Y, tr.Y+bl.Y-tl.Y)))),
  718. ).Intersect(c.img.Bounds())
  719. if box.Empty() {
  720. return
  721. }
  722. tmp := image.NewRGBA(box)
  723. c.transform(interp, s2d, src, srcRect, tmp)
  724. for yy := box.Min.Y; yy < box.Max.Y; yy++ {
  725. for xx := box.Min.X; xx < box.Max.X; xx++ {
  726. si := tmp.PixOffset(xx, yy)
  727. if tmp.Pix[si+3] == 0 {
  728. continue
  729. }
  730. di := c.img.PixOffset(xx, yy)
  731. c.ropPixel(c.img.Pix[di:di+4], tmp.Pix[si:si+4], rop)
  732. }
  733. }
  734. }
  735. func (c *mfCanvas) transform(interp xdraw.Transformer, s2d f64.Aff3, src image.Image, sr image.Rectangle, dst *image.RGBA) {
  736. // a 1:1 copy at whole pixel offsets needs no resampling
  737. if s2d[0] == 1 && s2d[4] == 1 && s2d[1] == 0 && s2d[3] == 0 &&
  738. s2d[2] == math.Trunc(s2d[2]) && s2d[5] == math.Trunc(s2d[5]) {
  739. off := image.Pt(int(s2d[2]), int(s2d[5]))
  740. xdraw.Draw(dst, sr.Add(off), src, sr.Min, xdraw.Over)
  741. return
  742. }
  743. interp.Transform(dst, s2d, src, sr, xdraw.Over, nil)
  744. }
  745. // ropPixel combines a source pixel into a destination pixel with a GDI
  746. // raster op. The empty (transparent) canvas counts as the white page, and
  747. // a result that is still white there stays transparent, so the classic
  748. // mask (AND) + image (OR) pair keeps its transparent background.
  749. func (c *mfCanvas) ropPixel(d, s []uint8, rop uint32) {
  750. empty := d[3] == 0
  751. var dc [3]uint32
  752. for i := 0; i < 3; i++ {
  753. // premultiplied over white
  754. dc[i] = uint32(d[i]) + 255 - uint32(d[3])
  755. }
  756. var out [3]uint32
  757. for i := 0; i < 3; i++ {
  758. sv := uint32(s[i]) + 255 - uint32(s[3])
  759. dv := dc[i]
  760. switch rop {
  761. case ropSrcAnd:
  762. out[i] = sv & dv
  763. case ropSrcPaint:
  764. out[i] = sv | dv
  765. case ropSrcInvert:
  766. out[i] = (sv ^ dv) & 0xFF
  767. case ropSrcErase:
  768. out[i] = sv & (^dv & 0xFF)
  769. case ropNotSrcCopy:
  770. out[i] = ^sv & 0xFF
  771. case ropMergePaint:
  772. out[i] = (^sv & 0xFF) | dv
  773. default:
  774. out[i] = sv
  775. }
  776. }
  777. if empty && out[0] == 255 && out[1] == 255 && out[2] == 255 {
  778. return
  779. }
  780. d[0], d[1], d[2], d[3] = uint8(out[0]), uint8(out[1]), uint8(out[2]), 255
  781. }
  782. // patBlt fills a logical rectangle for the source-less raster ops
  783. func (c *mfCanvas) patBlt(x, y, w, h float64, rop uint32) {
  784. var col color.NRGBA
  785. switch rop {
  786. case ropPatCopy:
  787. if c.dc.brush.null {
  788. return
  789. }
  790. col = c.dc.brush.col
  791. case ropBlackness:
  792. col = color.NRGBA{A: 255}
  793. case ropWhiteness:
  794. col = color.NRGBA{255, 255, 255, 255}
  795. default:
  796. return
  797. }
  798. poly := rectPoly(x, y, x+w, y+h)
  799. px := make([]mfPt, len(poly))
  800. for i, p := range poly {
  801. px[i] = c.px(p)
  802. }
  803. c.drewVector = true
  804. if !c.measure {
  805. c.fillPolys([][]mfPt{px}, col)
  806. }
  807. }
  808. /* ---------------- DIB decoding ---------------- */
  809. // dibInfo is the parsed part of a BITMAPINFO header
  810. type dibInfo struct {
  811. w, h int
  812. topDown bool
  813. bpp int
  814. comp uint32
  815. masks [4]uint32 // r g b a (bit fields)
  816. palette []color.NRGBA
  817. headerLen int // header + masks + colour table
  818. }
  819. func parseDIBHeader(b []byte, usage uint32) (*dibInfo, error) {
  820. if len(b) < 12 {
  821. return nil, errors.New("DIB header truncated")
  822. }
  823. hs := int(binary.LittleEndian.Uint32(b))
  824. d := &dibInfo{}
  825. entry := 4
  826. nColors := 0
  827. if hs == 12 {
  828. d.w = int(binary.LittleEndian.Uint16(b[4:]))
  829. d.h = int(int16(binary.LittleEndian.Uint16(b[6:])))
  830. d.bpp = int(binary.LittleEndian.Uint16(b[10:]))
  831. entry = 3
  832. } else {
  833. if hs < 40 || len(b) < 40 {
  834. return nil, errors.New("unsupported DIB header")
  835. }
  836. d.w = int(int32(binary.LittleEndian.Uint32(b[4:])))
  837. d.h = int(int32(binary.LittleEndian.Uint32(b[8:])))
  838. d.bpp = int(binary.LittleEndian.Uint16(b[14:]))
  839. d.comp = binary.LittleEndian.Uint32(b[16:])
  840. nColors = int(binary.LittleEndian.Uint32(b[32:]))
  841. }
  842. if d.h < 0 {
  843. d.h = -d.h
  844. d.topDown = true
  845. }
  846. // the area in int64: two sizes under 1<<16 still overflow a 32-bit int
  847. if d.w <= 0 || d.h <= 0 || d.w > 1<<16 || d.h > 1<<16 || int64(d.w)*int64(d.h) > mfMaxDIBPixels {
  848. return nil, errors.New("DIB has an unusable size")
  849. }
  850. off := hs
  851. if d.comp == 3 || d.comp == 6 { // BI_BITFIELDS / BI_ALPHABITFIELDS
  852. n := 3
  853. if d.comp == 6 {
  854. n = 4
  855. }
  856. if hs >= 52 {
  857. // V2+ headers hold the masks themselves
  858. for i := 0; i < 4 && 40+4*i+4 <= hs && 40+4*i+4 <= len(b); i++ {
  859. d.masks[i] = binary.LittleEndian.Uint32(b[40+4*i:])
  860. }
  861. } else {
  862. if len(b) < hs+4*n {
  863. return nil, errors.New("DIB masks truncated")
  864. }
  865. for i := 0; i < n; i++ {
  866. d.masks[i] = binary.LittleEndian.Uint32(b[hs+4*i:])
  867. }
  868. off += 4 * n
  869. }
  870. } else if hs >= 56 && len(b) >= 56 {
  871. d.masks[3] = binary.LittleEndian.Uint32(b[52:])
  872. }
  873. if d.bpp <= 8 {
  874. if nColors == 0 || nColors > 1<<d.bpp {
  875. nColors = 1 << d.bpp
  876. }
  877. }
  878. if usage == 1 { // DIB_PAL_COLORS: 16-bit indices into a palette we do not have
  879. entry = 2
  880. }
  881. if nColors > 0 {
  882. if len(b) < off+nColors*entry {
  883. return nil, errors.New("DIB colour table truncated")
  884. }
  885. d.palette = make([]color.NRGBA, nColors)
  886. for i := range d.palette {
  887. e := b[off+i*entry:]
  888. if entry == 2 {
  889. v := uint8(255 * i / maxInt(nColors-1, 1))
  890. d.palette[i] = color.NRGBA{v, v, v, 255}
  891. } else {
  892. d.palette[i] = color.NRGBA{e[2], e[1], e[0], 255}
  893. }
  894. }
  895. off += nColors * entry
  896. }
  897. d.headerLen = off
  898. return d, nil
  899. }
  900. // decodePackedDIB decodes a DIB whose pixels follow the header and
  901. // colour table directly (the WMF layout)
  902. func decodePackedDIB(b []byte, usage uint32) (image.Image, *dibInfo, error) {
  903. d, err := parseDIBHeader(b, usage)
  904. if err != nil {
  905. return nil, nil, err
  906. }
  907. if d.headerLen > len(b) {
  908. return nil, nil, errors.New("DIB truncated")
  909. }
  910. img, err := d.decode(b[d.headerLen:])
  911. return img, d, err
  912. }
  913. // decodeDIB decodes a DIB with its header and pixels apart (the EMF layout)
  914. func decodeDIB(bmi, bits []byte, usage uint32) (image.Image, *dibInfo, error) {
  915. d, err := parseDIBHeader(bmi, usage)
  916. if err != nil {
  917. return nil, nil, err
  918. }
  919. img, err := d.decode(bits)
  920. return img, d, err
  921. }
  922. // isPhoto reports a bitmap that compresses better as JPEG than PNG
  923. func (d *dibInfo) isPhoto() bool {
  924. return d.bpp >= 16 || d.comp == 4
  925. }
  926. func (d *dibInfo) decode(bits []byte) (image.Image, error) {
  927. switch d.comp {
  928. case 4, 5: // BI_JPEG / BI_PNG
  929. img, _, err := image.Decode(bytes.NewReader(bits))
  930. return img, err
  931. case 1:
  932. if d.bpp != 8 {
  933. return nil, errors.New("RLE8 DIB with wrong depth")
  934. }
  935. return d.fromIndices(decodeRLE(bits, d.w, d.h, false), d.w)
  936. case 2:
  937. if d.bpp != 4 {
  938. return nil, errors.New("RLE4 DIB with wrong depth")
  939. }
  940. return d.fromIndices(decodeRLE(bits, d.w, d.h, true), d.w)
  941. case 0, 3, 6:
  942. default:
  943. return nil, errors.New("unsupported DIB compression")
  944. }
  945. img := image.NewNRGBA(image.Rect(0, 0, d.w, d.h))
  946. stride := ((d.w*d.bpp + 31) / 32) * 4
  947. masks := d.masks
  948. if d.comp == 0 {
  949. switch d.bpp {
  950. case 16:
  951. masks = [4]uint32{0x7C00, 0x03E0, 0x001F, 0}
  952. case 32:
  953. masks = [4]uint32{0xFF0000, 0x00FF00, 0x0000FF, d.masks[3]}
  954. }
  955. }
  956. type field struct {
  957. shift uint
  958. max uint32
  959. }
  960. var fields [4]field
  961. for i, m := range masks {
  962. if m == 0 {
  963. continue
  964. }
  965. s := uint(0)
  966. for m&1 == 0 {
  967. m >>= 1
  968. s++
  969. }
  970. fields[i] = field{s, m}
  971. }
  972. hasAlpha := masks[3] != 0
  973. anyAlpha := false
  974. for y := 0; y < d.h; y++ {
  975. sy := d.h - 1 - y
  976. if d.topDown {
  977. sy = y
  978. }
  979. row := sy * stride
  980. if row+stride > len(bits) {
  981. if row >= len(bits) {
  982. continue
  983. }
  984. }
  985. line := bits[row:min(row+stride, len(bits))]
  986. o := img.PixOffset(0, y)
  987. for x := 0; x < d.w; x++ {
  988. var c color.NRGBA
  989. switch d.bpp {
  990. case 1, 2, 4, 8:
  991. bit := x * d.bpp
  992. if bit/8 >= len(line) {
  993. continue
  994. }
  995. idx := int(line[bit/8]>>(8-uint(d.bpp)-uint(bit%8))) & (1<<d.bpp - 1)
  996. if idx < len(d.palette) {
  997. c = d.palette[idx]
  998. } else {
  999. c = color.NRGBA{A: 255}
  1000. }
  1001. case 24:
  1002. i := x * 3
  1003. if i+2 >= len(line) {
  1004. continue
  1005. }
  1006. c = color.NRGBA{line[i+2], line[i+1], line[i], 255}
  1007. case 16, 32:
  1008. n := d.bpp / 8
  1009. i := x * n
  1010. if i+n > len(line) {
  1011. continue
  1012. }
  1013. var v uint32
  1014. if n == 2 {
  1015. v = uint32(binary.LittleEndian.Uint16(line[i:]))
  1016. } else {
  1017. v = binary.LittleEndian.Uint32(line[i:])
  1018. }
  1019. ch := func(f field) uint8 {
  1020. if f.max == 0 {
  1021. return 0
  1022. }
  1023. return uint8(((v >> f.shift) & f.max) * 255 / f.max)
  1024. }
  1025. c = color.NRGBA{ch(fields[0]), ch(fields[1]), ch(fields[2]), 255}
  1026. if hasAlpha {
  1027. c.A = ch(fields[3])
  1028. if c.A != 0 {
  1029. anyAlpha = true
  1030. }
  1031. }
  1032. default:
  1033. return nil, errors.New("unsupported DIB depth")
  1034. }
  1035. copy(img.Pix[o+4*x:], []uint8{c.R, c.G, c.B, c.A})
  1036. }
  1037. }
  1038. if hasAlpha && !anyAlpha {
  1039. // an alpha channel that is all zero is unused, not invisible
  1040. for i := 3; i < len(img.Pix); i += 4 {
  1041. img.Pix[i] = 255
  1042. }
  1043. }
  1044. return img, nil
  1045. }
  1046. // fromIndices builds an image from palette indices laid out bottom-up
  1047. func (d *dibInfo) fromIndices(idx []uint8, w int) (image.Image, error) {
  1048. img := image.NewNRGBA(image.Rect(0, 0, d.w, d.h))
  1049. for y := 0; y < d.h; y++ {
  1050. sy := d.h - 1 - y
  1051. if d.topDown {
  1052. sy = y
  1053. }
  1054. for x := 0; x < d.w; x++ {
  1055. v := int(idx[sy*w+x])
  1056. c := color.NRGBA{A: 255}
  1057. if v < len(d.palette) {
  1058. c = d.palette[v]
  1059. }
  1060. o := img.PixOffset(x, y)
  1061. img.Pix[o], img.Pix[o+1], img.Pix[o+2], img.Pix[o+3] = c.R, c.G, c.B, c.A
  1062. }
  1063. }
  1064. return img, nil
  1065. }
  1066. // decodeRLE expands BI_RLE8 / BI_RLE4 data into one index per pixel, rows
  1067. // in file order (bottom-up)
  1068. func decodeRLE(b []byte, w, h int, four bool) []uint8 {
  1069. out := make([]uint8, w*h)
  1070. x, y := 0, 0
  1071. put := func(v uint8) {
  1072. if x < w && y < h {
  1073. out[y*w+x] = v
  1074. }
  1075. x++
  1076. }
  1077. for i := 0; i+1 < len(b); {
  1078. n, v := int(b[i]), b[i+1]
  1079. i += 2
  1080. if n > 0 {
  1081. for k := 0; k < n; k++ {
  1082. if four {
  1083. if k%2 == 0 {
  1084. put(v >> 4)
  1085. } else {
  1086. put(v & 0x0F)
  1087. }
  1088. } else {
  1089. put(v)
  1090. }
  1091. }
  1092. continue
  1093. }
  1094. switch v {
  1095. case 0: // end of line
  1096. x, y = 0, y+1
  1097. case 1: // end of bitmap
  1098. return out
  1099. case 2: // delta
  1100. if i+1 >= len(b) {
  1101. return out
  1102. }
  1103. x += int(b[i])
  1104. y += int(b[i+1])
  1105. i += 2
  1106. default: // absolute run of v pixels
  1107. cnt := int(v)
  1108. if four {
  1109. nb := (cnt + 1) / 2
  1110. for k := 0; k < cnt && i+k/2 < len(b); k++ {
  1111. p := b[i+k/2]
  1112. if k%2 == 0 {
  1113. put(p >> 4)
  1114. } else {
  1115. put(p & 0x0F)
  1116. }
  1117. }
  1118. i += nb
  1119. if nb%2 == 1 {
  1120. i++
  1121. }
  1122. } else {
  1123. for k := 0; k < cnt && i+k < len(b); k++ {
  1124. put(b[i+k])
  1125. }
  1126. i += cnt
  1127. if cnt%2 == 1 {
  1128. i++
  1129. }
  1130. }
  1131. }
  1132. if y >= h {
  1133. return out
  1134. }
  1135. }
  1136. return out
  1137. }
  1138. /* ---------------- text ---------------- */
  1139. var (
  1140. mfFontsOnce sync.Once
  1141. mfFonts map[string]*opentype.Font
  1142. )
  1143. // mfFontFor picks the bundled Go font closest to a metafile font
  1144. func mfFontFor(f mfFont) *opentype.Font {
  1145. mfFontsOnce.Do(func() {
  1146. mfFonts = map[string]*opentype.Font{}
  1147. for name, ttf := range map[string][]byte{
  1148. "regular": goregular.TTF, "bold": gobold.TTF, "italic": goitalic.TTF,
  1149. "bolditalic": gobolditalic.TTF, "mono": gomono.TTF,
  1150. } {
  1151. if fnt, err := opentype.Parse(ttf); err == nil {
  1152. mfFonts[name] = fnt
  1153. }
  1154. }
  1155. })
  1156. face := strings.ToLower(f.face)
  1157. if strings.Contains(face, "courier") || strings.Contains(face, "mono") || strings.Contains(face, "consolas") {
  1158. return mfFonts["mono"]
  1159. }
  1160. bold := f.weight >= 600
  1161. switch {
  1162. case bold && f.italic:
  1163. return mfFonts["bolditalic"]
  1164. case bold:
  1165. return mfFonts["bold"]
  1166. case f.italic:
  1167. return mfFonts["italic"]
  1168. }
  1169. return mfFonts["regular"]
  1170. }
  1171. // text draws a run of text at a logical reference point; dx, when given,
  1172. // is the logical advance of each character
  1173. func (c *mfCanvas) text(ref mfPt, s []rune, dx []float64) {
  1174. if len(s) == 0 {
  1175. return
  1176. }
  1177. c.drewVector = true
  1178. f := c.dc.font
  1179. update := c.dc.textAlign&1 != 0 // TA_UPDATECP
  1180. if update {
  1181. ref = c.dc.cur
  1182. }
  1183. _, sy := c.pxLen(f.height)
  1184. size := sy
  1185. if f.height > 0 {
  1186. // a positive height is the cell height, internal leading included
  1187. size *= 0.82
  1188. }
  1189. if f.height == 0 {
  1190. _, size = c.pxLen(12)
  1191. }
  1192. if size < 1 || size > 2000 {
  1193. return
  1194. }
  1195. fnt := mfFontFor(f)
  1196. if fnt == nil {
  1197. return
  1198. }
  1199. face, err := opentype.NewFace(fnt, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingNone})
  1200. if err != nil {
  1201. return
  1202. }
  1203. defer face.Close()
  1204. // glyph positions along the baseline, in output pixels from the start
  1205. pos := make([]float64, len(s)+1)
  1206. if len(dx) >= len(s) {
  1207. for i := range s {
  1208. w, _ := c.pxLen(dx[i])
  1209. pos[i+1] = pos[i] + w
  1210. }
  1211. } else {
  1212. for i, r := range s {
  1213. adv, _ := face.GlyphAdvance(r)
  1214. pos[i+1] = pos[i] + float64(adv)/64
  1215. }
  1216. }
  1217. width := pos[len(s)]
  1218. m := face.Metrics()
  1219. ascent, descent := float64(m.Ascent)/64, float64(m.Descent)/64
  1220. // alignment, measured along the text direction
  1221. ox := 0.0
  1222. switch c.dc.textAlign & 6 {
  1223. case 2: // TA_RIGHT
  1224. ox = -width
  1225. case 6: // TA_CENTER
  1226. ox = -width / 2
  1227. }
  1228. oy := ascent // TA_TOP
  1229. switch c.dc.textAlign & 24 {
  1230. case 8: // TA_BOTTOM
  1231. oy = -descent
  1232. case 24: // TA_BASELINE
  1233. oy = 0
  1234. }
  1235. if update {
  1236. // the current position moves to the end of the text
  1237. w, _ := c.pxLen(1)
  1238. if w > 0 {
  1239. c.dc.cur.X += width / w
  1240. }
  1241. }
  1242. if c.measure {
  1243. return
  1244. }
  1245. // render horizontally into a scratch image, then place it (rotated
  1246. // when the font has an escapement)
  1247. pad := 2
  1248. tw := int(math.Ceil(width)) + 2*pad
  1249. th := int(math.Ceil(ascent+descent)) + 2*pad
  1250. if tw <= 0 || th <= 0 || int64(tw)*int64(th) > mfMaxPixels {
  1251. return
  1252. }
  1253. tmp := image.NewRGBA(image.Rect(0, 0, tw, th))
  1254. src := image.NewUniform(c.dc.textColor)
  1255. base := float64(pad) + ascent
  1256. for i, r := range s {
  1257. d := font.Drawer{Dst: tmp, Src: src, Face: face,
  1258. Dot: fixed.Point26_6{X: fixed.Int26_6((float64(pad) + pos[i]) * 64), Y: fixed.Int26_6(base * 64)}}
  1259. d.DrawString(string(r))
  1260. }
  1261. if f.underline || f.strike {
  1262. lw := math.Max(1, size/16)
  1263. yy := base + size*0.12
  1264. if f.strike {
  1265. yy = base - ascent*0.3
  1266. }
  1267. for y := int(yy); y < int(yy+lw) && y < th; y++ {
  1268. for x := pad; x < pad+int(width) && x < tw; x++ {
  1269. o := tmp.PixOffset(x, y)
  1270. cc := c.dc.textColor
  1271. tmp.Pix[o], tmp.Pix[o+1], tmp.Pix[o+2], tmp.Pix[o+3] = cc.R, cc.G, cc.B, 255
  1272. }
  1273. }
  1274. }
  1275. p := c.px(ref)
  1276. ang := -f.escapement / 10 * math.Pi / 180 // screen y grows downward
  1277. if c.toCSSFlipsY() {
  1278. ang = -ang
  1279. }
  1280. cos, sin := math.Cos(ang), math.Sin(ang)
  1281. // scratch (u, v) -> canvas: rotate the offset from the reference point
  1282. u0 := float64(pad) - ox
  1283. v0 := base - oy
  1284. aff := f64.Aff3{cos, -sin, 0, sin, cos, 0}
  1285. aff[2] = p.X - (cos*u0 - sin*v0)
  1286. aff[5] = p.Y - (sin*u0 + cos*v0)
  1287. if ang == 0 && aff[2] == math.Trunc(aff[2]) && aff[5] == math.Trunc(aff[5]) {
  1288. xdraw.Draw(c.img, tmp.Bounds().Add(image.Pt(int(aff[2]), int(aff[5]))), tmp, image.Point{}, xdraw.Over)
  1289. return
  1290. }
  1291. xdraw.BiLinear.Transform(c.img, aff, tmp, tmp.Bounds(), xdraw.Over, nil)
  1292. }
  1293. // toCSSFlipsY reports a mapping whose y axis points up (the metric and
  1294. // English map modes), which mirrors the sense of an escapement angle
  1295. func (c *mfCanvas) toCSSFlipsY() bool {
  1296. a := c.px(mfPt{0, 0})
  1297. b := c.px(mfPt{0, 1})
  1298. return b.Y < a.Y
  1299. }
  1300. // opaqueBox fills a logical rectangle with the background colour (the
  1301. // ETO_OPAQUE box behind a text run)
  1302. func (c *mfCanvas) opaqueBox(l, t, r, b float64) {
  1303. if r == l || b == t {
  1304. return
  1305. }
  1306. poly := rectPoly(l, t, r, b)
  1307. px := make([]mfPt, len(poly))
  1308. for i, p := range poly {
  1309. px[i] = c.px(p)
  1310. }
  1311. c.drewVector = true
  1312. if !c.measure {
  1313. c.fillPolys([][]mfPt{px}, c.dc.bkColor)
  1314. }
  1315. }