Ver código fonte

Add metafile rendering and native Office host

Implement WMF/EMF support in the Office import pipeline by detecting Windows metafiles, rendering them to browser-safe PNG/JPEG output, and wiring this into DOCX/PPTX/ODT/ODP readers. The change adds a full metafile renderer (drawing primitives, text, transforms, DIB decoding, raster ops) plus focused tests for decoding, rendering behavior, and import integration.

Also introduce a new `native` Office host mode for desktop shells via `common/native.js` and `platform.js`. This adds native file open/save handling, native recents, multi-window document behavior, native print flow, and close-confirmation hooks, with corresponding app/home UI updates and contract/docs updates.
Toby Chui 1 mês atrás
pai
commit
51f940fdf3

+ 4 - 1
src/mod/office/docx_reader.go

@@ -1616,7 +1616,10 @@ func (cv *docxConv) mediaBytes(part *docxPartCtx, rid string) ([]byte, string, b
 	switch ext {
 	case "jpg":
 		ext = "jpeg"
-	case "emf", "wmf", "tif", "tiff":
+	case "emf", "wmf":
+		// a Windows metafile is rendered to a bitmap the browser can show
+		return browserPicture(data, ext)
+	case "tif", "tiff":
 		// browsers cannot show these - keep the space, lose the picture
 		return nil, "", false
 	}

+ 1395 - 0
src/mod/office/metafile.go

@@ -0,0 +1,1395 @@
+package office
+
+/*
+	metafile.go - Windows metafiles (WMF / EMF) as pictures a browser can show
+
+	Decks and documents made with older Office versions often carry their
+	pictures as Windows metafiles: a scanned figure pasted into PowerPoint
+	2003 is stored as a .wmf whose only drawing record stretches one DIB
+	over the frame, and diagrams are .emf drawings. No browser decodes
+	either format, so the editor showed an empty frame. The import plays
+	the metafile into a raster image instead (metafile_wmf.go and
+	metafile_emf.go read the records; this file holds the canvas they draw
+	on and the DIB decoder both formats share).
+
+	Supported: bitmap records (stretched, mirrored, the common raster ops),
+	pens and brushes, lines, polylines, polygons, rectangles, rounded
+	rectangles, ellipses, arcs / pies / chords, Bezier curves, EMF paths,
+	world transforms and text. Clipping regions and EMF+ records (the dual
+	EMF+ files carry a plain EMF fallback that is played instead) are not.
+
+	A picture that is only bitmaps is rendered at the bitmap's own
+	resolution so no detail is lost or invented; a drawing is rendered at
+	twice its 96 DPI size so it stays sharp on a high density screen.
+*/
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"image"
+	"image/color"
+	"image/jpeg"
+	"image/png"
+	"math"
+	"strings"
+	"sync"
+
+	xdraw "golang.org/x/image/draw"
+	"golang.org/x/image/font"
+	"golang.org/x/image/font/gofont/gobold"
+	"golang.org/x/image/font/gofont/gobolditalic"
+	"golang.org/x/image/font/gofont/goitalic"
+	"golang.org/x/image/font/gofont/gomono"
+	"golang.org/x/image/font/gofont/goregular"
+	"golang.org/x/image/font/opentype"
+	"golang.org/x/image/math/f64"
+	"golang.org/x/image/math/fixed"
+	"golang.org/x/image/vector"
+)
+
+const (
+	// the largest picture a metafile is rendered to
+	mfMaxSide   = 4096
+	mfMaxPixels = 16 << 20
+	// the largest DIB decoded out of a metafile
+	mfMaxDIBPixels = 64 << 20
+)
+
+var errNotMetafile = errors.New("not a WMF or EMF metafile")
+
+// metafileKind reports "wmf", "emf" or "" from the leading bytes
+func metafileKind(data []byte) string {
+	if len(data) >= 44 && binary.LittleEndian.Uint32(data) == 1 && string(data[40:44]) == " EMF" {
+		return "emf"
+	}
+	if len(data) >= 4 && binary.LittleEndian.Uint32(data) == 0x9AC6CDD7 {
+		return "wmf"
+	}
+	if len(data) >= 18 {
+		typ := binary.LittleEndian.Uint16(data)
+		hs := binary.LittleEndian.Uint16(data[2:])
+		ver := binary.LittleEndian.Uint16(data[4:])
+		if (typ == 1 || typ == 2) && hs == 9 && (ver == 0x100 || ver == 0x300) {
+			return "wmf"
+		}
+	}
+	return ""
+}
+
+// browserPicture returns a picture in a format the browser can draw. A
+// Windows metafile is rendered to PNG (or JPEG for a photo); any other
+// picture comes back unchanged. ok is false only for a metafile that
+// could not be rendered.
+func browserPicture(data []byte, ext string) ([]byte, string, bool) {
+	ext = strings.ToLower(ext)
+	kind := metafileKind(data)
+	if kind == "" && ext != "wmf" && ext != "emf" {
+		return data, ext, true
+	}
+	out, outExt, err := metafileToImage(data)
+	if err != nil {
+		return data, ext, false
+	}
+	return out, outExt, true
+}
+
+// metafileToImage renders a WMF or EMF and encodes the result
+func metafileToImage(data []byte) ([]byte, string, error) {
+	img, photo, err := renderMetafile(data)
+	if err != nil {
+		return nil, "", err
+	}
+	var buf bytes.Buffer
+	if photo {
+		if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
+			return nil, "", err
+		}
+		return buf.Bytes(), "jpeg", nil
+	}
+	enc := png.Encoder{CompressionLevel: png.BestSpeed}
+	if err := enc.Encode(&buf, img); err != nil {
+		return nil, "", err
+	}
+	return buf.Bytes(), "png", nil
+}
+
+// mfPlayer is one metafile format's record reader
+type mfPlayer interface {
+	// baseSize is the picture's size in CSS pixels (96 DPI)
+	baseSize() (float64, float64)
+	// play draws every record onto the canvas
+	play(c *mfCanvas) error
+}
+
+// renderMetafile plays a metafile twice: once to measure the bitmaps it
+// holds (which decides the output resolution) and once to draw. photo
+// reports a picture that is only photographic bitmaps, best kept as JPEG.
+func renderMetafile(data []byte) (image.Image, bool, error) {
+	var p mfPlayer
+	var err error
+	switch metafileKind(data) {
+	case "wmf":
+		p, err = newWmfPlayer(data)
+	case "emf":
+		p, err = newEmfPlayer(data)
+	default:
+		return nil, false, errNotMetafile
+	}
+	if err != nil {
+		return nil, false, err
+	}
+	bw, bh := p.baseSize()
+	if !(bw >= 1 && bh >= 1) || math.IsInf(bw, 0) || math.IsInf(bh, 0) {
+		return nil, false, errors.New("metafile has no usable picture frame")
+	}
+
+	measure := newMfCanvas(bw, bh, 1, true)
+	if err := p.play(measure); err != nil {
+		return nil, false, err
+	}
+	if !measure.drewBitmap && !measure.drewVector {
+		return nil, false, errors.New("metafile holds nothing that can be drawn")
+	}
+	scale := 2.0
+	if !measure.drewVector && measure.maxRatio > 0 {
+		scale = measure.maxRatio
+	} else if measure.maxRatio > scale {
+		scale = measure.maxRatio
+	}
+	scale = math.Min(scale, mfMaxSide/math.Max(bw, bh))
+	scale = math.Min(scale, math.Sqrt(mfMaxPixels/(bw*bh)))
+	if bw*scale < 1 || bh*scale < 1 {
+		scale = math.Max(1/bw, 1/bh)
+	}
+
+	c := newMfCanvas(bw, bh, scale, false)
+	if err := p.play(c); err != nil {
+		return nil, false, err
+	}
+	photo := measure.photo && !measure.drewVector
+	if photo {
+		// a scan stretched over (nearly) the whole frame: GDI shows the
+		// uncovered sliver as the white page, so flatten it for JPEG
+		if transparentShare(c.img) > 0.02 {
+			photo = false
+		} else {
+			flattenOnWhite(c.img)
+		}
+	}
+	return c.img, photo, nil
+}
+
+// transparentShare is the fraction of pixels that are not fully opaque
+func transparentShare(img *image.RGBA) float64 {
+	n, total := 0, 0
+	for i := 3; i < len(img.Pix); i += 4 {
+		total++
+		if img.Pix[i] != 0xFF {
+			n++
+		}
+	}
+	if total == 0 {
+		return 1
+	}
+	return float64(n) / float64(total)
+}
+
+// flattenOnWhite composites a premultiplied image over white in place
+func flattenOnWhite(img *image.RGBA) {
+	p := img.Pix
+	for i := 0; i+3 < len(p); i += 4 {
+		inv := 255 - uint32(p[i+3])
+		p[i] = uint8(uint32(p[i]) + inv)
+		p[i+1] = uint8(uint32(p[i+1]) + inv)
+		p[i+2] = uint8(uint32(p[i+2]) + inv)
+		p[i+3] = 255
+	}
+}
+
+/* ---------------- device context ---------------- */
+
+type mfPt struct{ X, Y float64 }
+
+type mfPen struct {
+	col   color.NRGBA
+	width float64 // logical units; 0 is a one pixel cosmetic pen
+	null  bool
+}
+
+type mfBrush struct {
+	col  color.NRGBA
+	null bool
+}
+
+type mfFont struct {
+	height     float64 // logical units; < 0 is the em height, > 0 the cell height
+	weight     int
+	italic     bool
+	underline  bool
+	strike     bool
+	escapement float64 // tenths of a degree, counterclockwise
+	face       string
+}
+
+// mfObject is one slot of the metafile's object table; an object the
+// canvas cannot use (palette, region) is a slot with nothing set
+type mfObject struct {
+	pen   *mfPen
+	brush *mfBrush
+	font  *mfFont
+}
+
+const (
+	mmText        = 1
+	mmLoMetric    = 2
+	mmHiMetric    = 3
+	mmLoEnglish   = 4
+	mmHiEnglish   = 5
+	mmTwips       = 6
+	mmIsotropic   = 7
+	mmAnisotropic = 8
+)
+
+type mfDC struct {
+	pen       mfPen
+	brush     mfBrush
+	font      mfFont
+	textColor color.NRGBA
+	bkColor   color.NRGBA
+	bkOpaque  bool
+	textAlign uint32
+	winding   bool // polygon fill mode WINDING (else ALTERNATE)
+
+	mapMode        int
+	winOrg, winExt mfPt
+	vpOrg, vpExt   mfPt
+	winExtSet      bool
+	vpExtSet       bool
+	// EMF world transform: x' = a*x + c*y + e, y' = b*x + d*y + f
+	xf [6]float64
+
+	cur mfPt
+}
+
+func defaultMfDC() mfDC {
+	black := color.NRGBA{A: 255}
+	white := color.NRGBA{255, 255, 255, 255}
+	return mfDC{
+		pen:       mfPen{col: black},
+		brush:     mfBrush{col: white},
+		font:      mfFont{height: -12, weight: 400},
+		textColor: black,
+		bkColor:   white,
+		bkOpaque:  true,
+		mapMode:   mmText,
+		winExt:    mfPt{1, 1},
+		vpExt:     mfPt{1, 1},
+		xf:        [6]float64{1, 0, 0, 1, 0, 0},
+	}
+}
+
+func colorRef(v uint32) color.NRGBA {
+	return color.NRGBA{uint8(v), uint8(v >> 8), uint8(v >> 16), 255}
+}
+
+/* ---------------- canvas ---------------- */
+
+type mfCanvas struct {
+	img     *image.RGBA
+	w, h    int
+	scale   float64 // output pixels per CSS pixel
+	measure bool
+
+	// measure pass results
+	maxRatio   float64 // bitmap source pixels per CSS pixel, the largest seen
+	drewBitmap bool
+	drewVector bool
+	photo      bool // a bitmap of 16+ bits per pixel or a JPEG was drawn
+
+	dc    mfDC
+	saved []mfDC
+	objs  map[uint32]*mfObject
+
+	// toCSS maps a logical point to CSS pixels of the picture; set by the
+	// player, it reads the current device context
+	toCSS func(p mfPt) mfPt
+
+	ras *vector.Rasterizer
+
+	// EMF path bracket: subpaths in output pixels
+	inPath   bool
+	path     [][]mfPt
+	pathOpen []bool
+}
+
+func newMfCanvas(bw, bh, scale float64, measure bool) *mfCanvas {
+	c := &mfCanvas{
+		scale:   scale,
+		measure: measure,
+		dc:      defaultMfDC(),
+		objs:    map[uint32]*mfObject{},
+	}
+	c.w = int(math.Round(bw * scale))
+	c.h = int(math.Round(bh * scale))
+	if c.w < 1 {
+		c.w = 1
+	}
+	if c.h < 1 {
+		c.h = 1
+	}
+	if !measure {
+		c.img = image.NewRGBA(image.Rect(0, 0, c.w, c.h))
+		c.ras = vector.NewRasterizer(c.w, c.h)
+	}
+	return c
+}
+
+// px maps a logical point to output pixels
+func (c *mfCanvas) px(p mfPt) mfPt {
+	q := c.toCSS(p)
+	return mfPt{q.X * c.scale, q.Y * c.scale}
+}
+
+// pxLen is the output length of a logical length along x and along y
+func (c *mfCanvas) pxLen(v float64) (float64, float64) {
+	o := c.px(mfPt{0, 0})
+	x := c.px(mfPt{v, 0})
+	y := c.px(mfPt{0, v})
+	return math.Hypot(x.X-o.X, x.Y-o.Y), math.Hypot(y.X-o.X, y.Y-o.Y)
+}
+
+func (c *mfCanvas) save() {
+	c.saved = append(c.saved, c.dc)
+}
+
+// restore pops to a saved state; rel < 0 counts back from the newest
+func (c *mfCanvas) restore(rel int) {
+	if rel >= 0 || len(c.saved) == 0 {
+		rel = -1
+	}
+	i := len(c.saved) + rel
+	if i < 0 {
+		i = 0
+	}
+	c.dc = c.saved[i]
+	c.saved = c.saved[:i]
+}
+
+func (c *mfCanvas) selectObject(o *mfObject) {
+	if o == nil {
+		return
+	}
+	switch {
+	case o.pen != nil:
+		c.dc.pen = *o.pen
+	case o.brush != nil:
+		c.dc.brush = *o.brush
+	case o.font != nil:
+		c.dc.font = *o.font
+	}
+}
+
+// stockObject resolves GetStockObject handles (high bit set)
+func stockObject(h uint32) *mfObject {
+	white := color.NRGBA{255, 255, 255, 255}
+	gray := func(v uint8) color.NRGBA { return color.NRGBA{v, v, v, 255} }
+	switch h & 0x7FFFFFFF {
+	case 0:
+		return &mfObject{brush: &mfBrush{col: white}}
+	case 1:
+		return &mfObject{brush: &mfBrush{col: gray(0xC0)}}
+	case 2:
+		return &mfObject{brush: &mfBrush{col: gray(0x80)}}
+	case 3:
+		return &mfObject{brush: &mfBrush{col: gray(0x40)}}
+	case 4:
+		return &mfObject{brush: &mfBrush{col: gray(0)}}
+	case 5:
+		return &mfObject{brush: &mfBrush{null: true}}
+	case 6:
+		return &mfObject{pen: &mfPen{col: white}}
+	case 7:
+		return &mfObject{pen: &mfPen{col: gray(0)}}
+	case 8:
+		return &mfObject{pen: &mfPen{null: true}}
+	case 10, 11, 12, 13, 14, 16, 17:
+		return &mfObject{font: &mfFont{height: -12, weight: 400}}
+	}
+	return nil
+}
+
+// penFromStyle builds a pen from a GDI pen style, width and colour
+func penFromStyle(style uint32, width float64, col uint32) *mfPen {
+	if style&0x0F == 5 { // PS_NULL
+		return &mfPen{null: true}
+	}
+	return &mfPen{col: colorRef(col), width: math.Abs(width)}
+}
+
+// brushFromStyle builds a brush from a GDI brush style and colour
+func brushFromStyle(style uint32, col uint32) *mfBrush {
+	switch style {
+	case 1: // BS_NULL
+		return &mfBrush{null: true}
+	case 2: // BS_HATCHED: the hatch lines cover about a third of the area
+		cl := colorRef(col)
+		cl.A = 90
+		return &mfBrush{col: cl}
+	case 0:
+		return &mfBrush{col: colorRef(col)}
+	}
+	// pattern brushes: a neutral fill keeps the shape visible
+	return &mfBrush{col: color.NRGBA{0xC0, 0xC0, 0xC0, 255}}
+}
+
+/* ---------------- drawing ---------------- */
+
+// shape fills (when closed) and outlines a set of logical polygons
+func (c *mfCanvas) shape(polys [][]mfPt, closed bool) {
+	px := make([][]mfPt, 0, len(polys))
+	for _, poly := range polys {
+		if len(poly) < 2 {
+			continue
+		}
+		q := make([]mfPt, len(poly))
+		for i, p := range poly {
+			q[i] = c.px(p)
+		}
+		px = append(px, q)
+	}
+	if len(px) == 0 {
+		return
+	}
+	if c.inPath {
+		for _, q := range px {
+			c.path = append(c.path, q)
+			c.pathOpen = append(c.pathOpen, !closed)
+		}
+		return
+	}
+	c.drawPx(px, closed, closed, true)
+}
+
+// drawPx fills and / or strokes polygons already in output pixels
+func (c *mfCanvas) drawPx(px [][]mfPt, fill, closed, stroke bool) {
+	if fill && !c.dc.brush.null && c.dc.brush.col.A > 0 {
+		c.drewVector = true
+		if !c.measure {
+			c.fillPolys(px, c.dc.brush.col)
+		}
+	}
+	if stroke && !c.dc.pen.null {
+		c.drewVector = true
+		if !c.measure {
+			wx, wy := c.pxLen(c.dc.pen.width)
+			w := (wx + wy) / 2
+			if c.dc.pen.width == 0 || w < 1 {
+				w = 1
+			}
+			c.strokePolys(px, closed, w, c.dc.pen.col)
+		}
+	}
+}
+
+func (c *mfCanvas) fillPolys(px [][]mfPt, col color.NRGBA) {
+	c.ras.Reset(c.w, c.h)
+	for _, poly := range px {
+		if len(poly) < 3 {
+			continue
+		}
+		c.ras.MoveTo(float32(poly[0].X), float32(poly[0].Y))
+		for _, p := range poly[1:] {
+			c.ras.LineTo(float32(p.X), float32(p.Y))
+		}
+		c.ras.ClosePath()
+	}
+	c.ras.Draw(c.img, c.img.Bounds(), image.NewUniform(col), image.Point{})
+}
+
+// strokePolys outlines polylines as one coverage pass: a quad per segment
+// and a round-ish cap at every vertex, all wound the same way so the
+// overlaps do not cancel out
+func (c *mfCanvas) strokePolys(px [][]mfPt, closed bool, width float64, col color.NRGBA) {
+	hw := width / 2
+	c.ras.Reset(c.w, c.h)
+	quad := func(a, b mfPt) {
+		dx, dy := b.X-a.X, b.Y-a.Y
+		l := math.Hypot(dx, dy)
+		if l < 1e-9 {
+			return
+		}
+		nx, ny := -dy/l*hw, dx/l*hw
+		c.ras.MoveTo(float32(a.X+nx), float32(a.Y+ny))
+		c.ras.LineTo(float32(b.X+nx), float32(b.Y+ny))
+		c.ras.LineTo(float32(b.X-nx), float32(b.Y-ny))
+		c.ras.LineTo(float32(a.X-nx), float32(a.Y-ny))
+		c.ras.ClosePath()
+	}
+	join := func(p mfPt) {
+		if hw <= 0.75 {
+			return
+		}
+		const n = 10
+		for i := 0; i <= n; i++ {
+			t := -2 * math.Pi * float64(i) / n
+			x, y := float32(p.X+hw*math.Cos(t)), float32(p.Y+hw*math.Sin(t))
+			if i == 0 {
+				c.ras.MoveTo(x, y)
+			} else {
+				c.ras.LineTo(x, y)
+			}
+		}
+		c.ras.ClosePath()
+	}
+	for _, poly := range px {
+		for i := 0; i+1 < len(poly); i++ {
+			quad(poly[i], poly[i+1])
+			join(poly[i])
+		}
+		if len(poly) > 0 {
+			join(poly[len(poly)-1])
+		}
+		if closed && len(poly) > 2 {
+			quad(poly[len(poly)-1], poly[0])
+		}
+	}
+	c.ras.Draw(c.img, c.img.Bounds(), image.NewUniform(col), image.Point{})
+}
+
+/* ---------------- geometry helpers (logical space) ---------------- */
+
+func rectPoly(l, t, r, b float64) []mfPt {
+	return []mfPt{{l, t}, {r, t}, {r, b}, {l, b}}
+}
+
+func ellipsePoly(l, t, r, b float64) []mfPt {
+	cx, cy := (l+r)/2, (t+b)/2
+	rx, ry := math.Abs(r-l)/2, math.Abs(b-t)/2
+	n := 64
+	pts := make([]mfPt, n)
+	for i := range pts {
+		a := 2 * math.Pi * float64(i) / float64(n)
+		pts[i] = mfPt{cx + rx*math.Cos(a), cy + ry*math.Sin(a)}
+	}
+	return pts
+}
+
+func roundRectPoly(l, t, r, b, cw, ch float64) []mfPt {
+	if r < l {
+		l, r = r, l
+	}
+	if b < t {
+		t, b = b, t
+	}
+	rx := math.Min(math.Abs(cw)/2, (r-l)/2)
+	ry := math.Min(math.Abs(ch)/2, (b-t)/2)
+	if rx <= 0 || ry <= 0 {
+		return rectPoly(l, t, r, b)
+	}
+	var pts []mfPt
+	corner := func(cx, cy, a0 float64) {
+		for i := 0; i <= 8; i++ {
+			a := a0 + math.Pi/2*float64(i)/8
+			pts = append(pts, mfPt{cx + rx*math.Cos(a), cy + ry*math.Sin(a)})
+		}
+	}
+	corner(r-rx, t+ry, -math.Pi/2)
+	corner(r-rx, b-ry, 0)
+	corner(l+rx, b-ry, math.Pi/2)
+	corner(l+rx, t+ry, math.Pi)
+	return pts
+}
+
+// arcPoly walks an ellipse counterclockwise (as seen on screen) from the
+// ray through start to the ray through end, as GDI's Arc / Pie / Chord do
+func arcPoly(l, t, r, b float64, start, end mfPt) []mfPt {
+	cx, cy := (l+r)/2, (t+b)/2
+	rx, ry := math.Abs(r-l)/2, math.Abs(b-t)/2
+	if rx == 0 || ry == 0 {
+		return nil
+	}
+	a0 := math.Atan2(-(start.Y-cy)/ry, (start.X-cx)/rx)
+	a1 := math.Atan2(-(end.Y-cy)/ry, (end.X-cx)/rx)
+	for a1 <= a0 {
+		a1 += 2 * math.Pi
+	}
+	n := int(math.Ceil((a1-a0)/(2*math.Pi)*64)) + 1
+	pts := make([]mfPt, 0, n+1)
+	for i := 0; i <= n; i++ {
+		a := a0 + (a1-a0)*float64(i)/float64(n)
+		pts = append(pts, mfPt{cx + rx*math.Cos(a), cy - ry*math.Sin(a)})
+	}
+	return pts
+}
+
+// bezierPoly flattens cubic segments: pts is a start point followed by
+// (control, control, end) triples
+func bezierPoly(pts []mfPt) []mfPt {
+	if len(pts) == 0 {
+		return nil
+	}
+	out := []mfPt{pts[0]}
+	for i := 1; i+2 < len(pts); i += 3 {
+		p0, p1, p2, p3 := out[len(out)-1], pts[i], pts[i+1], pts[i+2]
+		const n = 16
+		for k := 1; k <= n; k++ {
+			t := float64(k) / n
+			u := 1 - t
+			out = append(out, mfPt{
+				u*u*u*p0.X + 3*u*u*t*p1.X + 3*u*t*t*p2.X + t*t*t*p3.X,
+				u*u*u*p0.Y + 3*u*u*t*p1.Y + 3*u*t*t*p2.Y + t*t*t*p3.Y,
+			})
+		}
+	}
+	return out
+}
+
+/* ---------------- path bracket (EMF) ---------------- */
+
+func (c *mfCanvas) beginPath() {
+	c.inPath = true
+	c.path, c.pathOpen = nil, nil
+}
+
+// pathMoveTo starts a new subpath at a logical point
+func (c *mfCanvas) pathMoveTo(p mfPt) {
+	c.path = append(c.path, []mfPt{c.px(p)})
+	c.pathOpen = append(c.pathOpen, true)
+}
+
+// pathLineTo appends logical points to the open subpath
+func (c *mfCanvas) pathLineTo(pts ...mfPt) {
+	if len(c.path) == 0 || !c.pathOpen[len(c.path)-1] {
+		c.pathMoveTo(c.dc.cur)
+	}
+	i := len(c.path) - 1
+	for _, p := range pts {
+		c.path[i] = append(c.path[i], c.px(p))
+	}
+}
+
+func (c *mfCanvas) closeFigure() {
+	if n := len(c.path); n > 0 {
+		c.pathOpen[n-1] = false
+	}
+}
+
+func (c *mfCanvas) drawPath(fill, stroke bool) {
+	if len(c.path) == 0 {
+		return
+	}
+	var closed, open [][]mfPt
+	for i, sp := range c.path {
+		if fill || !c.pathOpen[i] {
+			closed = append(closed, sp)
+		} else {
+			open = append(open, sp)
+		}
+	}
+	if len(closed) > 0 {
+		c.drawPx(closed, fill, true, stroke)
+	}
+	if len(open) > 0 {
+		c.drawPx(open, false, false, stroke)
+	}
+	c.path, c.pathOpen = nil, nil
+}
+
+/* ---------------- bitmaps ---------------- */
+
+const (
+	ropSrcCopy    = 0x00CC0020
+	ropSrcPaint   = 0x00EE0086
+	ropSrcAnd     = 0x008800C6
+	ropSrcInvert  = 0x00660046
+	ropSrcErase   = 0x00440328
+	ropNotSrcCopy = 0x00330008
+	ropMergePaint = 0x00BB0226
+	ropPatCopy    = 0x00F00021
+	ropBlackness  = 0x00000042
+	ropWhiteness  = 0x00FF0062
+)
+
+// blit draws src (only srcRect of it) into the logical destination
+// rectangle at (x, y) with size (w, h); a negative size mirrors
+func (c *mfCanvas) blit(src image.Image, srcRect image.Rectangle, x, y, w, h float64, rop uint32, photo bool) {
+	srcRect = srcRect.Canon()
+	b := src.Bounds()
+	if !srcRect.Overlaps(b) {
+		return
+	}
+	// a source rectangle past the bitmap edge: keep the part that exists
+	// and shrink the destination with it
+	clip := srcRect.Intersect(b)
+	if clip != srcRect {
+		fx := w / float64(srcRect.Dx())
+		fy := h / float64(srcRect.Dy())
+		x += float64(clip.Min.X-srcRect.Min.X) * fx
+		y += float64(clip.Min.Y-srcRect.Min.Y) * fy
+		w = float64(clip.Dx()) * fx
+		h = float64(clip.Dy()) * fy
+		srcRect = clip
+	}
+	tl := c.px(mfPt{x, y})
+	tr := c.px(mfPt{x + w, y})
+	bl := c.px(mfPt{x, y + h})
+	dw := math.Hypot(tr.X-tl.X, tr.Y-tl.Y)
+	dh := math.Hypot(bl.X-tl.X, bl.Y-tl.Y)
+	if dw < 0.5 || dh < 0.5 {
+		return
+	}
+	c.drewBitmap = true
+	if c.measure {
+		// the CSS size the bitmap covers decides the output resolution
+		r := math.Max(float64(srcRect.Dx())/dw, float64(srcRect.Dy())/dh)
+		if r > c.maxRatio {
+			c.maxRatio = r
+		}
+		if photo {
+			c.photo = true
+		}
+		return
+	}
+	sw, sh := float64(srcRect.Dx()), float64(srcRect.Dy())
+	s2d := f64.Aff3{
+		(tr.X - tl.X) / sw, (bl.X - tl.X) / sh, 0,
+		(tr.Y - tl.Y) / sw, (bl.Y - tl.Y) / sh, 0,
+	}
+	s2d[2] = tl.X - s2d[0]*float64(srcRect.Min.X) - s2d[1]*float64(srcRect.Min.Y)
+	s2d[5] = tl.Y - s2d[3]*float64(srcRect.Min.X) - s2d[4]*float64(srcRect.Min.Y)
+
+	var interp xdraw.Transformer = xdraw.BiLinear
+	if sw/dw > 1.5 || sh/dh > 1.5 {
+		interp = xdraw.CatmullRom
+	}
+	switch rop {
+	case ropSrcCopy, 0:
+		c.transform(interp, s2d, src, srcRect, c.img)
+		return
+	}
+	// a bitwise raster op: render the source alone, then combine
+	box := image.Rect(
+		int(math.Floor(math.Min(math.Min(tl.X, tr.X), math.Min(bl.X, tr.X+bl.X-tl.X)))),
+		int(math.Floor(math.Min(math.Min(tl.Y, tr.Y), math.Min(bl.Y, tr.Y+bl.Y-tl.Y)))),
+		int(math.Ceil(math.Max(math.Max(tl.X, tr.X), math.Max(bl.X, tr.X+bl.X-tl.X)))),
+		int(math.Ceil(math.Max(math.Max(tl.Y, tr.Y), math.Max(bl.Y, tr.Y+bl.Y-tl.Y)))),
+	).Intersect(c.img.Bounds())
+	if box.Empty() {
+		return
+	}
+	tmp := image.NewRGBA(box)
+	c.transform(interp, s2d, src, srcRect, tmp)
+	for yy := box.Min.Y; yy < box.Max.Y; yy++ {
+		for xx := box.Min.X; xx < box.Max.X; xx++ {
+			si := tmp.PixOffset(xx, yy)
+			if tmp.Pix[si+3] == 0 {
+				continue
+			}
+			di := c.img.PixOffset(xx, yy)
+			c.ropPixel(c.img.Pix[di:di+4], tmp.Pix[si:si+4], rop)
+		}
+	}
+}
+
+func (c *mfCanvas) transform(interp xdraw.Transformer, s2d f64.Aff3, src image.Image, sr image.Rectangle, dst *image.RGBA) {
+	// a 1:1 copy at whole pixel offsets needs no resampling
+	if s2d[0] == 1 && s2d[4] == 1 && s2d[1] == 0 && s2d[3] == 0 &&
+		s2d[2] == math.Trunc(s2d[2]) && s2d[5] == math.Trunc(s2d[5]) {
+		off := image.Pt(int(s2d[2]), int(s2d[5]))
+		xdraw.Draw(dst, sr.Add(off), src, sr.Min, xdraw.Over)
+		return
+	}
+	interp.Transform(dst, s2d, src, sr, xdraw.Over, nil)
+}
+
+// ropPixel combines a source pixel into a destination pixel with a GDI
+// raster op. The empty (transparent) canvas counts as the white page, and
+// a result that is still white there stays transparent, so the classic
+// mask (AND) + image (OR) pair keeps its transparent background.
+func (c *mfCanvas) ropPixel(d, s []uint8, rop uint32) {
+	empty := d[3] == 0
+	var dc [3]uint32
+	for i := 0; i < 3; i++ {
+		// premultiplied over white
+		dc[i] = uint32(d[i]) + 255 - uint32(d[3])
+	}
+	var out [3]uint32
+	for i := 0; i < 3; i++ {
+		sv := uint32(s[i]) + 255 - uint32(s[3])
+		dv := dc[i]
+		switch rop {
+		case ropSrcAnd:
+			out[i] = sv & dv
+		case ropSrcPaint:
+			out[i] = sv | dv
+		case ropSrcInvert:
+			out[i] = (sv ^ dv) & 0xFF
+		case ropSrcErase:
+			out[i] = sv & (^dv & 0xFF)
+		case ropNotSrcCopy:
+			out[i] = ^sv & 0xFF
+		case ropMergePaint:
+			out[i] = (^sv & 0xFF) | dv
+		default:
+			out[i] = sv
+		}
+	}
+	if empty && out[0] == 255 && out[1] == 255 && out[2] == 255 {
+		return
+	}
+	d[0], d[1], d[2], d[3] = uint8(out[0]), uint8(out[1]), uint8(out[2]), 255
+}
+
+// patBlt fills a logical rectangle for the source-less raster ops
+func (c *mfCanvas) patBlt(x, y, w, h float64, rop uint32) {
+	var col color.NRGBA
+	switch rop {
+	case ropPatCopy:
+		if c.dc.brush.null {
+			return
+		}
+		col = c.dc.brush.col
+	case ropBlackness:
+		col = color.NRGBA{A: 255}
+	case ropWhiteness:
+		col = color.NRGBA{255, 255, 255, 255}
+	default:
+		return
+	}
+	poly := rectPoly(x, y, x+w, y+h)
+	px := make([]mfPt, len(poly))
+	for i, p := range poly {
+		px[i] = c.px(p)
+	}
+	c.drewVector = true
+	if !c.measure {
+		c.fillPolys([][]mfPt{px}, col)
+	}
+}
+
+/* ---------------- DIB decoding ---------------- */
+
+// dibInfo is the parsed part of a BITMAPINFO header
+type dibInfo struct {
+	w, h      int
+	topDown   bool
+	bpp       int
+	comp      uint32
+	masks     [4]uint32 // r g b a (bit fields)
+	palette   []color.NRGBA
+	headerLen int // header + masks + colour table
+}
+
+func parseDIBHeader(b []byte, usage uint32) (*dibInfo, error) {
+	if len(b) < 12 {
+		return nil, errors.New("DIB header truncated")
+	}
+	hs := int(binary.LittleEndian.Uint32(b))
+	d := &dibInfo{}
+	entry := 4
+	nColors := 0
+	if hs == 12 {
+		d.w = int(binary.LittleEndian.Uint16(b[4:]))
+		d.h = int(int16(binary.LittleEndian.Uint16(b[6:])))
+		d.bpp = int(binary.LittleEndian.Uint16(b[10:]))
+		entry = 3
+	} else {
+		if hs < 40 || len(b) < 40 {
+			return nil, errors.New("unsupported DIB header")
+		}
+		d.w = int(int32(binary.LittleEndian.Uint32(b[4:])))
+		d.h = int(int32(binary.LittleEndian.Uint32(b[8:])))
+		d.bpp = int(binary.LittleEndian.Uint16(b[14:]))
+		d.comp = binary.LittleEndian.Uint32(b[16:])
+		nColors = int(binary.LittleEndian.Uint32(b[32:]))
+	}
+	if d.h < 0 {
+		d.h = -d.h
+		d.topDown = true
+	}
+	if d.w <= 0 || d.h <= 0 || d.w*d.h > mfMaxDIBPixels || d.w > 1<<16 || d.h > 1<<16 {
+		return nil, errors.New("DIB has an unusable size")
+	}
+	off := hs
+	if d.comp == 3 || d.comp == 6 { // BI_BITFIELDS / BI_ALPHABITFIELDS
+		n := 3
+		if d.comp == 6 {
+			n = 4
+		}
+		if hs >= 52 {
+			// V2+ headers hold the masks themselves
+			for i := 0; i < 4 && 40+4*i+4 <= hs && 40+4*i+4 <= len(b); i++ {
+				d.masks[i] = binary.LittleEndian.Uint32(b[40+4*i:])
+			}
+		} else {
+			if len(b) < hs+4*n {
+				return nil, errors.New("DIB masks truncated")
+			}
+			for i := 0; i < n; i++ {
+				d.masks[i] = binary.LittleEndian.Uint32(b[hs+4*i:])
+			}
+			off += 4 * n
+		}
+	} else if hs >= 56 && len(b) >= 56 {
+		d.masks[3] = binary.LittleEndian.Uint32(b[52:])
+	}
+	if d.bpp <= 8 {
+		if nColors == 0 || nColors > 1<<d.bpp {
+			nColors = 1 << d.bpp
+		}
+	}
+	if usage == 1 { // DIB_PAL_COLORS: 16-bit indices into a palette we do not have
+		entry = 2
+	}
+	if nColors > 0 {
+		if len(b) < off+nColors*entry {
+			return nil, errors.New("DIB colour table truncated")
+		}
+		d.palette = make([]color.NRGBA, nColors)
+		for i := range d.palette {
+			e := b[off+i*entry:]
+			if entry == 2 {
+				v := uint8(255 * i / maxInt(nColors-1, 1))
+				d.palette[i] = color.NRGBA{v, v, v, 255}
+			} else {
+				d.palette[i] = color.NRGBA{e[2], e[1], e[0], 255}
+			}
+		}
+		off += nColors * entry
+	}
+	d.headerLen = off
+	return d, nil
+}
+
+// decodePackedDIB decodes a DIB whose pixels follow the header and
+// colour table directly (the WMF layout)
+func decodePackedDIB(b []byte, usage uint32) (image.Image, *dibInfo, error) {
+	d, err := parseDIBHeader(b, usage)
+	if err != nil {
+		return nil, nil, err
+	}
+	if d.headerLen > len(b) {
+		return nil, nil, errors.New("DIB truncated")
+	}
+	img, err := d.decode(b[d.headerLen:])
+	return img, d, err
+}
+
+// decodeDIB decodes a DIB with its header and pixels apart (the EMF layout)
+func decodeDIB(bmi, bits []byte, usage uint32) (image.Image, *dibInfo, error) {
+	d, err := parseDIBHeader(bmi, usage)
+	if err != nil {
+		return nil, nil, err
+	}
+	img, err := d.decode(bits)
+	return img, d, err
+}
+
+// isPhoto reports a bitmap that compresses better as JPEG than PNG
+func (d *dibInfo) isPhoto() bool {
+	return d.bpp >= 16 || d.comp == 4
+}
+
+func (d *dibInfo) decode(bits []byte) (image.Image, error) {
+	switch d.comp {
+	case 4, 5: // BI_JPEG / BI_PNG
+		img, _, err := image.Decode(bytes.NewReader(bits))
+		return img, err
+	case 1:
+		if d.bpp != 8 {
+			return nil, errors.New("RLE8 DIB with wrong depth")
+		}
+		return d.fromIndices(decodeRLE(bits, d.w, d.h, false), d.w)
+	case 2:
+		if d.bpp != 4 {
+			return nil, errors.New("RLE4 DIB with wrong depth")
+		}
+		return d.fromIndices(decodeRLE(bits, d.w, d.h, true), d.w)
+	case 0, 3, 6:
+	default:
+		return nil, errors.New("unsupported DIB compression")
+	}
+	img := image.NewNRGBA(image.Rect(0, 0, d.w, d.h))
+	stride := ((d.w*d.bpp + 31) / 32) * 4
+	masks := d.masks
+	if d.comp == 0 {
+		switch d.bpp {
+		case 16:
+			masks = [4]uint32{0x7C00, 0x03E0, 0x001F, 0}
+		case 32:
+			masks = [4]uint32{0xFF0000, 0x00FF00, 0x0000FF, d.masks[3]}
+		}
+	}
+	type field struct {
+		shift uint
+		max   uint32
+	}
+	var fields [4]field
+	for i, m := range masks {
+		if m == 0 {
+			continue
+		}
+		s := uint(0)
+		for m&1 == 0 {
+			m >>= 1
+			s++
+		}
+		fields[i] = field{s, m}
+	}
+	hasAlpha := masks[3] != 0
+	anyAlpha := false
+	for y := 0; y < d.h; y++ {
+		sy := d.h - 1 - y
+		if d.topDown {
+			sy = y
+		}
+		row := sy * stride
+		if row+stride > len(bits) {
+			if row >= len(bits) {
+				continue
+			}
+		}
+		line := bits[row:min(row+stride, len(bits))]
+		o := img.PixOffset(0, y)
+		for x := 0; x < d.w; x++ {
+			var c color.NRGBA
+			switch d.bpp {
+			case 1, 2, 4, 8:
+				bit := x * d.bpp
+				if bit/8 >= len(line) {
+					continue
+				}
+				idx := int(line[bit/8]>>(8-uint(d.bpp)-uint(bit%8))) & (1<<d.bpp - 1)
+				if idx < len(d.palette) {
+					c = d.palette[idx]
+				} else {
+					c = color.NRGBA{A: 255}
+				}
+			case 24:
+				i := x * 3
+				if i+2 >= len(line) {
+					continue
+				}
+				c = color.NRGBA{line[i+2], line[i+1], line[i], 255}
+			case 16, 32:
+				n := d.bpp / 8
+				i := x * n
+				if i+n > len(line) {
+					continue
+				}
+				var v uint32
+				if n == 2 {
+					v = uint32(binary.LittleEndian.Uint16(line[i:]))
+				} else {
+					v = binary.LittleEndian.Uint32(line[i:])
+				}
+				ch := func(f field) uint8 {
+					if f.max == 0 {
+						return 0
+					}
+					return uint8(((v >> f.shift) & f.max) * 255 / f.max)
+				}
+				c = color.NRGBA{ch(fields[0]), ch(fields[1]), ch(fields[2]), 255}
+				if hasAlpha {
+					c.A = ch(fields[3])
+					if c.A != 0 {
+						anyAlpha = true
+					}
+				}
+			default:
+				return nil, errors.New("unsupported DIB depth")
+			}
+			copy(img.Pix[o+4*x:], []uint8{c.R, c.G, c.B, c.A})
+		}
+	}
+	if hasAlpha && !anyAlpha {
+		// an alpha channel that is all zero is unused, not invisible
+		for i := 3; i < len(img.Pix); i += 4 {
+			img.Pix[i] = 255
+		}
+	}
+	return img, nil
+}
+
+// fromIndices builds an image from palette indices laid out bottom-up
+func (d *dibInfo) fromIndices(idx []uint8, w int) (image.Image, error) {
+	img := image.NewNRGBA(image.Rect(0, 0, d.w, d.h))
+	for y := 0; y < d.h; y++ {
+		sy := d.h - 1 - y
+		if d.topDown {
+			sy = y
+		}
+		for x := 0; x < d.w; x++ {
+			v := int(idx[sy*w+x])
+			c := color.NRGBA{A: 255}
+			if v < len(d.palette) {
+				c = d.palette[v]
+			}
+			o := img.PixOffset(x, y)
+			img.Pix[o], img.Pix[o+1], img.Pix[o+2], img.Pix[o+3] = c.R, c.G, c.B, c.A
+		}
+	}
+	return img, nil
+}
+
+// decodeRLE expands BI_RLE8 / BI_RLE4 data into one index per pixel, rows
+// in file order (bottom-up)
+func decodeRLE(b []byte, w, h int, four bool) []uint8 {
+	out := make([]uint8, w*h)
+	x, y := 0, 0
+	put := func(v uint8) {
+		if x < w && y < h {
+			out[y*w+x] = v
+		}
+		x++
+	}
+	for i := 0; i+1 < len(b); {
+		n, v := int(b[i]), b[i+1]
+		i += 2
+		if n > 0 {
+			for k := 0; k < n; k++ {
+				if four {
+					if k%2 == 0 {
+						put(v >> 4)
+					} else {
+						put(v & 0x0F)
+					}
+				} else {
+					put(v)
+				}
+			}
+			continue
+		}
+		switch v {
+		case 0: // end of line
+			x, y = 0, y+1
+		case 1: // end of bitmap
+			return out
+		case 2: // delta
+			if i+1 >= len(b) {
+				return out
+			}
+			x += int(b[i])
+			y += int(b[i+1])
+			i += 2
+		default: // absolute run of v pixels
+			cnt := int(v)
+			if four {
+				nb := (cnt + 1) / 2
+				for k := 0; k < cnt && i+k/2 < len(b); k++ {
+					p := b[i+k/2]
+					if k%2 == 0 {
+						put(p >> 4)
+					} else {
+						put(p & 0x0F)
+					}
+				}
+				i += nb
+				if nb%2 == 1 {
+					i++
+				}
+			} else {
+				for k := 0; k < cnt && i+k < len(b); k++ {
+					put(b[i+k])
+				}
+				i += cnt
+				if cnt%2 == 1 {
+					i++
+				}
+			}
+		}
+		if y >= h {
+			return out
+		}
+	}
+	return out
+}
+
+/* ---------------- text ---------------- */
+
+var (
+	mfFontsOnce sync.Once
+	mfFonts     map[string]*opentype.Font
+)
+
+// mfFontFor picks the bundled Go font closest to a metafile font
+func mfFontFor(f mfFont) *opentype.Font {
+	mfFontsOnce.Do(func() {
+		mfFonts = map[string]*opentype.Font{}
+		for name, ttf := range map[string][]byte{
+			"regular": goregular.TTF, "bold": gobold.TTF, "italic": goitalic.TTF,
+			"bolditalic": gobolditalic.TTF, "mono": gomono.TTF,
+		} {
+			if fnt, err := opentype.Parse(ttf); err == nil {
+				mfFonts[name] = fnt
+			}
+		}
+	})
+	face := strings.ToLower(f.face)
+	if strings.Contains(face, "courier") || strings.Contains(face, "mono") || strings.Contains(face, "consolas") {
+		return mfFonts["mono"]
+	}
+	bold := f.weight >= 600
+	switch {
+	case bold && f.italic:
+		return mfFonts["bolditalic"]
+	case bold:
+		return mfFonts["bold"]
+	case f.italic:
+		return mfFonts["italic"]
+	}
+	return mfFonts["regular"]
+}
+
+// text draws a run of text at a logical reference point; dx, when given,
+// is the logical advance of each character
+func (c *mfCanvas) text(ref mfPt, s []rune, dx []float64) {
+	if len(s) == 0 {
+		return
+	}
+	c.drewVector = true
+	f := c.dc.font
+	update := c.dc.textAlign&1 != 0 // TA_UPDATECP
+	if update {
+		ref = c.dc.cur
+	}
+	_, sy := c.pxLen(f.height)
+	size := sy
+	if f.height > 0 {
+		// a positive height is the cell height, internal leading included
+		size *= 0.82
+	}
+	if f.height == 0 {
+		_, size = c.pxLen(12)
+	}
+	if size < 1 || size > 2000 {
+		return
+	}
+	fnt := mfFontFor(f)
+	if fnt == nil {
+		return
+	}
+	face, err := opentype.NewFace(fnt, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingNone})
+	if err != nil {
+		return
+	}
+	defer face.Close()
+
+	// glyph positions along the baseline, in output pixels from the start
+	pos := make([]float64, len(s)+1)
+	if len(dx) >= len(s) {
+		for i := range s {
+			w, _ := c.pxLen(dx[i])
+			pos[i+1] = pos[i] + w
+		}
+	} else {
+		for i, r := range s {
+			adv, _ := face.GlyphAdvance(r)
+			pos[i+1] = pos[i] + float64(adv)/64
+		}
+	}
+	width := pos[len(s)]
+	m := face.Metrics()
+	ascent, descent := float64(m.Ascent)/64, float64(m.Descent)/64
+
+	// alignment, measured along the text direction
+	ox := 0.0
+	switch c.dc.textAlign & 6 {
+	case 2: // TA_RIGHT
+		ox = -width
+	case 6: // TA_CENTER
+		ox = -width / 2
+	}
+	oy := ascent // TA_TOP
+	switch c.dc.textAlign & 24 {
+	case 8: // TA_BOTTOM
+		oy = -descent
+	case 24: // TA_BASELINE
+		oy = 0
+	}
+	if update {
+		// the current position moves to the end of the text
+		w, _ := c.pxLen(1)
+		if w > 0 {
+			c.dc.cur.X += width / w
+		}
+	}
+	if c.measure {
+		return
+	}
+
+	// render horizontally into a scratch image, then place it (rotated
+	// when the font has an escapement)
+	pad := 2
+	tw := int(math.Ceil(width)) + 2*pad
+	th := int(math.Ceil(ascent+descent)) + 2*pad
+	if tw <= 0 || th <= 0 || tw*th > mfMaxPixels {
+		return
+	}
+	tmp := image.NewRGBA(image.Rect(0, 0, tw, th))
+	src := image.NewUniform(c.dc.textColor)
+	base := float64(pad) + ascent
+	for i, r := range s {
+		d := font.Drawer{Dst: tmp, Src: src, Face: face,
+			Dot: fixed.Point26_6{X: fixed.Int26_6((float64(pad) + pos[i]) * 64), Y: fixed.Int26_6(base * 64)}}
+		d.DrawString(string(r))
+	}
+	if f.underline || f.strike {
+		lw := math.Max(1, size/16)
+		yy := base + size*0.12
+		if f.strike {
+			yy = base - ascent*0.3
+		}
+		for y := int(yy); y < int(yy+lw) && y < th; y++ {
+			for x := pad; x < pad+int(width) && x < tw; x++ {
+				o := tmp.PixOffset(x, y)
+				cc := c.dc.textColor
+				tmp.Pix[o], tmp.Pix[o+1], tmp.Pix[o+2], tmp.Pix[o+3] = cc.R, cc.G, cc.B, 255
+			}
+		}
+	}
+
+	p := c.px(ref)
+	ang := -f.escapement / 10 * math.Pi / 180 // screen y grows downward
+	if c.toCSSFlipsY() {
+		ang = -ang
+	}
+	cos, sin := math.Cos(ang), math.Sin(ang)
+	// scratch (u, v) -> canvas: rotate the offset from the reference point
+	u0 := float64(pad) - ox
+	v0 := base - oy
+	aff := f64.Aff3{cos, -sin, 0, sin, cos, 0}
+	aff[2] = p.X - (cos*u0 - sin*v0)
+	aff[5] = p.Y - (sin*u0 + cos*v0)
+	if ang == 0 && aff[2] == math.Trunc(aff[2]) && aff[5] == math.Trunc(aff[5]) {
+		xdraw.Draw(c.img, tmp.Bounds().Add(image.Pt(int(aff[2]), int(aff[5]))), tmp, image.Point{}, xdraw.Over)
+		return
+	}
+	xdraw.BiLinear.Transform(c.img, aff, tmp, tmp.Bounds(), xdraw.Over, nil)
+}
+
+// toCSSFlipsY reports a mapping whose y axis points up (the metric and
+// English map modes), which mirrors the sense of an escapement angle
+func (c *mfCanvas) toCSSFlipsY() bool {
+	a := c.px(mfPt{0, 0})
+	b := c.px(mfPt{0, 1})
+	return b.Y < a.Y
+}
+
+// opaqueBox fills a logical rectangle with the background colour (the
+// ETO_OPAQUE box behind a text run)
+func (c *mfCanvas) opaqueBox(l, t, r, b float64) {
+	if r == l || b == t {
+		return
+	}
+	poly := rectPoly(l, t, r, b)
+	px := make([]mfPt, len(poly))
+	for i, p := range poly {
+		px[i] = c.px(p)
+	}
+	c.drewVector = true
+	if !c.measure {
+		c.fillPolys([][]mfPt{px}, c.dc.bkColor)
+	}
+}

