Browse Source

Improve Slides PPTX/ODP fidelity and image tools

Overhauled Office slide import/export to preserve much more source formatting: style inheritance, theme color mapping, paragraph/run rich text, bullets/spacing, connectors, table cell formatting, image crop/radius/mask/opacity, and ODP master-page/style handling. Added PPTX chart-cache parsing and embedded font extraction support, expanded shape mappings, updated PDF text layout handling, and introduced broad fidelity tests plus docs/contract updates and new Slides UI for crop/mask/reset image workflows.
Toby Chui 2 months ago
parent
commit
dfac4be043

+ 2 - 1
src/mod/office/odf_test.go

@@ -232,7 +232,8 @@ func TestOdpRoundTrip(t *testing.T) {
 		t.Errorf("line lost: %+v", ln)
 	}
 	tb := byType["table"]
-	if tb == nil || len(tb.Props.Rows) != 2 || tb.Props.Rows[0][0] != "A" {
+	// cells come back as the editor's rich HTML; compare the text they show
+	if tb == nil || len(tb.Props.Rows) != 2 || cellText(tb.Props.Rows[0][0]) != "A" {
 		b, _ := json.Marshal(tb)
 		t.Errorf("table lost: %s", b)
 	}

+ 909 - 116
src/mod/office/odp_reader.go

@@ -4,20 +4,72 @@ package office
 	odp_reader.go - Parse an OpenDocument Presentation (.odp) into a
 	Presentation, scaled into the 960x540 editor space.
 
-	Frames with text boxes become text objects (paragraph lines joined with
-	<br>), draw:image frames become image objects (pictures re-inlined as
-	data URLs), draw:rect / draw:ellipse become shapes, draw:line lines and
-	framed tables become table objects. Slide backgrounds and speaker
-	notes are kept.
+	ODF states appearance the same way PresentationML does: almost never on
+	the element itself. A paragraph names a style, that style names a parent,
+	the parent lives in styles.xml, and a frame with presentation:class="title"
+	takes its position and its typography from the matching placeholder on the
+	master page. Reading only what a shape spells out - which is what the
+	first version of this reader did - gives every text box the same 24px
+	default and drops the deck's whole design.
+
+	So the reader resolves, lowest priority first:
+
+	    styles.xml   office:styles       the named style and its parents
+	    styles.xml   automatic-styles    the master page's own styles
+	    content.xml  automatic-styles    the per-document generated styles
+	    the paragraph's style, then the span's
+
+	and draws each page on top of its master page's decoration, the way an
+	ODF viewer does.
 */
 
 import (
 	"encoding/base64"
 	"errors"
 	"fmt"
+	"math"
+	"strconv"
 	"strings"
 )
 
+// odpStyle is a resolved ODF style: the graphic, paragraph and text
+// properties that matter to the editor, folded down the parent chain
+type odpStyle struct {
+	// text
+	SizePt    float64
+	Font      string
+	Bold      bool
+	Italic    bool
+	Underline bool
+	Strike    bool
+	Color     string
+	Highlight string
+	// paragraph
+	Align      string
+	LineHeight float64 // unitless
+	SpaceTop   float64 // px
+	SpaceBot   float64 // px
+	MarginLeft float64 // px
+	Indent     float64 // px
+	// graphic
+	Fill      string // "" unset, "none", or "#rrggbb"
+	Stroke    string
+	StrokeW   float64
+	Dash      bool
+	VAlign    string // top | middle | bottom
+	PadT      float64
+	PadR      float64
+	PadB      float64
+	PadL      float64
+	HasPad    bool
+	AutoGrow  bool
+	Rotation  float64
+	ArrowEnd  bool
+	ArrowHead bool
+}
+
+var odpDefaultStyle = odpStyle{SizePt: 18, Align: "left", Color: "#000000"}
+
 // ParseOdp converts raw .odp bytes into a Presentation
 func ParseOdp(data []byte) (*Presentation, error) {
 	files, mime, err := readOdfZip(data)
@@ -40,65 +92,68 @@ func ParseOdp(data []byte) (*Presentation, error) {
 		return nil, errors.New("content.xml has no document-content root")
 	}
 
-	// source page size -> scale into the 960x540 editor space
-	scaleX, scaleY := 1.0, 1.0
+	cv := &odpConverter{
+		files:  files,
+		sx:     1,
+		sy:     1,
+		styles: map[string]*onode{},
+		lists:  map[string]*onode{},
+		pageBg: map[string]string{},
+	}
+
+	var stylesRoot *onode
 	if raw, ok := files["styles.xml"]; ok {
 		if st, err := parseOdfXML(raw); err == nil {
-			if pp := st.path("document-styles", "automatic-styles", "page-layout", "page-layout-properties"); pp != nil {
+			stylesRoot = st.first("document-styles")
+		}
+	}
+	if stylesRoot != nil {
+		// source page size -> scale into the 960x540 editor space
+		for _, auto := range []*onode{stylesRoot.first("automatic-styles")} {
+			if auto == nil {
+				continue
+			}
+			for _, pl := range auto.all("page-layout") {
+				pp := pl.first("page-layout-properties")
+				if pp == nil {
+					continue
+				}
 				if wPx := odfLenToPx(pp.attr("page-width")); wPx > 0 {
-					scaleX = float64(slidePxW) / wPx
+					cv.sx = float64(slidePxW) / wPx
 				}
 				if hPx := odfLenToPx(pp.attr("page-height")); hPx > 0 {
-					scaleY = float64(slidePxH) / hPx
+					cv.sy = float64(slidePxH) / hPx
 				}
 			}
 		}
-	}
-
-	pageBg := map[string]string{}
-	shapeStyle := map[string]*onode{}
-	if auto := root.first("automatic-styles"); auto != nil {
-		for _, st := range auto.all("style") {
-			name := st.attr("name")
-			if name == "" {
-				continue
-			}
-			switch st.attr("family") {
-			case "drawing-page":
-				if dp := st.first("drawing-page-properties"); dp != nil {
-					if c := dp.attr("fill-color"); strings.HasPrefix(c, "#") {
-						pageBg[name] = strings.ToLower(c)
-					}
-				}
-			case "graphic", "presentation":
-				shapeStyle[name] = st
+		cv.collectStyles(stylesRoot.first("styles"))
+		cv.collectStyles(stylesRoot.first("automatic-styles"))
+		if ms := stylesRoot.first("master-styles"); ms != nil {
+			cv.masters = map[string]*onode{}
+			for _, mp := range ms.all("master-page") {
+				cv.masters[mp.attr("name")] = mp
 			}
 		}
 	}
+	cv.collectStyles(root.first("automatic-styles"))
 
 	pres := root.path("body", "presentation")
 	if pres == nil {
 		return nil, errors.New("odp has no presentation body")
 	}
 	out := &Presentation{Size: []int{slidePxW, slidePxH}, Slides: []*Slide{}}
-	cv := &odpConverter{files: files, sx: scaleX, sy: scaleY, shapeStyle: shapeStyle}
 	for pi, page := range pres.all("page") {
 		slide := &Slide{ID: fmt.Sprintf("s-odp-%d", pi+1), Objects: []*Object{}}
-		if bg, ok := pageBg[page.attr("style-name")]; ok {
-			slide.Bg = bg
+		master := cv.masterOf(page)
+		slide.Bg = cv.backgroundOf(page, master)
+		cv.master = master
+		// the master page's own drawing sits underneath the slide's
+		if master != nil {
+			cv.walkPage(master, slide, true)
 		}
+		cv.walkPage(page, slide, false)
 		for _, c := range page.children {
-			if c.el == nil {
-				continue
-			}
-			switch c.el.name {
-			case "frame":
-				cv.frame(c.el, slide)
-			case "rect", "ellipse", "custom-shape":
-				cv.shape(c.el, slide)
-			case "line":
-				cv.line(c.el, slide)
-			case "notes":
+			if c.el != nil && c.el.name == "notes" {
 				slide.Notes = strings.TrimSpace(c.el.allText())
 			}
 		}
@@ -111,15 +166,324 @@ func ParseOdp(data []byte) (*Presentation, error) {
 }
 
 type odpConverter struct {
-	files      map[string][]byte
-	sx, sy     float64
-	shapeStyle map[string]*onode
-	seq        int
+	files   map[string][]byte
+	sx, sy  float64
+	styles  map[string]*onode
+	lists   map[string]*onode
+	masters map[string]*onode
+	master  *onode
+	pageBg  map[string]string
+	seq     int
+}
+
+// collectStyles indexes every style:style and text:list-style in a container
+func (cv *odpConverter) collectStyles(container *onode) {
+	if container == nil {
+		return
+	}
+	for _, st := range container.all("style") {
+		if n := st.attr("name"); n != "" {
+			cv.styles[n] = st
+		}
+	}
+	for _, st := range container.all("list-style") {
+		if n := st.attr("name"); n != "" {
+			cv.lists[n] = st
+		}
+	}
+	for _, st := range container.all("default-style") {
+		if f := st.attr("family"); f != "" {
+			cv.styles["#default-"+f] = st
+		}
+	}
+	for _, dp := range container.all("style") {
+		if dp.attr("family") != "drawing-page" {
+			continue
+		}
+		if props := dp.first("drawing-page-properties"); props != nil {
+			if c := props.attr("fill-color"); strings.HasPrefix(c, "#") {
+				cv.pageBg[dp.attr("name")] = strings.ToLower(c)
+			}
+		}
+	}
+}
+
+func (cv *odpConverter) masterOf(page *onode) *onode {
+	if cv.masters == nil {
+		return nil
+	}
+	return cv.masters[page.attr("master-page-name")]
+}
+
+// backgroundOf resolves a page's fill, falling back to its master's
+func (cv *odpConverter) backgroundOf(page, master *onode) string {
+	if bg, ok := cv.pageBg[page.attr("style-name")]; ok {
+		return bg
+	}
+	if master != nil {
+		if bg, ok := cv.pageBg[master.attr("style-name")]; ok {
+			return bg
+		}
+		if bg, ok := cv.pageBg[master.attr("page-layout-name")]; ok {
+			return bg
+		}
+	}
+	return ""
+}
+
+// walkPage draws every shape on a page. When masterOnly is set the
+// placeholders are skipped: on a master page they are prototypes that
+// state where a slide's title and body go, not content of their own.
+func (cv *odpConverter) walkPage(page *onode, slide *Slide, masterOnly bool) {
+	for _, c := range page.children {
+		if c.el == nil {
+			continue
+		}
+		if masterOnly && c.el.attr("class") != "" {
+			continue
+		}
+		cv.drawShape(c.el, slide, 0, 0, 1, 1)
+	}
 }
 
-func (cv *odpConverter) geom(n *onode) (x, y, w, h float64) {
-	return odfLenToPx(n.attr("x")) * cv.sx, odfLenToPx(n.attr("y")) * cv.sy,
-		odfLenToPx(n.attr("width")) * cv.sx, odfLenToPx(n.attr("height")) * cv.sy
+// drawShape converts one drawing element, recursing into groups. ox/oy and
+// kx/ky carry the transform a draw:g imposes on its children.
+func (cv *odpConverter) drawShape(n *onode, slide *Slide, ox, oy, kx, ky float64) {
+	switch n.name {
+	case "frame":
+		cv.frame(n, slide, ox, oy, kx, ky)
+	case "rect", "ellipse", "circle", "custom-shape", "polygon", "regular-polygon":
+		cv.shape(n, slide, ox, oy, kx, ky)
+	case "line", "connector":
+		cv.line(n, slide, ox, oy, kx, ky)
+	case "g":
+		// a group has no transform of its own in ODF - its children carry
+		// absolute coordinates - so it is simply flattened
+		for _, c := range n.children {
+			if c.el != nil {
+				cv.drawShape(c.el, slide, ox, oy, kx, ky)
+			}
+		}
+	}
+}
+
+/* ---------------- style resolution ---------------- */
+
+// resolveStyle folds a style and its parent chain into one odpStyle
+func (cv *odpConverter) resolveStyle(name string, base odpStyle) odpStyle {
+	if name == "" {
+		return base
+	}
+	// walk to the root of the parent chain first, then apply downwards so
+	// the most specific style wins
+	var chain []*onode
+	seen := map[string]bool{}
+	for cur := name; cur != "" && !seen[cur]; {
+		seen[cur] = true
+		st, ok := cv.styles[cur]
+		if !ok {
+			break
+		}
+		chain = append([]*onode{st}, chain...)
+		cur = st.attr("parent-style-name")
+	}
+	out := base
+	for _, st := range chain {
+		cv.applyStyleNode(&out, st)
+	}
+	return out
+}
+
+// applyStyleNode folds one style:style element's properties into dst
+func (cv *odpConverter) applyStyleNode(dst *odpStyle, st *onode) {
+	if tp := st.first("text-properties"); tp != nil {
+		applyOdfTextProps(dst, tp)
+	}
+	if pp := st.first("paragraph-properties"); pp != nil {
+		cv.applyOdfParaProps(dst, pp)
+	}
+	if gp := st.first("graphic-properties"); gp != nil {
+		cv.applyOdfGraphicProps(dst, gp)
+	}
+}
+
+func applyOdfTextProps(dst *odpStyle, tp *onode) {
+	if v := tp.attr("font-size"); v != "" {
+		if pt := odfFontSizePt(v, dst.SizePt); pt > 0 {
+			dst.SizePt = pt
+		}
+	}
+	if v := tp.attr("font-name"); v != "" {
+		dst.Font = v
+	}
+	if v := tp.attr("font-family"); v != "" {
+		dst.Font = strings.Trim(v, "'\"")
+	}
+	if v := tp.attr("font-weight"); v != "" {
+		dst.Bold = v == "bold" || parseNum(v) >= 600
+	}
+	if v := tp.attr("font-style"); v != "" {
+		dst.Italic = v == "italic" || v == "oblique"
+	}
+	if v := tp.attr("text-underline-style"); v != "" {
+		dst.Underline = v != "none"
+	}
+	if v := tp.attr("text-line-through-style"); v != "" {
+		dst.Strike = v != "none"
+	}
+	if v := tp.attr("color"); strings.HasPrefix(v, "#") {
+		dst.Color = strings.ToLower(v)
+	}
+	if v := tp.attr("background-color"); strings.HasPrefix(v, "#") {
+		dst.Highlight = strings.ToLower(v)
+	}
+}
+
+func (cv *odpConverter) applyOdfParaProps(dst *odpStyle, pp *onode) {
+	switch pp.attr("text-align") {
+	case "center":
+		dst.Align = "center"
+	case "end", "right":
+		dst.Align = "right"
+	case "justify":
+		dst.Align = "justify"
+	case "start", "left":
+		dst.Align = "left"
+	}
+	if v := pp.attr("line-height"); v != "" {
+		if strings.HasSuffix(v, "%") {
+			dst.LineHeight = parseNum(v) / 100 * pptxLineHeightFactor
+		} else if px := odfLenToPx(v); px > 0 && dst.SizePt > 0 {
+			dst.LineHeight = px / ptToPx(dst.SizePt)
+		}
+	}
+	if v := pp.attr("margin-top"); v != "" {
+		dst.SpaceTop = odfLenToPx(v) * cv.sy
+	}
+	if v := pp.attr("margin-bottom"); v != "" {
+		dst.SpaceBot = odfLenToPx(v) * cv.sy
+	}
+	if v := pp.attr("margin-left"); v != "" {
+		dst.MarginLeft = odfLenToPx(v) * cv.sx
+	}
+	if v := pp.attr("text-indent"); v != "" {
+		dst.Indent = odfLenToPx(v) * cv.sx
+	}
+}
+
+func (cv *odpConverter) applyOdfGraphicProps(dst *odpStyle, gp *onode) {
+	switch gp.attr("fill") {
+	case "none":
+		dst.Fill = "none"
+	case "solid", "bitmap", "gradient", "hatch":
+		if c := gp.attr("fill-color"); strings.HasPrefix(c, "#") {
+			dst.Fill = strings.ToLower(c)
+		}
+	default:
+		if c := gp.attr("fill-color"); strings.HasPrefix(c, "#") {
+			dst.Fill = strings.ToLower(c)
+		}
+	}
+	switch gp.attr("stroke") {
+	case "none":
+		dst.Stroke = "none"
+		dst.StrokeW = 0
+	case "dash":
+		dst.Dash = true
+		fallthrough
+	case "solid":
+		if c := gp.attr("stroke-color"); strings.HasPrefix(c, "#") {
+			dst.Stroke = strings.ToLower(c)
+		} else if dst.Stroke == "" || dst.Stroke == "none" {
+			dst.Stroke = "#000000"
+		}
+		if w := odfLenToPx(gp.attr("stroke-width")) * cv.sx; w > 0 {
+			dst.StrokeW = w
+		} else if dst.StrokeW <= 0 {
+			dst.StrokeW = 1
+		}
+	}
+	switch gp.attr("textarea-vertical-align") {
+	case "middle":
+		dst.VAlign = "middle"
+	case "bottom":
+		dst.VAlign = "bottom"
+	case "top":
+		dst.VAlign = "top"
+	}
+	for attr, field := range map[string]*float64{
+		"padding-top": &dst.PadT, "padding-right": &dst.PadR,
+		"padding-bottom": &dst.PadB, "padding-left": &dst.PadL,
+	} {
+		if v := gp.attr(attr); v != "" {
+			*field = odfLenToPx(v) * cv.sx
+			dst.HasPad = true
+		}
+	}
+	if v := gp.attr("padding"); v != "" {
+		p := odfLenToPx(v) * cv.sx
+		dst.PadT, dst.PadR, dst.PadB, dst.PadL = p, p, p, p
+		dst.HasPad = true
+	}
+	if v := gp.attr("marker-end"); v != "" && v != "none" {
+		dst.ArrowEnd = true
+	}
+	if v := gp.attr("marker-start"); v != "" && v != "none" {
+		dst.ArrowHead = true
+	}
+}
+
+// odfFontSizePt reads a font size, which may be relative ("120%")
+func odfFontSizePt(v string, current float64) float64 {
+	if strings.HasSuffix(v, "%") {
+		return current * parseNum(v) / 100
+	}
+	if strings.HasSuffix(v, "pt") {
+		return parseNum(v)
+	}
+	if px := odfLenToPx(v); px > 0 {
+		return px * 0.75
+	}
+	return 0
+}
+
+/* ---------------- geometry ---------------- */
+
+func (cv *odpConverter) geom(n *onode, ox, oy, kx, ky float64) (x, y, w, h float64) {
+	x = ox + odfLenToPx(n.attr("x"))*cv.sx*kx
+	y = oy + odfLenToPx(n.attr("y"))*cv.sy*ky
+	w = odfLenToPx(n.attr("width")) * cv.sx * kx
+	h = odfLenToPx(n.attr("height")) * cv.sy * ky
+	return x, y, w, h
+}
+
+// odfRotation reads the rotation out of a draw:transform attribute, in
+// degrees clockwise (ODF states radians counter-clockwise)
+func odfRotation(n *onode) (deg float64, tx, ty float64) {
+	t := n.attr("transform")
+	if t == "" {
+		return 0, 0, 0
+	}
+	if i := strings.Index(t, "rotate"); i >= 0 {
+		if open := strings.Index(t[i:], "("); open >= 0 {
+			rest := t[i+open+1:]
+			if close := strings.Index(rest, ")"); close >= 0 {
+				deg = -parseNum(strings.TrimSpace(rest[:close])) * 180 / math.Pi
+			}
+		}
+	}
+	if i := strings.Index(t, "translate"); i >= 0 {
+		if open := strings.Index(t[i:], "("); open >= 0 {
+			rest := t[i+open+1:]
+			if close := strings.Index(rest, ")"); close >= 0 {
+				parts := strings.Fields(strings.TrimSpace(rest[:close]))
+				if len(parts) == 2 {
+					tx, ty = odfLenToPx(parts[0]), odfLenToPx(parts[1])
+				}
+			}
+		}
+	}
+	return deg, tx, ty
 }
 
 func (cv *odpConverter) nextID() string {
@@ -127,132 +491,561 @@ func (cv *odpConverter) nextID() string {
 	return fmt.Sprintf("o-odp-%d", cv.seq)
 }
 
-func (cv *odpConverter) frame(n *onode, slide *Slide) {
-	x, y, w, h := cv.geom(n)
+func (cv *odpConverter) add(slide *Slide, o *Object) {
+	o.ID = cv.nextID()
+	o.Z = len(slide.Objects) + 1
+	slide.Objects = append(slide.Objects, o)
+}
+
+// styleOf resolves the drawing style of a shape, including the
+// presentation style a placeholder inherits
+func (cv *odpConverter) styleOf(n *onode) odpStyle {
+	st := odpDefaultStyle
+	st = cv.resolveStyle("#default-graphic", st)
+	if ps := n.attr("class"); ps != "" && cv.master != nil {
+		// a placeholder takes the master's matching frame's style
+		if mf := cv.masterFrame(ps); mf != nil {
+			st = cv.resolveStyle(mf.attr("style-name"), st)
+			st = cv.resolveStyle(mf.attr("text-style-name"), st)
+		}
+	}
+	st = cv.resolveStyle(n.attr("style-name"), st)
+	st = cv.resolveStyle(n.attr("text-style-name"), st)
+	return st
+}
+
+// masterFrame finds the placeholder frame of a given class on the master
+func (cv *odpConverter) masterFrame(class string) *onode {
+	if cv.master == nil {
+		return nil
+	}
+	for _, c := range cv.master.children {
+		if c.el != nil && c.el.name == "frame" && c.el.attr("class") == class {
+			return c.el
+		}
+	}
+	return nil
+}
+
+/* ---------------- shapes ---------------- */
+
+func (cv *odpConverter) frame(n *onode, slide *Slide, ox, oy, kx, ky float64) {
+	x, y, w, h := cv.geom(n, ox, oy, kx, ky)
+	if (w <= 0 || h <= 0) && n.attr("class") != "" {
+		// a placeholder with no geometry of its own takes the master's
+		if mf := cv.masterFrame(n.attr("class")); mf != nil {
+			x, y, w, h = cv.geom(mf, ox, oy, kx, ky)
+		}
+	}
 	if w <= 0 || h <= 0 {
-		w, h = 200, 100
+		return
 	}
+	rot, _, _ := odfRotation(n)
+	st := cv.styleOf(n)
+
 	if img := n.first("image"); img != nil {
-		raw, ok := cv.files[strings.TrimPrefix(img.attr("href"), "./")]
+		href := strings.TrimPrefix(img.attr("href"), "./")
+		raw, ok := cv.files[href]
 		if !ok {
 			return
 		}
-		ext := strings.TrimPrefix(strings.ToLower(pathExtOf(img.attr("href"))), ".")
+		ext := strings.TrimPrefix(strings.ToLower(pathExtOf(href)), ".")
 		if ext == "jpg" {
 			ext = "jpeg"
 		}
 		if ext != "png" && ext != "jpeg" && ext != "gif" {
 			return
 		}
-		slide.Objects = append(slide.Objects, &Object{
-			ID: cv.nextID(), Type: "image", X: x, Y: y, W: w, H: h,
-			Z: len(slide.Objects) + 1,
-			Props: Props{Src: "data:image/" + ext + ";base64," +
-				base64.StdEncoding.EncodeToString(raw), Fit: "contain"},
-		})
+		props := Props{Src: "data:image/" + ext + ";base64," +
+			base64.StdEncoding.EncodeToString(raw), Fit: "fill"}
+		if c := odfClipFractions(n.attr("clip")); c != nil {
+			props.Crop = c
+		}
+		cv.add(slide, &Object{Type: "image", X: x, Y: y, W: w, H: h, Rot: rot, Props: props})
 		return
 	}
 	if tbl := n.first("table"); tbl != nil {
-		cv.table(tbl, slide, x, y, w, h)
+		cv.table(tbl, slide, x, y, w, h, st)
 		return
 	}
 	if tb := n.first("text-box"); tb != nil {
-		var lines []string
-		for _, p := range tb.all("p") {
-			lines = append(lines, p.allText())
-		}
-		if len(lines) == 0 {
+		res := cv.buildText(tb, st)
+		if res.HTML == "" {
 			return
 		}
-		slide.Objects = append(slide.Objects, &Object{
-			ID: cv.nextID(), Type: "text", X: x, Y: y, W: w, H: h,
-			Z:     len(slide.Objects) + 1,
-			Props: Props{HTML: linesToHTML(lines), FontSize: 24, Align: "left"},
-		})
+		cv.add(slide, &Object{Type: "text", X: x, Y: y, W: w, H: h, Rot: rot,
+			Props: cv.textProps(res, st)})
 	}
 }
 
-func (cv *odpConverter) styleFill(n *onode) (fill, stroke string, strokeW float64) {
-	st, ok := cv.shapeStyle[n.attr("style-name")]
-	if !ok {
-		return "", "", 0
+// textProps assembles the editor properties of a text body
+func (cv *odpConverter) textProps(res odpText, st odpStyle) Props {
+	p := Props{
+		HTML: res.HTML, FontSize: round2(ptToPx(res.First.SizePt)),
+		Color: res.First.Color, Align: res.First.Align,
+		Bold: res.First.Bold, Italic: res.First.Italic,
+		Underline:  res.First.Underline,
+		FontFamily: fontStackFor(res.First.Font, res.First.Font),
+		VAlign:     st.VAlign,
+		LineHeight: round2(odpLineHeight(res.First)),
 	}
-	gp := st.first("graphic-properties")
-	if gp == nil {
-		return "", "", 0
+	if p.VAlign == "" {
+		p.VAlign = "top"
 	}
-	if c := gp.attr("fill-color"); strings.HasPrefix(c, "#") {
-		fill = strings.ToLower(c)
+	if st.HasPad {
+		p.Pad = []float64{round2(st.PadT), round2(st.PadR), round2(st.PadB), round2(st.PadL)}
 	}
-	if c := gp.attr("stroke-color"); strings.HasPrefix(c, "#") {
-		stroke = strings.ToLower(c)
+	return p
+}
+
+func odpLineHeight(st odpStyle) float64 {
+	if st.LineHeight > 0 {
+		return st.LineHeight
 	}
-	strokeW = odfLenToPx(gp.attr("stroke-width"))
-	return fill, stroke, strokeW
+	return pptxLineHeightFactor
 }
 
-func (cv *odpConverter) shape(n *onode, slide *Slide) {
-	x, y, w, h := cv.geom(n)
+func (cv *odpConverter) shape(n *onode, slide *Slide, ox, oy, kx, ky float64) {
+	x, y, w, h := cv.geom(n, ox, oy, kx, ky)
 	if w <= 0 || h <= 0 {
 		return
 	}
+	rot, _, _ := odfRotation(n)
+	st := cv.styleOf(n)
 	kind := "rect"
-	if n.name == "ellipse" {
+	switch n.name {
+	case "ellipse", "circle":
 		kind = "ellipse"
-	} else if n.attr("corner-radius") != "" {
-		kind = "round"
+	case "polygon", "regular-polygon":
+		kind = "diamond"
+	case "custom-shape":
+		kind = odpCustomShapeKind(n)
+	default:
+		if n.attr("corner-radius") != "" {
+			kind = "round"
+		}
 	}
-	fill, stroke, sw := cv.styleFill(n)
+	fill := st.Fill
 	if fill == "" {
 		fill = "#e07b1f"
 	}
-	slide.Objects = append(slide.Objects, &Object{
-		ID: cv.nextID(), Type: "shape", X: x, Y: y, W: w, H: h,
-		Z: len(slide.Objects) + 1,
-		Props: Props{Kind: kind, Fill: fill, Stroke: stroke, StrokeW: sw,
-			Text: strings.TrimSpace(n.allText())},
-	})
+	stroke := st.Stroke
+	if stroke == "none" {
+		stroke = ""
+	}
+	res := cv.buildText(n, st)
+	props := Props{Kind: kind, Fill: fill, Stroke: stroke, StrokeW: round2(st.StrokeW),
+		Dash: st.Dash, HTML: res.HTML, Text: res.Plain,
+		TextColor: res.First.Color, FontSize: round2(ptToPx(res.First.SizePt)),
+		FontFamily: fontStackFor(res.First.Font, res.First.Font),
+		Bold:       res.First.Bold, Italic: res.First.Italic,
+		Align: res.First.Align, VAlign: st.VAlign,
+		LineHeight: round2(odpLineHeight(res.First)),
+	}
+	if props.VAlign == "" {
+		props.VAlign = "middle"
+	}
+	if st.HasPad {
+		props.Pad = []float64{round2(st.PadT), round2(st.PadR), round2(st.PadB), round2(st.PadL)}
+	}
+	if r := odfLenToPx(n.attr("corner-radius")) * cv.sx; r > 0 {
+		props.Radius = round2(r)
+	}
+	cv.add(slide, &Object{Type: "shape", X: x, Y: y, W: w, H: h, Rot: rot, Props: props})
+}
+
+// odpCustomShapeKind maps a draw:custom-shape's enhanced geometry type
+func odpCustomShapeKind(n *onode) string {
+	eg := n.first("enhanced-geometry")
+	if eg == nil {
+		return "rect"
+	}
+	switch eg.attr("type") {
+	case "ellipse", "circle":
+		return "ellipse"
+	case "round-rectangle", "rounded-rectangle":
+		return "round"
+	case "isosceles-triangle", "triangle":
+		return "triangle"
+	case "right-triangle":
+		return "rtTriangle"
+	case "diamond":
+		return "diamond"
+	case "right-arrow":
+		return "arrow"
+	case "left-arrow":
+		return "leftArrow"
+	case "up-arrow":
+		return "upArrow"
+	case "down-arrow":
+		return "downArrow"
+	case "star5", "star":
+		return "star"
+	case "pentagon", "pentagon-right":
+		return "chevron"
+	case "hexagon":
+		return "hexagon"
+	case "parallelogram":
+		return "parallelogram"
+	case "trapezoid":
+		return "trapezoid"
+	case "cross":
+		return "plus"
+	}
+	return "rect"
 }
 
-func (cv *odpConverter) line(n *onode, slide *Slide) {
-	x1 := odfLenToPx(n.attr("x1")) * cv.sx
-	y1 := odfLenToPx(n.attr("y1")) * cv.sy
-	x2 := odfLenToPx(n.attr("x2")) * cv.sx
-	y2 := odfLenToPx(n.attr("y2")) * cv.sy
-	_, stroke, sw := cv.styleFill(n)
-	if stroke == "" {
+func (cv *odpConverter) line(n *onode, slide *Slide, ox, oy, kx, ky float64) {
+	x1 := ox + odfLenToPx(n.attr("x1"))*cv.sx*kx
+	y1 := oy + odfLenToPx(n.attr("y1"))*cv.sy*ky
+	x2 := ox + odfLenToPx(n.attr("x2"))*cv.sx*kx
+	y2 := oy + odfLenToPx(n.attr("y2"))*cv.sy*ky
+	st := cv.styleOf(n)
+	stroke := st.Stroke
+	if stroke == "" || stroke == "none" {
 		stroke = "#333333"
 	}
+	sw := st.StrokeW
 	if sw <= 0 {
 		sw = 2
 	}
-	slide.Objects = append(slide.Objects, &Object{
-		ID: cv.nextID(), Type: "line", X: x1, Y: y1, W: x2 - x1, H: y2 - y1,
-		Z:     len(slide.Objects) + 1,
-		Props: Props{Stroke: stroke, StrokeW: sw},
-	})
+	cv.add(slide, &Object{Type: "line", X: x1, Y: y1, W: x2 - x1, H: y2 - y1,
+		Props: Props{Stroke: stroke, StrokeW: round2(sw), Dash: st.Dash,
+			ArrowEnd: st.ArrowEnd, ArrowStart: st.ArrowHead}})
 }
 
-func (cv *odpConverter) table(tbl *onode, slide *Slide, x, y, w, h float64) {
+func (cv *odpConverter) table(tbl *onode, slide *Slide, x, y, w, h float64, st odpStyle) {
 	var rows [][]string
+	var fills [][]string
+	// relative column widths, so a table keeps its proportions
+	var colW []float64
+	var colSum float64
+	for _, col := range tbl.all("table-column") {
+		cw := 0.0
+		if cs, ok := cv.styles[col.attr("style-name")]; ok {
+			if tp := cs.first("table-column-properties"); tp != nil {
+				cw = odfLenToPx(tp.attr("column-width"))
+			}
+		}
+		colW = append(colW, cw)
+		colSum += cw
+	}
+	if colSum <= 0 {
+		colW = nil
+	} else {
+		for i := range colW {
+			colW[i] = round2(colW[i] / colSum * 100)
+		}
+	}
+
 	for _, tr := range tbl.all("table-row") {
-		var row []string
+		var row, rowFills []string
 		for _, c := range tr.children {
 			if c.el == nil || c.el.name != "table-cell" {
 				continue
 			}
-			row = append(row, xmlEscape(strings.TrimSpace(c.el.allText())))
+			cellStyle := cv.resolveStyle(c.el.attr("style-name"), st)
+			fill := ""
+			if cs, ok := cv.styles[c.el.attr("style-name")]; ok {
+				if tp := cs.first("table-cell-properties"); tp != nil {
+					if v := tp.attr("background-color"); strings.HasPrefix(v, "#") {
+						fill = strings.ToLower(v)
+					}
+				}
+			}
+			res := cv.buildText(c.el, cellStyle)
+			row = append(row, res.HTML)
+			rowFills = append(rowFills, fill)
+			// a spanned cell occupies the columns it covers
+			for i := 1; i < int(atofDefault(c.el.attr("number-columns-spanned"), 1)); i++ {
+				row = append(row, "")
+				rowFills = append(rowFills, fill)
+			}
 		}
 		if len(row) > 0 {
 			rows = append(rows, row)
+			fills = append(fills, rowFills)
 		}
 	}
 	if len(rows) == 0 {
 		return
 	}
-	slide.Objects = append(slide.Objects, &Object{
-		ID: cv.nextID(), Type: "table", X: x, Y: y, W: w, H: h,
-		Z:     len(slide.Objects) + 1,
-		Props: Props{Rows: rows, FontSize: 16},
+	if !anyFilled(fills) {
+		fills = nil
+	}
+	cv.add(slide, &Object{Type: "table", X: x, Y: y, W: w, H: h,
+		Props: Props{Rows: rows, FontSize: round2(ptToPx(st.SizePt)),
+			ColW: colW, CellFill: fills}})
+}
+
+/* ---------------- text ---------------- */
+
+// odpText is the rendered HTML of a text body plus its first run's style
+type odpText struct {
+	HTML  string
+	Plain string
+	First odpStyle
+}
+
+// buildText renders every paragraph and list under a container into the
+// editor's storage HTML, resolving each paragraph's and span's styles
+func (cv *odpConverter) buildText(container *onode, base odpStyle) odpText {
+	out := odpText{First: base}
+	var sb strings.Builder
+	var plain []string
+	first := true
+	counters := map[int]int{}
+
+	var walk func(n *onode, depth int, listStyle string)
+	walk = func(n *onode, depth int, listStyle string) {
+		for _, c := range n.children {
+			if c.el == nil {
+				continue
+			}
+			switch c.el.name {
+			case "p", "h":
+				ps := cv.resolveStyle(c.el.attr("style-name"), base)
+				bullet := ""
+				if depth > 0 {
+					bullet, counters = odpListMarker(cv.lists[listStyle], depth, counters)
+				}
+				html, text, firstRun := cv.paragraphHTML(c.el, ps, bullet, depth)
+				if first && strings.TrimSpace(text) != "" {
+					out.First = firstRun
+					first = false
+				}
+				sb.WriteString(html)
+				plain = append(plain, text)
+			case "list":
+				ls := c.el.attr("style-name")
+				if ls == "" {
+					ls = listStyle
+				}
+				if depth == 0 {
+					counters = map[int]int{}
+				}
+				for _, item := range c.el.all("list-item") {
+					walk(item, depth+1, ls)
+				}
+			case "text-box":
+				walk(c.el, depth, listStyle)
+			}
+		}
+	}
+	walk(container, 0, "")
+
+	out.HTML = sb.String()
+	out.Plain = strings.Join(plain, "\n")
+	if strings.TrimSpace(out.Plain) == "" {
+		out.HTML = ""
+	}
+	return out
+}
+
+// paragraphHTML renders one text:p / text:h into a storage-HTML block
+func (cv *odpConverter) paragraphHTML(p *onode, ps odpStyle, bullet string, depth int) (string, string, odpStyle) {
+	var runs strings.Builder
+	var text strings.Builder
+	firstRun := ps
+	haveRun := false
+	minSize := 0.0
+
+	var emit func(n *onode, st odpStyle)
+	emit = func(n *onode, st odpStyle) {
+		for _, c := range n.children {
+			if c.el == nil {
+				if c.text == "" {
+					continue
+				}
+				if !haveRun {
+					firstRun = st
+					haveRun = true
+				}
+				if minSize == 0 || st.SizePt < minSize {
+					minSize = st.SizePt
+				}
+				runs.WriteString(`<span style="` + odpRunCSS(st) + `">` +
+					xmlEscape(c.text) + `</span>`)
+				text.WriteString(c.text)
+				continue
+			}
+			switch c.el.name {
+			case "span":
+				emit(c.el, cv.resolveStyle(c.el.attr("style-name"), st))
+			case "a":
+				emit(c.el, st)
+			case "line-break":
+				runs.WriteString("<br>")
+				text.WriteString("\n")
+			case "tab":
+				runs.WriteString(`<span style="` + odpRunCSS(st) + `">&#9;</span>`)
+				text.WriteString("\t")
+			case "s":
+				n := int(atofDefault(c.el.attr("c"), 1))
+				runs.WriteString(strings.Repeat(" ", n))
+				text.WriteString(strings.Repeat(" ", n))
+			default:
+				emit(c.el, st)
+			}
+		}
+	}
+	emit(p, ps)
+	if minSize <= 0 {
+		minSize = ps.SizePt
+	}
+
+	var css strings.Builder
+	css.WriteString("text-align:" + ps.Align + ";")
+	css.WriteString("line-height:" + strconv.FormatFloat(round2(odpLineHeight(ps)), 'f', -1, 64) + ";")
+	css.WriteString("font-size:" + fmtPx(ptToPx(minSize)) + ";")
+	if ps.SpaceTop > 0 {
+		css.WriteString("margin-top:" + fmtPx(ps.SpaceTop) + ";")
+	}
+	if ps.SpaceBot > 0 {
+		css.WriteString("margin-bottom:" + fmtPx(ps.SpaceBot) + ";")
+	}
+	marL := ps.MarginLeft
+	if depth > 0 && marL == 0 {
+		marL = float64(depth) * 24
+	}
+	if marL != 0 {
+		css.WriteString("padding-left:" + fmtPx(marL) + ";")
+	}
+	body := runs.String()
+	marker := ""
+	if bullet != "" {
+		indent := ps.Indent
+		if indent == 0 {
+			indent = -18
+		}
+		css.WriteString("position:relative;")
+		bs := firstRun
+		bs.Underline, bs.Strike, bs.Highlight = false, false, ""
+		marker = `<span style="position:absolute;left:` + fmtPx(marL+indent) + `;` +
+			odpRunCSS(bs) + `">` + xmlEscape(bullet) + `</span>`
+	} else if ps.Indent != 0 {
+		css.WriteString("text-indent:" + fmtPx(ps.Indent) + ";")
+	}
+	if body == "" {
+		body = `<span style="font-size:` + fmtPx(ptToPx(minSize)) + `">&#8203;</span>`
+	}
+	return `<div style="` + css.String() + `">` + marker + body + `</div>`,
+		text.String(), firstRun
+}
+
+// odpRunCSS renders the inline style of one text run
+func odpRunCSS(st odpStyle) string {
+	var sb strings.Builder
+	sb.WriteString("font-size:" + fmtPx(ptToPx(st.SizePt)) + ";")
+	if st.Font != "" {
+		sb.WriteString("font-family:" + fontStackFor(st.Font, st.Font) + ";")
+	}
+	weight := 0
+	if st.Bold {
+		weight = 700
+	} else if w := fontWeightOf(st.Font); w != 0 {
+		weight = w
+	}
+	if weight != 0 {
+		sb.WriteString("font-weight:" + strconv.Itoa(weight) + ";")
+	}
+	if st.Italic {
+		sb.WriteString("font-style:italic;")
+	}
+	deco := ""
+	if st.Underline {
+		deco = "underline"
+	}
+	if st.Strike {
+		if deco != "" {
+			deco += " "
+		}
+		deco += "line-through"
+	}
+	if deco != "" {
+		sb.WriteString("text-decoration:" + deco + ";")
+	}
+	if st.Color != "" {
+		sb.WriteString("color:" + st.Color + ";")
+	}
+	if st.Highlight != "" {
+		sb.WriteString("background-color:" + st.Highlight + ";")
+	}
+	return sb.String()
+}
+
+// odpListMarker renders the marker of a list level, advancing the counter
+// of a numbered list
+func odpListMarker(listStyle *onode, depth int, counters map[int]int) (string, map[int]int) {
+	bullet := "•"
+	if listStyle != nil {
+		for _, lvl := range listStyle.children {
+			if lvl.el == nil {
+				continue
+			}
+			if int(atofDefault(lvl.el.attr("level"), 0)) != depth {
+				continue
+			}
+			switch lvl.el.name {
+			case "list-level-style-bullet":
+				if c := lvl.el.attr("bullet-char"); c != "" {
+					bullet = c
+				}
+			case "list-level-style-number":
+				counters[depth]++
+				return numberedMarker(lvl.el, counters[depth]), counters
+			}
+		}
+	}
+	return bullet, counters
+}
+
+func numberedMarker(lvl *onode, n int) string {
+	format := lvl.attr("num-format")
+	prefix := lvl.attr("num-prefix")
+	suffix := lvl.attr("num-suffix")
+	if suffix == "" {
+		suffix = "."
+	}
+	var body string
+	switch format {
+	case "a":
+		body = alphaMarker(n, 'a')
+	case "A":
+		body = alphaMarker(n, 'A')
+	case "i":
+		body = strings.ToLower(romanMarker(n))
+	case "I":
+		body = romanMarker(n)
+	default:
+		body = strconv.Itoa(n)
+	}
+	return prefix + body + suffix
+}
+
+// odfClipFractions turns an fo:clip rect into the editor's crop fractions.
+// ODF states the clip as inset lengths, which is only convertible into
+// fractions when the frame states them as percentages.
+func odfClipFractions(clip string) []float64 {
+	clip = strings.TrimSpace(clip)
+	if !strings.HasPrefix(clip, "rect(") || !strings.HasSuffix(clip, ")") {
+		return nil
+	}
+	parts := strings.FieldsFunc(clip[5:len(clip)-1], func(r rune) bool {
+		return r == ',' || r == ' '
 	})
+	if len(parts) != 4 {
+		return nil
+	}
+	out := make([]float64, 4)
+	// fo:clip lists top, right, bottom, left; the editor wants l,t,r,b
+	order := []int{3, 0, 1, 2}
+	for i, src := range order {
+		v := strings.TrimSpace(parts[src])
+		if !strings.HasSuffix(v, "%") {
+			return nil
+		}
+		out[i] = round4(parseNum(v) / 100)
+	}
+	return out
 }

+ 255 - 19
src/mod/office/odp_writer.go

@@ -151,50 +151,253 @@ func (b *odpBuilder) textStyleFor(o *Object, p *Presentation) string {
 	return b.newStyle("paragraph", align+`<style:text-properties`+props+`/>`)
 }
 
+// emitText writes a text object as a draw:frame, one text:p per paragraph
+// and one text:span per run, so the per-run typography an imported deck
+// carries survives a save into .odp instead of flattening to plain lines
 func (b *odpBuilder) emitText(body *strings.Builder, o *Object, p *Presentation) {
-	ps := b.textStyleFor(o, p)
-	body.WriteString(`<draw:frame` + odpGeom(o) + `><draw:text-box>`)
-	for _, ln := range htmlToLines(o.Props.HTML) {
-		body.WriteString(`<text:p text:style-name="` + ps + `">` + xmlEscape(ln) + `</text:p>`)
-	}
+	body.WriteString(`<draw:frame draw:style-name="` + b.frameStyleFor(o) + `"` +
+		odpGeom(o) + `><draw:text-box>`)
+	b.emitParagraphs(body, o, p)
 	body.WriteString(`</draw:text-box></draw:frame>`)
 }
 
+// emitParagraphs renders the object's rich HTML into ODF paragraphs
+func (b *odpBuilder) emitParagraphs(body *strings.Builder, o *Object, p *Presentation) {
+	base := inlineStyle{
+		sizePx: o.Props.FontSize,
+		font:   firstFontFamily(o.Props.FontFamily),
+		bold:   o.Props.Bold, italic: o.Props.Italic, underline: o.Props.Underline,
+		color: o.Props.Color,
+	}
+	if base.color == "" {
+		base.color = o.Props.TextColor
+	}
+	if base.color == "" {
+		if c, ok := themeText[p.Theme]; ok {
+			base.color = "#" + c
+		}
+	}
+	if base.sizePx <= 0 {
+		base.sizePx = 24
+	}
+	for _, para := range parseStorageHTML(o.Props.HTML, base) {
+		align := para.Align
+		if align == "" {
+			align = o.Props.Align
+		}
+		ps := b.paraStyleFor(align, para, o.Props.LineHeight)
+		body.WriteString(`<text:p text:style-name="` + ps + `">`)
+		if para.Bullet != "" {
+			body.WriteString(xmlEscape(para.Bullet) + " ")
+		}
+		for _, r := range para.Runs {
+			if r.Break {
+				body.WriteString(`<text:line-break/>`)
+				continue
+			}
+			if r.Text == "" {
+				continue
+			}
+			body.WriteString(`<text:span text:style-name="` + b.runStyleFor(r, base) + `">` +
+				xmlEscape(r.Text) + `</text:span>`)
+		}
+		body.WriteString(`</text:p>`)
+	}
+}
+
+// paraStyleFor mints the automatic paragraph style of one paragraph
+func (b *odpBuilder) paraStyleFor(align string, para htmlPara, objLineHeight float64) string {
+	props := ""
+	switch align {
+	case "center":
+		props += ` fo:text-align="center"`
+	case "right":
+		props += ` fo:text-align="end"`
+	case "justify":
+		props += ` fo:text-align="justify"`
+	}
+	lh := para.LineHeight
+	if lh <= 0 {
+		lh = objLineHeight
+	}
+	if lh > 0 {
+		props += fmt.Sprintf(` fo:line-height="%d%%"`, int(lh/pptxLineHeightFactor*100))
+	}
+	if para.MarginTop > 0 {
+		props += ` fo:margin-top="` + pxToCm(para.MarginTop) + `"`
+	}
+	if para.MarginBot > 0 {
+		props += ` fo:margin-bottom="` + pxToCm(para.MarginBot) + `"`
+	}
+	if para.PadLeft != 0 {
+		props += ` fo:margin-left="` + pxToCm(para.PadLeft) + `"`
+	}
+	if para.Indent != 0 {
+		// a bulleted paragraph writes its marker inline, so the negative
+		// first-line indent is what puts the marker in the hanging position
+		props += ` fo:text-indent="` + pxToCm(para.Indent) + `"`
+	}
+	return b.newStyle("paragraph", `<style:paragraph-properties`+props+`/>`)
+}
+
+// runStyleFor mints the automatic text style of one run
+func (b *odpBuilder) runStyleFor(r htmlRun, base inlineStyle) string {
+	size := r.SizePx
+	if size <= 0 {
+		size = base.sizePx
+	}
+	props := fmt.Sprintf(` fo:font-size="%.1fpt"`, size*72.0/96.0)
+	if r.Bold {
+		props += ` fo:font-weight="bold"`
+	}
+	if r.Italic {
+		props += ` fo:font-style="italic"`
+	}
+	if r.Underline {
+		props += ` style:text-underline-style="solid"`
+	}
+	if r.Strike {
+		props += ` style:text-line-through-style="solid"`
+	}
+	color := r.Color
+	if color == "" {
+		color = base.color
+	}
+	if strings.HasPrefix(color, "#") {
+		props += ` fo:color="` + color + `"`
+	}
+	if strings.HasPrefix(r.Highlight, "#") {
+		props += ` fo:background-color="` + r.Highlight + `"`
+	}
+	font := r.Font
+	if font == "" {
+		font = base.font
+	}
+	if font != "" {
+		props += ` style:font-name="` + xmlEscape(font) + `"`
+	}
+	return b.newStyle("text", `<style:text-properties`+props+`/>`)
+}
+
+// frameStyleFor carries a text object's vertical anchor and insets
+func (b *odpBuilder) frameStyleFor(o *Object) string {
+	props := ` draw:fill="none" draw:stroke="none"`
+	switch o.Props.VAlign {
+	case "middle":
+		props += ` draw:textarea-vertical-align="middle"`
+	case "bottom":
+		props += ` draw:textarea-vertical-align="bottom"`
+	default:
+		props += ` draw:textarea-vertical-align="top"`
+	}
+	if len(o.Props.Pad) == 4 {
+		props += ` fo:padding-top="` + pxToCm(o.Props.Pad[0]) + `"` +
+			` fo:padding-right="` + pxToCm(o.Props.Pad[1]) + `"` +
+			` fo:padding-bottom="` + pxToCm(o.Props.Pad[2]) + `"` +
+			` fo:padding-left="` + pxToCm(o.Props.Pad[3]) + `"`
+	}
+	return b.newStyle("graphic", `<style:graphic-properties`+props+`/>`)
+}
+
 func (b *odpBuilder) emitImage(body *strings.Builder, o *Object, src string) {
 	pic := odfPicture(src, &b.media)
 	if pic == "" {
 		return
 	}
-	body.WriteString(`<draw:frame` + odpGeom(o) + `>` +
+	clip := ""
+	if len(o.Props.Crop) == 4 {
+		// fo:clip lists the insets top, right, bottom, left
+		clip = fmt.Sprintf(` fo:clip="rect(%.2f%% %.2f%% %.2f%% %.2f%%)"`,
+			o.Props.Crop[1]*100, o.Props.Crop[2]*100,
+			o.Props.Crop[3]*100, o.Props.Crop[0]*100)
+	}
+	body.WriteString(`<draw:frame` + odpGeom(o) + clip + `>` +
 		`<draw:image xlink:href="` + pic + `" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>` +
 		`</draw:frame>`)
 }
 
+// odpShapeTypes maps the editor's shape kinds onto ODF enhanced-geometry
+// types, for everything a plain draw:rect / draw:ellipse cannot express
+var odpShapeTypes = map[string]string{
+	"triangle":      "isosceles-triangle",
+	"rtTriangle":    "right-triangle",
+	"diamond":       "diamond",
+	"arrow":         "right-arrow",
+	"leftArrow":     "left-arrow",
+	"upArrow":       "up-arrow",
+	"downArrow":     "down-arrow",
+	"star":          "star5",
+	"chevron":       "pentagon-right",
+	"pentagon":      "pentagon-right",
+	"hexagon":       "hexagon",
+	"parallelogram": "parallelogram",
+	"trapezoid":     "trapezoid",
+	"plus":          "cross",
+}
+
 func (b *odpBuilder) emitShape(body *strings.Builder, o *Object) {
 	props := ""
+	// the fill is always stated: leaving it out lets a reader apply the
+	// format's own default, which is not what the object says
 	if strings.HasPrefix(o.Props.Fill, "#") {
 		props += ` draw:fill="solid" draw:fill-color="` + o.Props.Fill + `"`
+	} else {
+		props += ` draw:fill="none"`
 	}
 	if strings.HasPrefix(o.Props.Stroke, "#") && o.Props.StrokeW > 0 {
-		props += fmt.Sprintf(` draw:stroke="solid" svg:stroke-color="%s" svg:stroke-width="%s"`,
-			o.Props.Stroke, pxToCm(o.Props.StrokeW))
+		dash := "solid"
+		if o.Props.Dash {
+			dash = "dash"
+		}
+		props += fmt.Sprintf(` draw:stroke="%s" svg:stroke-color="%s" svg:stroke-width="%s"`,
+			dash, o.Props.Stroke, pxToCm(o.Props.StrokeW))
 	} else {
 		props += ` draw:stroke="none"`
 	}
+	switch o.Props.VAlign {
+	case "top":
+		props += ` draw:textarea-vertical-align="top"`
+	case "bottom":
+		props += ` draw:textarea-vertical-align="bottom"`
+	default:
+		props += ` draw:textarea-vertical-align="middle"`
+	}
+	if len(o.Props.Pad) == 4 {
+		props += ` fo:padding-top="` + pxToCm(o.Props.Pad[0]) + `"` +
+			` fo:padding-right="` + pxToCm(o.Props.Pad[1]) + `"` +
+			` fo:padding-bottom="` + pxToCm(o.Props.Pad[2]) + `"` +
+			` fo:padding-left="` + pxToCm(o.Props.Pad[3]) + `"`
+	}
 	gs := b.newStyle("graphic", `<style:graphic-properties`+props+`/>`)
+
 	tag := "draw:rect"
 	extra := ""
+	geomType := ""
 	switch o.Props.Kind {
 	case "ellipse":
 		tag = "draw:ellipse"
 	case "round":
-		extra = ` draw:corner-radius="0.3cm"`
+		r := o.Props.Radius
+		if r <= 0 {
+			r = minF(o.W, o.H) * 0.15
+		}
+		extra = ` draw:corner-radius="` + pxToCm(r) + `"`
+	default:
+		if t, ok := odpShapeTypes[o.Props.Kind]; ok {
+			tag = "draw:custom-shape"
+			geomType = t
+		}
 	}
 	body.WriteString(`<` + tag + ` draw:style-name="` + gs + `"` + odpGeom(o) + extra + `>`)
-	if strings.TrimSpace(o.Props.Text) != "" {
+	if o.Props.HTML != "" {
+		b.emitParagraphs(body, o, &Presentation{})
+	} else if strings.TrimSpace(o.Props.Text) != "" {
 		body.WriteString(`<text:p>` + xmlEscape(o.Props.Text) + `</text:p>`)
 	}
-	body.WriteString(`</` + strings.Split(tag, " ")[0] + `>`)
+	if geomType != "" {
+		body.WriteString(`<draw:enhanced-geometry draw:type="` + geomType + `"/>`)
+	}
+	body.WriteString(`</` + tag + `>`)
 }
 
 func (b *odpBuilder) emitLine(body *strings.Builder, o *Object) {
@@ -233,20 +436,53 @@ func (b *odpBuilder) emitTable(body *strings.Builder, o *Object) {
 			`<style:table-column-properties style:column-width="`+pxToCm(o.W*pct/100)+`"/>`)
 		body.WriteString(`<table:table-column table:style-name="` + cs + `"/>`)
 	}
+	fs := o.Props.FontSize
+	if fs <= 0 {
+		fs = 16
+	}
 	for ri, row := range rows {
-		body.WriteString(`<table:table-row>`)
+		rs := ""
+		if ri < len(o.Props.RowH) && o.Props.RowH[ri] > 0 {
+			rs = ` table:style-name="` + b.newStyle("table-row",
+				`<style:table-row-properties style:row-height="`+
+					pxToCm(o.H*o.Props.RowH[ri]/100)+`"/>`) + `"`
+		}
+		body.WriteString(`<table:table-row` + rs + `>`)
 		for ci := 0; ci < cols; ci++ {
 			cell := ""
 			if ci < len(row) {
-				cell = strings.Join(htmlToLines(row[ci]), " ")
+				cell = row[ci]
+			}
+			base := inlineStyle{
+				sizePx: fs, color: o.Props.Color,
+				bold: o.Props.HeaderRow && ri == 0,
+			}
+			cellStyle := ""
+			if ri < len(o.Props.CellFill) && ci < len(o.Props.CellFill[ri]) &&
+				strings.HasPrefix(o.Props.CellFill[ri][ci], "#") {
+				cellStyle = ` table:style-name="` + b.newStyle("table-cell",
+					`<style:table-cell-properties fo:background-color="`+
+						o.Props.CellFill[ri][ci]+`"/>`) + `"`
 			}
-			bold := o.Props.HeaderRow && ri == 0
-			inner := xmlEscape(cell)
-			if bold && inner != "" {
-				ts := b.newStyle("text", `<style:text-properties fo:font-weight="bold"/>`)
-				inner = `<text:span text:style-name="` + ts + `">` + inner + `</text:span>`
+			body.WriteString(`<table:table-cell` + cellStyle + `>`)
+			// cells hold the same rich HTML text objects do
+			for _, para := range parseStorageHTML(cell, base) {
+				body.WriteString(`<text:p text:style-name="` +
+					b.paraStyleFor(para.Align, para, 0) + `">`)
+				for _, r := range para.Runs {
+					if r.Break {
+						body.WriteString(`<text:line-break/>`)
+						continue
+					}
+					if r.Text == "" {
+						continue
+					}
+					body.WriteString(`<text:span text:style-name="` +
+						b.runStyleFor(r, base) + `">` + xmlEscape(r.Text) + `</text:span>`)
+				}
+				body.WriteString(`</text:p>`)
 			}
-			body.WriteString(`<table:table-cell><text:p>` + inner + `</text:p></table:table-cell>`)
+			body.WriteString(`</table:table-cell>`)
 		}
 		body.WriteString(`</table:table-row>`)
 	}

+ 53 - 4
src/mod/office/office.go

@@ -43,6 +43,26 @@ type Presentation struct {
 	Size   []int    `json:"size,omitempty"`
 	Theme  string   `json:"theme,omitempty"`
 	Slides []*Slide `json:"slides"`
+	// font faces the source file carried with it, so the deck renders in
+	// the typeface it was designed in even where that font is not
+	// installed. Empty for documents authored in the editor.
+	Fonts []*EmbeddedFont `json:"fonts,omitempty"`
+}
+
+// EmbeddedFont is one @font-face the Slides editor installs for a document
+type EmbeddedFont struct {
+	Family string `json:"family"`
+	Weight int    `json:"weight,omitempty"` // 400 or 700
+	Style  string `json:"style,omitempty"`  // "" or "italic"
+	Src    string `json:"src"`              // data URL
+}
+
+// Rect is a plain rectangle in slide units
+type Rect struct {
+	X float64 `json:"x"`
+	Y float64 `json:"y"`
+	W float64 `json:"w"`
+	H float64 `json:"h"`
 }
 
 // Slide is a single slide
@@ -77,9 +97,25 @@ type Props struct {
 	Bold      bool    `json:"bold,omitempty"`
 	Italic    bool    `json:"italic,omitempty"`
 	Underline bool    `json:"underline,omitempty"`
+	// text layout - set by the pptx/odp readers so an imported deck keeps
+	// the typography of the file it came from. All are optional: a text
+	// object without them renders on the editor's own defaults.
+	FontFamily string    `json:"fontFamily,omitempty"` // CSS font stack
+	VAlign     string    `json:"valign,omitempty"`     // top | middle | bottom
+	Pad        []float64 `json:"pad,omitempty"`        // insets [t,r,b,l] px
+	LineHeight float64   `json:"lineHeight,omitempty"` // unitless multiplier
 	// image
-	Src string `json:"src,omitempty"`
-	Fit string `json:"fit,omitempty"`
+	Src     string    `json:"src,omitempty"`
+	Fit     string    `json:"fit,omitempty"`
+	Crop    []float64 `json:"crop,omitempty"`    // [left,top,right,bottom] fractions
+	Radius  float64   `json:"radius,omitempty"`  // corner radius, px
+	Opacity float64   `json:"opacity,omitempty"` // 0..1, 0 = fully opaque
+	// a shaped crop: the picture is clipped to one of the shape kinds
+	// below ("" or "rect" = a plain rectangle)
+	Mask string `json:"mask,omitempty"`
+	// the frame the whole picture filled before it was first cropped, so
+	// Reset image can put it back. Editor state - no format stores it.
+	Orig *Rect `json:"orig,omitempty"`
 	// shape
 	Kind      string  `json:"kind,omitempty"`
 	Fill      string  `json:"fill,omitempty"`
@@ -88,13 +124,22 @@ type Props struct {
 	Text      string  `json:"text,omitempty"`
 	TextColor string  `json:"textColor,omitempty"`
 	// line
-	Dash     bool `json:"dash,omitempty"`
-	ArrowEnd bool `json:"arrowEnd,omitempty"`
+	Dash       bool `json:"dash,omitempty"`
+	ArrowEnd   bool `json:"arrowEnd,omitempty"`
+	ArrowStart bool `json:"arrowStart,omitempty"`
+	// elbow / rotated connectors imported from pptx: the polyline the
+	// connector actually follows, relative to the object's x/y. Absent on
+	// a plain two-point line, which is the only kind the editor draws.
+	Points [][]float64 `json:"points,omitempty"`
 	// table
 	Rows      [][]string `json:"rows,omitempty"`
 	HeaderRow bool       `json:"headerRow,omitempty"`
 	ColW      []float64  `json:"colW,omitempty"` // column widths, percent
 	RowH      []float64  `json:"rowH,omitempty"` // row heights, percent
+	// per-cell background colours ("" = none) and the cell insets, both
+	// set by the pptx reader so an imported table keeps its shading
+	CellFill [][]string `json:"cellFill,omitempty"`
+	CellPad  []float64  `json:"cellPad,omitempty"` // [t,r,b,l] px
 	// chart (spec kept opaque; Png is a client-side raster for export)
 	Spec json.RawMessage `json:"spec,omitempty"`
 	Png  string          `json:"png,omitempty"`
@@ -250,6 +295,10 @@ func htmlToLines(h string) []string {
 	s = blockOpenRe.ReplaceAllString(s, "")
 	s = tagRe.ReplaceAllString(s, "")
 	s = strings.ReplaceAll(s, "&nbsp;", " ")
+	// zero-width spaces are line-height padding the readers insert, not text
+	s = strings.ReplaceAll(s, "&#8203;", "")
+	s = strings.ReplaceAll(s, "&#x200b;", "")
+	s = strings.ReplaceAll(s, "​", "")
 	s = strings.ReplaceAll(s, "&lt;", "<")
 	s = strings.ReplaceAll(s, "&gt;", ">")
 	s = strings.ReplaceAll(s, "&quot;", "\"")

+ 25 - 3
src/mod/office/office_test.go

@@ -197,9 +197,14 @@ func TestPptxRoundtrip(t *testing.T) {
 			if len(o.Props.Rows) != 2 || len(o.Props.Rows[0]) != 2 {
 				t.Fatalf("table dims = %dx%d, want 2x2", len(o.Props.Rows), len(o.Props.Rows[0]))
 			}
-			if o.Props.Rows[0][0] != "h1" || o.Props.Rows[1][1] != "b" {
+			// cells come back as the editor's rich HTML - compare the
+			// text they render, not the markup around it
+			if cellText(o.Props.Rows[0][0]) != "h1" || cellText(o.Props.Rows[1][1]) != "b" {
 				t.Errorf("table content lost: %v", o.Props.Rows)
 			}
+			if !strings.Contains(o.Props.Rows[0][0], "font-weight:700") {
+				t.Errorf("header row bold lost: %q", o.Props.Rows[0][0])
+			}
 			if !o.Props.HeaderRow {
 				t.Errorf("headerRow flag lost")
 			}
@@ -239,9 +244,26 @@ func TestTableCellHtmlFlatten(t *testing.T) {
 		t.Fatalf("ParsePptx failed: %v", err)
 	}
 	cell := got.Slides[0].Objects[0].Props.Rows[0][0]
-	if cell != "x&amp;y<br>z" {
-		t.Errorf("cell after roundtrip = %q, want %q", cell, "x&amp;y<br>z")
+	if cellText(cell) != "x&y\nz" {
+		t.Errorf("cell text after roundtrip = %q, want %q", cellText(cell), "x&y\nz")
+	}
+	if !strings.Contains(cell, "font-weight:700") {
+		t.Errorf("cell bold run lost in roundtrip: %q", cell)
+	}
+}
+
+// cellText renders a table cell's storage HTML down to the text it shows,
+// so tests can assert on content without pinning the exact markup
+func cellText(html string) string {
+	lines := htmlToLines(html)
+	out := make([]string, 0, len(lines))
+	for _, l := range lines {
+		l = strings.TrimSpace(strings.ReplaceAll(l, "&#8203;", ""))
+		if l != "" {
+			out = append(out, l)
+		}
 	}
+	return strings.Join(out, "\n")
 }
 
 func TestParsePresentationJSON(t *testing.T) {

+ 29 - 3
src/mod/office/pdf_slides.go

@@ -106,9 +106,35 @@ func slidePdfText(pdf *fpdf.Fpdf, tr func(string) string, o *Object, theme strin
 	}
 	pdf.SetFont("Arial", pdfStyleStr(p.Bold, p.Italic, p.Underline), sizePt)
 	pdfSetTextHex(pdf, color, 32, 33, 36)
-	lineH := fs * 1.3 * pxToMM
-	pdf.SetXY(x, y)
-	pdf.MultiCell(w, lineH, tr(strings.Join(htmlToLines(p.HTML), "\n")), "", align, false)
+	// an imported deck states its own line height and text insets; a
+	// document made in the editor falls back to the editor's own metrics
+	lh := p.LineHeight
+	if lh <= 0 {
+		lh = 1.3
+	}
+	lineH := fs * lh * pxToMM
+	padT, padL, padR := 0.0, 0.0, 0.0
+	if len(p.Pad) == 4 {
+		padT, padR, padL = p.Pad[0]*pxToMM, p.Pad[1]*pxToMM, p.Pad[3]*pxToMM
+	}
+	lines := htmlToLines(p.HTML)
+	inner := w - padL - padR
+	if inner < 1 {
+		inner = 1
+	}
+	top := y + padT
+	if p.VAlign == "middle" || p.VAlign == "bottom" {
+		free := o.H*pxToMM - padT - float64(len(lines))*lineH
+		if free > 0 {
+			if p.VAlign == "middle" {
+				top += free / 2
+			} else {
+				top += free
+			}
+		}
+	}
+	pdf.SetXY(x+padL, top)
+	pdf.MultiCell(inner, lineH, tr(strings.Join(lines, "\n")), "", align, false)
 }
 
 func slidePdfShape(pdf *fpdf.Fpdf, tr func(string) string, o *Object, x, y, w, h float64) {

+ 205 - 0
src/mod/office/pptx_chart.go

@@ -0,0 +1,205 @@
+package office
+
+/*
+	pptx_chart.go - read a DrawingML chart part into the Slides editor's
+	chart object.
+
+	A chart on a slide is a graphicFrame pointing at a ppt/charts/chartN.xml
+	part, which carries both a reference to the spreadsheet the numbers came
+	from and a *cache* of the values as they were last drawn. The cache is
+	what makes this possible without opening the embedded workbook: it holds
+	the category labels and every series' numbers, which is exactly the shape
+	OfficeCharts renders from.
+
+	Only the chart kinds the editor can draw are read (bar/column, line,
+	area, pie, doughnut); anything else - scatter, radar, surface, stock,
+	3-D variants with no flat equivalent - is left alone, and its frame is
+	skipped rather than drawn as something it is not.
+*/
+
+import (
+	"encoding/json"
+	"strconv"
+	"strings"
+)
+
+// chartSpec mirrors the spec OfficeCharts (common/charts.js) renders
+type chartSpec struct {
+	Type    string           `json:"type"`
+	Title   string           `json:"title,omitempty"`
+	Labels  []string         `json:"labels"`
+	Series  []chartSeries    `json:"series"`
+	Options chartSpecOptions `json:"options"`
+}
+
+type chartSeries struct {
+	Name   string    `json:"name,omitempty"`
+	Values []float64 `json:"values"`
+	Color  string    `json:"color,omitempty"`
+}
+
+type chartSpecOptions struct {
+	Legend    bool `json:"legend"`
+	Gridlines bool `json:"gridlines"`
+	Stacked   bool `json:"stacked,omitempty"`
+}
+
+// pptxChartKinds maps the plot element name onto an editor chart type
+var pptxChartKinds = []struct{ node, kind string }{
+	{"barChart", "bar"}, {"bar3DChart", "bar"},
+	{"lineChart", "line"}, {"line3DChart", "line"},
+	{"areaChart", "line"}, {"area3DChart", "line"},
+	{"pieChart", "pie"}, {"pie3DChart", "pie"},
+	{"doughnutChart", "pie"}, {"ofPieChart", "pie"},
+}
+
+// parseChartSpec turns a chartSpace tree into the editor's chart spec.
+// Returns nil when the chart is of a kind the editor cannot draw or has
+// no cached values to draw.
+func (sc *slideCtx) parseChartSpec(tree *xnode) *chartSpec {
+	chart := tree.first("chart")
+	if chart == nil {
+		return nil
+	}
+	plotArea := chart.first("plotArea")
+	if plotArea == nil {
+		return nil
+	}
+	var plot *xnode
+	kind := ""
+	for _, cand := range pptxChartKinds {
+		if n := plotArea.first(cand.node); n != nil {
+			plot, kind = n, cand.kind
+			break
+		}
+	}
+	if plot == nil {
+		return nil
+	}
+
+	spec := &chartSpec{Type: kind, Labels: []string{}, Series: []chartSeries{}}
+	if t := chart.first("title"); t != nil && chart.first("autoTitleDeleted").attr("val") != "1" {
+		var texts []string
+		collectText(t, &texts)
+		spec.Title = strings.TrimSpace(strings.Join(texts, ""))
+	}
+	if g := plot.first("grouping"); g != nil {
+		v := g.attr("val")
+		spec.Options.Stacked = v == "stacked" || v == "percentStacked"
+	}
+	spec.Options.Legend = chart.first("legend") != nil
+	for _, ax := range plotArea.all("valAx") {
+		if ax.first("majorGridlines") != nil {
+			spec.Options.Gridlines = true
+		}
+	}
+
+	for _, ser := range plot.all("ser") {
+		values := cachedNumbers(ser.first("val"))
+		if len(values) == 0 {
+			continue
+		}
+		s := chartSeries{Values: values}
+		if names := cachedStrings(ser.first("tx")); len(names) > 0 {
+			s.Name = names[0]
+		}
+		if c := sc.cc.solidColorOf(ser.first("spPr")); c != "" {
+			s.Color = c
+		}
+		if len(spec.Labels) == 0 {
+			spec.Labels = cachedStrings(ser.first("cat"))
+		}
+		spec.Series = append(spec.Series, s)
+	}
+	if len(spec.Series) == 0 {
+		return nil
+	}
+	// a chart with no category cache still needs one label per point
+	if len(spec.Labels) == 0 {
+		for i := range spec.Series[0].Values {
+			spec.Labels = append(spec.Labels, strconv.Itoa(i+1))
+		}
+	}
+	return spec
+}
+
+// cachedPoints reads the <c:pt> cache under a chart reference, in index
+// order, filling gaps so a sparse cache does not shift the series
+func cachedPoints(holder *xnode) []string {
+	if holder == nil {
+		return nil
+	}
+	var cache *xnode
+	for _, ref := range []string{"strRef", "numRef", "multiLvlStrRef"} {
+		if r := holder.first(ref); r != nil {
+			for _, cn := range []string{"strCache", "numCache", "lvl"} {
+				if c := r.first(cn); c != nil {
+					cache = c
+					break
+				}
+			}
+		}
+		if cache != nil {
+			break
+		}
+	}
+	if cache == nil {
+		// literal values, written when the chart has no source range
+		for _, lit := range []string{"strLit", "numLit"} {
+			if c := holder.first(lit); c != nil {
+				cache = c
+				break
+			}
+		}
+	}
+	if cache == nil {
+		return nil
+	}
+	count := int(atofDefault(cache.first("ptCount").attr("val"), 0))
+	pts := cache.all("pt")
+	if count <= 0 {
+		count = len(pts)
+	}
+	if count <= 0 {
+		return nil
+	}
+	out := make([]string, count)
+	for _, pt := range pts {
+		idx := int(atofDefault(pt.attr("idx"), -1))
+		if idx < 0 || idx >= count {
+			continue
+		}
+		if v := pt.first("v"); v != nil {
+			out[idx] = v.Text
+		}
+	}
+	return out
+}
+
+func cachedStrings(holder *xnode) []string {
+	return cachedPoints(holder)
+}
+
+func cachedNumbers(holder *xnode) []float64 {
+	raw := cachedPoints(holder)
+	if len(raw) == 0 {
+		return nil
+	}
+	out := make([]float64, len(raw))
+	for i, s := range raw {
+		out[i] = atofDefault(strings.TrimSpace(s), 0)
+	}
+	return out
+}
+
+// chartSpecJSON serializes a spec for Props.Spec
+func chartSpecJSON(spec *chartSpec) json.RawMessage {
+	if spec == nil {
+		return nil
+	}
+	b, err := json.Marshal(spec)
+	if err != nil {
+		return nil
+	}
+	return json.RawMessage(b)
+}

+ 704 - 0
src/mod/office/pptx_fidelity_test.go

@@ -0,0 +1,704 @@
+package office
+
+/*
+	pptx_fidelity_test.go - the parts of PresentationML a deck's appearance
+	actually depends on: theme colours, placeholder inheritance, per-run
+	formatting, bullets, spacing, autofit, groups, crops and connectors.
+
+	Each test builds the smallest package that exercises one rule, so a
+	failure names the rule rather than "the import looks wrong".
+*/
+
+import (
+	"archive/zip"
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"strings"
+	"testing"
+)
+
+/* ---------------- package fixture ---------------- */
+
+// pptxParts is a minimal .pptx: the caller supplies slide bodies and may
+// override the layout, master and theme.
+type pptxParts struct {
+	slides     []string // the inner XML of each <p:cSld><p:spTree>
+	layoutBody string   // extra XML inside the layout's spTree
+	masterBody string   // extra XML inside the master's spTree
+	masterTx   string   // the master's <p:txStyles>
+	extraParts map[string]string
+	slideRels  map[string]string // rId -> Target, added to every slide
+	media      map[string][]byte
+}
+
+const testTheme = `<?xml version="1.0" encoding="UTF-8"?>` +
+	`<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="t">` +
+	`<a:themeElements><a:clrScheme name="c">` +
+	`<a:dk1><a:srgbClr val="1A1A1A"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>` +
+	`<a:dk2><a:srgbClr val="595959"/></a:dk2><a:lt2><a:srgbClr val="EEEEEE"/></a:lt2>` +
+	`<a:accent1><a:srgbClr val="4285F4"/></a:accent1><a:accent2><a:srgbClr val="212121"/></a:accent2>` +
+	`<a:accent3><a:srgbClr val="78909C"/></a:accent3><a:accent4><a:srgbClr val="FFAB40"/></a:accent4>` +
+	`<a:accent5><a:srgbClr val="0097A7"/></a:accent5><a:accent6><a:srgbClr val="EEFF41"/></a:accent6>` +
+	`<a:hlink><a:srgbClr val="0000EE"/></a:hlink><a:folHlink><a:srgbClr val="551A8B"/></a:folHlink>` +
+	`</a:clrScheme><a:fontScheme name="f">` +
+	`<a:majorFont><a:latin typeface="Verdana"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>` +
+	`<a:minorFont><a:latin typeface="Tahoma"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>` +
+	`</a:fontScheme><a:fmtScheme name="s"/></a:themeElements></a:theme>`
+
+const testNS = `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ` +
+	`xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` +
+	`xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"`
+
+func buildTestPptx(t *testing.T, parts pptxParts) []byte {
+	t.Helper()
+	buf := new(bytes.Buffer)
+	zw := zip.NewWriter(buf)
+	add := func(name, content string) {
+		w, err := zw.Create(name)
+		if err != nil {
+			t.Fatalf("zip create %s: %v", name, err)
+		}
+		if _, err := w.Write([]byte(content)); err != nil {
+			t.Fatalf("zip write %s: %v", name, err)
+		}
+	}
+
+	var sldIds, presRels strings.Builder
+	presRels.WriteString(`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>`)
+	for i := range parts.slides {
+		rid := fmt.Sprintf("rId%d", i+2)
+		sldIds.WriteString(fmt.Sprintf(`<p:sldId id="%d" r:id="%s"/>`, 256+i, rid))
+		presRels.WriteString(fmt.Sprintf(
+			`<Relationship Id="%s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide%d.xml"/>`,
+			rid, i+1))
+	}
+	add("ppt/presentation.xml", `<p:presentation `+testNS+`>`+
+		`<p:sldMasterIdLst><p:sldMasterId id="1" r:id="rId1"/></p:sldMasterIdLst>`+
+		`<p:sldIdLst>`+sldIds.String()+`</p:sldIdLst>`+
+		`<p:sldSz cx="9144000" cy="5143500"/></p:presentation>`)
+	add("ppt/_rels/presentation.xml.rels",
+		`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
+			presRels.String()+`</Relationships>`)
+	add("ppt/theme/theme1.xml", testTheme)
+
+	tx := parts.masterTx
+	if tx == "" {
+		tx = `<p:txStyles><p:titleStyle><a:lvl1pPr><a:defRPr sz="4000"/></a:lvl1pPr></p:titleStyle>` +
+			`<p:bodyStyle><a:lvl1pPr><a:defRPr sz="2000"/></a:lvl1pPr>` +
+			`<a:lvl2pPr marL="914400" indent="-228600"><a:defRPr sz="1600"/></a:lvl2pPr></p:bodyStyle>` +
+			`<p:otherStyle><a:lvl1pPr><a:defRPr sz="1400"/></a:lvl1pPr></p:otherStyle></p:txStyles>`
+	}
+	add("ppt/slideMasters/slideMaster1.xml", `<p:sldMaster `+testNS+`><p:cSld><p:spTree>`+
+		parts.masterBody+`</p:spTree></p:cSld>`+
+		`<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" `+
+		`accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" `+
+		`hlink="hlink" folHlink="folHlink"/>`+tx+`</p:sldMaster>`)
+	add("ppt/slideMasters/_rels/slideMaster1.xml.rels",
+		`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
+			`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>`+
+			`</Relationships>`)
+	add("ppt/slideLayouts/slideLayout1.xml", `<p:sldLayout `+testNS+`><p:cSld><p:spTree>`+
+		parts.layoutBody+`</p:spTree></p:cSld></p:sldLayout>`)
+	add("ppt/slideLayouts/_rels/slideLayout1.xml.rels",
+		`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
+			`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>`+
+			`</Relationships>`)
+
+	for i, body := range parts.slides {
+		add(fmt.Sprintf("ppt/slides/slide%d.xml", i+1),
+			`<p:sld `+testNS+`><p:cSld><p:spTree>`+body+`</p:spTree></p:cSld></p:sld>`)
+		rels := `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>`
+		for id, target := range parts.slideRels {
+			rels += fmt.Sprintf(`<Relationship Id="%s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="%s"/>`, id, target)
+		}
+		add(fmt.Sprintf("ppt/slides/_rels/slide%d.xml.rels", i+1),
+			`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
+				rels+`</Relationships>`)
+	}
+	for name, content := range parts.extraParts {
+		add(name, content)
+	}
+	for name, data := range parts.media {
+		w, err := zw.Create(name)
+		if err != nil {
+			t.Fatalf("zip create %s: %v", name, err)
+		}
+		if _, err := w.Write(data); err != nil {
+			t.Fatalf("zip write %s: %v", name, err)
+		}
+	}
+	if err := zw.Close(); err != nil {
+		t.Fatalf("zip close: %v", err)
+	}
+	return buf.Bytes()
+}
+
+// parseOneSlide builds a package from one slide body and returns its objects
+func parseOneSlide(t *testing.T, parts pptxParts) []*Object {
+	t.Helper()
+	data := buildTestPptx(t, parts)
+	pres, err := ParsePptx(data)
+	if err != nil {
+		t.Fatalf("ParsePptx: %v", err)
+	}
+	if len(pres.Slides) != 1 {
+		t.Fatalf("slides = %d, want 1", len(pres.Slides))
+	}
+	return pres.Slides[0].Objects
+}
+
+// textBox is a convenience wrapper for a plain text shape
+func textBox(x, y, cx, cy int, body string) string {
+	return fmt.Sprintf(`<p:sp><p:nvSpPr><p:cNvPr id="2" name="t"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>`+
+		`<p:spPr><a:xfrm><a:off x="%d" y="%d"/><a:ext cx="%d" cy="%d"/></a:xfrm>`+
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>`+
+		`<p:txBody><a:bodyPr/><a:lstStyle/>%s</p:txBody></p:sp>`, x, y, cx, cy, body)
+}
+
+/* ---------------- colours ---------------- */
+
+func TestPptxSchemeColorsResolveThroughClrMap(t *testing.T) {
+	tests := []struct {
+		name string
+		fill string
+		want string
+	}{
+		{"scheme accent", `<a:schemeClr val="accent1"/>`, "#4285f4"},
+		{"mapped text colour", `<a:schemeClr val="tx1"/>`, "#1a1a1a"},
+		{"mapped background", `<a:schemeClr val="bg1"/>`, "#ffffff"},
+		{"literal rgb", `<a:srgbClr val="FF8800"/>`, "#ff8800"},
+		{"preset name", `<a:prstClr val="red"/>`, "#ff0000"},
+		{"luminance modulated", `<a:schemeClr val="accent1"><a:lumMod val="50000"/></a:schemeClr>`, "#093c92"},
+		{"tinted toward white", `<a:srgbClr val="000000"><a:tint val="50000"/></a:srgbClr>`, "#808080"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			objs := parseOneSlide(t, pptxParts{slides: []string{
+				`<p:sp><p:nvSpPr><p:cNvPr id="2" name="s"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
+					`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
+					`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
+					`<a:solidFill>` + tc.fill + `</a:solidFill></p:spPr></p:sp>`,
+			}})
+			if len(objs) != 1 || objs[0].Type != "shape" {
+				t.Fatalf("objects = %+v, want one shape", objs)
+			}
+			if objs[0].Props.Fill != tc.want {
+				t.Errorf("fill = %q, want %q", objs[0].Props.Fill, tc.want)
+			}
+		})
+	}
+}
+
+/* ---------------- placeholder inheritance ---------------- */
+
+func TestPptxPlaceholderInheritsGeometryAndSize(t *testing.T) {
+	layout := `<p:sp><p:nvSpPr><p:cNvPr id="9" name="lt"/><p:cNvSpPr/>` +
+		`<p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="457200" y="228600"/><a:ext cx="4572000" cy="914400"/></a:xfrm></p:spPr>` +
+		`<p:txBody><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="3200">` +
+		`<a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle>` +
+		`<a:p/></p:txBody></p:sp>`
+	slide := `<p:sp><p:nvSpPr><p:cNvPr id="2" name="t"/><p:cNvSpPr txBox="1"/>` +
+		`<p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr><p:spPr/>` +
+		`<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>Title</a:t></a:r></a:p></p:txBody></p:sp>`
+
+	objs := parseOneSlide(t, pptxParts{slides: []string{slide}, layoutBody: layout})
+	if len(objs) != 1 || objs[0].Type != "text" {
+		t.Fatalf("objects = %+v, want one text object", objs)
+	}
+	o := objs[0]
+	// 457200 EMU = 48px, 228600 = 24px at this slide size
+	if o.X != 48 || o.Y != 24 || o.W != 480 || o.H != 96 {
+		t.Errorf("geometry = %v,%v %vx%v, want 48,24 480x96", o.X, o.Y, o.W, o.H)
+	}
+	// 32pt inherited from the layout placeholder = 42.67 css px
+	if o.Props.FontSize < 42 || o.Props.FontSize > 43 {
+		t.Errorf("font size = %v, want ~42.67 (32pt from the layout)", o.Props.FontSize)
+	}
+	if o.Props.Color != "#4285f4" {
+		t.Errorf("colour = %q, want the layout's accent1", o.Props.Color)
+	}
+}
+
+func TestPptxOutlineLevelPicksItsOwnStyle(t *testing.T) {
+	slide := `<p:sp><p:nvSpPr><p:cNvPr id="2" name="b"/><p:cNvSpPr txBox="1"/>` +
+		`<p:nvPr><p:ph idx="1" type="body"/></p:nvPr></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="4572000" cy="2743200"/></a:xfrm></p:spPr>` +
+		`<p:txBody><a:bodyPr/><a:lstStyle/>` +
+		`<a:p><a:pPr lvl="0"/><a:r><a:t>top</a:t></a:r></a:p>` +
+		`<a:p><a:pPr lvl="1"/><a:r><a:t>nested</a:t></a:r></a:p>` +
+		`</p:txBody></p:sp>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{slide}})
+	if len(objs) != 1 {
+		t.Fatalf("objects = %+v, want one", objs)
+	}
+	html := objs[0].Props.HTML
+	// lvl1 is 20pt (26.67px), lvl2 is 16pt (21.33px) from the master's bodyStyle
+	if !strings.Contains(html, "font-size:26.67px") {
+		t.Errorf("level 1 run did not take the 20pt body style: %s", html)
+	}
+	if !strings.Contains(html, "font-size:21.33px") {
+		t.Errorf("level 2 run did not take the 16pt body style: %s", html)
+	}
+	// and the deeper level takes its own indent
+	if !strings.Contains(html, "padding-left:96px") {
+		t.Errorf("level 2 paragraph did not take the 914400 EMU margin: %s", html)
+	}
+}
+
+/* ---------------- runs, breaks, autofit ---------------- */
+
+func TestPptxKeepsPerRunFormatting(t *testing.T) {
+	body := `<a:p><a:r><a:rPr sz="1800" b="1"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>` +
+		`<a:latin typeface="Georgia"/></a:rPr><a:t>red bold</a:t></a:r>` +
+		`<a:r><a:rPr sz="1200" i="1" u="sng"><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill></a:rPr>` +
+		`<a:t>small green</a:t></a:r></a:p>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{textBox(0, 0, 4572000, 914400, body)}})
+	html := objs[0].Props.HTML
+	for _, want := range []string{
+		"font-size:24px", "font-weight:700", "color:#ff0000", "Georgia",
+		"font-size:16px", "font-style:italic", "text-decoration:underline", "color:#00ff00",
+	} {
+		if !strings.Contains(html, want) {
+			t.Errorf("run formatting %q missing from %s", want, html)
+		}
+	}
+}
+
+func TestPptxLineBreakKeepsItsOwnHeight(t *testing.T) {
+	body := `<a:p><a:r><a:rPr sz="1600"/><a:t>one</a:t></a:r>` +
+		`<a:br><a:rPr sz="1600"/></a:br><a:br><a:rPr sz="1600"/></a:br></a:p>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{textBox(0, 0, 4572000, 914400, body)}})
+	html := objs[0].Props.HTML
+	// two breaks must leave two empty lines that still take up their height
+	if strings.Count(html, "<br>") != 2 {
+		t.Errorf("want 2 breaks, got %d: %s", strings.Count(html, "<br>"), html)
+	}
+	if strings.Count(html, "&#8203;") != 2 {
+		t.Errorf("each break needs a sized spacer so the empty line has height: %s", html)
+	}
+}
+
+func TestPptxAutofitScalesFontSizes(t *testing.T) {
+	body := `<a:p><a:r><a:rPr sz="2000"/><a:t>shrunk</a:t></a:r></a:p>`
+	sp := `<p:sp><p:nvSpPr><p:cNvPr id="2" name="t"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="4572000" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>` +
+		`<p:txBody><a:bodyPr><a:normAutofit fontScale="50000"/></a:bodyPr><a:lstStyle/>` + body + `</p:txBody></p:sp>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{sp}})
+	// 20pt = 26.67px, halved by the autofit scale
+	if !strings.Contains(objs[0].Props.HTML, "font-size:13.33px") {
+		t.Errorf("normAutofit fontScale was not applied: %s", objs[0].Props.HTML)
+	}
+}
+
+func TestPptxBodyAnchorAndInsets(t *testing.T) {
+	sp := `<p:sp><p:nvSpPr><p:cNvPr id="2" name="t"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="4572000" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>` +
+		`<p:txBody><a:bodyPr anchor="ctr" lIns="91440" tIns="91440" rIns="0" bIns="0"/><a:lstStyle/>` +
+		`<a:p><a:r><a:t>x</a:t></a:r></a:p></p:txBody></p:sp>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{sp}})
+	p := objs[0].Props
+	if p.VAlign != "middle" {
+		t.Errorf("valign = %q, want middle", p.VAlign)
+	}
+	// 91440 EMU = 9.6px
+	want := []float64{9.6, 0, 0, 9.6}
+	if len(p.Pad) != 4 {
+		t.Fatalf("pad = %v, want 4 values", p.Pad)
+	}
+	for i := range want {
+		if p.Pad[i] != want[i] {
+			t.Errorf("pad[%d] = %v, want %v", i, p.Pad[i], want[i])
+		}
+	}
+}
+
+/* ---------------- bullets ---------------- */
+
+func TestPptxBulletsUseHangingIndent(t *testing.T) {
+	body := `<a:p><a:pPr marL="457200" indent="-228600"><a:buChar char="-"/></a:pPr>` +
+		`<a:r><a:rPr sz="1600"/><a:t>item</a:t></a:r></a:p>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{textBox(0, 0, 4572000, 914400, body)}})
+	html := objs[0].Props.HTML
+	// 457200 EMU = 48px, 457200-228600 = 24px
+	if !strings.Contains(html, "padding-left:48px") {
+		t.Errorf("paragraph margin lost: %s", html)
+	}
+	if !strings.Contains(html, "position:absolute;left:24px") {
+		t.Errorf("bullet is not at the hanging position: %s", html)
+	}
+	if !strings.Contains(html, ">-</span>") {
+		t.Errorf("bullet glyph lost: %s", html)
+	}
+}
+
+func TestPptxAutoNumberedBulletsCount(t *testing.T) {
+	para := func(n string) string {
+		return `<a:p><a:pPr marL="457200" indent="-228600"><a:buAutoNum type="arabicPeriod"/></a:pPr>` +
+			`<a:r><a:t>` + n + `</a:t></a:r></a:p>`
+	}
+	objs := parseOneSlide(t, pptxParts{slides: []string{
+		textBox(0, 0, 4572000, 1828800, para("a")+para("b")+para("c"))}})
+	html := objs[0].Props.HTML
+	for _, want := range []string{">1.</span>", ">2.</span>", ">3.</span>"} {
+		if !strings.Contains(html, want) {
+			t.Errorf("auto number %q missing: %s", want, html)
+		}
+	}
+}
+
+/* ---------------- groups, crops, connectors ---------------- */
+
+func TestPptxGroupTransformsChildren(t *testing.T) {
+	// the group maps a 0..1000000 child space onto 914400..2743200 EMU,
+	// so a child at 500000 lands halfway across the group
+	grp := `<p:grpSp><p:nvGrpSpPr><p:cNvPr id="2" name="g"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>` +
+		`<p:grpSpPr><a:xfrm><a:off x="914400" y="0"/><a:ext cx="1828800" cy="914400"/>` +
+		`<a:chOff x="0" y="0"/><a:chExt cx="1000000" cy="500000"/></a:xfrm></p:grpSpPr>` +
+		`<p:sp><p:nvSpPr><p:cNvPr id="3" name="c"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="500000" y="0"/><a:ext cx="250000" cy="250000"/></a:xfrm>` +
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
+		`<a:solidFill><a:srgbClr val="112233"/></a:solidFill></p:spPr></p:sp></p:grpSp>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{grp}})
+	if len(objs) != 1 {
+		t.Fatalf("objects = %+v, want the group's one child", objs)
+	}
+	o := objs[0]
+	// group origin 914400 EMU = 96px, plus half of the 1828800 EMU (192px) width
+	if o.X != 96+96 {
+		t.Errorf("child x = %v, want 192", o.X)
+	}
+	// the child's 250000 of 1000000 becomes a quarter of the group's width
+	if o.W != 48 {
+		t.Errorf("child w = %v, want 48", o.W)
+	}
+}
+
+func TestPptxPictureCropAndRadius(t *testing.T) {
+	png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("x", 32))
+	pic := `<p:pic><p:nvPicPr><p:cNvPr id="2" name="p"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>` +
+		`<p:blipFill><a:blip r:embed="rId9"/><a:srcRect l="10000" t="20000" r="30000" b="0"/>` +
+		`<a:stretch><a:fillRect/></a:stretch></p:blipFill>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 10000"/></a:avLst></a:prstGeom>` +
+		`</p:spPr></p:pic>`
+	objs := parseOneSlide(t, pptxParts{
+		slides:    []string{pic},
+		slideRels: map[string]string{"rId9": "../media/image1.png"},
+		media:     map[string][]byte{"ppt/media/image1.png": png},
+	})
+	if len(objs) != 1 || objs[0].Type != "image" {
+		t.Fatalf("objects = %+v, want one image", objs)
+	}
+	p := objs[0].Props
+	want := []float64{0.1, 0.2, 0.3, 0}
+	if len(p.Crop) != 4 {
+		t.Fatalf("crop = %v, want 4 fractions", p.Crop)
+	}
+	for i := range want {
+		if p.Crop[i] != want[i] {
+			t.Errorf("crop[%d] = %v, want %v", i, p.Crop[i], want[i])
+		}
+	}
+	// 10% of the shorter side (914400 EMU = 96px)
+	if p.Radius != 9.6 {
+		t.Errorf("radius = %v, want 9.6", p.Radius)
+	}
+	if !strings.HasPrefix(p.Src, "data:image/png;base64,") {
+		t.Errorf("picture was not inlined: %.30s", p.Src)
+	}
+}
+
+func TestPptxPictureMaskRoundTrips(t *testing.T) {
+	// a shaped crop is a preset geometry on the picture; every kind the
+	// editor can draw must survive being written and read back
+	png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("x", 32))
+	for _, kind := range []string{"ellipse", "triangle", "diamond", "star",
+		"chevron", "hexagon", "downArrow", "plus"} {
+		t.Run(kind, func(t *testing.T) {
+			pres := &Presentation{Slides: []*Slide{{Objects: []*Object{{
+				Type: "image", X: 10, Y: 20, W: 200, H: 100, Z: 1,
+				Props: Props{
+					Src:  encodeDataURL(png, "png"),
+					Fit:  "fill",
+					Mask: kind,
+					Crop: []float64{0.1, 0, 0.2, 0},
+				},
+			}}}}}
+			data, err := BuildPptx(pres)
+			if err != nil {
+				t.Fatalf("BuildPptx: %v", err)
+			}
+			got, err := ParsePptx(data)
+			if err != nil {
+				t.Fatalf("ParsePptx: %v", err)
+			}
+			objs := got.Slides[0].Objects
+			if len(objs) != 1 || objs[0].Type != "image" {
+				t.Fatalf("objects = %+v, want one image", objs)
+			}
+			p := objs[0].Props
+			if p.Mask != kind {
+				t.Errorf("mask = %q, want %q", p.Mask, kind)
+			}
+			if len(p.Crop) != 4 || p.Crop[0] != 0.1 || p.Crop[2] != 0.2 {
+				t.Errorf("crop = %v, want [0.1 0 0.2 0]", p.Crop)
+			}
+		})
+	}
+}
+
+func TestPptxRoundPictureKeepsItsRadius(t *testing.T) {
+	png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("x", 32))
+	pres := &Presentation{Slides: []*Slide{{Objects: []*Object{{
+		Type: "image", X: 0, Y: 0, W: 200, H: 100, Z: 1,
+		Props: Props{Src: encodeDataURL(png, "png"), Mask: "round", Radius: 10},
+	}}}}}
+	data, err := BuildPptx(pres)
+	if err != nil {
+		t.Fatalf("BuildPptx: %v", err)
+	}
+	got, err := ParsePptx(data)
+	if err != nil {
+		t.Fatalf("ParsePptx: %v", err)
+	}
+	p := got.Slides[0].Objects[0].Props
+	if p.Mask != "round" {
+		t.Errorf("mask = %q, want round", p.Mask)
+	}
+	// 10px of the 100px short side is a 10% adjust
+	if p.Radius < 9.5 || p.Radius > 10.5 {
+		t.Errorf("radius = %v, want ~10", p.Radius)
+	}
+}
+
+func TestPptxBentConnectorKeepsItsElbow(t *testing.T) {
+	cxn := `<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="2" name="c"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1828800" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="bentConnector3"><a:avLst><a:gd name="adj1" fmla="val 50000"/></a:avLst></a:prstGeom>` +
+		`<a:ln w="12700"><a:solidFill><a:srgbClr val="000000"/></a:solidFill>` +
+		`<a:tailEnd type="triangle"/></a:ln></p:spPr></p:cxnSp>`
+	objs := parseOneSlide(t, pptxParts{slides: []string{cxn}})
+	if len(objs) != 1 || objs[0].Type != "line" {
+		t.Fatalf("objects = %+v, want one line", objs)
+	}
+	pts := objs[0].Props.Points
+	// 1828800 EMU = 192px wide, 914400 = 96px tall; the elbow bends halfway
+	want := [][]float64{{0, 0}, {96, 0}, {96, 96}, {192, 96}}
+	if len(pts) != len(want) {
+		t.Fatalf("points = %v, want %v", pts, want)
+	}
+	for i := range want {
+		if pts[i][0] != want[i][0] || pts[i][1] != want[i][1] {
+			t.Errorf("point %d = %v, want %v", i, pts[i], want[i])
+		}
+	}
+	if !objs[0].Props.ArrowEnd {
+		t.Errorf("connector lost its arrow head")
+	}
+}
+
+func TestPptxLayoutDecorationIsDrawnUnderTheSlide(t *testing.T) {
+	layout := `<p:sp><p:nvSpPr><p:cNvPr id="9" name="deco"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
+		`<a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></p:spPr></p:sp>` +
+		// a placeholder on the layout is a prototype and must NOT be drawn
+		`<p:sp><p:nvSpPr><p:cNvPr id="10" name="ph"/><p:cNvSpPr/>` +
+		`<p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>` +
+		`<p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="914400" cy="914400"/></a:xfrm>` +
+		`<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>` +
+		`<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></p:spPr></p:sp>`
+	objs := parseOneSlide(t, pptxParts{
+		slides:     []string{textBox(0, 0, 914400, 914400, `<a:p><a:r><a:t>hi</a:t></a:r></a:p>`)},
+		layoutBody: layout,
+	})
+	if len(objs) != 2 {
+		t.Fatalf("objects = %d, want the layout's decoration plus the slide's text", len(objs))
+	}
+	if objs[0].Type != "shape" || objs[0].Props.Fill != "#abcdef" {
+		t.Errorf("first object = %+v, want the layout's decoration underneath", objs[0])
+	}
+	if objs[1].Type != "text" {
+		t.Errorf("second object = %+v, want the slide's own text on top", objs[1])
+	}
+}
+
+func TestPptxSlideNumberField(t *testing.T) {
+	body := `<a:p><a:fld id="{1}" type="slidenum"><a:t>&#8249;#&#8250;</a:t></a:fld></a:p>`
+	data := buildTestPptx(t, pptxParts{slides: []string{
+		textBox(0, 0, 914400, 457200, `<a:p><a:r><a:t>one</a:t></a:r></a:p>`),
+		textBox(0, 0, 914400, 457200, body),
+	}})
+	pres, err := ParsePptx(data)
+	if err != nil {
+		t.Fatalf("ParsePptx: %v", err)
+	}
+	html := pres.Slides[1].Objects[0].Props.HTML
+	if !strings.Contains(html, ">2</span>") {
+		t.Errorf("slide number field did not resolve to 2: %s", html)
+	}
+}
+
+/* ---------------- charts ---------------- */
+
+func TestPptxChartFromCachedValues(t *testing.T) {
+	chartXML := `<?xml version="1.0"?><c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ` +
+		`xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart>` +
+		`<c:title><c:tx><c:rich><a:p><a:r><a:t>Sales</a:t></a:r></a:p></c:rich></c:tx></c:title>` +
+		`<c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="stacked"/>` +
+		`<c:ser><c:tx><c:strRef><c:strCache><c:ptCount val="1"/>` +
+		`<c:pt idx="0"><c:v>2025</c:v></c:pt></c:strCache></c:strRef></c:tx>` +
+		`<c:cat><c:strRef><c:strCache><c:ptCount val="2"/>` +
+		`<c:pt idx="0"><c:v>Jan</c:v></c:pt><c:pt idx="1"><c:v>Feb</c:v></c:pt>` +
+		`</c:strCache></c:strRef></c:cat>` +
+		`<c:val><c:numRef><c:numCache><c:ptCount val="2"/>` +
+		`<c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20.5</c:v></c:pt>` +
+		`</c:numCache></c:numRef></c:val></c:ser></c:barChart>` +
+		`<c:valAx><c:majorGridlines/></c:valAx></c:plotArea><c:legend/></c:chart></c:chartSpace>`
+
+	frame := `<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="2" name="ch"/>` +
+		`<p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>` +
+		`<p:xfrm><a:off x="0" y="0"/><a:ext cx="4572000" cy="2743200"/></p:xfrm>` +
+		`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart">` +
+		`<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" r:id="rId9"/>` +
+		`</a:graphicData></a:graphic></p:graphicFrame>`
+
+	objs := parseOneSlide(t, pptxParts{
+		slides:     []string{frame},
+		slideRels:  map[string]string{"rId9": "../charts/chart1.xml"},
+		extraParts: map[string]string{"ppt/charts/chart1.xml": chartXML},
+	})
+	if len(objs) != 1 || objs[0].Type != "chart" {
+		t.Fatalf("objects = %+v, want one chart", objs)
+	}
+	var spec chartSpec
+	if err := json.Unmarshal(objs[0].Props.Spec, &spec); err != nil {
+		t.Fatalf("chart spec is not valid JSON: %v", err)
+	}
+	if spec.Type != "bar" || spec.Title != "Sales" {
+		t.Errorf("spec = %+v, want a bar chart titled Sales", spec)
+	}
+	if !spec.Options.Stacked || !spec.Options.Legend || !spec.Options.Gridlines {
+		t.Errorf("chart options lost: %+v", spec.Options)
+	}
+	if len(spec.Labels) != 2 || spec.Labels[1] != "Feb" {
+		t.Errorf("labels = %v, want [Jan Feb]", spec.Labels)
+	}
+	if len(spec.Series) != 1 || spec.Series[0].Name != "2025" ||
+		len(spec.Series[0].Values) != 2 || spec.Series[0].Values[1] != 20.5 {
+		t.Errorf("series = %+v, want one series 2025 [10 20.5]", spec.Series)
+	}
+}
+
+/* ---------------- embedded fonts ---------------- */
+
+func TestDecodeEmbeddedFont(t *testing.T) {
+	ttf := append([]byte{0x00, 0x01, 0x00, 0x00}, bytes.Repeat([]byte{0x41}, 64)...)
+
+	// an uncompressed EOT: header, then the font file as the tail
+	eot := func(flags uint32, payload []byte) []byte {
+		head := make([]byte, 82)
+		putU32 := func(off int, v uint32) {
+			head[off] = byte(v)
+			head[off+1] = byte(v >> 8)
+			head[off+2] = byte(v >> 16)
+			head[off+3] = byte(v >> 24)
+		}
+		putU32(4, uint32(len(payload)))
+		putU32(8, 0x00020002)
+		putU32(12, flags)
+		head[34], head[35] = 0x4C, 0x50 // magic 0x504C, little endian
+		out := append(head, payload...)
+		putU32(0, uint32(len(out)))
+		out[0], out[1], out[2], out[3] = byte(len(out)), byte(len(out)>>8),
+			byte(len(out)>>16), byte(len(out)>>24)
+		return out
+	}
+
+	tests := []struct {
+		name string
+		in   []byte
+		ok   bool
+		mime string
+	}{
+		{"bare truetype", ttf, true, "font/ttf"},
+		{"bare opentype", append([]byte("OTTO"), ttf[4:]...), true, "font/otf"},
+		{"uncompressed eot", eot(0, ttf), true, "font/ttf"},
+		{"compressed eot is declined", eot(eotCompressed, ttf), false, ""},
+		{"not a font", []byte("hello there, not a font at all"), false, ""},
+		{"too short", []byte{1, 2, 3}, false, ""},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			out, mime, ok := decodeEmbeddedFont(tc.in)
+			if ok != tc.ok {
+				t.Fatalf("ok = %v, want %v", ok, tc.ok)
+			}
+			if !tc.ok {
+				return
+			}
+			if mime != tc.mime {
+				t.Errorf("mime = %q, want %q", mime, tc.mime)
+			}
+			if sfntMagic(out) == "" {
+				t.Errorf("decoded payload is not a font file")
+			}
+		})
+	}
+}
+
+/* ---------------- font stacks ---------------- */
+
+func TestFontStackFor(t *testing.T) {
+	tests := []struct {
+		name        string
+		latin, ea   string
+		wantParts   []string
+		wantGeneric string
+	}{
+		{"plain family", "Arial", "Arial", []string{"Arial"}, "sans-serif"},
+		{"weighted name offers its base", "Open Sans SemiBold", "Open Sans SemiBold",
+			[]string{"'Open Sans SemiBold'", "'Open Sans'"}, "sans-serif"},
+		{"east asian face is kept", "Arial", "Noto Sans TC",
+			[]string{"Arial", "'Noto Sans TC'"}, "sans-serif"},
+		{"monospace generic", "Courier New", "", []string{"'Courier New'"}, "monospace"},
+		{"serif generic", "Times New Roman", "", []string{"'Times New Roman'"}, "serif"},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			got := fontStackFor(tc.latin, tc.ea)
+			for _, part := range tc.wantParts {
+				if !strings.Contains(got, part) {
+					t.Errorf("stack %q is missing %q", got, part)
+				}
+			}
+			if !strings.HasSuffix(got, tc.wantGeneric) {
+				t.Errorf("stack %q does not end in %q", got, tc.wantGeneric)
+			}
+		})
+	}
+}
+
+func TestFontWeightOf(t *testing.T) {
+	tests := []struct {
+		name string
+		want int
+	}{
+		{"Open Sans", 0},
+		{"Open Sans SemiBold", 600},
+		{"Open Sans Medium", 500},
+		{"Roboto Light", 300},
+		{"Arial Black", 900},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := fontWeightOf(tc.name); got != tc.want {
+				t.Errorf("fontWeightOf(%q) = %d, want %d", tc.name, got, tc.want)
+			}
+		})
+	}
+}

+ 180 - 0
src/mod/office/pptx_fonts.go

@@ -0,0 +1,180 @@
+package office
+
+/*
+	pptx_fonts.go - fonts a deck carries with it.
+
+	A presentation may embed the font files it was designed in, so that it
+	looks the same on a machine that does not have them installed. The
+	Slides editor can use those directly: each face becomes an @font-face
+	rule built from a data URL, and the CSS font stacks the reader writes
+	then resolve to the real thing instead of falling back.
+
+	The payload behind <p:embeddedFont> is a .fntdata part, which is an
+	Embedded OpenType (EOT) wrapper around a font file. Two of the three
+	shapes it comes in can be unwrapped here:
+
+	  - a bare sfnt (TrueType / OpenType / WOFF) written straight into the
+	    part, which some producers do
+	  - an uncompressed EOT, where the font file is simply the tail of the
+	    part - this is what PowerPoint writes
+
+	The third is an EOT whose payload is MicroType Express compressed
+	(the TTEMBED_TTCOMPRESSED flag) - Google Slides writes these. Undoing
+	that needs a full MTX decompressor, which is a large piece of code for
+	a format nothing else in ArozOS reads, so those faces are skipped and
+	the text falls back to the CSS stack. Skipping is safe: the deck still
+	renders, just in a substitute face.
+*/
+
+import (
+	"encoding/base64"
+	"encoding/binary"
+	"strings"
+)
+
+// Size limits on embedded fonts. They ride in the document body, which is
+// posted whole on every save, so a deck that embeds a full CJK face (those
+// run to several megabytes) would make itself painful to edit. The cap
+// keeps the common case - a Latin family, tens of kilobytes per face -
+// while letting anything extravagant fall back to a substitute font.
+const (
+	maxEmbeddedFontBytes      = 1500 * 1024
+	maxEmbeddedFontTotalBytes = 4000 * 1024
+)
+
+// eotCompressed is TTEMBED_TTCOMPRESSED - the payload is MicroType Express
+const eotCompressed = 0x00000004
+
+// sfntMagic reports the mime type of a bare font file, "" when data is not one
+func sfntMagic(data []byte) string {
+	if len(data) < 4 {
+		return ""
+	}
+	switch string(data[:4]) {
+	case "OTTO":
+		return "font/otf"
+	case "wOFF":
+		return "font/woff"
+	case "wOF2":
+		return "font/woff2"
+	case "true", "ttcf":
+		return "font/ttf"
+	}
+	if data[0] == 0 && data[1] == 1 && data[2] == 0 && data[3] == 0 {
+		return "font/ttf"
+	}
+	return ""
+}
+
+// decodeEmbeddedFont unwraps a .fntdata part into a font file a browser can
+// load. ok is false when the part is compressed or otherwise unreadable.
+func decodeEmbeddedFont(data []byte) (out []byte, mime string, ok bool) {
+	if m := sfntMagic(data); m != "" {
+		return data, m, true
+	}
+	if len(data) < 82 {
+		return nil, "", false
+	}
+	eotSize := binary.LittleEndian.Uint32(data[0:4])
+	fontDataSize := binary.LittleEndian.Uint32(data[4:8])
+	flags := binary.LittleEndian.Uint32(data[12:16])
+	// the magic number sits at a fixed offset and pins that this really is
+	// an EOT rather than some other container
+	if binary.LittleEndian.Uint16(data[34:36]) != 0x504C {
+		return nil, "", false
+	}
+	if flags&eotCompressed != 0 {
+		return nil, "", false
+	}
+	if int(eotSize) != len(data) || fontDataSize == 0 || int(fontDataSize) > len(data) {
+		return nil, "", false
+	}
+	payload := data[len(data)-int(fontDataSize):]
+	m := sfntMagic(payload)
+	if m == "" {
+		return nil, "", false
+	}
+	return payload, m, true
+}
+
+// embeddedFontFaces reads <p:embeddedFontLst> and returns the faces of the
+// families in "used", smallest first so the cap spends its budget on the
+// faces most likely to matter
+func (d *pptxDoc) embeddedFontFaces(used map[string]bool) []*EmbeddedFont {
+	lst := d.pres.first("embeddedFontLst")
+	if lst == nil {
+		return nil
+	}
+	type candidate struct {
+		face *EmbeddedFont
+		size int
+	}
+	var cands []candidate
+	for _, ef := range lst.all("embeddedFont") {
+		family := ef.path("font")
+		if family == nil {
+			continue
+		}
+		name := family.attr("typeface")
+		if name == "" || !used[strings.ToLower(name)] {
+			continue
+		}
+		for _, variant := range []struct {
+			el     string
+			weight int
+			style  string
+		}{
+			{"regular", 400, ""},
+			{"bold", 700, ""},
+			{"italic", 400, "italic"},
+			{"boldItalic", 700, "italic"},
+		} {
+			ref := ef.first(variant.el)
+			if ref == nil {
+				continue
+			}
+			rid := ref.attrNS("relationships", "id")
+			if rid == "" {
+				rid = ref.attr("id")
+			}
+			target, okRel := d.presRels[rid]
+			if !okRel {
+				continue
+			}
+			raw, okFile := d.files[resolvePartPath("ppt", target)]
+			if !okFile || len(raw) > maxEmbeddedFontBytes {
+				continue
+			}
+			font, mime, okFont := decodeEmbeddedFont(raw)
+			if !okFont || len(font) > maxEmbeddedFontBytes {
+				continue
+			}
+			cands = append(cands, candidate{
+				face: &EmbeddedFont{
+					Family: name,
+					Weight: variant.weight,
+					Style:  variant.style,
+					Src: "data:" + mime + ";base64," +
+						base64.StdEncoding.EncodeToString(font),
+				},
+				size: len(font),
+			})
+		}
+	}
+	// smallest first, then fill up to the whole-deck budget
+	for i := 1; i < len(cands); i++ {
+		for j := i; j > 0 && cands[j].size < cands[j-1].size; j-- {
+			cands[j], cands[j-1] = cands[j-1], cands[j]
+		}
+	}
+	var out []*EmbeddedFont
+	total := 0
+	for _, c := range cands {
+		if total+c.size > maxEmbeddedFontTotalBytes {
+			break
+		}
+		total += c.size
+		out = append(out, c.face)
+	}
+	return out
+}

File diff suppressed because it is too large
+ 1172 - 340
src/mod/office/pptx_reader.go


+ 320 - 0
src/mod/office/pptx_richtext.go

@@ -0,0 +1,320 @@
+package office
+
+/*
+	pptx_richtext.go - turn the Slides editor's storage HTML back into
+	PresentationML paragraphs and runs.
+
+	The reader writes one <div> per paragraph and one <span> per run, and
+	the editor's own contenteditable produces the same shapes plus the
+	tags execCommand emits (<b>, <i>, <u>, <font>, <ul>/<ol>/<li>). Both
+	have to survive a save into .pptx, or every deck opened from a
+	PowerPoint file would lose its formatting the moment it was saved -
+	which is exactly what the first version of the writer did, flattening
+	the whole box to one font, size and colour.
+
+	Parsing goes through encoding/xml in non-strict mode with HTML entities
+	and auto-closing turned on, so an unclosed <br> and a bare &nbsp; are
+	both handled without pulling in an HTML parser.
+*/
+
+import (
+	"encoding/xml"
+	"strconv"
+	"strings"
+)
+
+// htmlRun is one run of uniformly formatted text, or a line break
+type htmlRun struct {
+	Text      string
+	Break     bool
+	SizePx    float64
+	Font      string // the first real family in the CSS stack
+	Bold      bool
+	Italic    bool
+	Underline bool
+	Strike    bool
+	Color     string // "#rrggbb"
+	Highlight string
+}
+
+// htmlPara is one paragraph with its block-level formatting
+type htmlPara struct {
+	Align      string  // left | center | right | justify
+	LineHeight float64 // unitless, 0 when unset
+	MarginTop  float64 // px
+	MarginBot  float64 // px
+	PadLeft    float64 // px
+	Indent     float64 // px, negative for a hanging bullet
+	Bullet     string  // the marker glyph, "" when the paragraph has none
+	Runs       []htmlRun
+}
+
+// inlineStyle is the formatting in force at a point in the tree
+type inlineStyle struct {
+	sizePx     float64
+	font       string
+	bold       bool
+	italic     bool
+	underline  bool
+	strike     bool
+	color      string
+	highlight  string
+	bulletSpan bool    // this subtree is a bullet marker, not body text
+	bulletLeft float64 // the marker's offset from the paragraph box, px
+}
+
+// parseStorageHTML turns the editor's stored HTML into paragraphs. A
+// document with no block markup at all comes back as a single paragraph.
+func parseStorageHTML(html string, base inlineStyle) []htmlPara {
+	dec := xml.NewDecoder(strings.NewReader("<root>" + html + "</root>"))
+	dec.Strict = false
+	dec.AutoClose = xml.HTMLAutoClose
+	dec.Entity = xml.HTMLEntity
+
+	var paras []htmlPara
+	cur := htmlPara{}
+	haveBlock := false
+	stack := []inlineStyle{base}
+	// list nesting, so <ol> numbers and <ul> bullets come out right
+	type listCtx struct {
+		ordered bool
+		n       int
+	}
+	var lists []listCtx
+
+	top := func() inlineStyle { return stack[len(stack)-1] }
+	flush := func() {
+		if len(cur.Runs) > 0 || haveBlock {
+			paras = append(paras, cur)
+		}
+		cur = htmlPara{}
+	}
+
+	for {
+		tok, err := dec.Token()
+		if err != nil {
+			break
+		}
+		switch t := tok.(type) {
+		case xml.StartElement:
+			name := strings.ToLower(t.Name.Local)
+			st := top()
+			switch name {
+			case "root":
+				continue
+			case "br":
+				cur.Runs = append(cur.Runs, htmlRun{Break: true, SizePx: st.sizePx, Font: st.font})
+				stack = append(stack, st)
+				continue
+			case "div", "p", "h1", "h2", "h3", "h4", "h5", "h6", "li":
+				flush()
+				haveBlock = true
+				applyBlockAttrs(&cur, t)
+				if name == "li" && len(lists) > 0 {
+					l := &lists[len(lists)-1]
+					if l.ordered {
+						l.n++
+						cur.Bullet = strconv.Itoa(l.n) + "."
+					} else {
+						cur.Bullet = "•"
+					}
+					if cur.PadLeft == 0 {
+						cur.PadLeft = 36 * float64(len(lists))
+					}
+					if cur.Indent == 0 {
+						cur.Indent = -18
+					}
+				}
+			case "ul", "ol":
+				lists = append(lists, listCtx{ordered: name == "ol"})
+			case "b", "strong":
+				st.bold = true
+			case "i", "em":
+				st.italic = true
+			case "u":
+				st.underline = true
+			case "s", "strike", "del":
+				st.strike = true
+			case "sup", "sub":
+				// baseline shifts are not modelled on the run
+			}
+			applyInlineAttrs(&st, t)
+			if st.bulletSpan && cur.Bullet == "" {
+				// the reader marks a bullet with an absolutely positioned
+				// span; it is a marker, not part of the text, and where it
+				// sits relative to the text is the hanging indent
+				cur.Bullet = "•"
+				cur.Indent = st.bulletLeft - cur.PadLeft
+			}
+			stack = append(stack, st)
+		case xml.EndElement:
+			name := strings.ToLower(t.Name.Local)
+			if name == "root" {
+				continue
+			}
+			if name == "ul" || name == "ol" {
+				if len(lists) > 0 {
+					lists = lists[:len(lists)-1]
+				}
+			}
+			if len(stack) > 1 {
+				stack = stack[:len(stack)-1]
+			}
+		case xml.CharData:
+			st := top()
+			text := strings.ReplaceAll(string(t), " ", " ")
+			// the reader pads an otherwise empty line with a zero-width
+			// space so it keeps its height; that is layout, not content
+			text = strings.ReplaceAll(text, "​", "")
+			if text == "" {
+				continue
+			}
+			if st.bulletSpan {
+				cur.Bullet = strings.TrimSpace(text)
+				continue
+			}
+			cur.Runs = append(cur.Runs, htmlRun{
+				Text: text, SizePx: st.sizePx, Font: st.font,
+				Bold: st.bold, Italic: st.italic, Underline: st.underline,
+				Strike: st.strike, Color: st.color, Highlight: st.highlight,
+			})
+		}
+	}
+	flush()
+	if len(paras) == 0 {
+		paras = []htmlPara{{}}
+	}
+	return paras
+}
+
+// applyBlockAttrs reads the paragraph-level CSS off a block element
+func applyBlockAttrs(p *htmlPara, el xml.StartElement) {
+	decls := styleDecls(el)
+	for prop, val := range decls {
+		switch prop {
+		case "text-align":
+			p.Align = val
+		case "line-height":
+			if strings.HasSuffix(val, "px") {
+				// an absolute line height cannot be expressed without the
+				// font size; leave it to the run sizes
+				continue
+			}
+			p.LineHeight = parseNum(val)
+		case "margin-top":
+			p.MarginTop = parseNum(val)
+		case "margin-bottom":
+			p.MarginBot = parseNum(val)
+		case "padding-left":
+			p.PadLeft = parseNum(val)
+		case "text-indent":
+			p.Indent = parseNum(val)
+		}
+	}
+}
+
+// applyInlineAttrs reads run-level CSS and the legacy <font> attributes
+func applyInlineAttrs(st *inlineStyle, el xml.StartElement) {
+	if strings.EqualFold(el.Name.Local, "font") {
+		for _, a := range el.Attr {
+			switch strings.ToLower(a.Name.Local) {
+			case "color":
+				st.color = a.Value
+			case "face":
+				st.font = firstFontFamily(a.Value)
+			}
+		}
+	}
+	decls := styleDecls(el)
+	if decls == nil {
+		return
+	}
+	for prop, val := range decls {
+		switch prop {
+		case "font-size":
+			if v := parseNum(val); v > 0 {
+				st.sizePx = v
+			}
+		case "font-family":
+			st.font = firstFontFamily(val)
+		case "font-weight":
+			st.bold = val == "bold" || parseNum(val) >= 600
+		case "font-style":
+			st.italic = val == "italic" || val == "oblique"
+		case "text-decoration", "text-decoration-line":
+			st.underline = strings.Contains(val, "underline")
+			st.strike = strings.Contains(val, "line-through")
+		case "color":
+			st.color = val
+		case "background-color", "background":
+			st.highlight = val
+		case "position":
+			if val == "absolute" {
+				st.bulletSpan = true
+			}
+		case "left":
+			st.bulletLeft = parseNum(val)
+		}
+	}
+}
+
+// styleDecls splits a style attribute into lower-cased property/value pairs
+func styleDecls(el xml.StartElement) map[string]string {
+	raw := ""
+	for _, a := range el.Attr {
+		if strings.EqualFold(a.Name.Local, "style") {
+			raw = a.Value
+		}
+	}
+	if raw == "" {
+		return nil
+	}
+	out := map[string]string{}
+	for _, decl := range strings.Split(raw, ";") {
+		i := strings.Index(decl, ":")
+		if i < 0 {
+			continue
+		}
+		out[strings.ToLower(strings.TrimSpace(decl[:i]))] =
+			strings.ToLower(strings.TrimSpace(decl[i+1:]))
+	}
+	return out
+}
+
+// firstFontFamily picks the first concrete family out of a CSS font stack
+func firstFontFamily(stack string) string {
+	for _, part := range strings.Split(stack, ",") {
+		name := strings.TrimSpace(part)
+		name = strings.Trim(name, "'\"")
+		switch strings.ToLower(name) {
+		case "", "sans-serif", "serif", "monospace", "cursive", "fantasy",
+			"system-ui", "ui-sans-serif", "ui-serif", "ui-monospace",
+			"inherit", "initial":
+			continue
+		}
+		return name
+	}
+	return ""
+}
+
+// parseNum reads the leading number out of a CSS value ("18.5px" -> 18.5)
+func parseNum(v string) float64 {
+	v = strings.TrimSpace(v)
+	end := 0
+	for end < len(v) {
+		c := v[end]
+		if (c >= '0' && c <= '9') || c == '.' || (end == 0 && (c == '-' || c == '+')) {
+			end++
+			continue
+		}
+		break
+	}
+	if end == 0 {
+		return 0
+	}
+	f, err := strconv.ParseFloat(v[:end], 64)
+	if err != nil {
+		return 0
+	}
+	return f
+}

+ 494 - 0
src/mod/office/pptx_text.go

@@ -0,0 +1,494 @@
+package office
+
+/*
+	pptx_text.go - PresentationML text: the property inheritance chain and
+	the HTML the Slides editor renders.
+
+	A run's appearance in a pptx is almost never written on the run. It is
+	assembled from, lowest priority first:
+
+	    presentation.xml  <p:defaultTextStyle>          (non-placeholder text)
+	    slideMaster       <p:txStyles>/title|body|other (by placeholder kind)
+	    slideMaster       the matching placeholder's <a:lstStyle>
+	    slideLayout       the matching placeholder's <a:lstStyle>
+	    the shape's own   <a:lstStyle>
+	    the paragraph's   <a:pPr>  (and its <a:defRPr>)
+	    the run's         <a:rPr>
+
+	Each level is looked up per outline level (lvl1pPr..lvl9pPr), so the
+	same body placeholder yields a different size, colour and bullet for
+	every indent level. Reading only the run - which is what the first
+	version of this reader did - loses nearly all of a real deck's design.
+
+	The result is emitted as the restricted HTML the Slides text object
+	stores: one <div> per paragraph carrying alignment, line height,
+	paragraph spacing and indents, one <span> per run carrying font, size,
+	colour and weight, and an absolutely positioned bullet span that
+	reproduces PowerPoint's hanging-indent geometry exactly.
+*/
+
+import (
+	"fmt"
+	"strconv"
+	"strings"
+)
+
+// PowerPoint's "single" line spacing is the font's line height, which is
+// about 1.2 em for the fonts office documents use. A <a:lnSpc> percentage
+// multiplies that, so 100% renders as CSS line-height 1.2 - checked
+// against Google Slides' own PDF export of the reference decks.
+const pptxLineHeightFactor = 1.2
+
+// EMU per point (a point is 1/72 inch, an EMU 1/914400 inch)
+const emuPerPt = 12700
+
+// runStyle is the resolved appearance of one text run. Zero values mean
+// "not yet specified" only while a chain is being resolved - resolution
+// always starts from pptxDefaultRun, so a fully resolved style is complete.
+type runStyle struct {
+	SizePt    float64
+	Bold      bool
+	Italic    bool
+	Underline bool
+	Strike    bool
+	Color     string
+	Latin     string
+	EastAsian string
+	Highlight string
+	Caps      string  // "all", "small" or ""
+	SpacingPt float64 // letter spacing
+	Baseline  float64 // per cent of font size; >0 superscript, <0 subscript
+}
+
+// paraStyle is the resolved appearance of one paragraph
+type paraStyle struct {
+	Align     string  // l, ctr, r, just
+	MarLeft   float64 // EMU
+	MarRight  float64 // EMU
+	Indent    float64 // EMU, negative for a hanging bullet
+	LnSpcPct  float64 // 1 = 100%; 0 when an exact spacing is set instead
+	LnSpcPt   float64 // exact line spacing in points
+	SpcBefPt  float64
+	SpcBefPct float64
+	SpcAftPt  float64
+	SpcAftPct float64
+	BuType    string // "", "none", "char", "autonum"
+	BuChar    string
+	BuAutoNum string
+	BuStartAt int
+	BuFont    string
+	BuColor   string
+	BuSizePct float64
+	BuSizePt  float64
+	DefRun    runStyle
+}
+
+var pptxDefaultRun = runStyle{SizePt: 18, Color: "#000000", Latin: "Arial"}
+
+var pptxDefaultPara = paraStyle{Align: "l", LnSpcPct: 1, BuSizePct: 1, DefRun: pptxDefaultRun}
+
+// applyRPr folds one <a:rPr> / <a:defRPr> / <a:endParaRPr> into dst,
+// touching only the properties that element actually states
+func applyRPr(dst *runStyle, n *xnode, cc *colorCtx) {
+	if n == nil {
+		return
+	}
+	if v := n.attr("sz"); v != "" {
+		if f := atofDefault(v, 0); f > 0 {
+			dst.SizePt = f / 100
+		}
+	}
+	if v := n.attr("b"); v != "" {
+		dst.Bold = v == "1" || v == "true"
+	}
+	if v := n.attr("i"); v != "" {
+		dst.Italic = v == "1" || v == "true"
+	}
+	if v := n.attr("u"); v != "" {
+		dst.Underline = v != "none"
+	}
+	if v := n.attr("strike"); v != "" {
+		dst.Strike = v != "noStrike"
+	}
+	if v := n.attr("cap"); v != "" {
+		if v == "none" {
+			dst.Caps = ""
+		} else {
+			dst.Caps = v
+		}
+	}
+	if v := n.attr("spc"); v != "" {
+		dst.SpacingPt = atofDefault(v, 0) / 100
+	}
+	if v := n.attr("baseline"); v != "" {
+		dst.Baseline = atofDefault(v, 0) / 1000
+	}
+	if n.first("noFill") != nil {
+		// text with no fill is invisible; approximate with transparency
+		dst.Color = "transparent"
+	} else if c := cc.solidColorOf(n); c != "" {
+		dst.Color = c
+	}
+	if hl := n.first("highlight"); hl != nil {
+		for i := range hl.Nodes {
+			if c := cc.resolveColor(&hl.Nodes[i]); c != "" {
+				dst.Highlight = c
+				break
+			}
+		}
+	}
+	if l := n.first("latin"); l != nil {
+		if tf := l.attr("typeface"); tf != "" {
+			dst.Latin = tf
+		}
+	}
+	if e := n.first("ea"); e != nil {
+		if tf := e.attr("typeface"); tf != "" {
+			dst.EastAsian = tf
+		}
+	}
+}
+
+// applyPPr folds one <a:pPr> / <a:lvlNpPr> / <a:defPPr> into dst
+func applyPPr(dst *paraStyle, n *xnode, cc *colorCtx) {
+	if n == nil {
+		return
+	}
+	if v := n.attr("algn"); v != "" {
+		dst.Align = v
+	}
+	if v := n.attr("marL"); v != "" {
+		dst.MarLeft = atofDefault(v, 0)
+	}
+	if v := n.attr("marR"); v != "" {
+		dst.MarRight = atofDefault(v, 0)
+	}
+	if v := n.attr("indent"); v != "" {
+		dst.Indent = atofDefault(v, 0)
+	}
+	if ls := n.first("lnSpc"); ls != nil {
+		if p := ls.first("spcPct"); p != nil {
+			dst.LnSpcPct = atofDefault(p.attr("val"), 100000) / 100000
+			dst.LnSpcPt = 0
+		} else if p := ls.first("spcPts"); p != nil {
+			dst.LnSpcPt = atofDefault(p.attr("val"), 0) / 100
+			dst.LnSpcPct = 0
+		}
+	}
+	readSpc := func(sp *xnode, pt, pct *float64) {
+		if sp == nil {
+			return
+		}
+		if p := sp.first("spcPts"); p != nil {
+			*pt = atofDefault(p.attr("val"), 0) / 100
+			*pct = 0
+		} else if p := sp.first("spcPct"); p != nil {
+			*pct = atofDefault(p.attr("val"), 0) / 100000
+			*pt = 0
+		}
+	}
+	readSpc(n.first("spcBef"), &dst.SpcBefPt, &dst.SpcBefPct)
+	readSpc(n.first("spcAft"), &dst.SpcAftPt, &dst.SpcAftPct)
+
+	if n.first("buNone") != nil {
+		dst.BuType = "none"
+	}
+	if bc := n.first("buChar"); bc != nil {
+		dst.BuType = "char"
+		dst.BuChar = bc.attr("char")
+	}
+	if ba := n.first("buAutoNum"); ba != nil {
+		dst.BuType = "autonum"
+		dst.BuAutoNum = ba.attr("type")
+		dst.BuStartAt = int(atofDefault(ba.attr("startAt"), 1))
+	}
+	if bf := n.first("buFont"); bf != nil {
+		if tf := bf.attr("typeface"); tf != "" {
+			dst.BuFont = tf
+		}
+	}
+	if bcl := n.first("buClr"); bcl != nil {
+		for i := range bcl.Nodes {
+			if c := cc.resolveColor(&bcl.Nodes[i]); c != "" {
+				dst.BuColor = c
+				break
+			}
+		}
+	}
+	if bs := n.first("buSzPct"); bs != nil {
+		dst.BuSizePct = atofDefault(bs.attr("val"), 100000) / 100000
+		dst.BuSizePt = 0
+	}
+	if bs := n.first("buSzPts"); bs != nil {
+		dst.BuSizePt = atofDefault(bs.attr("val"), 0) / 100
+		dst.BuSizePct = 0
+	}
+	applyRPr(&dst.DefRun, n.first("defRPr"), cc)
+}
+
+// lvlPPr picks the <a:lvlNpPr> for a zero-based outline level out of an
+// <a:lstStyle> (or a <p:titleStyle> / <p:bodyStyle> / <p:otherStyle>,
+// which use the same child elements)
+func lvlPPr(lst *xnode, lvl int) *xnode {
+	if lst == nil {
+		return nil
+	}
+	if lvl < 0 {
+		lvl = 0
+	}
+	if lvl > 8 {
+		lvl = 8
+	}
+	name := fmt.Sprintf("lvl%dpPr", lvl+1)
+	if n := lst.first(name); n != nil {
+		return n
+	}
+	// some producers only write defPPr
+	return lst.first("defPPr")
+}
+
+// resolveParaStyle walks the inheritance chain (lowest priority first) for
+// one outline level and folds the paragraph's own pPr on top
+func resolveParaStyle(chain []*xnode, pPr *xnode, lvl int, cc *colorCtx) paraStyle {
+	st := pptxDefaultPara
+	for _, lst := range chain {
+		applyPPr(&st, lvlPPr(lst, lvl), cc)
+	}
+	applyPPr(&st, pPr, cc)
+	return st
+}
+
+/* ---------------- HTML generation ---------------- */
+
+// fontStackFor turns a pptx typeface pair into a CSS font-family list.
+// The east-asian face is kept as a second entry so a browser picks it per
+// glyph, exactly the way PowerPoint switches fonts mid-run for CJK text.
+func fontStackFor(latin, ea string) string {
+	var parts []string
+	seen := map[string]bool{}
+	add := func(name string) {
+		name = strings.TrimSpace(name)
+		if name == "" || seen[name] {
+			return
+		}
+		// "+mj-lt" / "+mn-lt" are theme font references the caller has
+		// already resolved; anything still unresolved is not a real font
+		if strings.HasPrefix(name, "+") {
+			return
+		}
+		seen[name] = true
+		parts = append(parts, quoteFontName(name))
+	}
+	add(latin)
+	add(ea)
+	// a weighted family name ("Open Sans SemiBold") is not installed on most
+	// systems - offer the base family so the browser can synthesize instead
+	// of dropping to a completely unrelated default
+	if base := baseFontName(latin); base != latin {
+		add(base)
+	}
+	if base := baseFontName(ea); base != ea {
+		add(base)
+	}
+	generic := "sans-serif"
+	l := strings.ToLower(latin)
+	switch {
+	case strings.Contains(l, "courier"), strings.Contains(l, "mono"),
+		strings.Contains(l, "consolas"):
+		generic = "monospace"
+	case strings.Contains(l, "times"), strings.Contains(l, "georgia"),
+		strings.Contains(l, "serif") && !strings.Contains(l, "sans"),
+		strings.Contains(l, "garamond"), strings.Contains(l, "book antiqua"):
+		generic = "serif"
+	}
+	parts = append(parts, generic)
+	return strings.Join(parts, ",")
+}
+
+func quoteFontName(n string) string {
+	if strings.ContainsAny(n, " '\"") {
+		return "'" + strings.ReplaceAll(n, "'", "") + "'"
+	}
+	return n
+}
+
+var fontWeightSuffixes = []struct {
+	suffix string
+	weight int
+}{
+	{" thin", 100}, {" extralight", 200}, {" extra light", 200}, {" ultralight", 200},
+	{" light", 300}, {" regular", 400}, {" medium", 500},
+	{" semibold", 600}, {" semi bold", 600}, {" demibold", 600},
+	{" bold", 700}, {" extrabold", 800}, {" extra bold", 800}, {" black", 900},
+}
+
+// baseFontName strips a trailing weight word ("Open Sans SemiBold" ->
+// "Open Sans"); returns the name unchanged when there is none
+func baseFontName(n string) string {
+	l := strings.ToLower(n)
+	for _, w := range fontWeightSuffixes {
+		if strings.HasSuffix(l, w.suffix) {
+			return strings.TrimSpace(n[:len(n)-len(w.suffix)])
+		}
+	}
+	return n
+}
+
+// fontWeightOf reads the weight a font name implies, 0 when it implies none
+func fontWeightOf(n string) int {
+	l := strings.ToLower(n)
+	for _, w := range fontWeightSuffixes {
+		if strings.HasSuffix(l, w.suffix) {
+			return w.weight
+		}
+	}
+	return 0
+}
+
+func fmtPx(v float64) string {
+	return strconv.FormatFloat(round2(v), 'f', -1, 64) + "px"
+}
+
+func round2(v float64) float64 {
+	return float64(int64(v*100+copySign(0.5, v))) / 100
+}
+
+func copySign(v, sign float64) float64 {
+	if sign < 0 {
+		return -v
+	}
+	return v
+}
+
+// ptToPx converts points to CSS pixels at 96 dpi
+func ptToPx(pt float64) float64 { return pt / 0.75 }
+
+// runCSS renders the inline style for one text run
+func runCSS(rs runStyle, scale float64) string {
+	var sb strings.Builder
+	sb.WriteString("font-size:" + fmtPx(ptToPx(rs.SizePt)*scale) + ";")
+	sb.WriteString("font-family:" + fontStackFor(rs.Latin, rs.EastAsian) + ";")
+	weight := 0
+	if rs.Bold {
+		weight = 700
+	} else if w := fontWeightOf(rs.Latin); w != 0 {
+		weight = w
+	}
+	if weight != 0 {
+		sb.WriteString("font-weight:" + strconv.Itoa(weight) + ";")
+	}
+	if rs.Italic {
+		sb.WriteString("font-style:italic;")
+	}
+	deco := ""
+	if rs.Underline {
+		deco = "underline"
+	}
+	if rs.Strike {
+		if deco != "" {
+			deco += " "
+		}
+		deco += "line-through"
+	}
+	if deco != "" {
+		sb.WriteString("text-decoration:" + deco + ";")
+	}
+	if rs.Color != "" {
+		sb.WriteString("color:" + rs.Color + ";")
+	}
+	if rs.Highlight != "" {
+		sb.WriteString("background-color:" + rs.Highlight + ";")
+	}
+	if rs.Caps == "all" {
+		sb.WriteString("text-transform:uppercase;")
+	}
+	if rs.SpacingPt != 0 {
+		sb.WriteString("letter-spacing:" + fmtPx(ptToPx(rs.SpacingPt)*scale) + ";")
+	}
+	if rs.Baseline > 0 {
+		sb.WriteString("vertical-align:super;font-size:" + fmtPx(ptToPx(rs.SizePt)*scale*0.65) + ";")
+	} else if rs.Baseline < 0 {
+		sb.WriteString("vertical-align:sub;font-size:" + fmtPx(ptToPx(rs.SizePt)*scale*0.65) + ";")
+	}
+	return sb.String()
+}
+
+// lineSpacerFor renders the invisible span that gives an otherwise empty
+// line its height. A <a:br/> in PresentationML carries its own run
+// properties and the line it opens is as tall as those state, but an HTML
+// <br> with nothing after it adds no height at all - so a zero-width space
+// at the stated size stands in for the text that is not there.
+func lineSpacerFor(rs runStyle, scale float64) string {
+	return `<span style="font-size:` + fmtPx(ptToPx(rs.SizePt)*scale) +
+		`;font-family:` + fontStackFor(rs.Latin, rs.EastAsian) + `">&#8203;</span>`
+}
+
+// autoNumMarker renders the visible marker of an <a:buAutoNum> list
+func autoNumMarker(kind string, n int) string {
+	switch {
+	case strings.HasPrefix(kind, "alphaLc"):
+		return alphaMarker(n, 'a') + autoNumSuffix(kind)
+	case strings.HasPrefix(kind, "alphaUc"):
+		return alphaMarker(n, 'A') + autoNumSuffix(kind)
+	case strings.HasPrefix(kind, "romanLc"):
+		return strings.ToLower(romanMarker(n)) + autoNumSuffix(kind)
+	case strings.HasPrefix(kind, "romanUc"):
+		return romanMarker(n) + autoNumSuffix(kind)
+	}
+	return strconv.Itoa(n) + autoNumSuffix(kind)
+}
+
+func autoNumSuffix(kind string) string {
+	switch {
+	case strings.HasSuffix(kind, "ParenBoth"):
+		return ")"
+	case strings.HasSuffix(kind, "ParenR"):
+		return ")"
+	case strings.HasSuffix(kind, "Period"):
+		return "."
+	}
+	return "."
+}
+
+func alphaMarker(n int, base byte) string {
+	if n < 1 {
+		n = 1
+	}
+	out := ""
+	for n > 0 {
+		n--
+		out = string([]byte{base + byte(n%26)}) + out
+		n /= 26
+	}
+	return out
+}
+
+func romanMarker(n int) string {
+	if n < 1 {
+		return ""
+	}
+	vals := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
+	syms := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
+	var sb strings.Builder
+	for i, v := range vals {
+		for n >= v {
+			sb.WriteString(syms[i])
+			n -= v
+		}
+	}
+	return sb.String()
+}
+
+// spanSizes folds one run size into a paragraph's running max and min
+func spanSizes(size, curMax, curMin float64) (float64, float64) {
+	if size <= 0 {
+		return curMax, curMin
+	}
+	if size > curMax {
+		curMax = size
+	}
+	if curMin == 0 || size < curMin {
+		curMin = size
+	}
+	return curMax, curMin
+}

+ 324 - 40
src/mod/office/pptx_writer.go

@@ -32,15 +32,27 @@ import (
 
 const nsDecl = `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"`
 
+// shapeKindToPrst is the inverse of prstToShapeKind (pptx_reader.go) for
+// the kinds the editor can draw, so a shape or a shaped crop written here
+// reads back as the same thing
 var shapeKindToPrst = map[string]string{
-	"rect":     "rect",
-	"round":    "roundRect",
-	"ellipse":  "ellipse",
-	"triangle": "triangle",
-	"diamond":  "diamond",
-	"arrow":    "rightArrow",
-	"star":     "star5",
-	"chevron":  "chevron",
+	"rect":          "rect",
+	"round":         "roundRect",
+	"ellipse":       "ellipse",
+	"triangle":      "triangle",
+	"rtTriangle":    "rtTriangle",
+	"diamond":       "diamond",
+	"arrow":         "rightArrow",
+	"leftArrow":     "leftArrow",
+	"upArrow":       "upArrow",
+	"downArrow":     "downArrow",
+	"star":          "star5",
+	"chevron":       "chevron",
+	"pentagon":      "pentagon",
+	"hexagon":       "hexagon",
+	"parallelogram": "parallelogram",
+	"trapezoid":     "trapezoid",
+	"plus":          "mathPlus",
 }
 
 // BuildPptx serializes a Presentation without a media resolver (video /
@@ -474,7 +486,9 @@ func alignToAlgn(align string) string {
 	return "l"
 }
 
-// buildRuns renders paragraph runs for flattened text lines
+// buildRuns renders paragraph runs for flattened text lines. Kept for the
+// callers that genuinely have plain text (shape captions written in the
+// editor, table cells) - rich HTML goes through buildRichBody instead.
 func buildRuns(lines []string, fontSizePx float64, color string, bold, italic, underline bool, align string) string {
 	var sb strings.Builder
 	rpr := fmt.Sprintf(`<a:rPr lang="en-US" sz="%d"`, fontSizeToSz(fontSizePx))
@@ -502,6 +516,147 @@ func buildRuns(lines []string, fontSizePx float64, color string, bold, italic, u
 	return sb.String()
 }
 
+// pxToEmuRound converts CSS pixels to EMU
+func pxToEmuRound(px float64) int64 { return int64(px*emuPerPx + 0.5) }
+
+// buildRichBody renders the editor's storage HTML as PresentationML
+// paragraphs, keeping per-run font, size, weight, colour and highlight and
+// per-paragraph alignment, spacing, indents and bullets.
+func buildRichBody(o *Object, fallbackColor string) string {
+	p := o.Props
+	base := inlineStyle{
+		sizePx: p.FontSize,
+		font:   firstFontFamily(p.FontFamily),
+		bold:   p.Bold, italic: p.Italic, underline: p.Underline,
+		color: p.Color,
+	}
+	if base.color == "" {
+		base.color = p.TextColor
+	}
+	if base.color == "" {
+		base.color = fallbackColor
+	}
+	if base.sizePx <= 0 {
+		base.sizePx = 24
+	}
+	paras := parseStorageHTML(p.HTML, base)
+
+	var sb strings.Builder
+	for _, para := range paras {
+		align := para.Align
+		if align == "" {
+			align = p.Align
+		}
+		sb.WriteString(`<a:p><a:pPr`)
+		if a := alignToAlgn(align); a != "l" {
+			sb.WriteString(` algn="` + a + `"`)
+		}
+		if para.PadLeft != 0 {
+			sb.WriteString(fmt.Sprintf(` marL="%d"`, pxToEmuRound(para.PadLeft)))
+		}
+		if para.Indent != 0 {
+			sb.WriteString(fmt.Sprintf(` indent="%d"`, pxToEmuRound(para.Indent)))
+		}
+		sb.WriteString(`>`)
+		lh := para.LineHeight
+		if lh <= 0 {
+			lh = p.LineHeight
+		}
+		if lh > 0 {
+			// the reader turns a pptx percentage into a CSS multiplier by
+			// multiplying with the font's line height; undo that here
+			sb.WriteString(fmt.Sprintf(`<a:lnSpc><a:spcPct val="%d"/></a:lnSpc>`,
+				int(lh/pptxLineHeightFactor*100000)))
+		}
+		if para.MarginTop > 0 {
+			sb.WriteString(fmt.Sprintf(`<a:spcBef><a:spcPts val="%d"/></a:spcBef>`,
+				int(para.MarginTop*0.75*100)))
+		}
+		if para.MarginBot > 0 {
+			sb.WriteString(fmt.Sprintf(`<a:spcAft><a:spcPts val="%d"/></a:spcAft>`,
+				int(para.MarginBot*0.75*100)))
+		}
+		if para.Bullet != "" {
+			sb.WriteString(`<a:buChar char="` + xmlEscape(para.Bullet) + `"/>`)
+		} else {
+			sb.WriteString(`<a:buNone/>`)
+		}
+		sb.WriteString(`</a:pPr>`)
+		for _, r := range para.Runs {
+			if r.Break {
+				sb.WriteString(`<a:br>` + runRPr(r, base) + `</a:br>`)
+				continue
+			}
+			if r.Text == "" {
+				continue
+			}
+			sb.WriteString(`<a:r>` + runRPr(r, base) + `<a:t>` + xmlEscape(r.Text) + `</a:t></a:r>`)
+		}
+		sb.WriteString(`</a:p>`)
+	}
+	return sb.String()
+}
+
+// runRPr renders one run's <a:rPr>
+func runRPr(r htmlRun, base inlineStyle) string {
+	size := r.SizePx
+	if size <= 0 {
+		size = base.sizePx
+	}
+	var sb strings.Builder
+	sb.WriteString(fmt.Sprintf(`<a:rPr lang="en-US" sz="%d"`, fontSizeToSz(size)))
+	sb.WriteString(` b="` + boolAttr(r.Bold) + `" i="` + boolAttr(r.Italic) + `"`)
+	if r.Underline {
+		sb.WriteString(` u="sng"`)
+	}
+	if r.Strike {
+		sb.WriteString(` strike="sngStrike"`)
+	}
+	sb.WriteString(` dirty="0">`)
+	color := r.Color
+	if color == "" {
+		color = base.color
+	}
+	sb.WriteString(`<a:solidFill><a:srgbClr val="` + hexColor(color, "202124") + `"/></a:solidFill>`)
+	if r.Highlight != "" {
+		if h := hexColor(r.Highlight, ""); h != "" {
+			sb.WriteString(`<a:highlight><a:srgbClr val="` + h + `"/></a:highlight>`)
+		}
+	}
+	font := r.Font
+	if font == "" {
+		font = base.font
+	}
+	if font != "" {
+		f := xmlEscape(font)
+		sb.WriteString(`<a:latin typeface="` + f + `"/><a:ea typeface="` + f +
+			`"/><a:cs typeface="` + f + `"/>`)
+	}
+	sb.WriteString(`</a:rPr>`)
+	return sb.String()
+}
+
+// bodyPrFor renders the <a:bodyPr> for an object, honouring the vertical
+// anchor and the text insets an imported deck carries
+func bodyPrFor(p Props, defaultAnchor string) string {
+	anchor := defaultAnchor
+	switch p.VAlign {
+	case "middle":
+		anchor = "ctr"
+	case "bottom":
+		anchor = "b"
+	case "top":
+		anchor = "t"
+	}
+	ins := `lIns="0" tIns="0" rIns="0" bIns="0"`
+	if len(p.Pad) == 4 {
+		ins = fmt.Sprintf(`tIns="%d" rIns="%d" bIns="%d" lIns="%d"`,
+			pxToEmuRound(p.Pad[0]), pxToEmuRound(p.Pad[1]),
+			pxToEmuRound(p.Pad[2]), pxToEmuRound(p.Pad[3]))
+	}
+	return `<a:bodyPr wrap="square" anchor="` + anchor + `" anchorCtr="0" ` + ins + `><a:noAutofit/></a:bodyPr>`
+}
+
 func buildTextSp(id int, o *Object, theme string) string {
 	p := o.Props
 	color := p.Color
@@ -511,10 +666,11 @@ func buildTextSp(id int, o *Object, theme string) string {
 	return fmt.Sprintf(
 		`<p:sp><p:nvSpPr><p:cNvPr id="%d" name="TextBox %d"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>`+
 			`<p:spPr>%s<a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></p:spPr>`+
-			`<p:txBody><a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0"/><a:lstStyle/>%s</p:txBody></p:sp>`,
+			`<p:txBody>%s<a:lstStyle/>%s</p:txBody></p:sp>`,
 		id, id,
 		xfrm(o.X, o.Y, o.W, o.H, o.Rot, false, false),
-		buildRuns(htmlToLines(p.HTML), p.FontSize, color, p.Bold, p.Italic, p.Underline, p.Align))
+		bodyPrFor(p, "t"),
+		buildRichBody(o, color))
 }
 
 func buildShapeSp(id int, o *Object) string {
@@ -523,13 +679,39 @@ func buildShapeSp(id int, o *Object) string {
 	if !ok {
 		prst = "rect"
 	}
-	ln := ""
-	if p.StrokeW > 0 {
-		ln = fmt.Sprintf(`<a:ln w="%d"><a:solidFill><a:srgbClr val="%s"/></a:solidFill></a:ln>`,
+	geom := `<a:prstGeom prst="` + prst + `"><a:avLst/></a:prstGeom>`
+	if prst == "roundRect" && p.Radius > 0 && o.W > 0 && o.H > 0 {
+		adj := int(p.Radius / minF(o.W, o.H) * 100000)
+		if adj > 0 && adj <= 50000 {
+			geom = fmt.Sprintf(
+				`<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val %d"/></a:avLst></a:prstGeom>`, adj)
+		}
+	}
+	ln := `<a:ln><a:noFill/></a:ln>`
+	if p.StrokeW > 0 && p.Stroke != "" && p.Stroke != "none" {
+		ln = fmt.Sprintf(`<a:ln w="%d"><a:solidFill><a:srgbClr val="%s"/></a:solidFill>`,
 			pxToEmu(p.StrokeW), hexColor(p.Stroke, "333333"))
+		if p.Dash {
+			ln += `<a:prstDash val="dash"/>`
+		}
+		ln += `</a:ln>`
+	}
+	fill := `<a:noFill/>`
+	if p.Fill != "" && p.Fill != "none" {
+		fill = `<a:solidFill><a:srgbClr val="` + hexColor(p.Fill, "E07B1F") + `"/></a:solidFill>`
+	} else if p.Fill == "" {
+		fill = `<a:solidFill><a:srgbClr val="E07B1F"/></a:solidFill>`
 	}
-	tx := `<p:txBody><a:bodyPr anchor="ctr" anchorCtr="0"/><a:lstStyle/><a:p/></p:txBody>`
-	if strings.TrimSpace(p.Text) != "" {
+
+	tx := `<p:txBody>` + bodyPrFor(p, "ctr") + `<a:lstStyle/><a:p/></p:txBody>`
+	if p.HTML != "" {
+		tc := p.TextColor
+		if tc == "" {
+			tc = "#FFFFFF"
+		}
+		tx = `<p:txBody>` + bodyPrFor(p, "ctr") + `<a:lstStyle/>` +
+			buildRichBody(o, tc) + `</p:txBody>`
+	} else if strings.TrimSpace(p.Text) != "" {
 		tc := p.TextColor
 		if tc == "" {
 			tc = "#FFFFFF"
@@ -538,21 +720,34 @@ func buildShapeSp(id int, o *Object) string {
 		if fs <= 0 {
 			fs = 18
 		}
-		tx = `<p:txBody><a:bodyPr anchor="ctr" anchorCtr="0"/><a:lstStyle/>` +
-			buildRuns(strings.Split(p.Text, "\n"), fs, tc, p.Bold, false, false, "center") +
+		align := p.Align
+		if align == "" {
+			align = "center"
+		}
+		tx = `<p:txBody>` + bodyPrFor(p, "ctr") + `<a:lstStyle/>` +
+			buildRuns(strings.Split(p.Text, "\n"), fs, tc, p.Bold, false, false, align) +
 			`</p:txBody>`
 	}
 	return fmt.Sprintf(
 		`<p:sp><p:nvSpPr><p:cNvPr id="%d" name="Shape %d"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>`+
-			`<p:spPr>%s<a:prstGeom prst="%s"><a:avLst/></a:prstGeom>`+
-			`<a:solidFill><a:srgbClr val="%s"/></a:solidFill>%s</p:spPr>%s</p:sp>`,
+			`<p:spPr>%s%s%s%s</p:spPr>%s</p:sp>`,
 		id, id,
 		xfrm(o.X, o.Y, o.W, o.H, o.Rot, false, false),
-		prst, hexColor(p.Fill, "E07B1F"), ln, tx)
+		geom, fill, ln, tx)
+}
+
+func minF(a, b float64) float64 {
+	if a < b {
+		return a
+	}
+	return b
 }
 
 func buildLineSp(id int, o *Object) string {
 	p := o.Props
+	if len(p.Points) > 2 {
+		return buildPolylineSp(id, o)
+	}
 	// bounding box with flips encoding the line direction
 	x, y, w, h := o.X, o.Y, o.W, o.H
 	flipH, flipV := false, false
@@ -566,6 +761,15 @@ func buildLineSp(id int, o *Object) string {
 		h = -h
 		flipV = true
 	}
+	return fmt.Sprintf(
+		`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="%d" name="Line %d"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>`+
+			`<p:spPr>%s<a:prstGeom prst="line"><a:avLst/></a:prstGeom>%s</p:spPr></p:cxnSp>`,
+		id, id,
+		xfrm(x, y, w, h, 0, flipH, flipV), lineLn(p))
+}
+
+// lineLn renders the <a:ln> of a line object, with its dash and arrow heads
+func lineLn(p Props) string {
 	sw := p.StrokeW
 	if sw <= 0 {
 		sw = 2
@@ -575,24 +779,82 @@ func buildLineSp(id int, o *Object) string {
 	if p.Dash {
 		ln += `<a:prstDash val="dash"/>`
 	}
+	if p.ArrowStart {
+		ln += `<a:headEnd type="triangle"/>`
+	}
 	if p.ArrowEnd {
-		ln += `<a:tailEnd type="arrow"/>`
+		ln += `<a:tailEnd type="triangle"/>`
+	}
+	return ln + `</a:ln>`
+}
+
+// buildPolylineSp exports a bent connector as a freeform shape. Rebuilding
+// the original bentConnector preset would mean re-deriving its rotation and
+// flips from the path; a custGeom states the very path the editor draws, so
+// nothing can drift.
+func buildPolylineSp(id int, o *Object) string {
+	pts := o.Props.Points
+	minX, minY := pts[0][0], pts[0][1]
+	maxX, maxY := minX, minY
+	for _, pt := range pts {
+		minX, maxX = minF(minX, pt[0]), maxF(maxX, pt[0])
+		minY, maxY = minF(minY, pt[1]), maxF(maxY, pt[1])
+	}
+	w, h := maxX-minX, maxY-minY
+	var path strings.Builder
+	for i, pt := range pts {
+		x := pxToEmu(pt[0] - minX)
+		y := pxToEmu(pt[1] - minY)
+		if i == 0 {
+			path.WriteString(fmt.Sprintf(`<a:moveTo><a:pt x="%d" y="%d"/></a:moveTo>`, x, y))
+			continue
+		}
+		path.WriteString(fmt.Sprintf(`<a:lnTo><a:pt x="%d" y="%d"/></a:lnTo>`, x, y))
 	}
-	ln += `</a:ln>`
 	return fmt.Sprintf(
-		`<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="%d" name="Line %d"/><p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr>`+
-			`<p:spPr>%s<a:prstGeom prst="line"><a:avLst/></a:prstGeom>%s</p:spPr></p:cxnSp>`,
+		`<p:sp><p:nvSpPr><p:cNvPr id="%d" name="Connector %d"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>`+
+			`<p:spPr>%s<a:custGeom><a:avLst/><a:gdLst/><a:rect l="0" t="0" r="r" b="b"/>`+
+			`<a:pathLst><a:path w="%d" h="%d">%s</a:path></a:pathLst></a:custGeom>`+
+			`<a:noFill/>%s</p:spPr>`+
+			`<p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>`,
 		id, id,
-		xfrm(x, y, w, h, 0, flipH, flipV), ln)
+		xfrm(o.X+minX, o.Y+minY, maxF(w, 1), maxF(h, 1), 0, false, false),
+		pxToEmu(maxF(w, 1)), pxToEmu(maxF(h, 1)), path.String(), lineLn(o.Props))
 }
 
 func buildPicSp(id int, o *Object, rid string) string {
+	p := o.Props
+	srcRect := ""
+	if len(p.Crop) == 4 {
+		srcRect = fmt.Sprintf(`<a:srcRect l="%d" t="%d" r="%d" b="%d"/>`,
+			int(p.Crop[0]*100000), int(p.Crop[1]*100000),
+			int(p.Crop[2]*100000), int(p.Crop[3]*100000))
+	}
+	// a shaped crop is a preset geometry on the picture itself
+	prst := "rect"
+	if q, ok := shapeKindToPrst[p.Mask]; ok {
+		prst = q
+	}
+	geom := `<a:prstGeom prst="` + prst + `"><a:avLst/></a:prstGeom>`
+	if (prst == "roundRect" || p.Mask == "" || p.Mask == "rect") &&
+		p.Radius > 0 && o.W > 0 && o.H > 0 {
+		adj := int(p.Radius / minF(o.W, o.H) * 100000)
+		if adj > 0 && adj <= 50000 {
+			geom = fmt.Sprintf(
+				`<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val %d"/></a:avLst></a:prstGeom>`, adj)
+		}
+	}
+	blip := `<a:blip r:embed="` + rid + `"/>`
+	if p.Opacity > 0 && p.Opacity < 1 {
+		blip = `<a:blip r:embed="` + rid + `"><a:alphaModFix amt="` +
+			fmt.Sprintf("%d", int(p.Opacity*100000)) + `"/></a:blip>`
+	}
 	return fmt.Sprintf(
 		`<p:pic><p:nvPicPr><p:cNvPr id="%d" name="Picture %d"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>`+
-			`<p:blipFill><a:blip r:embed="%s"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>`+
-			`<p:spPr>%s<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic>`,
-		id, id, rid,
-		xfrm(o.X, o.Y, o.W, o.H, o.Rot, false, false))
+			`<p:blipFill>%s%s<a:stretch><a:fillRect/></a:stretch></p:blipFill>`+
+			`<p:spPr>%s%s</p:spPr></p:pic>`,
+		id, id, blip, srcRect,
+		xfrm(o.X, o.Y, o.W, o.H, o.Rot, false, false), geom)
 }
 
 func buildTableFrame(id int, o *Object) string {
@@ -643,22 +905,44 @@ func buildTableFrame(id int, o *Object) string {
 			if c < len(row) {
 				cell = row[c]
 			}
-			bold := p.HeaderRow && ri == 0
-			rpr := fmt.Sprintf(`<a:rPr lang="en-US" sz="%d"`, fontSizeToSz(fs))
-			if bold {
-				rpr += ` b="1"`
+			// cells hold the same limited HTML the text objects do, so
+			// per-cell bold / colour / font survive the round trip
+			base := inlineStyle{
+				sizePx: fs, color: color,
+				bold: p.HeaderRow && ri == 0,
 			}
-			rpr += ` dirty="0"><a:solidFill><a:srgbClr val="` + hexColor(color, "202124") + `"/></a:solidFill></a:rPr>`
-			// cells hold a limited HTML subset - flatten to text paragraphs
 			var paras strings.Builder
-			for _, line := range htmlToLines(cell) {
+			for _, para := range parseStorageHTML(cell, base) {
 				paras.WriteString(`<a:p>`)
-				if line != "" {
-					paras.WriteString(`<a:r>` + rpr + `<a:t>` + xmlEscape(line) + `</a:t></a:r>`)
+				if a := alignToAlgn(para.Align); a != "l" {
+					paras.WriteString(`<a:pPr algn="` + a + `"/>`)
+				}
+				for _, r := range para.Runs {
+					if r.Break {
+						paras.WriteString(`<a:br/>`)
+						continue
+					}
+					if r.Text == "" {
+						continue
+					}
+					paras.WriteString(`<a:r>` + runRPr(r, base) + `<a:t>` +
+						xmlEscape(r.Text) + `</a:t></a:r>`)
 				}
 				paras.WriteString(`</a:p>`)
 			}
-			sb.WriteString(`<a:tc><a:txBody><a:bodyPr/><a:lstStyle/>` + paras.String() + `</a:txBody><a:tcPr/></a:tc>`)
+			ins := ""
+			if len(p.CellPad) == 4 {
+				ins = fmt.Sprintf(` marT="%d" marR="%d" marB="%d" marL="%d"`,
+					pxToEmuRound(p.CellPad[0]), pxToEmuRound(p.CellPad[1]),
+					pxToEmuRound(p.CellPad[2]), pxToEmuRound(p.CellPad[3]))
+			}
+			tcPr := `<a:tcPr` + ins + `/>`
+			if ri < len(p.CellFill) && c < len(p.CellFill[ri]) && p.CellFill[ri][c] != "" {
+				tcPr = `<a:tcPr` + ins + `><a:solidFill><a:srgbClr val="` +
+					hexColor(p.CellFill[ri][c], "FFFFFF") + `"/></a:solidFill></a:tcPr>`
+			}
+			sb.WriteString(`<a:tc><a:txBody><a:bodyPr/><a:lstStyle/>` + paras.String() +
+				`</a:txBody>` + tcPr + `</a:tc>`)
 		}
 		sb.WriteString(`</a:tr>`)
 	}

+ 446 - 0
src/mod/office/pptx_xml.go

@@ -0,0 +1,446 @@
+package office
+
+/*
+	pptx_xml.go - the generic XML tree and DrawingML colour resolution
+	shared by the pptx reader.
+
+	OOXML is far too large to model with rigid structs for the subset the
+	Slides webapp consumes, so every part is parsed into an xnode tree and
+	walked by local element name (namespace prefixes are ignored - a:off,
+	p:off and dgm:off all read as "off").
+*/
+
+import (
+	"encoding/xml"
+	"math"
+	"strconv"
+	"strings"
+)
+
+// xnode is a generic XML tree node
+type xnode struct {
+	XMLName xml.Name
+	Attrs   []xml.Attr `xml:",any,attr"`
+	Nodes   []xnode    `xml:",any"`
+	Text    string     `xml:",chardata"`
+}
+
+func (n *xnode) attr(local string) string {
+	if n == nil {
+		return ""
+	}
+	for _, a := range n.Attrs {
+		if a.Name.Local == local {
+			return a.Value
+		}
+	}
+	return ""
+}
+
+// attrNS returns an attribute matching both a namespace URI suffix and a
+// local name - needed for r:id, which collides with the plain "id" attribute
+func (n *xnode) attrNS(nsSuffix, local string) string {
+	if n == nil {
+		return ""
+	}
+	for _, a := range n.Attrs {
+		if a.Name.Local == local && strings.HasSuffix(a.Name.Space, nsSuffix) {
+			return a.Value
+		}
+	}
+	return ""
+}
+
+// first returns the first direct child with the given local name
+func (n *xnode) first(local string) *xnode {
+	if n == nil {
+		return nil
+	}
+	for i := range n.Nodes {
+		if n.Nodes[i].XMLName.Local == local {
+			return &n.Nodes[i]
+		}
+	}
+	return nil
+}
+
+// path walks nested first() lookups; returns nil when any hop is missing
+func (n *xnode) path(locals ...string) *xnode {
+	cur := n
+	for _, l := range locals {
+		cur = cur.first(l)
+		if cur == nil {
+			return nil
+		}
+	}
+	return cur
+}
+
+// all returns every direct child with the given local name
+func (n *xnode) all(local string) []*xnode {
+	if n == nil {
+		return nil
+	}
+	var out []*xnode
+	for i := range n.Nodes {
+		if n.Nodes[i].XMLName.Local == local {
+			out = append(out, &n.Nodes[i])
+		}
+	}
+	return out
+}
+
+// findAll walks the whole subtree collecting elements with the given name
+func (n *xnode) findAll(local string, out *[]*xnode) {
+	if n == nil {
+		return
+	}
+	for i := range n.Nodes {
+		if n.Nodes[i].XMLName.Local == local {
+			*out = append(*out, &n.Nodes[i])
+		}
+		n.Nodes[i].findAll(local, out)
+	}
+}
+
+func parseXMLTree(data []byte) (*xnode, error) {
+	root := xnode{}
+	if err := xml.Unmarshal(data, &root); err != nil {
+		return nil, err
+	}
+	return &root, nil
+}
+
+// parseRels maps rId -> target path from a .rels part. Shared with the
+// docx and xlsx readers, which use the same relationship plumbing.
+func parseRels(data []byte) map[string]string {
+	out := map[string]string{}
+	if data == nil {
+		return out
+	}
+	tree, err := parseXMLTree(data)
+	if err != nil {
+		return out
+	}
+	for _, rel := range tree.all("Relationship") {
+		out[rel.attr("Id")] = rel.attr("Target")
+	}
+	return out
+}
+
+// collectText gathers every <a:t> text node under n
+func collectText(n *xnode, out *[]string) {
+	if n.XMLName.Local == "t" {
+		if strings.TrimSpace(n.Text) != "" {
+			*out = append(*out, n.Text)
+		}
+		return
+	}
+	for i := range n.Nodes {
+		collectText(&n.Nodes[i], out)
+	}
+}
+
+func atofDefault(s string, def float64) float64 {
+	if s == "" {
+		return def
+	}
+	v, err := strconv.ParseFloat(s, 64)
+	if err != nil {
+		return def
+	}
+	return v
+}
+
+/* ---------------- DrawingML colour resolution ---------------- */
+
+// the preset colour names DrawingML allows in prstClr. Only the handful
+// office documents actually use are listed; anything else falls back to
+// black, which is what PowerPoint does for a name it does not know.
+var prstClrTable = map[string]string{
+	"black": "000000", "white": "FFFFFF", "red": "FF0000", "green": "008000",
+	"blue": "0000FF", "yellow": "FFFF00", "cyan": "00FFFF", "magenta": "FF00FF",
+	"gray": "808080", "grey": "808080", "darkGray": "A9A9A9", "lightGray": "D3D3D3",
+	"orange": "FFA500", "purple": "800080", "brown": "A52A2A", "pink": "FFC0CB",
+	"lime": "00FF00", "navy": "000080", "teal": "008080", "olive": "808000",
+	"maroon": "800000", "silver": "C0C0C0", "gold": "FFD700",
+}
+
+// colorCtx is everything needed to turn a DrawingML colour element into a
+// concrete hex string: the theme's colour scheme plus the master's colour
+// map (which is what makes "tx1" mean "dk1" on one deck and "lt1" on another).
+type colorCtx struct {
+	scheme map[string]string // dk1, lt1, dk2, lt2, accent1..6, hlink, folHlink
+	clrMap map[string]string // bg1/tx1/bg2/tx2/accent1.. -> scheme slot
+}
+
+// resolveColor turns any of the DrawingML colour elements (srgbClr,
+// schemeClr, sysClr, prstClr, scrgbClr) into "#rrggbb", applying the child
+// transform elements. Returns "" when n is not a colour element.
+func (cc *colorCtx) resolveColor(n *xnode) string {
+	if n == nil {
+		return ""
+	}
+	var r, g, b float64
+	switch n.XMLName.Local {
+	case "srgbClr":
+		r, g, b = hexToRGB(n.attr("val"))
+	case "schemeClr":
+		hex := cc.schemeHex(n.attr("val"))
+		if hex == "" {
+			return ""
+		}
+		r, g, b = hexToRGB(hex)
+	case "sysClr":
+		// lastClr carries the value the producing application resolved
+		v := n.attr("lastClr")
+		if v == "" {
+			if n.attr("val") == "window" {
+				v = "FFFFFF"
+			} else {
+				v = "000000"
+			}
+		}
+		r, g, b = hexToRGB(v)
+	case "prstClr":
+		v, ok := prstClrTable[n.attr("val")]
+		if !ok {
+			v = "000000"
+		}
+		r, g, b = hexToRGB(v)
+	case "scrgbClr":
+		// percentages in thousandths of a percent
+		r = clamp01(atofDefault(n.attr("r"), 0)/100000.0) * 255
+		g = clamp01(atofDefault(n.attr("g"), 0)/100000.0) * 255
+		b = clamp01(atofDefault(n.attr("b"), 0)/100000.0) * 255
+	default:
+		return ""
+	}
+	r, g, b = applyColorMods(r, g, b, n)
+	return rgbToHex(r, g, b)
+}
+
+// schemeHex maps a schemeClr val through the colour map into the theme
+func (cc *colorCtx) schemeHex(val string) string {
+	if val == "" {
+		return ""
+	}
+	if val == "phClr" {
+		// the placeholder colour of a style matrix - there is no style
+		// context at this level, so treat it as the text colour
+		val = "tx1"
+	}
+	slot := val
+	if cc.clrMap != nil {
+		if mapped, ok := cc.clrMap[val]; ok && mapped != "" {
+			slot = mapped
+		}
+	}
+	// bg1/tx1/bg2/tx2 are colour-map names; when the map did not cover
+	// them fall back to the conventional pairing
+	switch slot {
+	case "bg1":
+		slot = "lt1"
+	case "tx1":
+		slot = "dk1"
+	case "bg2":
+		slot = "lt2"
+	case "tx2":
+		slot = "dk2"
+	}
+	if cc.scheme != nil {
+		if hex, ok := cc.scheme[slot]; ok {
+			return hex
+		}
+	}
+	return ""
+}
+
+// solidColorOf resolves the <a:solidFill> child of parent, if any
+func (cc *colorCtx) solidColorOf(parent *xnode) string {
+	sf := parent.first("solidFill")
+	if sf == nil {
+		return ""
+	}
+	for i := range sf.Nodes {
+		if c := cc.resolveColor(&sf.Nodes[i]); c != "" {
+			return c
+		}
+	}
+	return ""
+}
+
+// fillColorOf resolves a fill container into a CSS colour. Gradients are
+// approximated by their first stop (the editor has no gradient object),
+// pattern fills by their foreground, and <a:noFill/> returns "none".
+func (cc *colorCtx) fillColorOf(parent *xnode) string {
+	if parent == nil {
+		return ""
+	}
+	if parent.first("noFill") != nil {
+		return "none"
+	}
+	if c := cc.solidColorOf(parent); c != "" {
+		return c
+	}
+	if gs := parent.path("gradFill", "gsLst"); gs != nil {
+		for _, stop := range gs.all("gs") {
+			for i := range stop.Nodes {
+				if c := cc.resolveColor(&stop.Nodes[i]); c != "" {
+					return c
+				}
+			}
+		}
+	}
+	if fg := parent.path("pattFill", "fgClr"); fg != nil {
+		for i := range fg.Nodes {
+			if c := cc.resolveColor(&fg.Nodes[i]); c != "" {
+				return c
+			}
+		}
+	}
+	return ""
+}
+
+// applyColorMods applies the DrawingML colour transform children. Alpha is
+// deliberately not applied here - the caller reads it separately, because
+// the editor model carries opacity on the object, not on the colour.
+func applyColorMods(r, g, b float64, n *xnode) (float64, float64, float64) {
+	for i := range n.Nodes {
+		ch := &n.Nodes[i]
+		v := atofDefault(ch.attr("val"), 0) / 100000.0
+		switch ch.XMLName.Local {
+		case "lumMod":
+			h, s, l := rgbToHSL(r, g, b)
+			r, g, b = hslToRGB(h, s, clamp01(l*v))
+		case "lumOff":
+			h, s, l := rgbToHSL(r, g, b)
+			r, g, b = hslToRGB(h, s, clamp01(l+v))
+		case "shade":
+			// shade multiplies toward black; the sRGB approximation used
+			// here is what LibreOffice does and is visually close enough
+			r, g, b = r*v, g*v, b*v
+		case "tint":
+			r = r*v + 255*(1-v)
+			g = g*v + 255*(1-v)
+			b = b*v + 255*(1-v)
+		case "satMod":
+			h, s, l := rgbToHSL(r, g, b)
+			r, g, b = hslToRGB(h, clamp01(s*v), l)
+		case "hueMod":
+			h, s, l := rgbToHSL(r, g, b)
+			r, g, b = hslToRGB(math.Mod(h*v, 1), s, l)
+		case "gray":
+			y := 0.299*r + 0.587*g + 0.114*b
+			r, g, b = y, y, y
+		case "inv":
+			r, g, b = 255-r, 255-g, 255-b
+		}
+	}
+	return r, g, b
+}
+
+func hexToRGB(h string) (float64, float64, float64) {
+	h = strings.TrimPrefix(strings.TrimSpace(h), "#")
+	if len(h) == 3 {
+		h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})
+	}
+	if len(h) != 6 {
+		return 0, 0, 0
+	}
+	v, err := strconv.ParseUint(h, 16, 32)
+	if err != nil {
+		return 0, 0, 0
+	}
+	return float64((v >> 16) & 255), float64((v >> 8) & 255), float64(v & 255)
+}
+
+func rgbToHex(r, g, b float64) string {
+	cl := func(v float64) int64 {
+		if v < 0 {
+			return 0
+		}
+		if v > 255 {
+			return 255
+		}
+		return int64(v + 0.5)
+	}
+	const digits = "0123456789abcdef"
+	out := []byte{'#', 0, 0, 0, 0, 0, 0}
+	for i, v := range []int64{cl(r), cl(g), cl(b)} {
+		out[1+i*2] = digits[(v>>4)&15]
+		out[2+i*2] = digits[v&15]
+	}
+	return string(out)
+}
+
+func clamp01(v float64) float64 {
+	if v < 0 {
+		return 0
+	}
+	if v > 1 {
+		return 1
+	}
+	return v
+}
+
+func rgbToHSL(r, g, b float64) (float64, float64, float64) {
+	r, g, b = r/255, g/255, b/255
+	mx := math.Max(r, math.Max(g, b))
+	mn := math.Min(r, math.Min(g, b))
+	l := (mx + mn) / 2
+	if mx == mn {
+		return 0, 0, l
+	}
+	d := mx - mn
+	var s float64
+	if l > 0.5 {
+		s = d / (2 - mx - mn)
+	} else {
+		s = d / (mx + mn)
+	}
+	var h float64
+	switch mx {
+	case r:
+		h = (g - b) / d
+		if g < b {
+			h += 6
+		}
+	case g:
+		h = (b-r)/d + 2
+	default:
+		h = (r-g)/d + 4
+	}
+	return h / 6, s, l
+}
+
+func hslToRGB(h, s, l float64) (float64, float64, float64) {
+	if s == 0 {
+		return l * 255, l * 255, l * 255
+	}
+	var q float64
+	if l < 0.5 {
+		q = l * (1 + s)
+	} else {
+		q = l + s - l*s
+	}
+	p := 2*l - q
+	hue := func(t float64) float64 {
+		if t < 0 {
+			t++
+		}
+		if t > 1 {
+			t--
+		}
+		switch {
+		case t < 1.0/6:
+			return p + (q-p)*6*t
+		case t < 1.0/2:
+			return q
+		case t < 2.0/3:
+			return p + (q-p)*(2.0/3-t)*6
+		}
+		return p
+	}
+	return hue(h+1.0/3) * 255, hue(h) * 255, hue(h-1.0/3) * 255
+}

+ 78 - 1
src/web/Office/README.md

@@ -163,6 +163,31 @@ body before posting:
   (`rasterizeEmojiForPdf` in `docs.js`) because PDF core fonts are
   Latin-1 and have no emoji glyphs.
 
+### Slides: cropping a picture
+
+Cropping never touches the pixels. The object frame says which part of the
+picture is visible and `props.crop` says which part of the source that is —
+the same definition PowerPoint's `srcRect` uses, so a crop made in the
+editor and one made in PowerPoint are interchangeable. `fullImageRect()`
+in `slides.js` inverts the pair to find where the whole picture sits, and
+that is the whole of the crop tool's geometry.
+
+Three commands, on the picture's context menu and on the toolbar (which
+shows them only while a picture is selected):
+
+- **Crop image** (also a double-click) opens the tool: the object itself is
+  hidden and the overlay draws the whole picture ghosted with the kept part
+  at full strength over it. A grip moves the frame; dragging the picture
+  moves the source behind it. Enter or a click outside applies, Esc restores.
+- **Mask image** clips it to any of the editor's shape kinds (`props.mask`),
+  drawn as a `clip-path` built from the same `shapePoints()` the shape
+  objects use, and written to `.pptx` as a `prstGeom` on the picture.
+- **Reset image** clears the crop, the mask and the corner radius, puts the
+  frame back to `props.orig` — stamped the first time a picture is trimmed,
+  and holding the frame the *whole* picture filled — and corrects the height
+  to the source's own aspect ratio, so a picture stretched by dragging a
+  corner comes back undistorted too.
+
 ### Sheets formula engine
 
 [`sheets/formula.js`](sheets/formula.js) is a DOM-free tokenizer, parser and
@@ -332,6 +357,42 @@ the path that honours every mode exactly.
 
 ### Format notes (hard-won lessons — don't re-learn these)
 
+- **PPTX/ODP import is inheritance, not element reading.** A deck's
+  appearance is almost never stated on the shape you are looking at. The
+  readers ([`pptx_reader.go`](../../mod/office/pptx_reader.go) +
+  `pptx_text.go` / `pptx_xml.go`, [`odp_reader.go`](../../mod/office/odp_reader.go))
+  resolve, lowest priority first: the presentation's default text style,
+  the master's `txStyles` for the placeholder kind, the master's and then
+  the layout's matching placeholder `lstStyle`, the shape's own `lstStyle`,
+  the paragraph's `pPr`, the run's `rPr` — per outline level. Colours go
+  through the theme's `clrScheme` *and* the master's `clrMap` (that is what
+  makes `tx1` mean `dk1` on one deck and `lt1` on another), with the
+  `lumMod`/`lumOff`/`shade`/`tint` transforms applied. A slide is drawn on
+  top of its layout's decoration and the master's, minus their
+  placeholders, which are prototypes rather than content. Skipping any of
+  this does not merely lose polish — text lands at the wrong size, in the
+  wrong place, sometimes white on white. `pptx_fidelity_test.go` pins each
+  rule with the smallest package that exercises it; the ODF equivalents are
+  in `odf_test.go`.
+- **Line spacing is `1.2 × the stated percentage`.** PowerPoint's "single"
+  spacing is the font's line height, so `<a:lnSpc><a:spcPct val="115000"/>`
+  is CSS `line-height: 1.15 × 1.2`. The constant is `pptxLineHeightFactor`,
+  checked against Google Slides' own PDF export of a real deck. Two related
+  traps: a paragraph's block `font-size` must be its **smallest** run (it
+  is a floor under every line box, so a big run would inflate a short line
+  under it), and an `<a:br/>` needs a sized zero-width span after it or the
+  empty line it opens gets no height at all.
+- **Embedded fonts are usually undecodable.** `<p:embeddedFontLst>` points
+  at `.fntdata` parts, which are EOT wrappers.
+  [`pptx_fonts.go`](../../mod/office/pptx_fonts.go) unwraps a bare sfnt or
+  an *uncompressed* EOT (what PowerPoint writes) into an `@font-face` data
+  URL, under a per-face and per-deck size cap so a multi-megabyte CJK face
+  cannot make a document painful to edit. Google Slides writes
+  MicroType-Express-compressed EOT, which needs a decompressor far larger
+  than the rest of this package — those faces are declined and the text
+  falls back to the CSS stack. That is the one remaining reason an imported
+  deck can differ visibly from its source: the glyphs are a substitute, so
+  a line may wrap a word earlier.
 - **DOCX pagination** ([`docx_writer.go`](../../mod/office/docx_writer.go)):
   Word substitutes its own Normal-style defaults (Calibri etc.) unless the
   style sheet pins the editor's typography into `docDefaults` +
@@ -448,7 +509,23 @@ sh ../scripts/check-conventions.sh --diff origin/master
 ## Ideas / known gaps (future work)
 
 - CJK/Unicode text in PDF export (needs an embedded font — see above).
-- Native OOXML charts instead of PNG rasters.
+- **MicroType Express decompression** so Google-Slides-embedded fonts can
+  be used (see the format notes) — the last visible gap between an
+  imported deck and its source.
+- **Native OOXML chart *writing***. Charts are now *read* into live chart
+  objects ([`pptx_chart.go`](../../mod/office/pptx_chart.go), from the
+  `c:numCache` / `c:strCache` values, so no embedded workbook is needed),
+  but they are still *written* as the client-rendered PNG in `props.png`.
+  A round trip therefore turns a chart into a picture.
+- Embedded fonts are read but not written back, so a `.pptx` exported from
+  a deck that carried its fonts no longer carries them.
+- A **shaped crop** (`props.mask`) round-trips through `.pptx` as the
+  picture's `prstGeom`, but neither the `.odp` writer nor the PDF exporter
+  draws one — ODF would need a custom shape with a bitmap fill, and
+  `pdf_slides.go` places pictures as plain rectangles. The rectangular
+  crop itself is exported to all three.
+- Slides: SmartArt (`dgm:`), 3-D effects, shadows and animations are
+  skipped rather than approximated.
 - Real-time collaboration (the `sharedspace` AGI lib was built for this).
 - Docs: footnotes, section breaks, multi-column export to docx/pdf
   (`page.columns` renders in-editor and exports to docx, but the PDF

+ 61 - 0
src/web/Office/common/CONTRACT.md

@@ -541,6 +541,67 @@ lists via execCommand; htmlToLines (mod/office) flattens them to bullet/number
 prefixes for .pptx. present.js adds transitions, click-to-reveal animations,
 laser pointer (L), interactive links, and a presenter-view popup.
 
+## Imported-deck fidelity props (slides.js)
+
+A deck opened from a `.pptx` / `.odp` carries the typography and geometry of
+the file it came from, which the editor's own objects do not have. Every one
+of these is **optional** — a document made in the editor omits them and falls
+back to the stylesheet, so nothing here changes how a new deck looks.
+
+| prop | on | meaning |
+|---|---|---|
+| `fontFamily` | text, shape | CSS font stack (latin + east-asian face, then a generic) |
+| `valign` | text, shape | `top` / `middle` / `bottom` — the text box's vertical anchor |
+| `pad` | text, shape | text insets `[top, right, bottom, left]` in px |
+| `lineHeight` | text, shape | unitless line-height multiplier |
+| `crop` | image | `[left, top, right, bottom]` fractions clipped off the source |
+| `mask` | image | a shaped crop: a `SHAPE_KINDS` kind the picture is clipped to |
+| `orig` | image | `{x,y,w,h}` the frame before the first crop — Reset image |
+| `radius` | image, shape | corner radius in px |
+| `opacity` | image | 0..1; 0 means fully opaque |
+| `points` | line | the polyline a bent connector follows, relative to `x`/`y` |
+| `arrowStart` | line | arrow head at the first point |
+| `cellFill` | table | per-cell background colours, `rows`-shaped |
+| `cellPad` | table | cell insets `[t, r, b, l]` in px |
+| `html` | shape | rich paragraph HTML, used in place of the plain `text` |
+
+`props.html` is the same restricted HTML text objects use: one `<div>` per
+paragraph carrying `text-align` / `line-height` / margins / `padding-left`,
+one `<span>` per run carrying font, size, weight and colour, and — for a
+bulleted paragraph — an absolutely positioned marker span that reproduces
+PowerPoint's hanging indent. `renderObjectEl` renders it as-is, so anything
+written into it must already be escaped.
+
+**Cropping is a view, never a change to the pixels.** The object frame says
+which part of the picture is visible; `props.crop` says which part of the
+source that is. The two are tied together by one identity, which the crop
+tool, the renderer and both format writers all rely on:
+
+```
+fullWidth = frame.w / (1 - crop.left - crop.right)      // and the same for h
+fullLeft  = frame.x - crop.left * fullWidth             // where the whole picture sits
+```
+
+While the crop tool is open (`startCrop`, double-click a picture or the
+toolbar's crop button) the object itself is hidden — `.sl-obj.sl-cropping` —
+and `#slCrop` draws the whole picture ghosted with the kept part at full
+strength on top. Dragging a grip moves the *frame*; dragging the picture
+moves the *source underneath it*. Enter or a click outside applies, Esc
+restores. **Reset image** clears `crop`, `mask` and `radius`, puts the frame
+back to `props.orig` (stamped the first time a picture is trimmed) and
+corrects the height to the source's own aspect ratio.
+
+`mask` maps onto a `prstGeom` on the `p:pic` in .pptx, so a shaped crop made
+here and one made in PowerPoint are the same thing; the renderer draws it as
+a `clip-path` built from `shapePoints()`, so every shape the editor can draw
+is also a mask it can cut.
+
+The presentation body may also carry `fonts`: `[{family, weight, style, src}]`
+where `src` is a font-file data URL taken from the source deck's embedded
+fonts. `normalizeBody` installs them as `@font-face` rules in a single
+page-level `<style id="slEmbeddedFonts">`, shared by the editor, the
+thumbnails, present mode and print.
+
 ## OfficeCharts (common/charts.js) — for Sheets and Slides
 
 ```js

+ 68 - 0
src/web/Office/slides/slides.css

@@ -183,10 +183,17 @@
 .sl-obj > svg { display: block; width: 100%; height: 100%; overflow: visible; }
 .sl-obj img { display: block; width: 100%; height: 100%; pointer-events: none; }
 
+/* A column flex box so a text object can be anchored to the top, middle or
+   bottom of its frame the way PowerPoint anchors one - and so paragraph
+   margins add up instead of collapsing, which is also what PowerPoint does
+   with its space-before / space-after. */
 .sl-text-in {
     width: 100%;
     min-height: 100%;
     box-sizing: border-box;
+    display: flex;
+    flex-direction: column;
+    justify-content: flex-start;
     outline: none;
     word-wrap: break-word;
     overflow-wrap: break-word;
@@ -195,12 +202,65 @@
     padding: 2px 4px;
     cursor: default;
 }
+/* imported paragraphs carry their own spacing; keep the browser from
+   adding any of its own on top */
+.sl-text-in > div { margin: 0; }
 .sl-text-in ul, .sl-text-in ol {
     margin: 0;
     padding-left: 1.3em;
     white-space: normal;
 }
 .sl-text-in li { text-align: left; }
+
+/* picture frame: the wrapper clips a cropped, rounded or masked image */
+.sl-img-wrap {
+    position: relative;
+    width: 100%;
+    height: 100%;
+    overflow: hidden;
+}
+
+/* ---- image crop tool ----
+   the whole picture is shown ghosted, with the part that will be kept
+   drawn over it at full strength inside the crop rectangle */
+#slCrop { position: absolute; inset: 0; }
+/* the picture being cropped is drawn by the tool, not by the slide */
+.sl-obj.sl-cropping { visibility: hidden; }
+.sl-crop-ghost {
+    position: absolute;
+    overflow: hidden;
+    opacity: 0.32;
+    pointer-events: auto;
+    cursor: move;
+}
+.sl-crop-ghost img { display: block; width: 100%; height: 100%; }
+/* no border here on purpose: it would sit inside the box and shift the
+   kept part of the picture out of line with the ghost behind it. The
+   black grips are what marks the edge, as in Slides/Docs. */
+.sl-crop-rect {
+    position: absolute;
+    overflow: hidden;
+    box-sizing: border-box;
+    pointer-events: auto;
+    cursor: move;
+}
+.sl-crop-rect > img { position: absolute; display: block; }
+.sl-croph {
+    position: absolute;
+    background: #202124;
+    box-sizing: border-box;
+    pointer-events: auto;
+    z-index: 620;
+}
+body.dark .sl-croph { background: #f1f3f4; }
+body.dark .sl-croph[data-ch="nw"], body.dark .sl-croph[data-ch="ne"],
+body.dark .sl-croph[data-ch="sw"], body.dark .sl-croph[data-ch="se"] {
+    border-color: #f1f3f4 !important;
+}
+.sl-croph[data-ch="n"], .sl-croph[data-ch="s"] { cursor: ns-resize; }
+.sl-croph[data-ch="e"], .sl-croph[data-ch="w"] { cursor: ew-resize; }
+.sl-croph[data-ch="nw"], .sl-croph[data-ch="se"] { cursor: nwse-resize; }
+.sl-croph[data-ch="ne"], .sl-croph[data-ch="sw"] { cursor: nesw-resize; }
 .sl-editing, .sl-editing * { user-select: text !important; }
 /* table column / row resize bars (only present in table edit mode) */
 .sl-tbl-rz {
@@ -214,6 +274,14 @@
 .sl-editing .sl-text-in, .sl-editing .sl-shape-text { cursor: text; }
 .sl-obj.sl-editing { outline: 1px dashed var(--of-accent); }
 
+.sl-shape-rich {
+    display: flex;
+    flex-direction: column;
+    align-items: stretch;
+    text-align: inherit;
+}
+.sl-shape-rich > div { margin: 0; }
+
 .sl-shape-text {
     position: absolute;
     inset: 0;

+ 586 - 43
src/web/Office/slides/slides.js

@@ -42,8 +42,26 @@
                     }
                 ]
             }
-        ]
-    }
+        ],
+        fonts: [                       // optional: font faces a .pptx/.odp
+            { family, weight, style, src }   // brought with it, installed as
+        ]                              // @font-face (see installEmbeddedFonts)
+    }
+
+    Objects imported from a .pptx / .odp carry extra props that keep the
+    typography and geometry of the file they came from. All are optional -
+    an object made in the editor omits them and falls back to the
+    stylesheet. See "Imported-deck fidelity props" in common/CONTRACT.md:
+      text / shape : fontFamily, valign, pad[t,r,b,l], lineHeight,
+                     and on a shape, html (rich text in place of text)
+      image        : crop[l,t,r,b] fractions, radius, opacity
+      line         : points (a bent connector's polyline), arrowStart
+      table        : cellFill[][], cellPad[t,r,b,l]
+
+    An image also carries crop / mask / orig when it has been cropped in
+    the editor - the same props, since a crop made here and one made in
+    PowerPoint mean the same thing. See the "image crop tool" section
+    below and CONTRACT.md for the frame-vs-source identity they obey.
 */
 
 var SlidesApp = (function () {
@@ -83,14 +101,23 @@ var SlidesApp = (function () {
     var MEDIA_MAX_BYTES = 200 * 1024 * 1024;  // uploads stream to the workdir
 
     var SHAPE_KINDS = [
-        { kind: "rect",     label: "Rectangle" },
-        { kind: "round",    label: "Rounded rectangle" },
-        { kind: "ellipse",  label: "Ellipse" },
-        { kind: "triangle", label: "Triangle" },
-        { kind: "diamond",  label: "Diamond" },
-        { kind: "arrow",    label: "Arrow" },
-        { kind: "star",     label: "Star" },
-        { kind: "chevron",  label: "Chevron" }
+        { kind: "rect",          label: "Rectangle" },
+        { kind: "round",         label: "Rounded rectangle" },
+        { kind: "ellipse",       label: "Ellipse" },
+        { kind: "triangle",      label: "Triangle" },
+        { kind: "rtTriangle",    label: "Right triangle" },
+        { kind: "diamond",       label: "Diamond" },
+        { kind: "pentagon",      label: "Pentagon" },
+        { kind: "hexagon",       label: "Hexagon" },
+        { kind: "parallelogram", label: "Parallelogram" },
+        { kind: "trapezoid",     label: "Trapezoid" },
+        { kind: "plus",          label: "Cross" },
+        { kind: "star",          label: "Star" },
+        { kind: "chevron",       label: "Chevron" },
+        { kind: "arrow",         label: "Arrow (right)" },
+        { kind: "leftArrow",     label: "Arrow (left)" },
+        { kind: "upArrow",       label: "Arrow (up)" },
+        { kind: "downArrow",     label: "Arrow (down)" }
     ];
 
     /* ================= state ================= */
@@ -110,8 +137,16 @@ var SlidesApp = (function () {
     var lastPointerEvt = null;
     var thumbTimer = null;
     var snapGrid = false;
+    /* image crop mode: cropId is the picture being cropped, cropRect is the
+       part of it that will be kept and cropFull is where the whole picture
+       sits behind that (both in slide units), cropBefore is what to put
+       back if the crop is cancelled */
+    var cropId = null;
+    var cropRect = null;
+    var cropFull = null;
+    var cropBefore = null;
 
-    var canvasEl, layerEl, framesEl, guideVEl, guideHEl, marqueeEl;
+    var canvasEl, layerEl, framesEl, guideVEl, guideHEl, marqueeEl, cropEl;
 
     /* ================= small utils ================= */
     function esc(t) { return OfficeApp.escapeHtml(t); }
@@ -199,10 +234,52 @@ var SlidesApp = (function () {
                 if (!o.props || typeof o.props !== "object") o.props = {};
             });
         });
+        if (!Array.isArray(b.fonts)) delete b.fonts;
+        installEmbeddedFonts(b.fonts);
         return b;
     }
 
+    /* A deck imported from a file may carry the font faces it was designed
+       in, so text renders in the right typeface on a machine that does not
+       have them installed. They go in one stylesheet for the whole page:
+       the editor, the thumbnails, present mode and print all share it. */
+    function installEmbeddedFonts(fonts) {
+        var el = document.getElementById("slEmbeddedFonts");
+        if (!fonts || !fonts.length) {
+            if (el) el.parentNode.removeChild(el);
+            return;
+        }
+        if (!el) {
+            el = document.createElement("style");
+            el.id = "slEmbeddedFonts";
+            document.head.appendChild(el);
+        }
+        var css = "";
+        fonts.forEach(function (f) {
+            if (!f || typeof f.src !== "string" || f.src.indexOf("data:") !== 0) return;
+            if (!f.family) return;
+            css += "@font-face{font-family:'" + String(f.family).replace(/['\\]/g, "") +
+                "';src:url(" + f.src + ");font-weight:" + (Number(f.weight) || 400) +
+                ";font-style:" + (f.style === "italic" ? "italic" : "normal") +
+                ";font-display:block;}\n";
+        });
+        el.textContent = css;
+    }
+
     /* ================= rendering: objects ================= */
+    /* Imported decks (pptx / odp) carry their own typography on the text
+       object: the CSS font stack the file asked for, the text-box insets,
+       the paragraph line height and the vertical anchor. Documents made in
+       the editor have none of those and fall back to the stylesheet. */
+    var VALIGN_JUSTIFY = { top: "flex-start", middle: "center", bottom: "flex-end" };
+
+    function padStyle(pad) {
+        if (!pad || pad.length !== 4) return "";
+        return "padding:" + pad.map(function (v) {
+            return (Number(v) || 0) + "px";
+        }).join(" ") + ";";
+    }
+
     function textStyle(p) {
         var s = "font-size:" + (Number(p.fontSize) || 24) + "px;";
         if (p.color) s += "color:" + esc(p.color) + ";";
@@ -210,9 +287,57 @@ var SlidesApp = (function () {
         if (p.bold) s += "font-weight:700;";
         if (p.italic) s += "font-style:italic;";
         if (p.underline) s += "text-decoration:underline;";
+        if (p.fontFamily) s += "font-family:" + esc(p.fontFamily) + ";";
+        if (p.lineHeight) s += "line-height:" + (Number(p.lineHeight) || 1.3) + ";";
+        s += padStyle(p.pad);
+        s += "justify-content:" + (VALIGN_JUSTIFY[p.valign] || "flex-start") + ";";
         return s;
     }
 
+    /* An imported picture may be cropped (pptx srcRect), have rounded
+       corners and be partly transparent. The crop is reproduced the way
+       PowerPoint defines it: the visible rectangle is scaled up to fill
+       the frame and the rest is clipped by the wrapper. */
+    function imageHtml(p) {
+        var imgS = "object-fit:" + esc(p.fit || "contain") + ";" + cropImgStyle(p.crop);
+        var wrapS = "";
+        if (p.radius) wrapS += "border-radius:" + (Number(p.radius) || 0) + "px;";
+        if (p.opacity) wrapS += "opacity:" + clamp(Number(p.opacity) || 1, 0, 1) + ";";
+        var clip = maskClipPath(p.mask);
+        if (clip) wrapS += "clip-path:" + clip + ";-webkit-clip-path:" + clip + ";";
+        return '<div class="sl-img-wrap" style="' + wrapS + '">' +
+            '<img draggable="false" src="' + esc(p.src || "") +
+            '" style="' + imgS + '" alt=""></div>';
+    }
+
+    /* The visible rectangle is scaled up to fill the frame and the rest is
+       clipped by the wrapper - the same definition PowerPoint's srcRect
+       uses, so an imported crop and one made here mean the same thing. */
+    function cropImgStyle(c) {
+        if (!c || c.length !== 4) return "";
+        var l = Number(c[0]) || 0, t = Number(c[1]) || 0;
+        var kw = 1 - l - (Number(c[2]) || 0);
+        var kh = 1 - t - (Number(c[3]) || 0);
+        if (!(kw > 0.001) || !(kh > 0.001)) return "";
+        return "position:absolute;object-fit:fill;" +
+            "width:" + (100 / kw) + "%;height:" + (100 / kh) + "%;" +
+            "left:" + (-l / kw * 100) + "%;top:" + (-t / kh * 100) + "%;";
+    }
+
+    /* A shaped crop ("mask image"): the picture is clipped to one of the
+       editor's shape outlines. shapePoints() already defines every polygon
+       shape, so asking it for a 100x100 box yields percentages directly. */
+    function maskClipPath(kind) {
+        if (!kind || kind === "rect") return "";
+        if (kind === "ellipse") return "ellipse(50% 50% at 50% 50%)";
+        if (kind === "round") return "";        // border-radius draws this one
+        var pts = shapePoints(kind, 100, 100);
+        if (!pts) return "";
+        return "polygon(" + pts.map(function (pt) {
+            return pt[0].toFixed(2) + "% " + pt[1].toFixed(2) + "%";
+        }).join(",") + ")";
+    }
+
     function shapePoints(kind, w, h) {
         var pts;
         switch (kind) {
@@ -225,6 +350,31 @@ var SlidesApp = (function () {
                        [w * 0.62, h], [w * 0.62, h * 0.7], [0, h * 0.7]]; break;
             case "chevron":
                 pts = [[0, 0], [w * 0.72, 0], [w, h / 2], [w * 0.72, h], [0, h], [w * 0.28, h / 2]]; break;
+            case "leftArrow":
+                pts = [[w, h * 0.3], [w * 0.38, h * 0.3], [w * 0.38, 0], [0, h / 2],
+                       [w * 0.38, h], [w * 0.38, h * 0.7], [w, h * 0.7]]; break;
+            case "upArrow":
+                pts = [[w * 0.3, h], [w * 0.3, h * 0.38], [0, h * 0.38], [w / 2, 0],
+                       [w, h * 0.38], [w * 0.7, h * 0.38], [w * 0.7, h]]; break;
+            case "downArrow":
+                pts = [[w * 0.3, 0], [w * 0.3, h * 0.62], [0, h * 0.62], [w / 2, h],
+                       [w, h * 0.62], [w * 0.7, h * 0.62], [w * 0.7, 0]]; break;
+            case "rtTriangle":
+                pts = [[0, 0], [w, h], [0, h]]; break;
+            case "pentagon":
+                pts = [[w / 2, 0], [w, h * 0.38], [w * 0.81, h], [w * 0.19, h], [0, h * 0.38]]; break;
+            case "hexagon":
+                pts = [[w * 0.25, 0], [w * 0.75, 0], [w, h / 2],
+                       [w * 0.75, h], [w * 0.25, h], [0, h / 2]]; break;
+            case "parallelogram":
+                pts = [[w * 0.25, 0], [w, 0], [w * 0.75, h], [0, h]]; break;
+            case "trapezoid":
+                pts = [[w * 0.25, 0], [w * 0.75, 0], [w, h], [0, h]]; break;
+            case "plus":
+                pts = [[w * 0.35, 0], [w * 0.65, 0], [w * 0.65, h * 0.35], [w, h * 0.35],
+                       [w, h * 0.65], [w * 0.65, h * 0.65], [w * 0.65, h], [w * 0.35, h],
+                       [w * 0.35, h * 0.65], [0, h * 0.65], [0, h * 0.35], [w * 0.35, h * 0.35]];
+                break;
             case "star":
                 pts = [];
                 var cx = w / 2, cy = h / 2, rx = w / 2, ry = h / 2, inner = 0.42;
@@ -244,13 +394,18 @@ var SlidesApp = (function () {
         var w = Math.max(4, o.w), h = Math.max(4, o.h);
         var p = o.props;
         var sw = Number(p.strokeW) || 0;
-        var attrs = 'fill="' + esc(p.fill || "#e07b1f") + '"' +
-            (sw > 0 ? ' stroke="' + esc(p.stroke || "#333333") + '" stroke-width="' + sw + '"' : ' stroke="none"') +
+        // an imported shape may legitimately have no fill (an outline-only
+        // box); only an editor-made shape with nothing set gets the default
+        var fill = p.fill || "#e07b1f";
+        var attrs = 'fill="' + esc(fill) + '"' +
+            (sw > 0 ? ' stroke="' + esc(p.stroke || "#333333") + '" stroke-width="' + sw + '"' +
+                (p.dash ? ' stroke-dasharray="' + (sw * 3) + " " + (sw * 2.4) + '"' : "") : ' stroke="none"') +
             ' stroke-linejoin="round" vector-effect="non-scaling-stroke"';
         var inner;
-        var i = Math.max(1, sw / 2 + 0.5);
+        var i = sw > 0 ? Math.max(0.5, sw / 2) : 0;
         if (o.props.kind === "rect" || o.props.kind === "round" || !o.props.kind) {
-            var rx = o.props.kind === "round" ? Math.min(w, h) * 0.15 : 0;
+            var rx = o.props.kind === "round"
+                ? (p.radius !== undefined ? Number(p.radius) : Math.min(w, h) * 0.15) : 0;
             inner = '<rect x="' + i + '" y="' + i + '" width="' + (w - 2 * i) + '" height="' + (h - 2 * i) +
                 '" rx="' + rx + '" ' + attrs + "/>";
         } else if (o.props.kind === "ellipse") {
@@ -270,16 +425,39 @@ var SlidesApp = (function () {
         var s = "font-size:" + (Number(p.fontSize) || 18) + "px;";
         s += "color:" + esc(p.textColor || contrastText(p.fill)) + ";";
         if (p.bold) s += "font-weight:700;";
+        if (p.italic) s += "font-style:italic;";
+        if (p.fontFamily) s += "font-family:" + esc(p.fontFamily) + ";";
+        if (p.lineHeight) s += "line-height:" + (Number(p.lineHeight) || 1.25) + ";";
+        // an imported shape carries the same rich paragraph HTML a text
+        // object does, plus the alignment and insets its source stated
+        if (p.html) {
+            s += "text-align:" + esc(p.align || "center") + ";";
+            s += "justify-content:" + (VALIGN_JUSTIFY[p.valign] || "center") + ";";
+            s += padStyle(p.pad);
+            return '<div class="sl-shape-text sl-shape-rich" style="' + s + '">' + p.html + "</div>";
+        }
         return '<div class="sl-shape-text" style="' + s + '">' + esc(p.text || "") + "</div>";
     }
 
+    /* A line is normally two points: its origin and the vector in o.w/o.h.
+       A connector imported from a pptx may bend, and then carries the whole
+       polyline in props.points (relative to o.x/o.y) with o.w/o.h still
+       spanning end to end, so selection and dragging keep working. */
+    function linePoints(o) {
+        var p = o.props && o.props.points;
+        if (p && p.length >= 2) {
+            return p.map(function (pt) { return [Number(pt[0]) || 0, Number(pt[1]) || 0]; });
+        }
+        return [[0, 0], [o.w, o.h]];
+    }
     function lineBBox(o) {
-        return {
-            x: o.x + Math.min(0, o.w),
-            y: o.y + Math.min(0, o.h),
-            w: Math.abs(o.w),
-            h: Math.abs(o.h)
-        };
+        var pts = linePoints(o);
+        var x0 = pts[0][0], y0 = pts[0][1], x1 = x0, y1 = y0;
+        pts.forEach(function (pt) {
+            x0 = Math.min(x0, pt[0]); x1 = Math.max(x1, pt[0]);
+            y0 = Math.min(y0, pt[1]); y1 = Math.max(y1, pt[1]);
+        });
+        return { x: o.x + x0, y: o.y + y0, w: x1 - x0, h: y1 - y0 };
     }
     function positionLineEl(el, o) {
         var bb = lineBBox(o);
@@ -292,28 +470,43 @@ var SlidesApp = (function () {
         var p = o.props;
         var sw = Number(p.strokeW) || 2;
         var stroke = p.stroke || "#202124";
-        var x1 = Math.max(0, -o.w), y1 = Math.max(0, -o.h);
-        var x2 = x1 + o.w, y2 = y1 + o.h;
-        var out = '<svg xmlns="http://www.w3.org/2000/svg" style="overflow:visible;" width="100%" height="100%">';
-        // generous transparent hit area
-        out += '<line x1="' + x1 + '" y1="' + y1 + '" x2="' + x2 + '" y2="' + y2 +
-            '" stroke="rgba(0,0,0,0)" stroke-width="' + Math.max(14, sw + 10) + '"/>';
-        var ex = x2, ey = y2;
+        // draw in the element's own box: shift the polyline so its
+        // top-left corner sits at 0,0
+        var pts = linePoints(o);
+        var ox = 0, oy = 0;
+        pts.forEach(function (pt) { ox = Math.min(ox, pt[0]); oy = Math.min(oy, pt[1]); });
+        pts = pts.map(function (pt) { return [pt[0] - ox, pt[1] - oy]; });
         var head = "";
-        if (p.arrowEnd) {
-            var ang = Math.atan2(y2 - y1, x2 - x1);
+        var first = pts[0], last = pts[pts.length - 1];
+        var trimmed = pts.slice();
+
+        function arrowAt(tip, from) {
+            var ang = Math.atan2(tip[1] - from[1], tip[0] - from[0]);
             var s = 6 + sw * 2.4;
-            var bx = x2 - s * Math.cos(ang), by = y2 - s * Math.sin(ang);
+            var bx = tip[0] - s * Math.cos(ang), by = tip[1] - s * Math.sin(ang);
             var px = s * 0.45 * -Math.sin(ang), py = s * 0.45 * Math.cos(ang);
-            head = '<polygon points="' + x2.toFixed(1) + "," + y2.toFixed(1) + " " +
+            head += '<polygon points="' + tip[0].toFixed(1) + "," + tip[1].toFixed(1) + " " +
                 (bx + px).toFixed(1) + "," + (by + py).toFixed(1) + " " +
                 (bx - px).toFixed(1) + "," + (by - py).toFixed(1) +
                 '" fill="' + esc(stroke) + '"/>';
-            ex = x2 - s * 0.6 * Math.cos(ang);
-            ey = y2 - s * 0.6 * Math.sin(ang);
+            // pull the stroke back so it does not poke through the head
+            return [tip[0] - s * 0.6 * Math.cos(ang), tip[1] - s * 0.6 * Math.sin(ang)];
+        }
+        if (p.arrowEnd) trimmed[trimmed.length - 1] = arrowAt(last, pts[pts.length - 2]);
+        if (p.arrowStart) trimmed[0] = arrowAt(first, pts[1]);
+
+        function poly(list) {
+            return list.map(function (pt) {
+                return pt[0].toFixed(1) + "," + pt[1].toFixed(1);
+            }).join(" ");
         }
-        out += '<line x1="' + x1 + '" y1="' + y1 + '" x2="' + ex + '" y2="' + ey +
-            '" stroke="' + esc(stroke) + '" stroke-width="' + sw + '" stroke-linecap="round"' +
+        var out = '<svg xmlns="http://www.w3.org/2000/svg" style="overflow:visible;" width="100%" height="100%">';
+        // generous transparent hit area
+        out += '<polyline points="' + poly(pts) + '" fill="none" ' +
+            'stroke="rgba(0,0,0,0)" stroke-width="' + Math.max(14, sw + 10) + '"/>';
+        out += '<polyline points="' + poly(trimmed) + '" fill="none"' +
+            ' stroke="' + esc(stroke) + '" stroke-width="' + sw +
+            '" stroke-linecap="round" stroke-linejoin="round"' +
             (p.dash ? ' stroke-dasharray="' + (sw * 3) + " " + (sw * 2.4) + '"' : "") + "/>";
         out += head + "</svg>";
         return out;
@@ -390,13 +583,18 @@ var SlidesApp = (function () {
             out += '<col style="width:' + wPct + '%">';
         }
         out += "</colgroup>";
+        // an imported table states its own cell shading and insets
+        var cellPad = padStyle(p.cellPad);
         rows.forEach(function (r, ri) {
             var isHead = p.headerRow && ri === 0;
             var trStyle = (p.rowH && p.rowH[ri] !== undefined) ? ' style="height:' + p.rowH[ri] + '%;"' : "";
             out += '<tr class="' + (isHead ? "sl-thead" : "") + '"' + trStyle + ">";
             r.forEach(function (cell, ci) {
+                var bg = (p.cellFill && p.cellFill[ri]) ? p.cellFill[ri][ci] : "";
+                if (!bg && isHead) bg = headBg;
+                var tdStyle = cellPad + (bg ? "background:" + esc(bg) + ";" : "");
                 out += '<td data-r="' + ri + '" data-c="' + ci + '"' +
-                    (isHead ? ' style="background:' + headBg + ';"' : "") + ">" +
+                    (tdStyle ? ' style="' + tdStyle + '"' : "") + ">" +
                     sanitizeCellHtml(cell) + "</td>";
             });
             out += "</tr>";
@@ -426,8 +624,7 @@ var SlidesApp = (function () {
                     (o.props.html || "") + "</div>";
                 break;
             case "image":
-                d.innerHTML = '<img draggable="false" src="' + esc(o.props.src || "") +
-                    '" style="object-fit:' + esc(o.props.fit || "contain") + ';" alt="">';
+                d.innerHTML = imageHtml(o.props);
                 break;
             case "shape":
                 d.innerHTML = shapeSvg(o) + shapeTextDiv(o);
@@ -490,6 +687,12 @@ var SlidesApp = (function () {
     function renderOverlay() {
         if (!framesEl) return;
         framesEl.innerHTML = "";
+        if (cropId) {
+            // the crop tool replaces the selection frame while it is open
+            renderCropOverlay();
+            return;
+        }
+        if (cropEl) cropEl.innerHTML = "";
         var s = curScale() || 1;
         var hs = Math.max(7, 10 / s);
         var bw = Math.max(1, 1.6 / s);
@@ -506,9 +709,12 @@ var SlidesApp = (function () {
             if (sel.length === 1) {
                 if (o.type === "line") {
                     fr.className += " sl-frame-line";
-                    var x1 = Math.max(0, -o.w), y1 = Math.max(0, -o.h);
-                    fr.appendChild(mkHandle("p1", x1, y1, hs));
-                    fr.appendChild(mkHandle("p2", x1 + o.w, y1 + o.h, hs));
+                    // handles sit on the real endpoints, which for a bent
+                    // connector are the ends of its polyline
+                    var lp = linePoints(o);
+                    fr.appendChild(mkHandle("p1", lp[0][0] - (bb.x - o.x), lp[0][1] - (bb.y - o.y), hs));
+                    fr.appendChild(mkHandle("p2", lp[lp.length - 1][0] - (bb.x - o.x),
+                        lp[lp.length - 1][1] - (bb.y - o.y), hs));
                 } else {
                     var w = bb.w, hgt = bb.h;
                     [["nw", 0, 0], ["n", w / 2, 0], ["ne", w, 0], ["e", w, hgt / 2],
@@ -531,6 +737,202 @@ var SlidesApp = (function () {
         });
     }
 
+    /* ================= image crop tool =================
+       Cropping is a view onto the picture, never a change to its pixels:
+       the object frame states which part is visible and props.crop states
+       which part of the source that is. While the tool is open the whole
+       picture is shown ghosted, with the part that will be kept drawn at
+       full strength on top - so dragging a handle shrinks the visible
+       window and dragging the picture slides it behind that window. */
+
+    // fullImageRect returns where the whole picture sits, in slide units,
+    // given the frame and crop an object currently has
+    function fullImageRect(o) {
+        var c = o.props.crop;
+        var l = 0, t = 0, kw = 1, kh = 1;
+        if (c && c.length === 4) {
+            l = Number(c[0]) || 0;
+            t = Number(c[1]) || 0;
+            kw = 1 - l - (Number(c[2]) || 0);
+            kh = 1 - t - (Number(c[3]) || 0);
+        }
+        if (!(kw > 0.001) || !(kh > 0.001)) { l = 0; t = 0; kw = 1; kh = 1; }
+        var fw = o.w / kw, fh = o.h / kh;
+        return { x: o.x - l * fw, y: o.y - t * fh, w: fw, h: fh };
+    }
+
+    function startCrop(id) {
+        var o = objById(id);
+        if (!o || o.type !== "image") return;
+        if (editingId) endEdit(true);
+        if (cropId && cropId !== id) endCrop(true);
+        setSel([id]);
+        cropId = id;
+        cropBefore = { x: o.x, y: o.y, w: o.w, h: o.h,
+                       crop: o.props.crop ? o.props.crop.slice() : null };
+        cropFull = fullImageRect(o);
+        cropRect = { x: o.x, y: o.y, w: o.w, h: o.h };
+        renderOverlay();
+        syncToolbarFromSel();
+        OfficeApp.setStatus(
+            "Crop: drag the handles to trim, drag the picture to reposition, " +
+            "Enter to apply, Esc to cancel", "info", 6000);
+    }
+
+    function endCrop(apply) {
+        if (!cropId) return;
+        var o = objById(cropId);
+        cropId = null;
+        if (o) {
+            if (apply) {
+                var l = (cropRect.x - cropFull.x) / cropFull.w;
+                var t = (cropRect.y - cropFull.y) / cropFull.h;
+                var r = 1 - (cropRect.x + cropRect.w - cropFull.x) / cropFull.w;
+                var b = 1 - (cropRect.y + cropRect.h - cropFull.y) / cropFull.h;
+                var crop = [l, t, r, b].map(function (v) {
+                    return Math.round(clamp(v, 0, 0.99) * 10000) / 10000;
+                });
+                var cropped = crop.some(function (v) { return v > 0.0005; });
+                // the frame the whole picture would fill is what Reset image
+                // puts back, so it is stamped the first time one is trimmed
+                if (cropped && !o.props.orig) {
+                    o.props.orig = {
+                        x: Math.round(cropFull.x * 100) / 100,
+                        y: Math.round(cropFull.y * 100) / 100,
+                        w: Math.round(cropFull.w * 100) / 100,
+                        h: Math.round(cropFull.h * 100) / 100
+                    };
+                }
+                o.x = cropRect.x; o.y = cropRect.y;
+                o.w = cropRect.w; o.h = cropRect.h;
+                if (cropped) o.props.crop = crop; else delete o.props.crop;
+                commit();
+            } else {
+                o.x = cropBefore.x; o.y = cropBefore.y;
+                o.w = cropBefore.w; o.h = cropBefore.h;
+                if (cropBefore.crop) o.props.crop = cropBefore.crop;
+                else delete o.props.crop;
+                renderEditorSlide();
+            }
+        }
+        cropRect = cropFull = cropBefore = null;
+        renderOverlay();
+        syncToolbarFromSel();
+    }
+
+    var CROP_HANDLES = [
+        ["nw", 0, 0], ["n", 0.5, 0], ["ne", 1, 0], ["e", 1, 0.5],
+        ["se", 1, 1], ["s", 0.5, 1], ["sw", 0, 1], ["w", 0, 0.5]
+    ];
+
+    function renderCropOverlay() {
+        if (!cropEl) return;
+        var o = objById(cropId);
+        if (!o) { cropEl.innerHTML = ""; return; }
+        // the picture itself is hidden while the tool is open, so what is
+        // on screen is only the ghost and the part being kept
+        var srcEl = objEl(cropId);
+        if (srcEl) srcEl.classList.add("sl-cropping");
+        var s = curScale() || 1;
+        var src = esc(o.props.src || "");
+        var box = function (r) {
+            return "left:" + r.x + "px;top:" + r.y + "px;" +
+                "width:" + Math.max(1, r.w) + "px;height:" + Math.max(1, r.h) + "px;";
+        };
+        var html = '<div class="sl-crop-ghost" style="' + box(cropFull) + '">' +
+            '<img draggable="false" src="' + src + '" alt=""></div>';
+        // the kept part: the same picture, positioned so it lines up with
+        // the ghost behind it, clipped by the crop rectangle
+        html += '<div class="sl-crop-rect" style="' + box(cropRect) + '">' +
+            '<img draggable="false" src="' + src + '" alt="" style="' +
+            "left:" + (cropFull.x - cropRect.x) + "px;top:" + (cropFull.y - cropRect.y) + "px;" +
+            "width:" + cropFull.w + "px;height:" + cropFull.h + 'px;">';
+        // corner grips are drawn as an L hugging the corner, edge grips as
+        // a bar centred on the edge - the same language Slides/Docs use
+        var len = Math.min(Math.max(9, 14 / s), Math.min(cropRect.w, cropRect.h) / 2);
+        var th = Math.max(2.5, 4 / s);
+        CROP_HANDLES.forEach(function (h) {
+            var name = h[0];
+            var left, top, w, hgt, extra = "";
+            if (name === "n" || name === "s") {
+                w = len; hgt = th;
+                left = cropRect.w / 2 - len / 2;
+                top = name === "n" ? 0 : cropRect.h - th;
+            } else if (name === "e" || name === "w") {
+                w = th; hgt = len;
+                left = name === "w" ? 0 : cropRect.w - th;
+                top = cropRect.h / 2 - len / 2;
+            } else {
+                w = len; hgt = len;
+                left = name.indexOf("w") >= 0 ? 0 : cropRect.w - len;
+                top = name.indexOf("n") >= 0 ? 0 : cropRect.h - len;
+                extra = "background:transparent;" +
+                    "border-" + (name.indexOf("n") >= 0 ? "top" : "bottom") +
+                    ":" + th + "px solid #202124;" +
+                    "border-" + (name.indexOf("w") >= 0 ? "left" : "right") +
+                    ":" + th + "px solid #202124;";
+            }
+            html += '<div class="sl-croph" data-ch="' + name + '" style="' +
+                "left:" + left + "px;top:" + top + "px;" +
+                "width:" + w + "px;height:" + hgt + "px;" + extra + '"></div>';
+        });
+        html += "</div>";
+        cropEl.innerHTML = html;
+    }
+
+    /* Reset image: undo every crop and shaped crop and put the picture
+       back the way it came in. props.orig remembers the frame the whole
+       picture filled when it was first trimmed; without one (a picture
+       that was only masked) the frame stays where it is and only its
+       height is corrected to the source's own aspect ratio. */
+    function resetImage(o) {
+        if (!o || o.type !== "image") return;
+        if (cropId === o.id) endCrop(false);
+        var full = fullImageRect(o);
+        delete o.props.crop;
+        delete o.props.mask;
+        delete o.props.radius;
+        if (o.props.orig) {
+            o.x = o.props.orig.x; o.y = o.props.orig.y;
+            o.w = o.props.orig.w; o.h = o.props.orig.h;
+            delete o.props.orig;
+        } else {
+            o.x = full.x; o.y = full.y; o.w = full.w; o.h = full.h;
+        }
+        var nat = naturalSizeOf(o);
+        if (nat && nat.w > 0 && nat.h > 0) {
+            // a picture stretched by dragging a corner is undistorted too
+            o.h = Math.max(8, o.w * nat.h / nat.w);
+        }
+        commit();
+        OfficeApp.setStatus("Image reset", "success", 2000);
+    }
+
+    // naturalSizeOf reads the source's own pixel size off the live <img>,
+    // which is already decoded because the object is on screen
+    function naturalSizeOf(o) {
+        var el = objEl(o.id);
+        var img = el ? el.querySelector("img") : null;
+        if (img && img.naturalWidth > 0) {
+            return { w: img.naturalWidth, h: img.naturalHeight };
+        }
+        return null;
+    }
+
+    function setImageMask(o, kind) {
+        if (!o || o.type !== "image") return;
+        if (cropId === o.id) endCrop(true);
+        if (!kind || kind === "rect") {
+            delete o.props.mask;
+            delete o.props.radius;
+        } else {
+            o.props.mask = kind;
+            if (kind === "round") o.props.radius = Math.min(o.w, o.h) * 0.15;
+            else delete o.props.radius;
+        }
+        commit();
+    }
+
     /* ================= rendering: rail / thumbnails ================= */
     function renderThumb(i) {
         var $mini = $("#slThumbs .sl-thumb").eq(i).find(".sl-thumb-mini");
@@ -750,6 +1152,7 @@ var SlidesApp = (function () {
             updateRailActive();
             return;
         }
+        endCrop(true);
         endEdit(true);
         cur = clamp(i, 0, body.slides.length - 1);
         sel = [];
@@ -834,6 +1237,7 @@ var SlidesApp = (function () {
     }
     function deleteSelection() {
         if (!sel.length) return;
+        endCrop(false);
         endEdit(false);
         var slide = curSlide();
         slide.objects = slide.objects.filter(function (o) { return sel.indexOf(o.id) < 0; });
@@ -1658,6 +2062,7 @@ var SlidesApp = (function () {
     function startEdit(id) {
         var o = objById(id);
         if (!o) return;
+        endCrop(true);
         if (editingId && editingId !== id) endEdit(true);
         var el = objEl(id);
         if (!el) return;
@@ -1826,6 +2231,34 @@ var SlidesApp = (function () {
         OfficeApp.closeAllMenus();
         var pt = toSlideXY(e);
 
+        // crop mode owns every press until it is closed
+        if (cropId) {
+            if (e.target.classList && e.target.classList.contains("sl-croph")) {
+                drag = {
+                    mode: "crophandle", h: e.target.getAttribute("data-ch"),
+                    start: pt, moved: false,
+                    g: { x: cropRect.x, y: cropRect.y, w: cropRect.w, h: cropRect.h }
+                };
+                try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
+                e.preventDefault();
+                return;
+            }
+            if (e.target.closest && e.target.closest(".sl-crop-rect, .sl-crop-ghost")) {
+                drag = {
+                    mode: "croppan", start: pt, moved: false,
+                    g: { x: cropFull.x, y: cropFull.y }
+                };
+                try { canvasEl.setPointerCapture(e.pointerId); } catch (err) { }
+                e.preventDefault();
+                return;
+            }
+            // a press anywhere else closes the tool; the next click then
+            // does whatever it was going to do, against a settled DOM
+            endCrop(true);
+            e.preventDefault();
+            return;
+        }
+
         // table column/row resize bars (present in table edit mode)
         if (e.target.classList && e.target.classList.contains("sl-tbl-rz")) {
             var rzHost = e.target.closest(".sl-obj");
@@ -2032,10 +2465,46 @@ var SlidesApp = (function () {
                 renderOverlay();
                 break;
             }
+            case "crophandle": {
+                if (!cropRect || !cropFull) return;
+                g = drag.g;
+                var MINC = 8;
+                var nx = g.x, ny = g.y, nw = g.w, nh = g.h;
+                var name = drag.h;
+                if (name.indexOf("w") >= 0) {
+                    nx = clamp(g.x + dx, cropFull.x, g.x + g.w - MINC);
+                    nw = g.x + g.w - nx;
+                } else if (name.indexOf("e") >= 0) {
+                    nw = clamp(g.w + dx, MINC, cropFull.x + cropFull.w - g.x);
+                }
+                if (name.indexOf("n") >= 0) {
+                    ny = clamp(g.y + dy, cropFull.y, g.y + g.h - MINC);
+                    nh = g.y + g.h - ny;
+                } else if (name.indexOf("s") >= 0) {
+                    nh = clamp(g.h + dy, MINC, cropFull.y + cropFull.h - g.y);
+                }
+                cropRect = { x: nx, y: ny, w: nw, h: nh };
+                renderCropOverlay();
+                break;
+            }
+            case "croppan": {
+                if (!cropRect || !cropFull) return;
+                // the picture slides behind the window, so the window must
+                // stay inside the picture
+                cropFull.x = clamp(drag.g.x + dx,
+                    cropRect.x + cropRect.w - cropFull.w, cropRect.x);
+                cropFull.y = clamp(drag.g.y + dy,
+                    cropRect.y + cropRect.h - cropFull.h, cropRect.y);
+                renderCropOverlay();
+                break;
+            }
             case "lineend": {
                 o = objById(drag.id);
                 if (!o) return;
                 g = drag.g;
+                // dragging an endpoint straightens an imported bent
+                // connector - the editor only draws two-point lines
+                if (o.props && o.props.points) delete o.props.points;
                 if (drag.h === "p2") {
                     var e2x = g.x + g.w + dx, e2y = g.y + g.h + dy;
                     if (snapGrid) { e2x = Math.round(e2x / GRID) * GRID; e2y = Math.round(e2y / GRID) * GRID; }
@@ -2139,6 +2608,10 @@ var SlidesApp = (function () {
             if (d.moved) commit();
             return;
         }
+        if (d.mode === "crophandle" || d.mode === "croppan") {
+            // the crop tool stays open until it is applied or cancelled
+            return;
+        }
         if (d.mode === "move" && !d.moved) {
             if (d.pendingToggle) {
                 setSel(sel.filter(function (id) { return id !== d.pendingToggle; }));
@@ -2164,6 +2637,7 @@ var SlidesApp = (function () {
         if (!o) return;
         if (o.type === "text" || o.type === "shape" || o.type === "table") startEdit(id);
         else if (o.type === "chart") chartDialog(o);
+        else if (o.type === "image") startCrop(id);
     }
 
     /* ================= context menus ================= */
@@ -2266,6 +2740,30 @@ var SlidesApp = (function () {
             }
             if (o.type === "image") {
                 items.push({ sep: true });
+                items.push({
+                    label: "Crop image", icon: "crop",
+                    action: function () { startCrop(o.id); }
+                });
+                items.push({
+                    label: "Mask image", icon: "object ungroup outline",
+                    sub: [{
+                        label: "None (rectangle)",
+                        checked: function () { return !o.props.mask; },
+                        action: function () { setImageMask(o, ""); }
+                    }, { sep: true }].concat(SHAPE_KINDS.filter(function (s) {
+                        return s.kind !== "rect";
+                    }).map(function (s) {
+                        return {
+                            label: s.label,
+                            checked: function () { return o.props.mask === s.kind; },
+                            action: function () { setImageMask(o, s.kind); }
+                        };
+                    }))
+                });
+                items.push({
+                    label: "Reset image", icon: "history",
+                    action: function () { resetImage(o); }
+                });
                 items.push({
                     label: "Image fit", icon: "image outline", sub: ["contain", "cover", "fill"].map(function (f) {
                         return {
@@ -2322,7 +2820,7 @@ var SlidesApp = (function () {
         var HK = OfficeHotkeys;
         var GS = "Slides", GO = "Objects", GT = "Text editing";
         var notPresenting = function () { return !presActive(); };
-        var editorIdle = function () { return !presActive() && !editingId; };
+        var editorIdle = function () { return !presActive() && !editingId && !cropId; };
 
         HK.register("F5", function () { endEdit(true); startPresent(cur); },
             { id: "sl.present", description: "Start presentation", group: GS, allowInInput: true, when: notPresenting });
@@ -2352,11 +2850,17 @@ var SlidesApp = (function () {
         HK.register("Backspace", function () { deleteSelection(); },
             { id: "sl.delete2", when: function () { return editorIdle() && sel.length > 0; } });
         HK.register("Escape", function () {
+            if (cropId) { endCrop(false); return; }
             if (editingId) { endEdit(true); return; }
             if (pendingDraw) { disarmDraw(); return; }
             if (sel.length) { setSel([]); return; }
             return false;
         }, { id: "sl.escape", allowInInput: true, when: notPresenting });
+        HK.register("Enter", function () {
+            if (!cropId) return false;
+            endCrop(true);
+        }, { id: "sl.cropapply", description: "Apply crop", group: GO,
+             when: function () { return !presActive() && !!cropId; } });
 
         // arrows: nudge the selection (Shift = 10 px) or walk the deck
         ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].forEach(function (k) {
@@ -2571,6 +3075,34 @@ var SlidesApp = (function () {
         }, "slBtnArrow"));
         $tb.append(tbtn("table", "Insert table", tableDialog));
         $tb.append(tbtn("chart bar", "Insert chart", function () { chartDialog(null); }));
+        // picture tools: only meaningful with an image selected, so they
+        // are hidden until there is one (syncToolbarFromSel)
+        $tb.append(tbtn("crop", "Crop image", function () {
+            var io = selectedImage();
+            if (io) { if (cropId === io.id) endCrop(true); else startCrop(io.id); }
+        }, "slBtnCrop"));
+        $tb.append(tbtn("object ungroup outline", "Mask image to a shape", function (e) {
+            var io = selectedImage();
+            if (!io) return;
+            var r = e.currentTarget.getBoundingClientRect();
+            OfficeApp.showContextMenu(r.left, r.bottom + 4, [{
+                label: "None (rectangle)",
+                checked: function () { return !io.props.mask; },
+                action: function () { setImageMask(io, ""); }
+            }, { sep: true }].concat(SHAPE_KINDS.filter(function (s) {
+                return s.kind !== "rect";
+            }).map(function (s) {
+                return {
+                    label: s.label,
+                    checked: function () { return io.props.mask === s.kind; },
+                    action: function () { setImageMask(io, s.kind); }
+                };
+            })));
+        }, "slBtnMask"));
+        $tb.append(tbtn("history", "Reset image", function () {
+            var io = selectedImage();
+            if (io) resetImage(io);
+        }, "slBtnResetImg"));
         $tb.append('<div class="of-tsep"></div>');
 
         var $fs = $('<input type="number" class="of-tinput sl-num" id="slFontSize" min="6" max="200" step="1" title="Font size" value="24">');
@@ -2707,9 +3239,18 @@ var SlidesApp = (function () {
         $tb.append($present);
     }
 
+    // selectedImage returns the lone selected picture, or null
+    function selectedImage() {
+        var so = selObjs();
+        return (so.length === 1 && so[0].type === "image") ? so[0] : null;
+    }
+
     function syncToolbarFromSel() {
         var so = selObjs();
         var o = so.length ? so[0] : null;
+        var isImg = !!selectedImage();
+        $("#slBtnCrop, #slBtnMask, #slBtnResetImg").toggle(isImg);
+        $("#slBtnCrop").toggleClass("active", !!cropId);
         if (!o) return;
         var p = o.props;
         if (o.type === "text" || o.type === "shape" || o.type === "table") {
@@ -3216,10 +3757,12 @@ var SlidesApp = (function () {
         layerEl.className = "sl-slidebase";
         var overlay = document.getElementById("slOverlay");
         overlay.innerHTML = '<div id="slFrames"></div>' +
+            '<div id="slCrop"></div>' +
             '<div id="slGuideV" class="sl-guide"></div>' +
             '<div id="slGuideH" class="sl-guide"></div>' +
             '<div id="slMarquee"></div>';
         framesEl = document.getElementById("slFrames");
+        cropEl = document.getElementById("slCrop");
         guideVEl = document.getElementById("slGuideV");
         guideHEl = document.getElementById("slGuideH");
         marqueeEl = document.getElementById("slMarquee");

Some files were not shown because too many files changed in this diff