+ 465 - 0
src/mod/office/metafile_emf.go

@@ -0,0 +1,465 @@
+package office
+
+/*
+	metafile_emf.go - plays Enhanced Metafile (EMF) records onto an mfCanvas
+
+	An EMF is a list of records (32-bit type and size, then parameters).
+	Coordinates go logical -> world transform -> page -> device (through the
+	map mode, window and viewport); the header's frame (0.01 mm) and its
+	reference device size place the picture in device units.
+
+	EMF+ records ride inside GDI comments; files written in "dual" mode
+	keep the plain EMF drawing next to them, which is what is played.
+*/
+
+import (
+	"encoding/binary"
+	"errors"
+	"image"
+	"math"
+)
+
+type emfPlayer struct {
+	data []byte
+	// the picture frame in device units and its CSS pixel size
+	devOrg       mfPt
+	devW, devH   float64
+	cssW, cssH   float64
+	devPerMMX    float64
+	devPerMMY    float64
+	recordsStart int
+}
+
+func newEmfPlayer(data []byte) (*emfPlayer, error) {
+	if len(data) < 88 {
+		return nil, errors.New("EMF header truncated")
+	}
+	i32 := func(o int) float64 { return float64(int32(binary.LittleEndian.Uint32(data[o:]))) }
+	p := &emfPlayer{data: data}
+	bl, bt, br, bb := i32(8), i32(12), i32(16), i32(20)
+	fl, ft, fr, fb := i32(24), i32(28), i32(32), i32(36)
+	devCX, devCY := i32(72), i32(76)
+	mmCX, mmCY := i32(80), i32(84)
+	p.devPerMMX, p.devPerMMY = 96/25.4, 96/25.4
+	if devCX > 0 && devCY > 0 && mmCX > 0 && mmCY > 0 {
+		p.devPerMMX, p.devPerMMY = devCX/mmCX, devCY/mmCY
+	}
+	if fr > fl && fb > ft {
+		// frame: 0.01 mm, inclusive
+		p.devOrg = mfPt{fl / 100 * p.devPerMMX, ft / 100 * p.devPerMMY}
+		p.devW = (fr - fl) / 100 * p.devPerMMX
+		p.devH = (fb - ft) / 100 * p.devPerMMY
+		p.cssW = (fr - fl) / 100 / 25.4 * 96
+		p.cssH = (fb - ft) / 100 / 25.4 * 96
+	} else if br > bl && bb > bt {
+		p.devOrg = mfPt{bl, bt}
+		p.devW, p.devH = br-bl+1, bb-bt+1
+		p.cssW = p.devW / p.devPerMMX / 25.4 * 96
+		p.cssH = p.devH / p.devPerMMY / 25.4 * 96
+	} else {
+		return nil, errors.New("EMF has an empty frame")
+	}
+	p.recordsStart = int(binary.LittleEndian.Uint32(data[4:]))
+	if p.recordsStart < 88 || p.recordsStart > len(data) {
+		return nil, errors.New("EMF header size is invalid")
+	}
+	return p, nil
+}
+
+func (p *emfPlayer) baseSize() (float64, float64) {
+	return p.cssW, p.cssH
+}
+
+// toDevice maps a logical point through the world transform and the map
+// mode to device units
+func (p *emfPlayer) toDevice(dc *mfDC, q mfPt) mfPt {
+	x := dc.xf[0]*q.X + dc.xf[2]*q.Y + dc.xf[4]
+	y := dc.xf[1]*q.X + dc.xf[3]*q.Y + dc.xf[5]
+	x -= dc.winOrg.X
+	y -= dc.winOrg.Y
+	switch dc.mapMode {
+	case mmIsotropic, mmAnisotropic:
+		sx, sy := 1.0, 1.0
+		if dc.winExt.X != 0 && dc.winExt.Y != 0 {
+			sx, sy = dc.vpExt.X/dc.winExt.X, dc.vpExt.Y/dc.winExt.Y
+		}
+		if dc.mapMode == mmIsotropic {
+			m := math.Min(math.Abs(sx), math.Abs(sy))
+			sx, sy = math.Copysign(m, sx), math.Copysign(m, sy)
+		}
+		x, y = x*sx, y*sy
+	case mmLoMetric, mmHiMetric, mmLoEnglish, mmHiEnglish, mmTwips:
+		mm := map[int]float64{mmLoMetric: 0.1, mmHiMetric: 0.01, mmLoEnglish: 0.254,
+			mmHiEnglish: 0.0254, mmTwips: 25.4 / 1440}[dc.mapMode]
+		x, y = x*mm*p.devPerMMX, -y*mm*p.devPerMMY
+	}
+	return mfPt{x + dc.vpOrg.X, y + dc.vpOrg.Y}
+}
+
+// emfRec is one record's parameter reader (offsets from the record start)
+type emfRec []byte
+
+func (r emfRec) u32(o int) uint32 {
+	if o+4 > len(r) {
+		return 0
+	}
+	return binary.LittleEndian.Uint32(r[o:])
+}
+
+func (r emfRec) i32(o int) float64 { return float64(int32(r.u32(o))) }
+
+func (r emfRec) i16(o int) float64 {
+	if o+2 > len(r) {
+		return 0
+	}
+	return float64(int16(binary.LittleEndian.Uint16(r[o:])))
+}
+
+func (r emfRec) f32(o int) float64 { return float64(math.Float32frombits(r.u32(o))) }
+
+// points reads n points (32-bit or 16-bit pairs) at offset o
+func (r emfRec) points(o, n int, small bool) []mfPt {
+	sz := 8
+	if small {
+		sz = 4
+	}
+	if n <= 0 || o+n*sz > len(r) {
+		return nil
+	}
+	pts := make([]mfPt, n)
+	for i := range pts {
+		if small {
+			pts[i] = mfPt{r.i16(o + 4*i), r.i16(o + 4*i + 2)}
+		} else {
+			pts[i] = mfPt{r.i32(o + 8*i), r.i32(o + 8*i + 4)}
+		}
+	}
+	return pts
+}
+
+// slice returns the [off, off+size) part of the record, or nil
+func (r emfRec) slice(off, size uint32) []byte {
+	if size == 0 || uint64(off)+uint64(size) > uint64(len(r)) {
+		return nil
+	}
+	return r[off : off+size]
+}
+
+func (p *emfPlayer) play(c *mfCanvas) error {
+	sx, sy := p.cssW/p.devW, p.cssH/p.devH
+	c.toCSS = func(q mfPt) mfPt {
+		d := p.toDevice(&c.dc, q)
+		return mfPt{(d.X - p.devOrg.X) * sx, (d.Y - p.devOrg.Y) * sy}
+	}
+	d := p.data
+	for i := p.recordsStart; i+8 <= len(d); {
+		typ := binary.LittleEndian.Uint32(d[i:])
+		size := int(binary.LittleEndian.Uint32(d[i+4:]))
+		if size < 8 || i+size > len(d) {
+			break
+		}
+		if typ == 14 { // EOF
+			break
+		}
+		p.record(c, typ, emfRec(d[i:i+size]))
+		i += size
+	}
+	return nil
+}
+
+func (p *emfPlayer) record(c *mfCanvas, typ uint32, r emfRec) {
+	switch typ {
+	case 9: // SETWINDOWEXTEX
+		c.dc.winExt = mfPt{r.i32(8), r.i32(12)}
+	case 10: // SETWINDOWORGEX
+		c.dc.winOrg = mfPt{r.i32(8), r.i32(12)}
+	case 11: // SETVIEWPORTEXTEX
+		c.dc.vpExt = mfPt{r.i32(8), r.i32(12)}
+	case 12: // SETVIEWPORTORGEX
+		c.dc.vpOrg = mfPt{r.i32(8), r.i32(12)}
+	case 17: // SETMAPMODE
+		c.dc.mapMode = int(r.u32(8))
+	case 18: // SETBKMODE
+		c.dc.bkOpaque = r.u32(8) == 2
+	case 19: // SETPOLYFILLMODE
+		c.dc.winding = r.u32(8) == 2
+	case 22: // SETTEXTALIGN
+		c.dc.textAlign = r.u32(8)
+	case 24: // SETTEXTCOLOR
+		c.dc.textColor = colorRef(r.u32(8))
+	case 25: // SETBKCOLOR
+		c.dc.bkColor = colorRef(r.u32(8))
+	case 33: // SAVEDC
+		c.save()
+	case 34: // RESTOREDC
+		c.restore(int(int32(r.u32(8))))
+	case 35: // SETWORLDTRANSFORM
+		c.dc.xf = [6]float64{r.f32(8), r.f32(12), r.f32(16), r.f32(20), r.f32(24), r.f32(28)}
+	case 36: // MODIFYWORLDTRANSFORM
+		m := [6]float64{r.f32(8), r.f32(12), r.f32(16), r.f32(20), r.f32(24), r.f32(28)}
+		switch r.u32(32) {
+		case 1:
+			c.dc.xf = [6]float64{1, 0, 0, 1, 0, 0}
+		case 2: // left multiply: m * xf
+			c.dc.xf = xfMul(m, c.dc.xf)
+		case 3: // right multiply: xf * m
+			c.dc.xf = xfMul(c.dc.xf, m)
+		case 4:
+			c.dc.xf = m
+		}
+
+	case 37: // SELECTOBJECT
+		h := r.u32(8)
+		if h&0x80000000 != 0 {
+			c.selectObject(stockObject(h))
+		} else {
+			c.selectObject(c.objs[h])
+		}
+	case 40: // DELETEOBJECT
+		delete(c.objs, r.u32(8))
+	case 38: // CREATEPEN ih style width(x, y) colour
+		c.objs[r.u32(8)] = &mfObject{pen: penFromStyle(r.u32(12), r.i32(16), r.u32(24))}
+	case 95: // EXTCREATEPEN ih offBmi cbBmi offBits cbBits style width brushStyle colour
+		pen := penFromStyle(r.u32(28), r.i32(32), r.u32(40))
+		if r.u32(28)&0x000F0000 == 0 { // PS_COSMETIC: always one pixel
+			pen.width = 0
+		}
+		if r.u32(36) == 1 { // BS_NULL brush
+			pen.null = true
+		}
+		c.objs[r.u32(8)] = &mfObject{pen: pen}
+	case 39: // CREATEBRUSHINDIRECT ih style colour hatch
+		c.objs[r.u32(8)] = &mfObject{brush: brushFromStyle(r.u32(12), r.u32(16))}
+	case 93, 94: // CREATEDIBPATTERNBRUSHPT, CREATEMONOBRUSH
+		c.objs[r.u32(8)] = &mfObject{brush: brushFromStyle(3, 0)}
+	case 82: // EXTCREATEFONTINDIRECTW
+		c.objs[r.u32(8)] = &mfObject{font: emfFont(r[12:])}
+	case 49: // CREATEPALETTE
+		c.objs[r.u32(8)] = &mfObject{}
+
+	case 27: // MOVETOEX
+		c.dc.cur = mfPt{r.i32(8), r.i32(12)}
+		if c.inPath {
+			c.pathMoveTo(c.dc.cur)
+		}
+	case 54: // LINETO
+		to := mfPt{r.i32(8), r.i32(12)}
+		if c.inPath {
+			c.pathLineTo(to)
+		} else {
+			c.shape([][]mfPt{{c.dc.cur, to}}, false)
+		}
+		c.dc.cur = to
+	case 43: // RECTANGLE
+		c.shape([][]mfPt{rectPoly(r.i32(8), r.i32(12), r.i32(16), r.i32(20))}, true)
+	case 42: // ELLIPSE
+		c.shape([][]mfPt{ellipsePoly(r.i32(8), r.i32(12), r.i32(16), r.i32(20))}, true)
+	case 44: // ROUNDRECT
+		c.shape([][]mfPt{roundRectPoly(r.i32(8), r.i32(12), r.i32(16), r.i32(20), r.i32(24), r.i32(28))}, true)
+	case 45, 46, 47, 55: // ARC, CHORD, PIE, ARCTO
+		l, t, rr, b := r.i32(8), r.i32(12), r.i32(16), r.i32(20)
+		pts := arcPoly(l, t, rr, b, mfPt{r.i32(24), r.i32(28)}, mfPt{r.i32(32), r.i32(36)})
+		switch typ {
+		case 45:
+			c.shape([][]mfPt{pts}, false)
+		case 47:
+			c.shape([][]mfPt{append(pts, mfPt{(l + rr) / 2, (t + b) / 2})}, true)
+		case 46:
+			c.shape([][]mfPt{pts}, true)
+		case 55:
+			if len(pts) > 0 {
+				if c.inPath {
+					c.pathLineTo(pts...)
+				} else {
+					c.shape([][]mfPt{append([]mfPt{c.dc.cur}, pts...)}, false)
+				}
+				c.dc.cur = pts[len(pts)-1]
+			}
+		}
+
+	case 3, 4, 86, 87: // POLYGON, POLYLINE (32 / 16 bit)
+		small := typ >= 86
+		pts := r.points(28, int(r.u32(24)), small)
+		c.shape([][]mfPt{pts}, typ == 3 || typ == 86)
+	case 2, 85: // POLYBEZIER
+		pts := r.points(28, int(r.u32(24)), typ == 85)
+		c.shape([][]mfPt{bezierPoly(pts)}, false)
+	case 5, 88, 6, 89: // POLYBEZIERTO, POLYLINETO
+		small := typ == 88 || typ == 89
+		pts := r.points(28, int(r.u32(24)), small)
+		if len(pts) == 0 {
+			break
+		}
+		if typ == 5 || typ == 88 {
+			pts = bezierPoly(append([]mfPt{c.dc.cur}, pts...))[1:]
+		}
+		if c.inPath {
+			c.pathLineTo(pts...)
+		} else {
+			c.shape([][]mfPt{append([]mfPt{c.dc.cur}, pts...)}, false)
+		}
+		c.dc.cur = pts[len(pts)-1]
+	case 7, 8, 90, 91: // POLYPOLYLINE, POLYPOLYGON
+		small := typ >= 90
+		n := int(r.u32(24))
+		if n <= 0 || n > len(r)/4 {
+			break
+		}
+		at := 32 + 4*n
+		sz := 8
+		if small {
+			sz = 4
+		}
+		var polys [][]mfPt
+		for k := 0; k < n; k++ {
+			cnt := int(r.u32(32 + 4*k))
+			polys = append(polys, r.points(at, cnt, small))
+			at += cnt * sz
+		}
+		c.shape(polys, typ == 8 || typ == 91)
+
+	case 59: // BEGINPATH
+		c.beginPath()
+	case 60: // ENDPATH
+		c.inPath = false
+	case 61: // CLOSEFIGURE
+		c.closeFigure()
+	case 68: // ABORTPATH
+		c.inPath = false
+		c.path, c.pathOpen = nil, nil
+	case 62: // FILLPATH
+		c.drawPath(true, false)
+	case 63: // STROKEANDFILLPATH
+		c.drawPath(true, true)
+	case 64: // STROKEPATH
+		c.drawPath(false, true)
+	case 67: // SELECTCLIPPATH: clipping is not modelled; the path is used up
+		c.path, c.pathOpen = nil, nil
+
+	case 76, 77: // BITBLT, STRETCHBLT
+		// Bounds xDest yDest cxDest cyDest rop xSrc ySrc xform(24) bk usage
+		// offBmi cbBmi offBits cbBits [cxSrc cySrc]
+		x, y, w, h := r.i32(24), r.i32(28), r.i32(32), r.i32(36)
+		rop := r.u32(40)
+		bmi, bits := r.slice(r.u32(84), r.u32(88)), r.slice(r.u32(92), r.u32(96))
+		if bmi == nil {
+			c.patBlt(x, y, w, h, rop)
+			break
+		}
+		sw, sh := w, h
+		if typ == 77 {
+			sw, sh = r.i32(100), r.i32(104)
+		}
+		if img, info, err := decodeDIB(bmi, bits, r.u32(80)); err == nil {
+			sr := image.Rect(int(r.i32(44)), int(r.i32(48)), int(r.i32(44)+sw), int(r.i32(48)+sh))
+			c.blit(img, dibSrcRect(sr, info, false), x, y, w, h, rop, info.isPhoto())
+		}
+	case 81: // STRETCHDIBITS
+		// Bounds xDest yDest xSrc ySrc cxSrc cySrc offBmi cbBmi offBits
+		// cbBits usage rop cxDest cyDest
+		bmi, bits := r.slice(r.u32(48), r.u32(52)), r.slice(r.u32(56), r.u32(60))
+		x, y, w, h := r.i32(24), r.i32(28), r.i32(72), r.i32(76)
+		rop := r.u32(68)
+		if bmi == nil {
+			c.patBlt(x, y, w, h, rop)
+			break
+		}
+		if img, info, err := decodeDIB(bmi, bits, r.u32(64)); err == nil {
+			sr := image.Rect(int(r.i32(32)), int(r.i32(36)), int(r.i32(32)+r.i32(40)), int(r.i32(36)+r.i32(44)))
+			c.blit(img, dibSrcRect(sr, info, true), x, y, w, h, rop, info.isPhoto())
+		}
+	case 80: // SETDIBITSTODEVICE
+		// Bounds xDest yDest xSrc ySrc cxSrc cySrc offBmi cbBmi offBits cbBits usage start scans
+		bmi, bits := r.slice(r.u32(48), r.u32(52)), r.slice(r.u32(56), r.u32(60))
+		if img, info, err := decodeDIB(bmi, bits, r.u32(64)); err == nil {
+			w, h := r.i32(40), r.i32(44)
+			sr := image.Rect(int(r.i32(32)), int(r.i32(36)), int(r.i32(32)+w), int(r.i32(36)+h))
+			c.blit(img, dibSrcRect(sr, info, true), r.i32(24), r.i32(28), w, h, ropSrcCopy, info.isPhoto())
+		}
+	case 114: // ALPHABLEND
+		// Bounds xDest yDest cxDest cyDest blend xSrc ySrc xform bk usage
+		// offBmi cbBmi offBits cbBits cxSrc cySrc
+		bmi, bits := r.slice(r.u32(84), r.u32(88)), r.slice(r.u32(92), r.u32(96))
+		if img, info, err := decodeDIB(bmi, bits, r.u32(80)); err == nil {
+			sr := image.Rect(int(r.i32(44)), int(r.i32(48)), int(r.i32(44)+r.i32(100)), int(r.i32(48)+r.i32(104)))
+			c.blit(img, dibSrcRect(sr, info, false), r.i32(24), r.i32(28), r.i32(32), r.i32(36), ropSrcCopy, info.isPhoto())
+		}
+
+	case 83, 84: // EXTTEXTOUTA, EXTTEXTOUTW
+		// Bounds mode exScale eyScale | EMRTEXT: ref(x, y) nChars offString
+		// options rect(16) offDx
+		ref := mfPt{r.i32(36), r.i32(40)}
+		n := int(r.u32(44))
+		off := r.u32(48)
+		opts := r.u32(52)
+		if opts&0x2 != 0 { // ETO_OPAQUE
+			c.opaqueBox(r.i32(56), r.i32(60), r.i32(64), r.i32(68))
+		}
+		if n <= 0 || n > 1<<16 {
+			break
+		}
+		var s []rune
+		if typ == 84 {
+			if b := r.slice(off, uint32(2*n)); b != nil {
+				s = utf16Runes(b, n)
+			}
+		} else if b := r.slice(off, uint32(n)); b != nil {
+			s = ansiRunes(b)
+		}
+		var dx []float64
+		if offDx := r.u32(72); offDx != 0 {
+			step := 4
+			if opts&0x2000 != 0 { // ETO_PDY: (dx, dy) pairs
+				step = 8
+			}
+			if b := r.slice(offDx, uint32(step*n)); b != nil {
+				dx = make([]float64, n)
+				for k := range dx {
+					dx[k] = float64(int32(binary.LittleEndian.Uint32(b[step*k:])))
+				}
+			}
+		}
+		if len(dx) != len(s) {
+			dx = nil // surrogate pairs: fall back to the font's advances
+		}
+		c.text(ref, s, dx)
+	}
+}
+
+// xfMul composes two world transforms: the result applies a, then b
+func xfMul(a, b [6]float64) [6]float64 {
+	return [6]float64{
+		a[0]*b[0] + a[1]*b[2],
+		a[0]*b[1] + a[1]*b[3],
+		a[2]*b[0] + a[3]*b[2],
+		a[2]*b[1] + a[3]*b[3],
+		a[4]*b[0] + a[5]*b[2] + b[4],
+		a[4]*b[1] + a[5]*b[3] + b[5],
+	}
+}
+
+// emfFont reads an EMF LOGFONTW (32-bit fields, UTF-16 face name)
+func emfFont(b []byte) *mfFont {
+	r := emfRec(b)
+	f := &mfFont{
+		height:     r.i32(0),
+		escapement: r.i32(8),
+		weight:     int(r.i32(16)),
+	}
+	if len(b) >= 28 {
+		f.italic = b[20] != 0
+		f.underline = b[21] != 0
+		f.strike = b[22] != 0
+	}
+	if len(b) >= 28+64 {
+		name := utf16Runes(b[28:28+64], 32)
+		for i, ch := range name {
+			if ch == 0 {
+				name = name[:i]
+				break
+			}
+		}
+		f.face = string(name)
+	}
+	return f
+}

+ 579 - 0
src/mod/office/metafile_test.go

@@ -0,0 +1,579 @@
+package office
+
+import (
+	"bytes"
+	"encoding/binary"
+	"image"
+	"image/color"
+	"math"
+	"strings"
+	"testing"
+	"unicode/utf16"
+)
+
+/* ---------------- metafile fixtures ---------------- */
+
+var (
+	mfRed   = color.NRGBA{255, 0, 0, 255}
+	mfGreen = color.NRGBA{0, 255, 0, 255}
+	mfBlue  = color.NRGBA{0, 0, 255, 255}
+	mfWhite = color.NRGBA{255, 255, 255, 255}
+)
+
+func le16(v int) []byte {
+	b := make([]byte, 2)
+	binary.LittleEndian.PutUint16(b, uint16(int16(v)))
+	return b
+}
+
+func le32(v int64) []byte {
+	b := make([]byte, 4)
+	binary.LittleEndian.PutUint32(b, uint32(v))
+	return b
+}
+
+func cat(parts ...[]byte) []byte {
+	return bytes.Join(parts, nil)
+}
+
+// dib24 builds a packed bottom-up 24-bit BITMAPINFOHEADER DIB
+func dib24(w, h int, px func(x, y int) color.NRGBA) []byte {
+	stride := (w*3 + 3) &^ 3
+	hdr := cat(le32(40), le32(int64(w)), le32(int64(h)), le16(1), le16(24), le32(0),
+		le32(int64(stride*h)), le32(0), le32(0), le32(0), le32(0))
+	bits := make([]byte, stride*h)
+	for y := 0; y < h; y++ {
+		row := (h - 1 - y) * stride
+		for x := 0; x < w; x++ {
+			c := px(x, y)
+			bits[row+3*x], bits[row+3*x+1], bits[row+3*x+2] = c.B, c.G, c.R
+		}
+	}
+	return cat(hdr, bits)
+}
+
+// quadrants: red top-left, green top-right, blue bottom-left, white bottom-right
+func quadrants(w, h int) func(x, y int) color.NRGBA {
+	return func(x, y int) color.NRGBA {
+		switch {
+		case x < w/2 && y < h/2:
+			return mfRed
+		case y < h/2:
+			return mfGreen
+		case x < w/2:
+			return mfBlue
+		}
+		return mfWhite
+	}
+}
+
+// wmfRec builds one WMF record from 16-bit words and a byte tail
+func wmfRec(fn uint16, words []int, tail []byte) []byte {
+	if len(tail)%2 == 1 {
+		tail = append(tail, 0)
+	}
+	var b bytes.Buffer
+	b.Write(le32(int64(3 + len(words) + len(tail)/2)))
+	binary.Write(&b, binary.LittleEndian, fn)
+	for _, w := range words {
+		b.Write(le16(w))
+	}
+	b.Write(tail)
+	return b.Bytes()
+}
+
+func wmfColor(c color.NRGBA) []int {
+	return []int{int(c.R) | int(c.G)<<8, int(c.B)}
+}
+
+// buildWmf wraps records in a placeable header (box in logical units,
+// inch units per inch) and the standard header, ending with EOF
+func buildWmf(box [4]int, inch int, recs ...[]byte) []byte {
+	var b bytes.Buffer
+	b.Write(le32(0x9AC6CDD7))
+	b.Write(le16(0))
+	for _, v := range box {
+		b.Write(le16(v))
+	}
+	b.Write(le16(inch))
+	b.Write(le32(0))
+	b.Write(le16(0))
+	b.Write(cat(le16(1), le16(9), le16(0x300), le32(0), le16(8), le32(0), le16(0)))
+	for _, r := range recs {
+		b.Write(r)
+	}
+	b.Write(wmfRec(0, nil, nil))
+	return b.Bytes()
+}
+
+// emfRecBytes builds one EMF record from 32-bit values and a byte tail
+func emfRecBytes(typ int, vals []int64, tail []byte) []byte {
+	for len(tail)%4 != 0 {
+		tail = append(tail, 0)
+	}
+	var b bytes.Buffer
+	b.Write(le32(int64(typ)))
+	b.Write(le32(int64(8 + 4*len(vals) + len(tail))))
+	for _, v := range vals {
+		b.Write(le32(v))
+	}
+	b.Write(tail)
+	return b.Bytes()
+}
+
+// buildEmf writes a header whose frame is w x h millimetres on a 1 px per
+// 0.1 mm reference device (so a logical unit is 0.1 mm), records and EOF
+func buildEmf(wMM, hMM int, recs ...[]byte) []byte {
+	devW, devH := wMM*10, hMM*10
+	hdr := cat(le32(1), le32(88),
+		le32(0), le32(0), le32(int64(devW-1)), le32(int64(devH-1)),
+		le32(0), le32(0), le32(int64(wMM*100)), le32(int64(hMM*100)),
+		[]byte(" EMF"), le32(0x10000), le32(0), le32(0), le16(8), le16(0),
+		le32(0), le32(0), le32(0),
+		le32(int64(devW)), le32(int64(devH)), le32(int64(wMM)), le32(int64(hMM)))
+	var b bytes.Buffer
+	b.Write(hdr)
+	for _, r := range recs {
+		b.Write(r)
+	}
+	b.Write(emfRecBytes(14, []int64{0, 0, 20}, nil))
+	return b.Bytes()
+}
+
+func emfColor(c color.NRGBA) int64 {
+	return int64(c.R) | int64(c.G)<<8 | int64(c.B)<<16
+}
+
+// emfSolidBrush creates brush ih and selects it, with a null pen
+func emfSolidBrush(ih int64, c color.NRGBA) [][]byte {
+	return [][]byte{
+		emfRecBytes(39, []int64{ih, 0, emfColor(c), 0}, nil),
+		emfRecBytes(37, []int64{ih}, nil),
+		emfRecBytes(37, []int64{0x80000008}, nil), // NULL_PEN
+	}
+}
+
+func render(t *testing.T, data []byte) (*image.RGBA, bool) {
+	t.Helper()
+	img, photo, err := renderMetafile(data)
+	if err != nil {
+		t.Fatalf("renderMetafile: %v", err)
+	}
+	rgba, ok := img.(*image.RGBA)
+	if !ok {
+		t.Fatalf("rendered image is %T", img)
+	}
+	return rgba, photo
+}
+
+func near(a, b color.NRGBA, tol int) bool {
+	d := func(x, y uint8) bool { return int(x)-int(y) <= tol && int(y)-int(x) <= tol }
+	return d(a.R, b.R) && d(a.G, b.G) && d(a.B, b.B) && d(a.A, b.A)
+}
+
+func pixel(img *image.RGBA, x, y int) color.NRGBA {
+	return color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)
+}
+
+/* ---------------- detection and pass-through ---------------- */
+
+func TestMetafileKind(t *testing.T) {
+	std := cat(le16(1), le16(9), le16(0x300), make([]byte, 12))
+	tests := []struct {
+		name string
+		data []byte
+		want string
+	}{
+		{"placeable wmf", buildWmf([4]int{0, 0, 10, 10}, 96), "wmf"},
+		{"standard wmf", std, "wmf"},
+		{"emf", buildEmf(10, 10), "emf"},
+		{"png", []byte("\x89PNG\r\n\x1a\n0000000000"), ""},
+		{"short", []byte{1, 2}, ""},
+	}
+	for _, tc := range tests {
+		if got := metafileKind(tc.data); got != tc.want {
+			t.Errorf("%s: metafileKind = %q, want %q", tc.name, got, tc.want)
+		}
+	}
+}
+
+func TestBrowserPicture(t *testing.T) {
+	png := []byte("\x89PNG\r\n\x1a\nrest")
+	tests := []struct {
+		name    string
+		data    []byte
+		ext     string
+		wantExt string
+		wantOK  bool
+		same    bool
+	}{
+		{"png passes through", png, "png", "png", true, true},
+		{"unrenderable wmf keeps its bytes", []byte("not a metafile"), "wmf", "wmf", false, true},
+		{"empty metafile fails", buildWmf([4]int{0, 0, 10, 10}, 96), "wmf", "wmf", false, true},
+		{"bitmap wmf becomes a JPEG", buildWmf([4]int{0, 0, 8, 8}, 96,
+			wmfRec(0x0B41, []int{0x0020, 0x00CC, 8, 8, 0, 0, 8, 8, 0, 0}, dib24(8, 8, quadrants(8, 8)))),
+			"wmf", "jpeg", true, false},
+		{"drawing emf becomes a PNG", buildEmf(10, 10, append(emfSolidBrush(1, mfBlue),
+			emfRecBytes(43, []int64{0, 0, 50, 50}, nil))...), "emf", "png", true, false},
+	}
+	for _, tc := range tests {
+		out, ext, ok := browserPicture(tc.data, tc.ext)
+		if ok != tc.wantOK || ext != tc.wantExt {
+			t.Errorf("%s: got (%s, %v), want (%s, %v)", tc.name, ext, ok, tc.wantExt, tc.wantOK)
+		}
+		if same := bytes.Equal(out, tc.data); same != tc.same {
+			t.Errorf("%s: output unchanged = %v, want %v", tc.name, same, tc.same)
+		}
+	}
+}
+
+/* ---------------- WMF ---------------- */
+
+func TestWmfStretchBltKeepsBitmapResolution(t *testing.T) {
+	// a 16 x 8 scan stretched over a 1 x 0.5 inch frame (96 x 48 CSS px):
+	// the picture is rendered at the scan's own 16 x 8 pixels
+	wmf := buildWmf([4]int{0, 0, 1440, 720}, 1440,
+		wmfRec(0x0103, []int{8}, nil),
+		wmfRec(0x020B, []int{0, 0}, nil),
+		wmfRec(0x020C, []int{720, 1440}, nil),
+		wmfRec(0x0B41, []int{0x0020, 0x00CC, 8, 16, 0, 0, 720, 1440, 0, 0}, dib24(16, 8, quadrants(16, 8))))
+	img, photo := render(t, wmf)
+	if b := img.Bounds(); b.Dx() != 16 || b.Dy() != 8 {
+		t.Fatalf("size = %v, want 16x8", b)
+	}
+	if !photo {
+		t.Error("a 24-bit scan should be kept as a photo (JPEG)")
+	}
+	checks := []struct {
+		x, y int
+		want color.NRGBA
+	}{{1, 1, mfRed}, {14, 1, mfGreen}, {1, 6, mfBlue}, {14, 6, mfWhite}}
+	for _, c := range checks {
+		if got := pixel(img, c.x, c.y); !near(got, c.want, 8) {
+			t.Errorf("pixel (%d,%d) = %v, want %v", c.x, c.y, got, c.want)
+		}
+	}
+}
+
+func TestWmfSourceRectWiderThanBitmap(t *testing.T) {
+	// PowerPoint writes source rectangles a pixel or two wider than the
+	// DIB (the reference decks do): the part that exists is drawn
+	wmf := buildWmf([4]int{0, 0, 10, 8}, 96,
+		wmfRec(0x0B41, []int{0x0020, 0x00CC, 8, 10, 0, 0, 8, 10, 0, 0}, dib24(8, 8, quadrants(8, 8))))
+	img, _ := render(t, wmf)
+	if got := pixel(img, 0, 0); !near(got, mfRed, 8) {
+		t.Errorf("top-left = %v, want red", got)
+	}
+	if got := pixel(img, img.Bounds().Dx()-1, 0); got.A != 0 && !near(got, mfWhite, 8) {
+		t.Errorf("uncovered column = %v, want empty or the white page", got)
+	}
+}
+
+func TestWmfMirroredBlit(t *testing.T) {
+	// a negative destination width mirrors the bitmap
+	wmf := buildWmf([4]int{0, 0, 8, 8}, 96,
+		wmfRec(0x0B41, []int{0x0020, 0x00CC, 8, 8, 0, 0, 8, -8, 0, 8}, dib24(8, 8, quadrants(8, 8))))
+	img, _ := render(t, wmf)
+	if got := pixel(img, 1, 1); !near(got, mfGreen, 8) {
+		t.Errorf("mirrored top-left = %v, want green", got)
+	}
+}
+
+func TestWmfVectorShapes(t *testing.T) {
+	brush := wmfRec(0x02FC, append([]int{0}, append(wmfColor(mfGreen), 0)...), nil)
+	nullPen := wmfRec(0x02FA, []int{5, 0, 0, 0, 0}, nil)
+	tests := []struct {
+		name   string
+		shape  []byte
+		inside [2]int // in CSS px of a 100 x 100 frame
+		out    [2]int
+	}{
+		{"rectangle", wmfRec(0x041B, []int{75, 75, 25, 25}, nil), [2]int{50, 50}, [2]int{10, 10}},
+		{"ellipse", wmfRec(0x0418, []int{90, 90, 10, 10}, nil), [2]int{50, 50}, [2]int{12, 12}},
+		{"polygon", wmfRec(0x0324, []int{3, 10, 10, 90, 10, 10, 90}, nil), [2]int{25, 25}, [2]int{80, 80}},
+	}
+	for _, tc := range tests {
+		wmf := buildWmf([4]int{0, 0, 100, 100}, 96,
+			brush, nullPen,
+			wmfRec(0x012D, []int{0}, nil), wmfRec(0x012D, []int{1}, nil),
+			tc.shape)
+		img, photo := render(t, wmf)
+		if photo {
+			t.Errorf("%s: a drawing must not be encoded as a photo", tc.name)
+		}
+		if b := img.Bounds(); b.Dx() != 200 {
+			t.Errorf("%s: width = %d, want 200 (drawings render at 2x)", tc.name, b.Dx())
+		}
+		if got := pixel(img, tc.inside[0]*2, tc.inside[1]*2); !near(got, mfGreen, 2) {
+			t.Errorf("%s: inside = %v, want green", tc.name, got)
+		}
+		if got := pixel(img, tc.out[0]*2, tc.out[1]*2); got.A != 0 {
+			t.Errorf("%s: outside = %v, want transparent", tc.name, got)
+		}
+	}
+}
+
+func TestWmfObjectTableReusesFreedSlots(t *testing.T) {
+	red := wmfRec(0x02FC, append([]int{0}, append(wmfColor(mfRed), 0)...), nil)
+	blue := wmfRec(0x02FC, append([]int{0}, append(wmfColor(mfBlue), 0)...), nil)
+	wmf := buildWmf([4]int{0, 0, 10, 10}, 96,
+		wmfRec(0x02FA, []int{5, 0, 0, 0, 0}, nil), // slot 0: null pen
+		wmfRec(0x012D, []int{0}, nil),
+		red,                           // slot 1
+		wmfRec(0x01F0, []int{1}, nil), // free slot 1
+		blue,                          // takes slot 1 again
+		wmfRec(0x012D, []int{1}, nil),
+		wmfRec(0x041B, []int{10, 10, 0, 0}, nil))
+	img, _ := render(t, wmf)
+	if got := pixel(img, 10, 10); !near(got, mfBlue, 2) {
+		t.Errorf("fill = %v, want blue from the reused slot", got)
+	}
+}
+
+func TestWmfMaskRasterOps(t *testing.T) {
+	// the classic transparent-bitmap pair: AND a mask (black = keep), then
+	// OR the image (black = transparent). The background stays empty.
+	mask := dib24(8, 8, func(x, y int) color.NRGBA {
+		if x < 4 {
+			return color.NRGBA{A: 255}
+		}
+		return mfWhite
+	})
+	pic := dib24(8, 8, func(x, y int) color.NRGBA {
+		if x < 4 {
+			return mfRed
+		}
+		return color.NRGBA{A: 255}
+	})
+	wmf := buildWmf([4]int{0, 0, 8, 8}, 96,
+		wmfRec(0x0B41, []int{0x00C6, 0x0088, 8, 8, 0, 0, 8, 8, 0, 0}, mask),
+		wmfRec(0x0B41, []int{0x0086, 0x00EE, 8, 8, 0, 0, 8, 8, 0, 0}, pic))
+	img, _ := render(t, wmf)
+	if got := pixel(img, 1, 4); !near(got, mfRed, 8) {
+		t.Errorf("masked-in pixel = %v, want red", got)
+	}
+	if got := pixel(img, 6, 4); got.A != 0 {
+		t.Errorf("masked-out pixel = %v, want transparent", got)
+	}
+}
+
+/* ---------------- EMF ---------------- */
+
+func TestEmfStretchDIBits(t *testing.T) {
+	// an 8-bit palette DIB, bottom-up: the first row in the file is the
+	// bottom of the picture
+	hdr := cat(le32(40), le32(2), le32(2), le16(1), le16(8), le32(0), le32(8), le32(0), le32(0), le32(2), le32(0))
+	pal := cat([]byte{0, 0, 255, 0}, []byte{255, 0, 0, 0}) // index 0 red, 1 blue (BGRA)
+	bits := []byte{1, 1, 0, 0, 0, 0, 0, 0}                 // bottom row blue, top row red
+	bmi := cat(hdr, pal)
+	const fixed = 80
+	rec := emfRecBytes(81, []int64{
+		0, 0, 1, 1, // bounds
+		0, 0, 0, 0, 2, 2, // dest x y, src x y w h
+		fixed, int64(len(bmi)), fixed + int64(len(bmi)), int64(len(bits)),
+		0, ropSrcCopy, 100, 100,
+	}, cat(bmi, bits))
+	img, photo := render(t, buildEmf(10, 10, rec))
+	if photo {
+		t.Error("an 8-bit DIB is not a photo")
+	}
+	w, h := img.Bounds().Dx(), img.Bounds().Dy()
+	if got := pixel(img, w/2, h/4); !near(got, mfRed, 8) {
+		t.Errorf("top = %v, want red", got)
+	}
+	if got := pixel(img, w/2, 3*h/4); !near(got, mfBlue, 8) {
+		t.Errorf("bottom = %v, want blue", got)
+	}
+}
+
+func TestEmfShapesPathsAndTransforms(t *testing.T) {
+	// the frame is 10 x 10 mm = 100 x 100 logical units; output pixels per
+	// logical unit: 10 mm -> 37.8 CSS px -> 75.6 px at 2x
+	pxPer := 2 * 96 / 25.4 / 10
+	at := func(lx, ly float64) (int, int) {
+		return int(math.Round(lx * pxPer)), int(math.Round(ly * pxPer))
+	}
+	poly16 := func(pts ...int) []byte {
+		var tail []byte
+		for _, p := range pts {
+			tail = append(tail, le16(p)...)
+		}
+		return emfRecBytes(86, []int64{0, 0, 100, 100, int64(len(pts) / 2)}, tail)
+	}
+	f := func(v float32) int64 { return int64(math.Float32bits(v)) }
+	tests := []struct {
+		name    string
+		recs    [][]byte
+		inside  [2]float64
+		outside [2]float64
+	}{
+		{"polygon16", [][]byte{poly16(10, 10, 90, 10, 10, 90)}, [2]float64{25, 25}, [2]float64{80, 80}},
+		{"filled path", [][]byte{
+			emfRecBytes(59, nil, nil),
+			emfRecBytes(27, []int64{20, 20}, nil),
+			emfRecBytes(54, []int64{80, 20}, nil),
+			emfRecBytes(54, []int64{80, 80}, nil),
+			emfRecBytes(61, nil, nil),
+			emfRecBytes(60, nil, nil),
+			emfRecBytes(62, []int64{0, 0, 100, 100}, nil),
+		}, [2]float64{70, 30}, [2]float64{30, 70}},
+		{"world transform", [][]byte{
+			emfRecBytes(35, []int64{f(1), f(0), f(0), f(1), f(50), f(50)}, nil),
+			emfRecBytes(43, []int64{0, 0, 40, 40}, nil),
+		}, [2]float64{70, 70}, [2]float64{20, 20}},
+		{"anisotropic window", [][]byte{
+			emfRecBytes(17, []int64{mmAnisotropic}, nil),
+			emfRecBytes(9, []int64{10, 10}, nil),
+			emfRecBytes(11, []int64{100, 100}, nil),
+			emfRecBytes(43, []int64{5, 5, 10, 10}, nil),
+		}, [2]float64{75, 75}, [2]float64{25, 25}},
+	}
+	for _, tc := range tests {
+		recs := append(emfSolidBrush(1, mfBlue), tc.recs...)
+		img, _ := render(t, buildEmf(10, 10, recs...))
+		x, y := at(tc.inside[0], tc.inside[1])
+		if got := pixel(img, x, y); !near(got, mfBlue, 2) {
+			t.Errorf("%s: inside (%d,%d) = %v, want blue", tc.name, x, y, got)
+		}
+		x, y = at(tc.outside[0], tc.outside[1])
+		if got := pixel(img, x, y); got.A != 0 {
+			t.Errorf("%s: outside (%d,%d) = %v, want transparent", tc.name, x, y, got)
+		}
+	}
+}
+
+func TestEmfStrokedLine(t *testing.T) {
+	// a 4-unit red pen from (10,50) to (90,50)
+	recs := [][]byte{
+		emfRecBytes(38, []int64{1, 0, 4, 0, emfColor(mfRed)}, nil),
+		emfRecBytes(37, []int64{1}, nil),
+		emfRecBytes(27, []int64{10, 50}, nil),
+		emfRecBytes(54, []int64{90, 50}, nil),
+	}
+	img, _ := render(t, buildEmf(10, 10, recs...))
+	pxPer := 2 * 96 / 25.4 / 10
+	if got := pixel(img, int(50*pxPer), int(50*pxPer)); !near(got, mfRed, 2) {
+		t.Errorf("on the line = %v, want red", got)
+	}
+	if got := pixel(img, int(50*pxPer), int(60*pxPer)); got.A != 0 {
+		t.Errorf("off the line = %v, want transparent", got)
+	}
+}
+
+func TestEmfTextDrawsGlyphs(t *testing.T) {
+	text := utf16.Encode([]rune("Hi"))
+	var str []byte
+	for _, u := range text {
+		str = append(str, le16(int(u))...)
+	}
+	// EXTCREATEFONTINDIRECTW: ih + LOGFONTW (92 bytes)
+	logfont := cat(le32(-40), le32(0), le32(0), le32(0), le32(700), make([]byte, 8))
+	face := utf16.Encode([]rune("Arial"))
+	name := make([]byte, 64)
+	for i, u := range face {
+		binary.LittleEndian.PutUint16(name[2*i:], u)
+	}
+	logfont = cat(logfont, name)
+	const strOff = 76 // 8 header + 68 bytes of fields
+	recs := [][]byte{
+		emfRecBytes(82, []int64{1}, logfont),
+		emfRecBytes(37, []int64{1}, nil),
+		emfRecBytes(24, []int64{emfColor(mfBlue)}, nil),
+		emfRecBytes(22, []int64{24}, nil), // TA_BASELINE
+		emfRecBytes(84, []int64{
+			0, 0, 100, 100, // bounds
+			1, 0, 0, // graphics mode, scales
+			10, 60, 2, strOff, 0, // ref x y, chars, offString, options
+			0, 0, 0, 0, 0, // rect, offDx
+		}, str),
+	}
+	img, photo := render(t, buildEmf(10, 10, recs...))
+	if photo {
+		t.Error("text must not be encoded as a photo")
+	}
+	ink := 0
+	for y := 0; y < img.Bounds().Dy(); y++ {
+		for x := 0; x < img.Bounds().Dx(); x++ {
+			if c := pixel(img, x, y); c.A > 200 && c.B > 200 && c.R < 60 {
+				ink++
+			}
+		}
+	}
+	if ink < 50 {
+		t.Errorf("text drew %d blue pixels, want glyphs", ink)
+	}
+}
+
+/* ---------------- DIB decoding ---------------- */
+
+func TestDecodeRLE(t *testing.T) {
+	tests := []struct {
+		name string
+		data []byte
+		w, h int
+		four bool
+		want []uint8
+	}{
+		{"rle8 runs", []byte{3, 7, 0, 0, 2, 1, 0, 1}, 3, 2, false, []uint8{7, 7, 7, 1, 1, 0}},
+		{"rle8 absolute", []byte{0, 3, 4, 5, 6, 0, 0, 1}, 3, 1, false, []uint8{4, 5, 6}},
+		{"rle8 delta", []byte{0, 2, 1, 1, 1, 9, 0, 1}, 3, 2, false, []uint8{0, 0, 0, 0, 9, 0}},
+		{"rle4 runs", []byte{4, 0x12, 0, 1}, 4, 1, true, []uint8{1, 2, 1, 2}},
+	}
+	for _, tc := range tests {
+		got := decodeRLE(tc.data, tc.w, tc.h, tc.four)
+		if !bytes.Equal(got, tc.want) {
+			t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
+		}
+	}
+}
+
+func TestParseDIBHeaderRejectsBadSizes(t *testing.T) {
+	tests := []struct {
+		name string
+		hdr  []byte
+	}{
+		{"truncated", []byte{40, 0, 0}},
+		{"zero width", cat(le32(40), le32(0), le32(4), le16(1), le16(24), make([]byte, 24))},
+		{"huge", cat(le32(40), le32(60000), le32(60000), le16(1), le16(24), make([]byte, 24))},
+	}
+	for _, tc := range tests {
+		if _, err := parseDIBHeader(tc.hdr, 0); err == nil {
+			t.Errorf("%s: parseDIBHeader accepted a bad header", tc.name)
+		}
+	}
+}
+
+/* ---------------- import integration ---------------- */
+
+func TestPptxWmfPictureIsRendered(t *testing.T) {
+	wmf := buildWmf([4]int{0, 0, 8, 8}, 96,
+		wmfRec(0x0B41, []int{0x0020, 0x00CC, 8, 8, 0, 0, 8, 8, 0, 0}, dib24(8, 8, quadrants(8, 8))))
+	pic := `<p:pic><p:nvPicPr><p:cNvPr id="4" name="Picture 5"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
+		`<p:blipFill><a:blip r:embed="rId9"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
+		`<p:spPr><a:xfrm><a:off x="914400" y="914400"/><a:ext cx="914400" cy="914400"/></a:xfrm></p:spPr></p:pic>`
+	objs := parseOneSlide(t, pptxParts{
+		slides:    []string{pic},
+		slideRels: map[string]string{"rId9": "../media/image2.wmf"},
+		media:     map[string][]byte{"ppt/media/image2.wmf": wmf},
+	})
+	if len(objs) != 1 || objs[0].Type != "image" {
+		t.Fatalf("objects = %+v, want one image", objs)
+	}
+	if src := objs[0].Props.Src; !strings.HasPrefix(src, "data:image/jpeg;base64,") {
+		t.Errorf("src = %.40s..., want a JPEG data URL", src)
+	}
+}
+
+func TestDocxEmfPictureIsRendered(t *testing.T) {
+	emf := buildEmf(10, 10, append(emfSolidBrush(1, mfBlue), emfRecBytes(43, []int64{0, 0, 50, 50}, nil))...)
+	rels := `<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
+		`<Relationship Id="rIdImg" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/p.emf"/></Relationships>`
+	body := `<w:p><w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="508000"/>` +
+		`<a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rIdImg"/></pic:blipFill>` +
+		`</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>`
+	zipData := testDocx(t, body, map[string]string{"word/_rels/document.xml.rels": rels})
+	doc := parseDocxWithMedia(t, zipData, "word/media/p.emf", emf)
+	if !strings.Contains(doc.HTML, `<img src="data:image/png;base64,`) {
+		t.Errorf("EMF picture not imported as PNG: %.300s", doc.HTML)
+	}
+}

+ 425 - 0
src/mod/office/metafile_wmf.go

@@ -0,0 +1,425 @@
+package office
+
+/*
+	metafile_wmf.go - plays Windows Metafile (WMF) records onto an mfCanvas
+
+	A WMF is an optional "placeable" header (the picture's bounding box and
+	units per inch), the metafile header, then 16-bit records: a size in
+	words, a function number and parameters, mostly 16-bit signed values
+	listed in reverse (y before x, bottom before top).
+
+	The window (SETWINDOWORG / SETWINDOWEXT) is mapped onto the placeable
+	bounding box, as Office does; a metafile without a placeable header is
+	drawn at one pixel per logical unit of its window.
+*/
+
+import (
+	"encoding/binary"
+	"errors"
+	"image"
+	"math"
+	"unicode/utf16"
+)
+
+type wmfPlayer struct {
+	data    []byte
+	records int // offset of the first record
+	// placeable bounding box (logical units) and units per inch
+	hasBox   bool
+	box      [4]float64 // left, top, right, bottom
+	inch     float64
+	firstWin [4]float64 // the window set before the first drawing record
+	hasWin   bool
+}
+
+func newWmfPlayer(data []byte) (*wmfPlayer, error) {
+	p := &wmfPlayer{data: data}
+	off := 0
+	if len(data) >= 22 && binary.LittleEndian.Uint32(data) == 0x9AC6CDD7 {
+		s := func(i int) float64 { return float64(int16(binary.LittleEndian.Uint16(data[i:]))) }
+		p.box = [4]float64{s(6), s(8), s(10), s(12)}
+		p.inch = float64(binary.LittleEndian.Uint16(data[14:]))
+		if p.inch == 0 {
+			p.inch = 1440
+		}
+		p.hasBox = p.box[2] != p.box[0] && p.box[3] != p.box[1]
+		off = 22
+	}
+	if len(data) < off+18 {
+		return nil, errors.New("WMF header truncated")
+	}
+	hs := int(binary.LittleEndian.Uint16(data[off+2:])) * 2
+	if hs < 18 {
+		hs = 18
+	}
+	p.records = off + hs
+
+	// the window in force when drawing starts frames a metafile that has
+	// no placeable header
+	org, ext := [2]float64{}, [2]float64{}
+	extSet := false
+	p.walk(func(fn uint16, prm []byte) bool {
+		switch fn {
+		case 0x020B:
+			org = [2]float64{wmfS(prm, 1), wmfS(prm, 0)}
+		case 0x020C:
+			ext = [2]float64{wmfS(prm, 1), wmfS(prm, 0)}
+			extSet = true
+		case 0x0103, 0x0102, 0x0201, 0x0209, 0x012E, 0x0106, 0x001E, 0x0127,
+			0x012D, 0x01F0, 0x02FA, 0x02FC, 0x02FB, 0x00F7, 0x0626, 0x020D, 0x020E:
+		default:
+			return false
+		}
+		return true
+	})
+	if extSet && ext[0] != 0 && ext[1] != 0 {
+		p.firstWin = [4]float64{org[0], org[1], ext[0], ext[1]}
+		p.hasWin = true
+	}
+	if !p.hasBox && !p.hasWin {
+		return nil, errors.New("WMF has neither a placeable header nor a window")
+	}
+	return p, nil
+}
+
+// walk visits every record until EOF, a malformed record, or visit
+// returning false
+func (p *wmfPlayer) walk(visit func(fn uint16, prm []byte) bool) {
+	d := p.data
+	for i := p.records; i+6 <= len(d); {
+		size := int(binary.LittleEndian.Uint32(d[i:])) * 2
+		fn := binary.LittleEndian.Uint16(d[i+4:])
+		if fn == 0 || size < 6 || i+size > len(d) {
+			return
+		}
+		if !visit(fn, d[i+6:i+size]) {
+			return
+		}
+		i += size
+	}
+}
+
+// wmfS reads the n-th 16-bit signed parameter
+func wmfS(prm []byte, n int) float64 {
+	if 2*n+2 > len(prm) {
+		return 0
+	}
+	return float64(int16(binary.LittleEndian.Uint16(prm[2*n:])))
+}
+
+func wmfU(prm []byte, n int) uint32 {
+	if 2*n+2 > len(prm) {
+		return 0
+	}
+	return uint32(binary.LittleEndian.Uint16(prm[2*n:]))
+}
+
+func wmfU32(prm []byte, n int) uint32 {
+	return wmfU(prm, n) | wmfU(prm, n+1)<<16
+}
+
+func (p *wmfPlayer) baseSize() (float64, float64) {
+	if p.hasBox {
+		return math.Abs(p.box[2]-p.box[0]) / p.inch * 96, math.Abs(p.box[3]-p.box[1]) / p.inch * 96
+	}
+	return math.Abs(p.firstWin[2]), math.Abs(p.firstWin[3])
+}
+
+// wmfPoints reads count (x, y) pairs starting at parameter n
+func wmfPoints(prm []byte, n, count int) []mfPt {
+	if count <= 0 || 2*(n+2*count) > len(prm) {
+		return nil
+	}
+	pts := make([]mfPt, count)
+	for i := range pts {
+		pts[i] = mfPt{wmfS(prm, n+2*i), wmfS(prm, n+2*i+1)}
+	}
+	return pts
+}
+
+func (p *wmfPlayer) play(c *mfCanvas) error {
+	bw, bh := p.baseSize()
+	frame := p.firstWin
+	if p.hasBox {
+		frame = [4]float64{p.box[0], p.box[1], p.box[2] - p.box[0], p.box[3] - p.box[1]}
+	}
+	c.dc.winOrg = mfPt{frame[0], frame[1]}
+	c.dc.winExt = mfPt{frame[2], frame[3]}
+	c.toCSS = func(q mfPt) mfPt {
+		ex, ey := c.dc.winExt.X, c.dc.winExt.Y
+		if ex == 0 {
+			ex = 1
+		}
+		if ey == 0 {
+			ey = 1
+		}
+		return mfPt{(q.X - c.dc.winOrg.X) / ex * bw, (q.Y - c.dc.winOrg.Y) / ey * bh}
+	}
+
+	// the object table: a created object takes the lowest free slot
+	slots := []*mfObject{}
+	create := func(o *mfObject) {
+		if o == nil {
+			o = &mfObject{}
+		}
+		for i, s := range slots {
+			if s == nil {
+				slots[i] = o
+				return
+			}
+		}
+		slots = append(slots, o)
+	}
+
+	p.walk(func(fn uint16, prm []byte) bool {
+		switch fn {
+		case 0x001E: // SAVEDC
+			c.save()
+		case 0x0127: // RESTOREDC
+			c.restore(int(wmfS(prm, 0)))
+		case 0x0103: // SETMAPMODE
+			c.dc.mapMode = int(wmfU(prm, 0))
+		case 0x020B: // SETWINDOWORG
+			c.dc.winOrg = mfPt{wmfS(prm, 1), wmfS(prm, 0)}
+		case 0x020C: // SETWINDOWEXT
+			c.dc.winExt = mfPt{wmfS(prm, 1), wmfS(prm, 0)}
+		case 0x020F: // OFFSETWINDOWORG
+			c.dc.winOrg.X += wmfS(prm, 1)
+			c.dc.winOrg.Y += wmfS(prm, 0)
+		case 0x0410: // SCALEWINDOWEXT yDenom yNum xDenom xNum
+			if yd, xd := wmfS(prm, 0), wmfS(prm, 2); yd != 0 && xd != 0 {
+				c.dc.winExt.X = c.dc.winExt.X * wmfS(prm, 3) / xd
+				c.dc.winExt.Y = c.dc.winExt.Y * wmfS(prm, 1) / yd
+			}
+		case 0x0102: // SETBKMODE
+			c.dc.bkOpaque = wmfU(prm, 0) == 2
+		case 0x0201: // SETBKCOLOR
+			c.dc.bkColor = colorRef(wmfU32(prm, 0))
+		case 0x0209: // SETTEXTCOLOR
+			c.dc.textColor = colorRef(wmfU32(prm, 0))
+		case 0x012E: // SETTEXTALIGN
+			c.dc.textAlign = wmfU(prm, 0)
+		case 0x0106: // SETPOLYFILLMODE
+			c.dc.winding = wmfU(prm, 0) == 2
+
+		case 0x02FA: // CREATEPENINDIRECT style, width(x, y), colour
+			create(&mfObject{pen: penFromStyle(wmfU(prm, 0), wmfS(prm, 1), wmfU32(prm, 3))})
+		case 0x02FC: // CREATEBRUSHINDIRECT style, colour, hatch
+			create(&mfObject{brush: brushFromStyle(wmfU(prm, 0), wmfU32(prm, 1))})
+		case 0x02FB: // CREATEFONTINDIRECT
+			create(&mfObject{font: wmfFont(prm)})
+		case 0x0142, 0x01F9: // DIBCREATEPATTERNBRUSH, CREATEPATTERNBRUSH
+			create(&mfObject{brush: brushFromStyle(3, 0)})
+		case 0x00F7, 0x06FF: // CREATEPALETTE, CREATEREGION
+			create(nil)
+		case 0x012D: // SELECTOBJECT
+			if i := int(wmfU(prm, 0)); i < len(slots) {
+				c.selectObject(slots[i])
+			}
+		case 0x01F0: // DELETEOBJECT
+			if i := int(wmfU(prm, 0)); i < len(slots) {
+				slots[i] = nil
+			}
+
+		case 0x0214: // MOVETO
+			c.dc.cur = mfPt{wmfS(prm, 1), wmfS(prm, 0)}
+		case 0x0213: // LINETO
+			to := mfPt{wmfS(prm, 1), wmfS(prm, 0)}
+			c.shape([][]mfPt{{c.dc.cur, to}}, false)
+			c.dc.cur = to
+		case 0x041B: // RECTANGLE bottom right top left
+			c.shape([][]mfPt{rectPoly(wmfS(prm, 3), wmfS(prm, 2), wmfS(prm, 1), wmfS(prm, 0))}, true)
+		case 0x0418: // ELLIPSE
+			c.shape([][]mfPt{ellipsePoly(wmfS(prm, 3), wmfS(prm, 2), wmfS(prm, 1), wmfS(prm, 0))}, true)
+		case 0x061C: // ROUNDRECT height width bottom right top left
+			c.shape([][]mfPt{roundRectPoly(wmfS(prm, 5), wmfS(prm, 4), wmfS(prm, 3), wmfS(prm, 2), wmfS(prm, 1), wmfS(prm, 0))}, true)
+		case 0x0817, 0x081A, 0x0830: // ARC, PIE, CHORD
+			l, t, r, b := wmfS(prm, 7), wmfS(prm, 6), wmfS(prm, 5), wmfS(prm, 4)
+			pts := arcPoly(l, t, r, b, mfPt{wmfS(prm, 3), wmfS(prm, 2)}, mfPt{wmfS(prm, 1), wmfS(prm, 0)})
+			switch fn {
+			case 0x0817:
+				c.shape([][]mfPt{pts}, false)
+			case 0x081A:
+				c.shape([][]mfPt{append(pts, mfPt{(l + r) / 2, (t + b) / 2})}, true)
+			default:
+				c.shape([][]mfPt{pts}, true)
+			}
+		case 0x0324, 0x0325: // POLYGON, POLYLINE
+			pts := wmfPoints(prm, 1, int(wmfS(prm, 0)))
+			c.shape([][]mfPt{pts}, fn == 0x0324)
+		case 0x0538: // POLYPOLYGON
+			n := int(wmfU(prm, 0))
+			at := 1 + n
+			var polys [][]mfPt
+			for k := 0; k < n; k++ {
+				cnt := int(wmfU(prm, 1+k))
+				polys = append(polys, wmfPoints(prm, at, cnt))
+				at += 2 * cnt
+			}
+			c.shape(polys, true)
+
+		case 0x061D: // PATBLT rop(32) height width y x
+			c.patBlt(wmfS(prm, 5), wmfS(prm, 4), wmfS(prm, 3), wmfS(prm, 2), wmfU32(prm, 0))
+		case 0x0B41: // DIBSTRETCHBLT
+			p.stretchBlt(c, prm, 2, true)
+		case 0x0940: // DIBBITBLT
+			p.stretchBlt(c, prm, 2, false)
+		case 0x0F43: // STRETCHDIB rop(32) usage srcH srcW ySrc xSrc dstH dstW yDst xDst DIB
+			if len(prm) > 22 {
+				rop, usage := wmfU32(prm, 0), wmfU(prm, 2)
+				if img, info, err := decodePackedDIB(prm[22:], usage); err == nil {
+					sr := image.Rect(int(wmfS(prm, 6)), int(wmfS(prm, 5)), int(wmfS(prm, 6)+wmfS(prm, 4)), int(wmfS(prm, 5)+wmfS(prm, 3)))
+					c.blit(img, dibSrcRect(sr, info, true), wmfS(prm, 10), wmfS(prm, 9), wmfS(prm, 8), wmfS(prm, 7), rop, info.isPhoto())
+				}
+			}
+		case 0x0D33: // SETDIBTODEV usage scanCount startScan yDib xDib h w yDest xDest DIB
+			if len(prm) > 18 {
+				if img, info, err := decodePackedDIB(prm[18:], wmfU(prm, 0)); err == nil {
+					w, h := wmfS(prm, 6), wmfS(prm, 5)
+					sr := image.Rect(int(wmfS(prm, 4)), int(wmfS(prm, 3)), int(wmfS(prm, 4)+w), int(wmfS(prm, 3)+h))
+					c.blit(img, dibSrcRect(sr, info, true), wmfS(prm, 8), wmfS(prm, 7), w, h, ropSrcCopy, info.isPhoto())
+				}
+			}
+
+		case 0x0521: // TEXTOUT len string(padded) y x
+			n := int(wmfU(prm, 0))
+			sb := (n + 1) / 2 * 2
+			if 2+sb+4 <= len(prm) {
+				s := prm[2 : 2+n]
+				y := wmfS(prm[2+sb:], 0)
+				x := wmfS(prm[2+sb:], 1)
+				c.text(mfPt{x, y}, ansiRunes(s), nil)
+			}
+		case 0x0A32: // EXTTEXTOUT y x len opts [rect] string [dx]
+			y, x := wmfS(prm, 0), wmfS(prm, 1)
+			n := int(wmfU(prm, 2))
+			opts := wmfU(prm, 3)
+			at := 8
+			if opts&0x6 != 0 && len(prm) >= 16 {
+				if opts&0x2 != 0 { // ETO_OPAQUE
+					c.opaqueBox(wmfS(prm, 4), wmfS(prm, 5), wmfS(prm, 6), wmfS(prm, 7))
+				}
+				at = 16
+			}
+			if at+n <= len(prm) {
+				s := ansiRunes(prm[at : at+n])
+				var dx []float64
+				dAt := at + (n+1)/2*2
+				if dAt+2*n <= len(prm) {
+					dx = make([]float64, n)
+					for i := range dx {
+						dx[i] = wmfS(prm[dAt:], i)
+					}
+				}
+				c.text(mfPt{x, y}, s, dx)
+			}
+		}
+		return true
+	})
+	return nil
+}
+
+// stretchBlt plays DIBSTRETCHBLT (stretch) and DIBBITBLT. at is the
+// parameter index after the 32-bit raster op.
+func (p *wmfPlayer) stretchBlt(c *mfCanvas, prm []byte, at int, stretch bool) {
+	rop := wmfU32(prm, 0)
+	// a record without a bitmap carries one reserved word more than the
+	// parameters and no DIB: it is a pattern fill
+	nParams := 8
+	if !stretch {
+		nParams = 6
+	}
+	var srcW, srcH, ySrc, xSrc, dstW, dstH, yDst, xDst float64
+	read := func(base int) {
+		if stretch {
+			srcH, srcW, ySrc, xSrc = wmfS(prm, base), wmfS(prm, base+1), wmfS(prm, base+2), wmfS(prm, base+3)
+			dstH, dstW, yDst, xDst = wmfS(prm, base+4), wmfS(prm, base+5), wmfS(prm, base+6), wmfS(prm, base+7)
+		} else {
+			ySrc, xSrc = wmfS(prm, base), wmfS(prm, base+1)
+			dstH, dstW, yDst, xDst = wmfS(prm, base+2), wmfS(prm, base+3), wmfS(prm, base+4), wmfS(prm, base+5)
+			srcW, srcH = dstW, dstH
+		}
+	}
+	if len(prm) == 2*(at+nParams+1) {
+		read(at + 1)
+		c.patBlt(xDst, yDst, dstW, dstH, rop)
+		return
+	}
+	read(at)
+	dibAt := 2 * (at + nParams)
+	if dibAt >= len(prm) {
+		return
+	}
+	img, info, err := decodePackedDIB(prm[dibAt:], 0)
+	if err != nil {
+		return
+	}
+	sr := image.Rect(int(xSrc), int(ySrc), int(xSrc+srcW), int(ySrc+srcH))
+	c.blit(img, dibSrcRect(sr, info, false), xDst, yDst, dstW, dstH, rop, info.isPhoto())
+}
+
+// dibSrcRect turns a source rectangle into decoded-image coordinates.
+// StretchDIBits and SetDIBitsToDevice measure y from the bottom row of a
+// bottom-up DIB (fromBottom); the blt records read the DIB as a bitmap
+// whose origin is the top-left corner, like the decoded image.
+func dibSrcRect(r image.Rectangle, info *dibInfo, fromBottom bool) image.Rectangle {
+	r = r.Canon()
+	if fromBottom && !info.topDown {
+		r = image.Rect(r.Min.X, info.h-r.Max.Y, r.Max.X, info.h-r.Min.Y)
+	}
+	return r
+}
+
+// wmfFont reads a WMF LOGFONT (16-bit fields)
+func wmfFont(prm []byte) *mfFont {
+	f := &mfFont{
+		height:     wmfS(prm, 0),
+		escapement: wmfS(prm, 2),
+		weight:     int(wmfS(prm, 4)),
+	}
+	if len(prm) >= 18 {
+		f.italic = prm[10] != 0
+		f.underline = prm[11] != 0
+		f.strike = prm[12] != 0
+		name := prm[18:]
+		for i, b := range name {
+			if b == 0 {
+				name = name[:i]
+				break
+			}
+		}
+		f.face = string(ansiRunes(name))
+	}
+	return f
+}
+
+// ansiRunes reads 8-bit text as Windows-1252 (close enough for the
+// Western code pages metafiles from Office use)
+func ansiRunes(b []byte) []rune {
+	out := make([]rune, 0, len(b))
+	for _, c := range b {
+		if c >= 0x80 && c < 0xA0 {
+			out = append(out, cp1252High[c-0x80])
+			continue
+		}
+		out = append(out, rune(c))
+	}
+	return out
+}
+
+var cp1252High = [32]rune{
+	0x20AC, 0x81, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x8D, 0x017D, 0x8F,
+	0x90, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x9D, 0x017E, 0x0178,
+}
+
+// utf16Runes reads n UTF-16LE code units
+func utf16Runes(b []byte, n int) []rune {
+	if 2*n > len(b) {
+		n = len(b) / 2
+	}
+	u := make([]uint16, n)
+	for i := range u {
+		u[i] = binary.LittleEndian.Uint16(b[2*i:])
+	}
+	return utf16.Decode(u)
+}

+ 5 - 0
src/mod/office/odp_reader.go

@@ -561,6 +561,11 @@ func (cv *odpConverter) frame(n *onode, slide *Slide, ox, oy, kx, ky float64) {
 		if ext == "jpg" {
 			ext = "jpeg"
 		}
+		if ext == "wmf" || ext == "emf" {
+			if raw, ext, ok = browserPicture(raw, ext); !ok {
+				return
+			}
+		}
 		if ext != "png" && ext != "jpeg" && ext != "gif" {
 			return
 		}

+ 5 - 0
src/mod/office/odt_reader.go

@@ -360,6 +360,11 @@ func (cv *odtConverter) frameImage(frame *onode, sb *strings.Builder) {
 	if ext == "jpg" {
 		ext = "jpeg"
 	}
+	if ext == "wmf" || ext == "emf" {
+		if raw, ext, ok = browserPicture(raw, ext); !ok {
+			return
+		}
+	}
 	if ext != "png" && ext != "jpeg" && ext != "gif" {
 		return
 	}

+ 3 - 0
src/mod/office/pptx_reader.go

@@ -1519,6 +1519,9 @@ func (sc *slideCtx) parsePic(node *xnode, cm coordMap) *Object {
 		return nil
 	}
 	ext := strings.TrimPrefix(strings.ToLower(path.Ext(mediaPath)), ".")
+	// a Windows metafile (old decks store scans as .wmf) is rendered to a
+	// bitmap the browser can show
+	data, ext, _ = browserPicture(data, ext)
 
 	props := Props{Src: encodeDataURL(data, ext), Fit: "fill"}
 	// srcRect crops the source before it is stretched into the frame

+ 20 - 5
src/web/Office/common/CONTRACT.md

@@ -159,7 +159,10 @@ Menus re-render every time they open, so `checked`/`enabled`/`sub` are re-evalua
 ## OfficeApp API
 
 Lifecycle: `newDocument() open() openPath(fp,fn) save(cb) saveAs(cb)
-markDirty() isDirty() getFilePath() getFileName() getMeta() wasImported()`
+print() requestClose(done, cancelled) markDirty() isDirty() getFilePath()
+getFileName() getMeta() wasImported()` (`requestClose` asks about unsaved
+changes before a window goes away: `done()` = it may close, `cancelled()` =
+the person kept it)
 — **call `OfficeApp.markDirty()` after every user edit**; it drives the title
 asterisk, autosave and crash drafts.
 
@@ -220,16 +223,19 @@ your hooks, Ctrl+/ (shortcuts help). Register everything else yourself.
 
 ## OfficePlatform (common/platform.js) — the host abstraction
 
-The suite runs in two hosts from one code base, and this is the seam:
+The suite runs in three hosts from one code base, and this is the seam:
 
 | host | where | file dialogs | documents | open / save / conversions |
 |---|---|---|---|---|
 | `arozos` | the ArozOS desktop | `ao_module_openFileSelector` | ArozOS virtual file system | the AGI backends → `mod/office` |
 | `standalone` | any static web server ("ArozOS Office Web") | `<input type=file>` / drag and drop / `?open=<relative path>` | the visitor's device; `Save` downloads the file back | the same `mod/office` code compiled to WebAssembly (always shipped) |
+| `native` | the standalone build inside a desktop shell ("ArozOS Office for macOS", `apps/ArozOS Office Mac`) | the system Open / Save dialogs (`OfficeNative`, `common/native.js`) | real files, as `native:/<handle>/<name>`; Save writes back in place | the same WebAssembly module |
 
 The mode is one line in `common/mode.js` (`window.OFFICE_STANDALONE`, plus
 `window.OFFICE_WASM`), which `apps/arozos_office/generate.go` rewrites in
-its output tree. Never test those flags — ask `OfficePlatform`.
+its output tree; the native host is the standalone build when a shell
+answers (`OfficeNative.available()`). Never test those flags — ask
+`OfficePlatform`.
 
 ### Two capability questions, deliberately separate
 
@@ -247,12 +253,19 @@ They are not the same question and must not be conflated: the standalone
 build can write a .docx but still cannot render a server PDF.
 
 ```js
-OfficePlatform.mode()               // "arozos" | "standalone"
+OfficePlatform.mode()               // "arozos" | "standalone" | "native"
 OfficePlatform.isStandalone()       // !hasBackend()
 OfficePlatform.requireBackend(what) // guards: toast + return false when the
 OfficePlatform.requireConvert(what) // capability is missing
 OfficePlatform.tracksRecents()      // false in standalone (paths do not outlive the page)
 OfficePlatform.autosavesToFile()    // false in standalone (autosave would download)
+OfficePlatform.prefersNewWindows()  // true in native: another document opens
+                                    // beside this one, not in its place
+OfficePlatform.openNewWindow()      // a new blank document in another window;
+                                    // false = this host has none (start in place)
+OfficePlatform.print(done)          // print the page; done() once the print
+                                    // dialog is finished with it (at once in a
+                                    // browser, later behind a native panel)
 
 // dialogs - cb gets [{filepath, filename}] / {filepath, filename}
 OfficePlatform.pickOpen({filter:["docx","txt"], multiple, memoryKey}, cb)
@@ -532,7 +545,9 @@ dialog's **Discard** button deletes the snapshot (document.agi
 `session-delete`) so it stops prompting; **Start fresh** keeps it for a
 later launch. The framework also intercepts the floatWindow close button
 (overriding `ao_module_close`) to confirm before discarding unsaved
-changes (Cancel / Close without saving / Save & close).
+changes (Cancel / Close without saving / Save & close); a desktop shell asks
+the same question through `OfficeApp.requestClose` when its window's close
+button, Cmd+W or Quit is used.
 
 ## OfficeClipboard (common/clipboard.js) — cross-app copy/paste
 

+ 275 - 0
src/web/Office/common/native.js

@@ -0,0 +1,275 @@
+/*
+    OfficeNative - the bridge to a native desktop shell
+    ===================================================
+
+    A desktop shell (apps/ArozOS Office Mac: a Cocoa window around a
+    WKWebView, serving the standalone build from 127.0.0.1) runs the suite
+    as a real desktop application. It announces itself by defining
+    window.OFFICE_NATIVE before any page script runs:
+
+        { platform: "macos", version: "1.0.0",
+          token: "<per-launch secret>", window: <window id> }
+
+    and answers on the page's own origin under /__native/. Every request
+    carries the token (X-Office-Token) and the window it comes from
+    (X-Office-Window); the shell refuses anything else, so another page or
+    program on this machine cannot drive it.
+
+    Files are capabilities, not paths. The page never names a file on disk:
+    the shell hands out "native:/<handle>/<name>" for a file the person
+    picked in a system dialog, opened from Finder or dropped on a window,
+    and only those can be read or written. Script that a hostile document
+    managed to run in the editor still could not reach anything else.
+
+    Endpoints (JSON in and out unless noted; errors are {error} with a
+    non-2xx status):
+
+      POST pick-open       {exts:[".docx"], multiple}  -> {files:[{path,name}]}
+      POST pick-save       {name, ext, near}           -> {path,name} | {cancelled:true}
+      GET  file?path=<p>   -> the file's bytes
+      PUT  file?path=<p>   <- the file's bytes, written atomically
+      POST recents         -> {items:[{path,name,app,ext,folder,at}]}
+      POST recents/forget  {path}
+      POST window          {action, ...} where action is
+                             open    {path} or {url}: another window
+                             close   this window, now (the page has agreed)
+                             close-cancelled  the person kept the window
+                             info    {edited, path, seq}: close-button dot,
+                                     proxy icon (the newest seq wins)
+                             theme   {theme: "light" | "dark" | "system"}
+                             print   the system print panel (answers when done)
+                             reveal  {path}: show the file in Finder
+
+    The shell calls into the page through two functions:
+
+      OfficeNative.requestClose()  the window's close button. true = close
+                                   now; false = the page is asking the
+                                   person and will answer with close or
+                                   close-cancelled
+      OfficeNative.menu(name)      an item of the system menu bar that the
+                                   page carries out (save, saveAs, print,
+                                   undo, redo)
+
+    Without a shell (ArozOS, the web edition) available() is false and
+    nothing here does anything: platform.js only picks its native host
+    when it is true.
+
+    Load order: mode.js, native.js, ... platform.js.
+*/
+var OfficeNative = (function () {
+    "use strict";
+
+    var cfg = window.OFFICE_NATIVE || null;
+    var PREFIX = "native:/";
+    var BASE = "/__native/";
+
+    function available() {
+        return !!(cfg && typeof cfg.token === "string" && cfg.token.length > 0 &&
+            typeof window.fetch === "function");
+    }
+    function isNativePath(p) { return String(p || "").indexOf(PREFIX) === 0; }
+
+    /* ---------- transport ---------- */
+    function headers(extra) {
+        var h = {
+            "X-Office-Token": cfg.token,
+            "X-Office-Window": String(cfg.window || 0)
+        };
+        Object.keys(extra || {}).forEach(function (k) { h[k] = extra[k]; });
+        return h;
+    }
+    function failure(res) {
+        return res.text().then(function (t) {
+            var msg = "HTTP " + res.status;
+            try {
+                var o = JSON.parse(t);
+                if (o && o.error) msg = o.error;
+            } catch (e) { if (t) msg = t; }
+            throw new Error(msg);
+        });
+    }
+    function call(endpoint, payload) {
+        if (!available()) return Promise.reject(new Error("no native shell"));
+        return fetch(BASE + endpoint, {
+            method: "POST",
+            headers: headers({ "Content-Type": "application/json" }),
+            body: JSON.stringify(payload || {}),
+            cache: "no-store"
+        }).then(function (res) {
+            if (!res.ok) return failure(res);
+            return res.json();
+        });
+    }
+    function fileUrl(path) { return BASE + "file?path=" + encodeURIComponent(path); }
+
+    // ".docx" and "docx" both appear in the suite's filters
+    function normExts(list) {
+        return (list || []).map(function (e) {
+            e = String(e).toLowerCase();
+            return e.charAt(0) === "." ? e : "." + e;
+        });
+    }
+
+    /* ---------- files ---------- */
+    function read(path) {
+        if (!available()) return Promise.reject(new Error("no native shell"));
+        return fetch(fileUrl(path), { headers: headers(), cache: "no-store" }).then(function (res) {
+            if (!res.ok) return failure(res);
+            return res.arrayBuffer();
+        }).then(function (buf) { return new Uint8Array(buf); });
+    }
+    // data: a Uint8Array, or a string (written as UTF-8)
+    function write(path, data) {
+        if (!available()) return Promise.reject(new Error("no native shell"));
+        return fetch(fileUrl(path), {
+            method: "PUT",
+            headers: headers({ "Content-Type": "application/octet-stream" }),
+            body: data,
+            cache: "no-store"
+        }).then(function (res) {
+            if (!res.ok) return failure(res);
+            return res.json();
+        });
+    }
+    // -> [{path, name}], empty when the person cancelled
+    function pickOpen(opts) {
+        opts = opts || {};
+        return call("pick-open", {
+            exts: normExts(opts.exts),
+            multiple: !!opts.multiple
+        }).then(function (r) { return (r && r.files) || []; });
+    }
+    // -> {path, name}, or null when the person cancelled. near: a native
+    // path whose folder the dialog starts in
+    function pickSave(opts) {
+        opts = opts || {};
+        return call("pick-save", {
+            name: opts.name || "",
+            ext: opts.ext || "",
+            near: isNativePath(opts.near) ? opts.near : ""
+        }).then(function (r) { return (r && r.path) ? r : null; });
+    }
+    function recents() {
+        return call("recents").then(function (r) { return (r && r.items) || []; });
+    }
+    function forgetRecent(path) { return call("recents/forget", { path: path }); }
+
+    /* ---------- the window ---------- */
+    function windowAction(action, extra) {
+        var p = extra || {};
+        p.action = action;
+        return call("window", p);
+    }
+    // {path: native path} opens that document; {url: page path} opens a page
+    function openWindow(target) {
+        target = target || {};
+        return windowAction("open", { path: target.path || "", url: target.url || "" });
+    }
+    function closeWindow() { return windowAction("close"); }
+    /* Each update is its own request, and requests can overtake each
+       other: seq orders them (the shell keeps the newest), and it grows
+       across page loads in the window too. */
+    var infoCount = 0;
+    function windowInfo(info) {
+        info = info || {};
+        infoCount = (infoCount + 1) % 1000;
+        return windowAction("info", {
+            edited: !!info.edited,
+            path: isNativePath(info.path) ? info.path : "",
+            seq: Date.now() * 1000 + infoCount
+        });
+    }
+    // dark: true / false, or null to follow the system
+    function setTheme(dark) {
+        return windowAction("theme", { theme: dark === null ? "system" : (dark ? "dark" : "light") });
+    }
+    // resolves once the print panel is finished with the page
+    function print() { return windowAction("print"); }
+    function reveal(path) { return windowAction("reveal", { path: path }); }
+
+    /* ---------- the shell calling in ---------- */
+    var closing = false;
+    function requestClose() {
+        var app = window.OfficeApp;
+        if (!app || typeof app.requestClose !== "function") return true;
+        if (typeof app.isDirty === "function" && !app.isDirty()) return true;
+        // the close button again while the question is up: keep asking once
+        if (closing) return false;
+        closing = true;
+        app.requestClose(function () {
+            closing = false;
+            closeWindow();
+        }, function () {
+            closing = false;
+            windowAction("close-cancelled");
+        });
+        return false;
+    }
+
+    /* A key combination the page's own shortcuts answer (OfficeHotkeys),
+       for menu items whose command lives in the app rather than in
+       OfficeApp: the same handler runs whether the person pressed the keys
+       or picked the menu item. Falls back to the browser's command when no
+       handler claimed it (a plain text field's own undo). */
+    function sendKey(key, shift, fallback) {
+        var target = document.activeElement || document.body;
+        var ev;
+        try {
+            ev = new KeyboardEvent("keydown", {
+                key: key, code: "Key" + key.toUpperCase(), metaKey: true,
+                shiftKey: !!shift, bubbles: true, cancelable: true
+            });
+        } catch (e) { return false; }
+        if (target.dispatchEvent(ev) && fallback) {
+            try { document.execCommand(fallback); } catch (e) { }
+        }
+        return true;
+    }
+    function menu(name) {
+        var app = window.OfficeApp;
+        switch (name) {
+            case "save":
+                if (app && app.save) { app.save(); return true; }
+                return false;
+            case "saveAs":
+                if (app && app.saveAs) { app.saveAs(); return true; }
+                return false;
+            case "print":
+                if (app && app.print) { app.print(); return true; }
+                window.print();
+                return true;
+            case "undo":
+                return sendKey("z", false, "undo");
+            case "redo":
+                return sendKey("z", true, "redo");
+        }
+        return false;
+    }
+
+    /* window.print() does nothing in a WKWebView: hand it to the shell's
+       print panel. OfficeApp prints through OfficePlatform.print, which
+       waits for the panel; this only catches a direct call. */
+    if (available()) {
+        window.print = function () { print(); };
+    }
+
+    return {
+        available: available,
+        platform: function () { return cfg ? cfg.platform || "" : ""; },
+        isNativePath: isNativePath,
+        read: read,
+        write: write,
+        pickOpen: pickOpen,
+        pickSave: pickSave,
+        recents: recents,
+        forgetRecent: forgetRecent,
+        openWindow: openWindow,
+        closeWindow: closeWindow,
+        windowInfo: windowInfo,
+        setTheme: setTheme,
+        print: print,
+        reveal: reveal,
+        requestClose: requestClose,
+        menu: menu
+    };
+})();

+ 76 - 30
src/web/Office/common/office.js

@@ -594,7 +594,23 @@ var OfficeApp = (function () {
             setStatus("Failed to load " + fn, "error");
         });
     }
+    /*
+        A host that keeps each document in a window of its own (the desktop
+        shell: OfficePlatform.prefersNewWindows) opens another document
+        beside this one once this window holds something - a file, or
+        unsaved work - the way a desktop app does. An empty untitled window
+        is simply reused. Elsewhere the document replaces this one.
+    */
+    function holdsDocument() { return !!filepath || dirty; }
+    function openElsewhere(fp, fn) {
+        if (!OfficePlatform.prefersNewWindows() || !holdsDocument()) return false;
+        return OfficePlatform.openDocument(fp, fn, { appIcon: cfg.appIcon });
+    }
     function newDocument() {
+        if (OfficePlatform.prefersNewWindows() && holdsDocument() &&
+            OfficePlatform.openNewWindow()) {
+            return;
+        }
         var go = function () {
             filepath = null;
             filename = null;
@@ -620,10 +636,12 @@ var OfficeApp = (function () {
                 filter.push(e.substring(1));
             });
             OfficePlatform.pickOpen({ filter: filter, memoryKey: "document" }, function (files) {
+                if (openElsewhere(files[0].filepath, files[0].filename)) return;
                 openPath(files[0].filepath, files[0].filename);
             });
         };
-        if (dirty) {
+        // nothing is discarded when the document goes to a window of its own
+        if (dirty && !OfficePlatform.prefersNewWindows()) {
             confirmDialog("Discard unsaved changes?",
                 "The current document has unsaved changes that will be lost.",
                 "Discard", "Cancel", function (yes) { if (yes) go(); });
@@ -1265,6 +1283,7 @@ var OfficeApp = (function () {
                         return getRecents().map(function (r) {
                             return {
                                 label: r.fn, action: function () {
+                                    if (openElsewhere(r.fp, r.fn)) return;
                                     if (dirty) {
                                         confirmDialog("Discard unsaved changes?",
                                             "The current document has unsaved changes.",
@@ -1360,8 +1379,11 @@ var OfficeApp = (function () {
         closeAllMenus();
         if (cfg.onBeforePrint) { try { cfg.onBeforePrint(); } catch (e) { } }
         setTimeout(function () {
-            window.print();
-            if (cfg.onAfterPrint) { try { cfg.onAfterPrint(); } catch (e) { } }
+            // the print layout stays up until the dialog is done with it -
+            // at once in a browser, later behind a native print panel
+            OfficePlatform.print(function () {
+                if (cfg.onAfterPrint) { try { cfg.onAfterPrint(); } catch (e) { } }
+            });
         }, 60);
     }
 
@@ -1392,9 +1414,14 @@ var OfficeApp = (function () {
             $dl.append($act);
         }
         $ov.append($dl);
-        $ov.on("mousedown", function (e) { if (e.target === $ov[0] && opt.dismissable !== false) close(); });
+        // dismissed without a button: opt.onDismiss hears about it
+        var dismiss = function () {
+            close();
+            if (opt.onDismiss) opt.onDismiss();
+        };
+        $ov.on("mousedown", function (e) { if (e.target === $ov[0] && opt.dismissable !== false) dismiss(); });
         $(document).on("keydown.ofdialog", function (e) {
-            if (e.key === "Escape" && opt.dismissable !== false) close();
+            if (e.key === "Escape" && opt.dismissable !== false) dismiss();
         });
         $("body").append($ov);
         return { close: close, body: $body };
@@ -1666,9 +1693,10 @@ var OfficeApp = (function () {
 
         updateTitle();
 
-        // the standalone build has no storage behind it - say so once, so
-        // "Save downloads a copy" is not a surprise the first time
-        if (OfficePlatform.isStandalone() && (!inputs || !inputs.length)) {
+        // the web edition has no storage behind it - say so once, so "Save
+        // downloads a copy" is not a surprise the first time (a desktop
+        // shell saves to real files and needs no such warning)
+        if (OfficePlatform.mode() === "standalone" && (!inputs || !inputs.length)) {
             setStatus("Web edition - open a " + cfg.extension +
                 " from this device, and Save downloads it back", "info", 9000);
         }
@@ -1716,6 +1744,42 @@ var OfficeApp = (function () {
         }, true);
     }
 
+    /*
+        Ask before a window holding unsaved changes goes away. done() once
+        it may close - nothing to lose, saved, or the changes thrown away;
+        cancelled() when the person keeps it open. The ArozOS desktop asks
+        through ao_module_close (below), a desktop shell through
+        OfficeNative.requestClose.
+    */
+    function requestClose(done, cancelled) {
+        cancelled = cancelled || function () { };
+        if (!dirty) { done(); return; }
+        dialog({
+            title: "Unsaved changes",
+            body: "<b>" + escapeHtml(filename || (cfg.defaultFileName + cfg.extension)) +
+                "</b> has unsaved changes. Close it anyway?",
+            dismissable: true,
+            onDismiss: cancelled,
+            buttons: [
+                { label: "Cancel", action: function (close) { close(); cancelled(); } },
+                {
+                    label: "Close without saving", danger: true,
+                    action: function (close) {
+                        close();
+                        markClean();   // never re-prompt while the window tears down
+                        done();
+                    }
+                },
+                {
+                    label: "Save & close", primary: true,
+                    // save() only calls back on success, so a failed or
+                    // cancelled save leaves the window open
+                    action: function (close) { close(); save(done); }
+                }
+            ]
+        });
+    }
+
     /* The desktop routes a floatWindow's X button through the iframe's
        ao_module_close() (see ao_module.js + desktop.html: it calls
        contentWindow.ao_module_close() when defined). beforeunload does NOT
@@ -1732,28 +1796,7 @@ var OfficeApp = (function () {
                 ao_module_closeHandler();
             }
         };
-        window.ao_module_close = function () {
-            if (!dirty) { reallyClose(); return; }
-            dialog({
-                title: "Unsaved changes",
-                body: "<b>" + escapeHtml(filename || (cfg.defaultFileName + cfg.extension)) +
-                    "</b> has unsaved changes. Close it anyway?",
-                dismissable: true,
-                buttons: [
-                    { label: "Cancel" },
-                    {
-                        label: "Close without saving", danger: true,
-                        action: function (close) { close(); reallyClose(); }
-                    },
-                    {
-                        label: "Save & close", primary: true,
-                        // save() only calls back on success, so a failed or
-                        // cancelled save leaves the window open
-                        action: function (close) { close(); save(reallyClose); }
-                    }
-                ]
-            });
-        };
+        window.ao_module_close = function () { requestClose(reallyClose); };
     }
 
     /* ---------- public API ---------- */
@@ -1765,6 +1808,9 @@ var OfficeApp = (function () {
         openPath: openPath,
         save: save,
         saveAs: saveAs,
+        print: printDoc,
+        // ask before the window closes: done() = it may, cancelled() = kept
+        requestClose: requestClose,
         markDirty: markDirty,
         isDirty: function () { return dirty; },
         getFilePath: function () { return filepath; },

+ 203 - 5
src/web/Office/common/platform.js

@@ -17,7 +17,14 @@
                     WebAssembly (common/wasm.js), and saving hands the file
                     back as a download.
 
-    Documents are .docx / .xlsx / .pptx in both hosts: documentLoad turns
+      "native"      the standalone build inside a desktop shell (ArozOS
+                    Office for macOS, apps/ArozOS Office Mac) that answers
+                    OfficeNative (common/native.js). The same WebAssembly
+                    converters, but files are real files: system Open and
+                    Save dialogs, Save writes back in place, and autosave
+                    and the recent list work as they do in ArozOS.
+
+    Documents are .docx / .xlsx / .pptx in every host: documentLoad turns
     the file into the editor envelope and documentSave writes the envelope
     back as the file (mod/office native.go - the OOXML plus the editor's own
     copy embedded in the package).
@@ -36,10 +43,12 @@
     and the wasm converter, and pick the right one.
 
     The mode comes from common/mode.js (window.OFFICE_STANDALONE), which the
-    web-viewer generator rewrites in its output tree. Nothing else in the
-    suite should test that flag: ask OfficePlatform instead.
+    web-viewer generator rewrites in its output tree, and the native host is
+    the standalone build when a shell is answering (OfficeNative.available).
+    Nothing else in the suite should test either: ask OfficePlatform instead.
 
-    Load order: mode.js, recents.js, wasm.js, platform.js, office.js.
+    Load order: mode.js, native.js, recents.js, wasm.js, platform.js,
+    office.js.
 
     Path shapes in standalone mode
     ------------------------------
@@ -52,6 +61,12 @@
                         which is how ?open= and ?template= work (a template
                         is a plain envelope JSON file, templates/*.json)
 
+    and in native mode, besides those:
+      "native:/<handle>/<name>"  a file on disk the person picked, opened
+                        from Finder or dropped on the window. The shell
+                        keeps the handle across relaunches, so ?open= with
+                        one reopens the file itself
+
     Query parameters the home page uses (see home/home.js):
       ?open=<relative path>      open that document
       ?template=<relative path>  start a new unsaved document from it
@@ -1018,10 +1033,179 @@ var OfficePlatform = (function () {
         }
     };
 
+    /* ================================================================
+       Native host (the standalone build inside a desktop shell)
+       ================================================================ */
+    /*
+        Everything the web edition does still holds here - the converters
+        are the same WebAssembly module, templates are fetched next to the
+        page, the crash snapshot stays in localStorage - except that files
+        are real files: the pickers are the system's own dialogs, and a
+        "native:/<handle>/<name>" path survives a reload and a relaunch, so
+        Save writes back in place and autosave and recents come back.
+
+        The shell keeps its own recent list (the home page and the system's
+        Open Recent menu read it): it notes a document whenever one is read
+        or written, so nothing here has to.
+    */
+    function isNativePath(p) {
+        return !!(window.OfficeNative && OfficeNative.isNativePath(p));
+    }
+    function nativeFail(errcb) {
+        return function (e) { if (errcb) errcb((e && e.message) || String(e)); };
+    }
+    function nativeReadBytes(path, cb, errcb) {
+        if (!isNativePath(path)) { standalone.readBytes(path, cb, errcb); return; }
+        OfficeNative.read(path).then(cb, nativeFail(errcb));
+    }
+    /* Write to a file the person chose. A path that is no file on disk (a
+       template, a shared link, a dropped file the shell could not place)
+       has nowhere to be written back to, so the Save dialog asks where -
+       what the web edition's download stands in for. A cancelled dialog is
+       reported as a failure: the caller is waiting for one or the other. */
+    function nativeWrite(path, data, cb, errcb) {
+        var fail = nativeFail(errcb);
+        var put = function (target) {
+            OfficeNative.write(target, data).then(function () { if (cb) cb(); }, fail);
+        };
+        if (isNativePath(path)) { put(path); return; }
+        var name = saveName(path);
+        OfficeNative.pickSave({ name: name, ext: extOf(name) }).then(function (f) {
+            if (f) put(f.path);
+            else fail(new Error("cancelled"));
+        }, fail);
+    }
+    // what the shell shows for this window: the dot in the close button and
+    // the file behind the title's proxy icon
+    function nativeWindowState() {
+        var app = window.OfficeApp;
+        return {
+            edited: !!(app && app.isDirty && app.isDirty()),
+            path: (app && app.getFilePath && app.getFilePath()) || ""
+        };
+    }
+
+    var nativeShell = {
+        name: "native",
+        hasBackend: false,
+        tracksRecents: true,
+        autosavesToFile: true,
+        // a desktop app opens another document in a window of its own
+        prefersNewWindows: true,
+
+        canConvert: standalone.canConvert,
+        convertIn: function (spec, srcRef, cb, errcb) {
+            if (!spec.wasm) { errcb(NO_CONVERTER); return; }
+            nativeReadBytes(srcRef, function (bytesIn) {
+                OfficeWasm.runImport(spec.wasm, bytesIn, cb, errcb);
+            }, function (msg) { errcb("could not read the file: " + msg); });
+        },
+        convertOut: function (spec, destRef, bodyJson, cb, errcb) {
+            if (!spec.wasm) { errcb(NO_CONVERTER); return; }
+            OfficeWasm.runExport(spec.wasm, bodyJson, function (res) {
+                nativeWrite(destRef, res.data, function () { cb({ mediaZip: null }); }, errcb);
+            }, errcb);
+        },
+
+        prepareWorkdir: standalone.prepareWorkdir,
+        releaseWorkdir: standalone.releaseWorkdir,
+        agirun: standalone.agirun,
+        agirunLarge: standalone.agirunLarge,
+
+        pickOpen: function (opts, cb) {
+            OfficeNative.pickOpen({ exts: opts.filter, multiple: !!opts.multiple }).then(function (files) {
+                if (!files.length) return;
+                cb(files.map(function (f) { return { filepath: f.path, filename: f.name }; }));
+            }, function (e) { toast("Could not show the Open dialog: " + e.message, "error"); });
+        },
+        pickSave: function (opts, cb) {
+            OfficeNative.pickSave({
+                name: opts.defaultName || "document",
+                ext: opts.ext || "",
+                near: nativeWindowState().path
+            }).then(function (f) {
+                if (f) cb({ filepath: f.path, filename: f.name });
+            }, function (e) { toast("Could not show the Save dialog: " + e.message, "error"); });
+        },
+
+        readText: function (path, cb, errcb) {
+            errcb = errcb || function () { };
+            if (!isNativePath(path)) { standalone.readText(path, cb, errcb); return; }
+            nativeReadBytes(path, function (bytes) {
+                cb(new TextDecoder("utf-8").decode(bytes));
+            }, errcb);
+        },
+        readBytes: function (path, cb, errcb) {
+            nativeReadBytes(path, cb, errcb || function () { });
+        },
+        writeText: function (path, content, cb, errcb) {
+            nativeWrite(path, String(content), cb, errcb);
+        },
+        writeBytes: function (path, bytes, cb, errcb) {
+            nativeWrite(path, bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes), cb, errcb);
+        },
+
+        documentLoad: function (path, cb, errcb) {
+            var nat = nativeOf(saveName(path));
+            if (!nat) { errcb("not a .docx, .xlsx or .pptx file"); return; }
+            if (!nativeShell.canConvert()) { errcb(NO_WASM); return; }
+            nativeReadBytes(path, function (bytes) {
+                OfficeWasm.runImport(nat.wasm, bytes, cb, errcb);
+            }, function (msg) { errcb("could not read the file: " + msg); });
+        },
+        documentSave: function (path, envelopeJson, cb, errcb) {
+            var nat = nativeOf(saveName(path));
+            if (!nat) { errcb("documents are saved as .docx, .xlsx or .pptx"); return; }
+            if (!nativeShell.canConvert()) { errcb(NO_WASM); return; }
+            OfficeWasm.runExport(nat.wasm, envelopeJson, function (res) {
+                nativeWrite(path, res.data, cb, errcb);
+            }, errcb);
+        },
+
+        sessionSave: standalone.sessionSave,
+        sessionLoad: standalone.sessionLoad,
+        sessionDelete: standalone.sessionDelete,
+
+        // pictures stay inline, as in the web edition: there is no server
+        // to link them to, and the file on disk carries them anyway
+        mediaUrl: standalone.mediaUrl,
+        blobToSrc: standalone.blobToSrc,
+        cacheBlob: standalone.cacheBlob,
+        adoptSrc: standalone.adoptSrc,
+        isForeignWorkingCopy: standalone.isForeignWorkingCopy,
+
+        loadInputFiles: entryPointFiles,
+        openDocument: function (filepath) {
+            if (!isNativePath(filepath)) return false;
+            OfficeNative.openWindow({ path: filepath });
+            return true;
+        },
+        // a new, empty document of this app in a window of its own
+        openNewWindow: function () {
+            OfficeNative.openWindow({ url: window.location.pathname });
+            return true;
+        },
+        // the system print panel is asynchronous: done once it is finished
+        // with the page, so the app keeps its print layout up until then
+        print: function (done) {
+            OfficeNative.print().then(done, done);
+        },
+        setWindowTitle: function (t) {
+            // the shell shows "edited" as the dot in the close button
+            document.title = String(t).replace(" •", "");
+            OfficeNative.windowInfo(nativeWindowState());
+        },
+        setWindowTheme: function (dark) { OfficeNative.setTheme(dark); },
+        // the shell opens dropped documents itself (with their real path);
+        // a File that still reaches the page is held like the web edition's
+        adoptDroppedFile: standalone.adoptDroppedFile
+    };
+
     /* ================================================================
        Chosen host
        ================================================================ */
-    var host = STANDALONE ? standalone : arozos;
+    var host = !STANDALONE ? arozos :
+        (window.OfficeNative && OfficeNative.available()) ? nativeShell : standalone;
 
     // Uniform "this needs a server" guard for the apps' menu entries: they
     // gate on hasBackend() so the item is absent rather than failing late.
@@ -1101,6 +1285,20 @@ var OfficePlatform = (function () {
         // open a document in a second window of this app; false = this host
         // has nowhere to open it from (the standalone build saves by download)
         openDocument: function (fp, fn, o) { return !!host.openDocument(fp, fn, o || {}); },
+        // true where another document belongs in a window of its own rather
+        // than in place of this one (a desktop app, not a browser tab)
+        prefersNewWindows: function () { return !!host.prefersNewWindows; },
+        // a new, empty document of this app in another window; false = this
+        // host has no such thing, so the caller starts one in place
+        openNewWindow: function () { return !!(host.openNewWindow && host.openNewWindow()); },
+        // print the page; done() once the print dialog is finished with it,
+        // which the browser's window.print() already is when it returns
+        print: function (done) {
+            done = done || function () { };
+            if (host.print) { host.print(done); return; }
+            window.print();
+            done();
+        },
         adoptDroppedFile: function (f, cb) {
             if (host.adoptDroppedFile) host.adoptDroppedFile(f, cb);
         },

+ 1 - 0
src/web/Office/docs/index.html

@@ -24,6 +24,7 @@
     <script src="../../script/jquery.min.js"></script>
     <script src="../../script/ao_module.js"></script>
     <script src="../common/mode.js"></script>
+    <script src="../common/native.js"></script>
     <script src="../common/share.js"></script>
     <script src="../common/recents.js"></script>
     <script src="../common/wasm.js"></script>

+ 111 - 11
src/web/Office/home/home.js

@@ -16,6 +16,12 @@
     OfficePlatform resolves back to those bytes. That is the same path the
     "Recently opened" list uses, so there is one mechanism rather than two.
 
+    Inside a desktop shell (OfficeNative, common/native.js - ArozOS Office
+    for macOS) none of that hand-off is needed: files are real files there.
+    The recent list is the shell's own, "Open" is the system dialog, and a
+    document is opened by its path (?open=native:/<handle>/<name>), so Save
+    in the editor writes back to it.
+
     ?request=<share link> (standalone build) uses the same hand-off: the page
     downloads the document from the ArozOS share's preview endpoint, reads
     which app it belongs to from the parts its zip holds (word/, xl/, ppt/),
@@ -117,6 +123,12 @@
     }
     function go(url) { window.location.href = url; }
 
+    // running inside a desktop shell that keeps real files (see the top)
+    var NATIVE = !!(window.OfficeNative && OfficeNative.available());
+    function nativeOpenUrl(entry) {
+        return appUrl(entry.app, "?open=" + encodeURIComponent(entry.path));
+    }
+
     function ago(ts) {
         if (!ts) return "";
         var diff = new Date().getTime() - ts;
@@ -139,6 +151,8 @@
         try { t = localStorage.getItem("office_theme"); } catch (e) { }
         if (t === "dark") document.documentElement.setAttribute("data-theme", "dark");
         else if (t === "light") document.documentElement.setAttribute("data-theme", "light");
+        // the window's title bar follows along (null: the system setting)
+        if (NATIVE) OfficeNative.setTheme(t === "dark" ? true : (t === "light" ? false : null));
     }
 
     /* ================= state ================= */
@@ -148,7 +162,8 @@
         recentsAll: false,
         tplPage: 0,
         tplAll: false,
-        templates: []
+        templates: [],
+        nativeRecents: []  // the shell's recent files, when NATIVE
     };
     var TPL_PER_PAGE = 6;
     var RECENT_SHOWN = 5;
@@ -187,7 +202,8 @@
             menu.appendChild(b);
         });
         menu.appendChild(el("div", "hm-menu-sep"));
-        var open = el("button", "", svgIcon("#i-folder") + "<span>Open from device</span>");
+        var open = el("button", "", svgIcon("#i-folder") + "<span>" +
+            (NATIVE ? "Open a file" : "Open from device") + "</span>");
         open.type = "button";
         open.addEventListener("click", function () { closeMenus(); pickFile(); });
         menu.appendChild(open);
@@ -199,9 +215,12 @@
     }
 
     /* ================= recently opened ================= */
+    function recentsAvailable() {
+        return NATIVE || !!(window.OfficeRecents && OfficeRecents.supported());
+    }
     function recentEntries() {
-        if (!window.OfficeRecents || !OfficeRecents.supported()) return [];
-        var list = OfficeRecents.index();
+        if (!recentsAvailable()) return [];
+        var list = NATIVE ? state.nativeRecents : OfficeRecents.index();
         if (state.filter) {
             list = list.filter(function (e) { return e.app === state.filter; });
         }
@@ -228,9 +247,29 @@
         shown.forEach(function (entry) { host.appendChild(recentRow(entry)); });
     }
 
+    /* The shell's list is asked for, not read: it changes whenever any
+       window opens or saves a document, so it is fetched again each time
+       this window comes back to the front. Entries take the shape of
+       OfficeRecents' ones, with the native path as the id. */
+    function loadNativeRecents() {
+        OfficeNative.recents().then(function (items) {
+            state.nativeRecents = items.map(function (e) {
+                return {
+                    id: e.path, path: e.path, name: e.name, app: e.app,
+                    ext: e.ext, at: e.at, folder: e.folder || ""
+                };
+            });
+            renderRecents();
+        }, function () { /* keep what is shown */ });
+    }
+
     function emptyRecents() {
         var why;
-        if (!window.OfficeRecents || !OfficeRecents.supported()) {
+        if (NATIVE) {
+            why = state.query
+                ? "No recent document matches &ldquo;" + esc(state.query) + "&rdquo;."
+                : "Documents you open or save will show up here.";
+        } else if (!window.OfficeRecents || !OfficeRecents.supported()) {
             why = "This browser will not let the page store documents, so recent " +
                 "files are unavailable. Opening and editing still work.";
         } else if (state.query) {
@@ -255,7 +294,8 @@
             '<span class="hm-row-ic">' + svgIcon(app.icon) + "</span>" +
             '<span class="hm-row-body">' +
             '<div class="hm-row-name">' + esc(entry.name) + "</div>" +
-            '<div class="hm-row-sub">' + esc(app.label) + "</div></span>" +
+            '<div class="hm-row-sub">' + esc(app.label) +
+            (entry.folder ? " &middot; " + esc(entry.folder) : "") + "</div></span>" +
             '<span class="hm-row-time">' + esc(ago(entry.at)) + "</span>";
         var more = el("button", "hm-row-more", svgIcon("#i-more"));
         more.type = "button";
@@ -271,6 +311,10 @@
 
     function openRecent(entry) {
         var app = APPS[entry.app] ? entry.app : appForExt(entry.ext) || "document";
+        if (NATIVE) {
+            go(nativeOpenUrl({ app: app, path: entry.path }));
+            return;
+        }
         go(appUrl(app, "?recent=" + encodeURIComponent(entry.id)));
     }
 
@@ -288,11 +332,19 @@
             menu.appendChild(b);
         };
         add("#i-open", "Open", function () { openRecent(entry); });
-        add("#i-download", "Download a copy", function () { downloadRecent(entry); });
-        menu.appendChild(el("div", "hm-menu-sep"));
-        add("#i-trash", "Remove from list", function () {
-            OfficeRecents.forget(entry.id, renderRecents);
-        });
+        if (NATIVE) {
+            add("#i-folder", "Show in Finder", function () { OfficeNative.reveal(entry.path); });
+            menu.appendChild(el("div", "hm-menu-sep"));
+            add("#i-trash", "Remove from list", function () {
+                OfficeNative.forgetRecent(entry.path).then(loadNativeRecents, loadNativeRecents);
+            });
+        } else {
+            add("#i-download", "Download a copy", function () { downloadRecent(entry); });
+            menu.appendChild(el("div", "hm-menu-sep"));
+            add("#i-trash", "Remove from list", function () {
+                OfficeRecents.forget(entry.id, renderRecents);
+            });
+        }
 
         // positioned against the page, not the row, so a scrolling card
         // cannot clip it
@@ -567,6 +619,7 @@
 
     /* ================= opening a file from the device ================= */
     function pickFile() {
+        if (NATIVE) { pickNativeFiles(); return; }
         var input = $("#hmFile");
         input.value = "";
         input.accept = Object.keys(openableExts()).join(",");
@@ -599,6 +652,24 @@
         reader.readAsArrayBuffer(file);
     }
 
+    /* The system Open dialog: the first document opens in this window, any
+       others in windows of their own. */
+    function pickNativeFiles() {
+        OfficeNative.pickOpen({ exts: Object.keys(openableExts()), multiple: true }).then(function (files) {
+            var first = true;
+            files.forEach(function (f) {
+                var app = appForExt(extOf(f.name));
+                if (!app) return;
+                if (first) {
+                    first = false;
+                    go(nativeOpenUrl({ app: app, path: f.path }));
+                } else {
+                    OfficeNative.openWindow({ path: f.path });
+                }
+            });
+        }, function (e) { window.alert("Could not show the Open dialog: " + e.message); });
+    }
+
     /* ================= ?request=<ArozOS share link> ================= */
     function queryParam(name) {
         var m = new RegExp("[?&]" + name + "=([^&]*)").exec(window.location.search || "");
@@ -677,6 +748,30 @@
         return true;
     }
 
+    /* The page's words are the web edition's. In a desktop shell this is a
+       Mac app working on the Mac's own files, so it says that instead. */
+    function nativeWording() {
+        var set = function (sel, text) {
+            var e = document.querySelector(sel);
+            if (e) e.textContent = text;
+        };
+        set(".hm-brand-text span", "for Mac");
+        set(".hm-privacy-head b", "Files stay on this Mac");
+        set(".hm-privacy p", "Documents open and save in place. No account required.");
+        set(".hm-version div", "ArozOS Office for Mac");
+        set(".hm-hero-text p", "Create and edit documents, spreadsheets and presentations " +
+            "\u2014 the .docx, .xlsx and .pptx files on this Mac.");
+        // "device" means nothing in a desktop app: these open a file
+        var buttons = document.querySelectorAll('[data-action="open-device"]');
+        for (var i = 0; i < buttons.length; i++) {
+            var b = buttons[i];
+            var span = b.querySelector("span");
+            if (span) { span.textContent = "Open a file"; continue; }
+            var last = b.lastChild;
+            if (last && last.nodeType === 3) last.textContent = " Open a file";
+        }
+    }
+
     /* ================= filters ================= */
     function setFilter(f) {
         state.filter = f;
@@ -698,6 +793,11 @@
         buildCreateMenu();
         renderRecents();
         loadTemplates();
+        if (NATIVE) {
+            nativeWording();
+            loadNativeRecents();
+            window.addEventListener("focus", loadNativeRecents);
+        }
 
         // formats line in the tip, so it never claims more than the build does
         var tip = $(".hm-tip-formats");

+ 1 - 0
src/web/Office/home/index.html

@@ -237,6 +237,7 @@
 <input type="file" id="hmFile" hidden>
 
 <script src="../common/mode.js"></script>
+<script src="../common/native.js"></script>
 <script src="../common/share.js"></script>
 <script src="../common/recents.js"></script>
 <script src="../home/home.js"></script>

+ 1 - 0
src/web/Office/sheets/index.html

@@ -20,6 +20,7 @@
     <script src="../../script/jquery.min.js"></script>
     <script src="../../script/ao_module.js"></script>
     <script src="../common/mode.js"></script>
+    <script src="../common/native.js"></script>
     <script src="../common/share.js"></script>
     <script src="../common/recents.js"></script>
     <script src="../common/wasm.js"></script>

+ 1 - 0
src/web/Office/slides/index.html

@@ -20,6 +20,7 @@
     <script src="../../script/jquery.min.js"></script>
     <script src="../../script/ao_module.js"></script>
     <script src="../common/mode.js"></script>
+    <script src="../common/native.js"></script>
     <script src="../common/share.js"></script>
     <script src="../common/recents.js"></script>
     <script src="../common/wasm.js"></script>