reader.go 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273
  1. package pptx
  2. /*
  3. reader.go - Parse a PowerPoint (.pptx) file into a Presentation.
  4. The goal is that a deck authored in PowerPoint or Google Slides looks
  5. the same in the Slides webapp as it does in the application it came
  6. from. That means resolving the parts of PresentationML that decide what
  7. a slide actually looks like, not just the ones a shape states outright:
  8. - theme colours (schemeClr) through the master's colour map, with the
  9. lumMod / lumOff / shade / tint transforms applied
  10. - placeholder inheritance: a shape with no position, size, body
  11. properties or text style takes them from the matching placeholder
  12. on its layout, and failing that on the master
  13. - per-run and per-paragraph formatting, bullets, indents, line
  14. spacing, paragraph spacing, vertical anchoring and text insets
  15. - autofit font scaling (normAutofit), which is how a deck keeps
  16. oversized text inside its box
  17. - group shapes, with the child coordinate transform (which sizes the
  18. children but never their type)
  19. - picture cropping (srcRect) and rounded picture frames
  20. - backgrounds of every kind, gradient and translucent fills, picture
  21. fills (fill.go), table styles and merged cells (table.go),
  22. custom geometry (custgeom.go), SmartArt (from the drawing
  23. PowerPoint stores with it) and simple inline Office math
  24. Everything is scaled from the source slide size into the coordinate
  25. space of the Slides editor: 960 px wide and as tall as the deck's shape
  26. (540 for 16:9, 720 for 4:3), so the scale is the same both ways.
  27. Anything the editor cannot model - 3D effects, animations - is skipped
  28. rather than approximated badly.
  29. */
  30. import (
  31. "archive/zip"
  32. "bytes"
  33. "errors"
  34. "fmt"
  35. "io"
  36. "math"
  37. "path"
  38. "strconv"
  39. "strings"
  40. "imuslab.com/arozos/mod/office/internal/fonts"
  41. "imuslab.com/arozos/mod/office/internal/media"
  42. "imuslab.com/arozos/mod/office/internal/units"
  43. "imuslab.com/arozos/mod/office/internal/xmltree"
  44. "imuslab.com/arozos/mod/office/metafile"
  45. "imuslab.com/arozos/mod/office/model"
  46. )
  47. // prstToShapeKind maps a PresentationML preset geometry onto the shape the
  48. // editor draws for it. The editor's catalogue
  49. // (web/Office/slides/slides_shapes.js) uses these very names, so most of
  50. // this table is an identity - it exists to say which presets are covered,
  51. // and to send the ones that are not to the nearest outline that is. Keep
  52. // it in step with that file.
  53. var prstToShapeKind = map[string]string{
  54. // drawn as themselves
  55. "rect": "rect",
  56. "roundRect": "roundRect",
  57. "snip1Rect": "snip1Rect",
  58. "snip2SameRect": "snip2SameRect",
  59. "snip2DiagRect": "snip2DiagRect",
  60. "round1Rect": "round1Rect",
  61. "round2SameRect": "round2SameRect",
  62. "round2DiagRect": "round2DiagRect",
  63. "ellipse": "ellipse",
  64. "triangle": "triangle",
  65. "rtTriangle": "rtTriangle",
  66. "parallelogram": "parallelogram",
  67. "trapezoid": "trapezoid",
  68. "diamond": "diamond",
  69. "pentagon": "pentagon",
  70. "hexagon": "hexagon",
  71. "heptagon": "heptagon",
  72. "octagon": "octagon",
  73. "decagon": "decagon",
  74. "dodecagon": "dodecagon",
  75. "plus": "plus",
  76. "teardrop": "teardrop",
  77. "frame": "frame",
  78. "halfFrame": "halfFrame",
  79. "corner": "corner",
  80. "diagStripe": "diagStripe",
  81. "plaque": "plaque",
  82. "can": "can",
  83. "cube": "cube",
  84. "bevel": "bevel",
  85. "donut": "donut",
  86. "noSmoking": "noSmoking",
  87. "blockArc": "blockArc",
  88. "foldedCorner": "foldedCorner",
  89. "smileyFace": "smileyFace",
  90. "heart": "heart",
  91. "lightningBolt": "lightningBolt",
  92. "sun": "sun",
  93. "moon": "moon",
  94. "cloud": "cloud",
  95. "arc": "arc",
  96. "chord": "chord",
  97. "pie": "pie",
  98. "flowChartProcess": "flowChartProcess",
  99. "flowChartAlternateProcess": "flowChartAlternateProcess",
  100. "flowChartDecision": "flowChartDecision",
  101. "flowChartInputOutput": "flowChartInputOutput",
  102. "flowChartPredefinedProcess": "flowChartPredefinedProcess",
  103. "flowChartInternalStorage": "flowChartInternalStorage",
  104. "flowChartDocument": "flowChartDocument",
  105. "flowChartMultidocument": "flowChartMultidocument",
  106. "flowChartTerminator": "flowChartTerminator",
  107. "flowChartPreparation": "flowChartPreparation",
  108. "flowChartManualInput": "flowChartManualInput",
  109. "flowChartManualOperation": "flowChartManualOperation",
  110. "flowChartConnector": "flowChartConnector",
  111. "flowChartOffpageConnector": "flowChartOffpageConnector",
  112. "flowChartPunchedCard": "flowChartPunchedCard",
  113. "flowChartPunchedTape": "flowChartPunchedTape",
  114. "flowChartSummingJunction": "flowChartSummingJunction",
  115. "flowChartOr": "flowChartOr",
  116. "flowChartCollate": "flowChartCollate",
  117. "flowChartSort": "flowChartSort",
  118. "flowChartExtract": "flowChartExtract",
  119. "flowChartMerge": "flowChartMerge",
  120. "flowChartDelay": "flowChartDelay",
  121. "flowChartMagneticDisk": "flowChartMagneticDisk",
  122. "flowChartDisplay": "flowChartDisplay",
  123. "rightArrow": "rightArrow",
  124. "leftArrow": "leftArrow",
  125. "upArrow": "upArrow",
  126. "downArrow": "downArrow",
  127. "leftRightArrow": "leftRightArrow",
  128. "upDownArrow": "upDownArrow",
  129. "quadArrow": "quadArrow",
  130. "leftRightUpArrow": "leftRightUpArrow",
  131. "bentArrow": "bentArrow",
  132. "uturnArrow": "uturnArrow",
  133. "leftUpArrow": "leftUpArrow",
  134. "bentUpArrow": "bentUpArrow",
  135. "stripedRightArrow": "stripedRightArrow",
  136. "notchedRightArrow": "notchedRightArrow",
  137. "chevron": "chevron",
  138. "homePlate": "homePlate",
  139. "curvedRightArrow": "curvedRightArrow",
  140. "curvedLeftArrow": "curvedLeftArrow",
  141. "curvedUpArrow": "curvedUpArrow",
  142. "curvedDownArrow": "curvedDownArrow",
  143. "circularArrow": "circularArrow",
  144. "rightArrowCallout": "rightArrowCallout",
  145. "leftArrowCallout": "leftArrowCallout",
  146. "upArrowCallout": "upArrowCallout",
  147. "downArrowCallout": "downArrowCallout",
  148. "leftRightArrowCallout": "leftRightArrowCallout",
  149. "star4": "star4",
  150. "star5": "star5",
  151. "star6": "star6",
  152. "star7": "star7",
  153. "star8": "star8",
  154. "star10": "star10",
  155. "star12": "star12",
  156. "star16": "star16",
  157. "star24": "star24",
  158. "star32": "star32",
  159. "irregularSeal1": "irregularSeal1",
  160. "irregularSeal2": "irregularSeal2",
  161. "ribbon": "ribbon",
  162. "ribbon2": "ribbon2",
  163. "wave": "wave",
  164. "doubleWave": "doubleWave",
  165. "verticalScroll": "verticalScroll",
  166. "horizontalScroll": "horizontalScroll",
  167. "wedgeRectCallout": "wedgeRectCallout",
  168. "wedgeRoundRectCallout": "wedgeRoundRectCallout",
  169. "wedgeEllipseCallout": "wedgeEllipseCallout",
  170. "cloudCallout": "cloudCallout",
  171. "mathPlus": "mathPlus",
  172. "mathMinus": "mathMinus",
  173. "mathMultiply": "mathMultiply",
  174. "mathDivide": "mathDivide",
  175. "mathEqual": "mathEqual",
  176. "mathNotEqual": "mathNotEqual",
  177. "leftBracket": "leftBracket",
  178. "rightBracket": "rightBracket",
  179. "bracketPair": "bracketPair",
  180. "rightBrace": "rightBrace",
  181. "leftBrace": "leftBrace",
  182. "bracePair": "bracePair",
  183. // not drawn, so sent to the nearest outline that is
  184. "snipRoundRect": "roundRect",
  185. "plaque2": "plaque",
  186. "flowChartMagneticTape": "flowChartConnector",
  187. "flowChartMagneticDrum": "can",
  188. "flowChartOnlineStorage": "flowChartDelay",
  189. "flowChartSequentialAccessStorage": "flowChartConnector",
  190. "flowChartOfflineStorage": "flowChartExtract",
  191. "mathMinus2": "mathMinus",
  192. "bentConnector2": "rect",
  193. "callout1": "wedgeRectCallout",
  194. "callout2": "wedgeRectCallout",
  195. "callout3": "wedgeRectCallout",
  196. "accentCallout1": "wedgeRectCallout",
  197. "borderCallout1": "wedgeRectCallout",
  198. "borderCallout2": "wedgeRectCallout",
  199. "borderCallout3": "wedgeRectCallout",
  200. "swooshArrow": "curvedRightArrow",
  201. "stripedRightArrow2": "stripedRightArrow",
  202. "circularArrow2": "circularArrow",
  203. "leftCircularArrow": "circularArrow",
  204. "leftRightCircularArrow": "circularArrow",
  205. "upDownArrowCallout": "upArrowCallout",
  206. "quadArrowCallout": "quadArrow",
  207. "curvedConnector2": "rect",
  208. "gear6": "sun",
  209. "gear9": "sun",
  210. "funnel": "trapezoid",
  211. "pieWedge": "pie",
  212. "chartPlus": "mathPlus",
  213. "chartStar": "star4",
  214. "chartX": "mathMultiply",
  215. "triangleRight": "rtTriangle",
  216. "halfFrame2": "halfFrame",
  217. }
  218. // pptxDoc is the whole package plus everything shared across slides
  219. type pptxDoc struct {
  220. files map[string][]byte
  221. pres *xmltree.Node
  222. presRels map[string]string
  223. defTxStyle *xmltree.Node
  224. sx, sy float64 // source EMU -> editor px scale
  225. // the editor size of a slide, px
  226. slideW, slideH float64
  227. // parsed part cache, keyed by part path
  228. trees map[string]*xmltree.Node
  229. rels map[string]map[string]string
  230. // typefaces some run actually asks for, lower-cased - only these are
  231. // worth pulling out of the embedded font list
  232. usedFonts map[string]bool
  233. // slide part path -> 1-based position, for "go to slide" links
  234. slideIndex map[string]int
  235. }
  236. // slideCtx is the resolution context of one slide: its layout, master,
  237. // theme colours and colour map
  238. type slideCtx struct {
  239. doc *pptxDoc
  240. baseDir string
  241. rels map[string]string
  242. layout *xmltree.Node
  243. layoutDir string
  244. layoutRels map[string]string
  245. master *xmltree.Node
  246. masterDir string
  247. masterRels map[string]string
  248. cc colorCtx
  249. majorLatin string
  250. minorLatin string
  251. fmtScheme *xmltree.Node
  252. // the theme's relationships: a background style's picture is one of
  253. // the theme's parts
  254. themeRels map[string]string
  255. themeDir string
  256. slideNum int
  257. // the part whose shapes are being walked right now - a layout's or
  258. // master's picture resolves through that part's own rels, not the
  259. // slide's
  260. curRels map[string]string
  261. curDir string
  262. }
  263. // walkPart walks one part's shape tree with that part's relationships in
  264. // scope, then restores the previous scope
  265. func (sc *slideCtx) walkPart(tree *xmltree.Node, rels map[string]string, dir string, slide *model.Slide, z *int, phOnly bool) {
  266. spTree := tree.Path("cSld", "spTree")
  267. if spTree == nil {
  268. return
  269. }
  270. prevRels, prevDir := sc.curRels, sc.curDir
  271. sc.curRels, sc.curDir = rels, dir
  272. sc.walkShapes(spTree, sc.rootMap(), slide, z, phOnly)
  273. sc.curRels, sc.curDir = prevRels, prevDir
  274. }
  275. // coordMap converts EMU in the current (possibly grouped) coordinate space
  276. // into editor pixels. Group shapes nest these: a child's coordinates are
  277. // expressed in the group's child space and scaled by ext/chExt.
  278. type coordMap struct {
  279. kx, ky float64 // px per EMU
  280. bx, by float64 // px origin of this space
  281. cx, cy float64 // EMU origin of this space
  282. fs float64 // font scale accumulated from group scaling
  283. }
  284. func (c coordMap) px(emuX, emuY float64) (float64, float64) {
  285. return c.bx + (emuX-c.cx)*c.kx, c.by + (emuY-c.cy)*c.ky
  286. }
  287. func (c coordMap) size(emuW, emuH float64) (float64, float64) {
  288. return emuW * c.kx, emuH * c.ky
  289. }
  290. // Parse converts raw .pptx bytes into a Presentation
  291. func Parse(data []byte) (*model.Presentation, error) {
  292. zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
  293. if err != nil {
  294. return nil, errors.New("not a valid pptx (zip) file")
  295. }
  296. files := map[string][]byte{}
  297. for _, f := range zr.File {
  298. // presentations can carry large videos - only read the parts we need
  299. name := path.Clean(f.Name)
  300. if strings.HasSuffix(name, ".xml") || strings.HasSuffix(name, ".rels") ||
  301. strings.HasPrefix(name, "ppt/media/") {
  302. rc, err := f.Open()
  303. if err != nil {
  304. continue
  305. }
  306. b, err := io.ReadAll(rc)
  307. rc.Close()
  308. if err != nil {
  309. continue
  310. }
  311. files[name] = b
  312. }
  313. }
  314. presXML, ok := files["ppt/presentation.xml"]
  315. if !ok {
  316. return nil, errors.New("pptx is missing ppt/presentation.xml")
  317. }
  318. pres, err := xmltree.Parse(presXML)
  319. if err != nil {
  320. return nil, errors.New("cannot parse presentation.xml: " + err.Error())
  321. }
  322. doc := &pptxDoc{
  323. files: files, pres: pres, sx: 1, sy: 1,
  324. trees: map[string]*xmltree.Node{},
  325. rels: map[string]map[string]string{},
  326. usedFonts: map[string]bool{},
  327. }
  328. doc.presRels = doc.relsFor("ppt/presentation.xml")
  329. doc.defTxStyle = pres.First("defaultTextStyle")
  330. // source slide size -> the editor's: 960 wide, the deck's own shape
  331. pw, ph := model.SlidePxW, model.SlidePxH
  332. if sz := pres.First("sldSz"); sz != nil {
  333. cx := units.AtofDefault(sz.Attr("cx"), 0)
  334. cy := units.AtofDefault(sz.Attr("cy"), 0)
  335. if cx > 0 && cy > 0 {
  336. pw, ph = model.SlideSizeFor(cx, cy)
  337. doc.sx = float64(pw) / (cx / units.EmuPerPx)
  338. doc.sy = float64(ph) / (cy / units.EmuPerPx)
  339. }
  340. }
  341. doc.slideW, doc.slideH = float64(pw), float64(ph)
  342. slidePaths := doc.slideOrder()
  343. if len(slidePaths) == 0 {
  344. return nil, errors.New("pptx contains no slides")
  345. }
  346. doc.slideIndex = map[string]int{}
  347. for i, sp := range slidePaths {
  348. doc.slideIndex[sp] = i + 1
  349. }
  350. out := &model.Presentation{
  351. Size: []int{pw, ph},
  352. Theme: "clean",
  353. Slides: []*model.Slide{},
  354. }
  355. for si, sp := range slidePaths {
  356. tree := doc.tree(sp)
  357. if tree == nil {
  358. continue
  359. }
  360. sc := doc.slideContext(sp, tree)
  361. sc.slideNum = si + 1
  362. slide := sc.parseSlide(tree)
  363. slide.ID = fmt.Sprintf("s-import%d", si+1)
  364. slide.Transition = transitionOf(tree)
  365. slide.Hidden = hiddenSlide(tree)
  366. slide.Notes = sc.extractNotes()
  367. out.Slides = append(out.Slides, slide)
  368. }
  369. if len(out.Slides) == 0 {
  370. return nil, errors.New("no readable slides found in pptx")
  371. }
  372. out.Fonts = doc.embeddedFontFaces(doc.usedFonts)
  373. return out, nil
  374. }
  375. /* ---------------- package plumbing ---------------- */
  376. // tree parses (and caches) one XML part
  377. func (d *pptxDoc) tree(part string) *xmltree.Node {
  378. if t, ok := d.trees[part]; ok {
  379. return t
  380. }
  381. raw, ok := d.files[part]
  382. if !ok {
  383. d.trees[part] = nil
  384. return nil
  385. }
  386. t, err := xmltree.Parse(raw)
  387. if err != nil {
  388. t = nil
  389. }
  390. d.trees[part] = t
  391. return t
  392. }
  393. // relsFor loads (and caches) the relationship map of a part
  394. func (d *pptxDoc) relsFor(part string) map[string]string {
  395. if r, ok := d.rels[part]; ok {
  396. return r
  397. }
  398. relPath := path.Dir(part) + "/_rels/" + path.Base(part) + ".rels"
  399. out := map[string]string{}
  400. if raw, ok := d.files[relPath]; ok {
  401. if tree, err := xmltree.Parse(raw); err == nil {
  402. for _, rel := range tree.All("Relationship") {
  403. out[rel.Attr("Id")] = rel.Attr("Target")
  404. }
  405. }
  406. }
  407. d.rels[part] = out
  408. return out
  409. }
  410. // slideOrder resolves sldIdLst into slide part paths
  411. func (d *pptxDoc) slideOrder() []string {
  412. var out []string
  413. if lst := d.pres.First("sldIdLst"); lst != nil {
  414. for _, sid := range lst.All("sldId") {
  415. rid := sid.AttrNS("relationships", "id")
  416. if rid == "" {
  417. // some producers write r:id without a resolvable namespace
  418. for _, a := range sid.Attrs {
  419. if a.Name.Local == "id" && strings.HasPrefix(a.Value, "rId") {
  420. rid = a.Value
  421. }
  422. }
  423. }
  424. if target, ok := d.presRels[rid]; ok {
  425. out = append(out, xmltree.ResolvePart("ppt", target))
  426. }
  427. }
  428. }
  429. if len(out) == 0 {
  430. for i := 1; ; i++ {
  431. p := fmt.Sprintf("ppt/slides/slide%d.xml", i)
  432. if _, ok := d.files[p]; !ok {
  433. break
  434. }
  435. out = append(out, p)
  436. }
  437. }
  438. return out
  439. }
  440. // relTarget finds the first relationship whose type ends with the given
  441. // suffix and returns the part path it points at
  442. func relTarget(rels map[string]string, baseDir, typeSuffix string, files map[string][]byte) string {
  443. for _, target := range rels {
  444. if strings.Contains(target, typeSuffix) {
  445. p := xmltree.ResolvePart(baseDir, target)
  446. if _, ok := files[p]; ok {
  447. return p
  448. }
  449. }
  450. }
  451. return ""
  452. }
  453. // slideContext resolves a slide's layout, master, theme and colour map
  454. func (d *pptxDoc) slideContext(slidePath string, slide *xmltree.Node) *slideCtx {
  455. sc := &slideCtx{doc: d, baseDir: path.Dir(slidePath), rels: d.relsFor(slidePath)}
  456. layoutPath := relTarget(sc.rels, sc.baseDir, "slideLayout", d.files)
  457. if layoutPath != "" {
  458. sc.layout = d.tree(layoutPath)
  459. sc.layoutDir = path.Dir(layoutPath)
  460. sc.layoutRels = d.relsFor(layoutPath)
  461. }
  462. masterPath := ""
  463. if sc.layoutRels != nil {
  464. masterPath = relTarget(sc.layoutRels, sc.layoutDir, "slideMaster", d.files)
  465. }
  466. if masterPath == "" {
  467. masterPath = "ppt/slideMasters/slideMaster1.xml"
  468. }
  469. sc.master = d.tree(masterPath)
  470. sc.masterDir = path.Dir(masterPath)
  471. sc.masterRels = d.relsFor(masterPath)
  472. // theme through the master's rels
  473. var theme *xmltree.Node
  474. if sc.masterRels != nil {
  475. if tp := relTarget(sc.masterRels, sc.masterDir, "theme", d.files); tp != "" {
  476. theme = d.tree(tp)
  477. sc.themeRels = d.relsFor(tp)
  478. sc.themeDir = path.Dir(tp)
  479. }
  480. }
  481. sc.cc.scheme = map[string]string{}
  482. if theme != nil {
  483. if cs := theme.Path("themeElements", "clrScheme"); cs != nil {
  484. for i := range cs.Nodes {
  485. slot := cs.Nodes[i].XMLName.Local
  486. for j := range cs.Nodes[i].Nodes {
  487. c := &cs.Nodes[i].Nodes[j]
  488. plain := colorCtx{}
  489. if hex := plain.resolveColor(c); hex != "" {
  490. sc.cc.scheme[slot] = strings.TrimPrefix(hex, "#")
  491. break
  492. }
  493. }
  494. }
  495. }
  496. if fs := theme.Path("themeElements", "fontScheme"); fs != nil {
  497. if l := fs.Path("majorFont", "latin"); l != nil {
  498. sc.majorLatin = l.Attr("typeface")
  499. }
  500. if l := fs.Path("minorFont", "latin"); l != nil {
  501. sc.minorLatin = l.Attr("typeface")
  502. }
  503. }
  504. sc.fmtScheme = theme.Path("themeElements", "fmtScheme")
  505. }
  506. // colour map: the master's, optionally overridden per slide
  507. sc.cc.clrMap = map[string]string{}
  508. if cm := sc.master.First("clrMap"); cm != nil {
  509. for _, a := range cm.Attrs {
  510. sc.cc.clrMap[a.Name.Local] = a.Value
  511. }
  512. }
  513. if ovr := slide.Path("clrMapOvr", "overrideClrMapping"); ovr != nil {
  514. for _, a := range ovr.Attrs {
  515. sc.cc.clrMap[a.Name.Local] = a.Value
  516. }
  517. }
  518. return sc
  519. }
  520. /* ---------------- slide parsing ---------------- */
  521. func (sc *slideCtx) rootMap() coordMap {
  522. return coordMap{
  523. kx: sc.doc.sx / units.EmuPerPx, ky: sc.doc.sy / units.EmuPerPx,
  524. fs: math.Sqrt(sc.doc.sx * sc.doc.sy),
  525. }
  526. }
  527. // parseSlide converts one slide part into the editor model
  528. func (sc *slideCtx) parseSlide(tree *xmltree.Node) *model.Slide {
  529. slide := &model.Slide{Objects: []*model.Object{}}
  530. slide.Bg, slide.BgImage, slide.BgGrad = sc.slideBackground(tree)
  531. z := 0
  532. // PowerPoint paints a slide on top of its layout, and the layout on
  533. // top of its master. Only the decoration is inherited - a placeholder
  534. // on a layout or master is a prototype, not something that is drawn.
  535. if tree.Attr("showMasterSp") != "0" {
  536. if sc.master != nil && sc.layout.Attr("showMasterSp") != "0" {
  537. sc.walkPart(sc.master, sc.masterRels, sc.masterDir, slide, &z, true)
  538. }
  539. if sc.layout != nil {
  540. sc.walkPart(sc.layout, sc.layoutRels, sc.layoutDir, slide, &z, true)
  541. }
  542. }
  543. sc.walkPart(tree, sc.rels, sc.baseDir, slide, &z, false)
  544. return slide
  545. }
  546. // walkShapes appends every drawable descendant of a shape tree, recursing
  547. // into group shapes with the transform their child space implies
  548. func (sc *slideCtx) walkShapes(spTree *xmltree.Node, cm coordMap, slide *model.Slide, z *int, skipPh bool) {
  549. for i := range spTree.Nodes {
  550. node := &spTree.Nodes[i]
  551. if skipPh {
  552. if _, isPh := phOf(node); isPh {
  553. continue
  554. }
  555. }
  556. switch node.XMLName.Local {
  557. case "sp":
  558. sc.addObject(slide, sc.withLink(node, sc.parseSp(node, cm)), z)
  559. case "cxnSp":
  560. sc.addObject(slide, sc.withLink(node, sc.parseCxnSp(node, cm)), z)
  561. case "pic":
  562. sc.addObject(slide, sc.withLink(node, sc.parsePic(node, cm)), z)
  563. case "graphicFrame":
  564. if sc.walkDiagram(node, cm, slide, z) {
  565. continue
  566. }
  567. sc.addObject(slide, sc.withLink(node, sc.parseGraphicFrame(node, cm)), z)
  568. case "grpSp":
  569. sc.walkShapes(node, groupMap(node, cm), slide, z, false)
  570. case "AlternateContent":
  571. // mc:AlternateContent wraps a preferred and a fallback rendering.
  572. // The Fallback branch is plain DrawingML - for Office math it is
  573. // a picture of the whole text box - so it is the safe one, except
  574. // where the Choice is ordinary text with simple inline math in
  575. // it (a "≥" set as an equation), which stays editable text
  576. ch := node.First("Choice")
  577. if ch != nil && choiceReadable(ch) {
  578. sc.walkShapes(ch, cm, slide, z, skipPh)
  579. } else if fb := node.First("Fallback"); fb != nil {
  580. sc.walkShapes(fb, cm, slide, z, skipPh)
  581. } else if ch != nil {
  582. sc.walkShapes(ch, cm, slide, z, skipPh)
  583. }
  584. }
  585. }
  586. }
  587. func (sc *slideCtx) addObject(slide *model.Slide, obj *model.Object, z *int) {
  588. if obj == nil {
  589. return
  590. }
  591. *z++
  592. obj.ID = fmt.Sprintf("o-import%d", *z)
  593. obj.Z = *z
  594. slide.Objects = append(slide.Objects, obj)
  595. }
  596. // groupMap builds the coordinate map of a group's children
  597. func groupMap(grp *xmltree.Node, parent coordMap) coordMap {
  598. xf := grp.Path("grpSpPr", "xfrm")
  599. if xf == nil {
  600. return parent
  601. }
  602. off, ext := xf.First("off"), xf.First("ext")
  603. chOff, chExt := xf.First("chOff"), xf.First("chExt")
  604. if off == nil || ext == nil || chOff == nil || chExt == nil {
  605. return parent
  606. }
  607. cex := units.AtofDefault(chExt.Attr("cx"), 0)
  608. cey := units.AtofDefault(chExt.Attr("cy"), 0)
  609. if cex == 0 || cey == 0 {
  610. return parent
  611. }
  612. rx := units.AtofDefault(ext.Attr("cx"), 0) / cex
  613. ry := units.AtofDefault(ext.Attr("cy"), 0) / cey
  614. bx, by := parent.px(units.AtofDefault(off.Attr("x"), 0), units.AtofDefault(off.Attr("y"), 0))
  615. // a group's scale moves and sizes its children but not their type:
  616. // PowerPoint draws a run at the size it states however the group is
  617. // stretched (its own PDF of a group at 75% keeps 33 pt titles 33 pt)
  618. return coordMap{
  619. kx: parent.kx * rx, ky: parent.ky * ry,
  620. bx: bx, by: by,
  621. cx: units.AtofDefault(chOff.Attr("x"), 0), cy: units.AtofDefault(chOff.Attr("y"), 0),
  622. fs: parent.fs,
  623. }
  624. }
  625. // xfrmBox is a resolved position/size/rotation in editor pixels
  626. type xfrmBox struct {
  627. X, Y, W, H, Rot float64
  628. FlipH, FlipV bool
  629. OK bool
  630. }
  631. // parseXfrm extracts position/size/rotation/flips from an xfrm block
  632. func parseXfrm(xf *xmltree.Node, cm coordMap) xfrmBox {
  633. if xf == nil {
  634. return xfrmBox{}
  635. }
  636. off, ext := xf.First("off"), xf.First("ext")
  637. if off == nil || ext == nil {
  638. return xfrmBox{}
  639. }
  640. x, y := cm.px(units.AtofDefault(off.Attr("x"), 0), units.AtofDefault(off.Attr("y"), 0))
  641. w, h := cm.size(units.AtofDefault(ext.Attr("cx"), 0), units.AtofDefault(ext.Attr("cy"), 0))
  642. b := xfrmBox{X: x, Y: y, W: w, H: h, OK: true}
  643. if r := xf.Attr("rot"); r != "" {
  644. b.Rot = units.AtofDefault(r, 0) / 60000.0
  645. }
  646. b.FlipH = xf.Attr("flipH") == "1"
  647. b.FlipV = xf.Attr("flipV") == "1"
  648. return b
  649. }
  650. /* ---------------- placeholder inheritance ---------------- */
  651. // phKey identifies a placeholder: its type and its index
  652. type phKey struct {
  653. typ string
  654. idx string
  655. }
  656. func phOf(node *xmltree.Node) (phKey, bool) {
  657. ph := node.Path("nvSpPr", "nvPr", "ph")
  658. if ph == nil {
  659. ph = node.Path("nvPicPr", "nvPr", "ph")
  660. }
  661. if ph == nil {
  662. ph = node.Path("nvGraphicFramePr", "nvPr", "ph")
  663. }
  664. if ph == nil {
  665. return phKey{}, false
  666. }
  667. t := ph.Attr("type")
  668. if t == "" {
  669. t = "body"
  670. }
  671. return phKey{typ: t, idx: ph.Attr("idx")}, true
  672. }
  673. // findPh looks for the shape carrying a matching placeholder in a layout
  674. // or master. An exact type+index match wins; a type match is next; an
  675. // index match last, which is how PowerPoint pairs body placeholders whose
  676. // type was omitted.
  677. func findPh(root *xmltree.Node, want phKey) *xmltree.Node {
  678. spTree := root.Path("cSld", "spTree")
  679. if spTree == nil {
  680. return nil
  681. }
  682. var shapes []*xmltree.Node
  683. spTree.FindAll("sp", &shapes)
  684. var byType, byIdx *xmltree.Node
  685. for _, sp := range shapes {
  686. got, ok := phOf(sp)
  687. if !ok {
  688. continue
  689. }
  690. if got.typ == want.typ && got.idx == want.idx {
  691. return sp
  692. }
  693. if byType == nil && phTypeAlike(got.typ, want.typ) {
  694. byType = sp
  695. }
  696. if byIdx == nil && want.idx != "" && got.idx == want.idx {
  697. byIdx = sp
  698. }
  699. }
  700. if byType != nil {
  701. return byType
  702. }
  703. return byIdx
  704. }
  705. // phRole is what a text placeholder is for, in the editor's terms (props.ph):
  706. // "title", "subtitle" or "body"; "" for anything else, a date or a slide
  707. // number placeholder included
  708. func phRole(node *xmltree.Node) string {
  709. key, ok := phOf(node)
  710. if !ok {
  711. return ""
  712. }
  713. switch key.typ {
  714. case "title", "ctrTitle":
  715. return "title"
  716. case "subTitle":
  717. return "subtitle"
  718. case "body", "obj":
  719. return "body"
  720. }
  721. return ""
  722. }
  723. // phTypeAlike treats the title variants as one kind, the way PowerPoint does
  724. func phTypeAlike(a, b string) bool {
  725. norm := func(s string) string {
  726. switch s {
  727. case "ctrTitle":
  728. return "title"
  729. case "subTitle":
  730. return "body"
  731. }
  732. return s
  733. }
  734. return norm(a) == norm(b)
  735. }
  736. // phChain returns the layout's and master's shape for a placeholder
  737. func (sc *slideCtx) phChain(node *xmltree.Node) (layoutSp, masterSp *xmltree.Node) {
  738. key, ok := phOf(node)
  739. if !ok {
  740. return nil, nil
  741. }
  742. if sc.layout != nil {
  743. layoutSp = findPh(sc.layout, key)
  744. }
  745. if sc.master != nil {
  746. masterSp = findPh(sc.master, key)
  747. }
  748. return layoutSp, masterSp
  749. }
  750. // masterTxStyle picks the master text style block a placeholder kind uses
  751. func (sc *slideCtx) masterTxStyle(key phKey, isPh bool) *xmltree.Node {
  752. ts := sc.master.First("txStyles")
  753. if ts == nil {
  754. return nil
  755. }
  756. if !isPh {
  757. return ts.First("otherStyle")
  758. }
  759. switch key.typ {
  760. case "title", "ctrTitle":
  761. return ts.First("titleStyle")
  762. case "body", "subTitle", "obj", "":
  763. return ts.First("bodyStyle")
  764. }
  765. return ts.First("otherStyle")
  766. }
  767. // styleChain builds the list of <a:lstStyle>-shaped nodes to fold, lowest
  768. // priority first, for the text inside one shape
  769. func (sc *slideCtx) styleChain(node, layoutSp, masterSp *xmltree.Node) []*xmltree.Node {
  770. key, isPh := phOf(node)
  771. var chain []*xmltree.Node
  772. if !isPh && sc.doc.defTxStyle != nil {
  773. chain = append(chain, sc.doc.defTxStyle)
  774. }
  775. if s := sc.masterTxStyle(key, isPh); s != nil {
  776. chain = append(chain, s)
  777. }
  778. if masterSp != nil {
  779. if l := masterSp.Path("txBody", "lstStyle"); l != nil {
  780. chain = append(chain, l)
  781. }
  782. }
  783. if layoutSp != nil {
  784. if l := layoutSp.Path("txBody", "lstStyle"); l != nil {
  785. chain = append(chain, l)
  786. }
  787. }
  788. if l := node.Path("txBody", "lstStyle"); l != nil {
  789. chain = append(chain, l)
  790. }
  791. return chain
  792. }
  793. // firstNonNil returns the first node in the list that is not nil
  794. func firstNonNil(nodes ...*xmltree.Node) *xmltree.Node {
  795. for _, n := range nodes {
  796. if n != nil {
  797. return n
  798. }
  799. }
  800. return nil
  801. }
  802. /* ---------------- body properties ---------------- */
  803. // bodyProps is the resolved <a:bodyPr> of a text body
  804. type bodyProps struct {
  805. Anchor string // t, ctr, b
  806. LIns float64 // px
  807. TIns float64
  808. RIns float64
  809. BIns float64
  810. FontScale float64 // normAutofit fontScale, 1 when none
  811. LnSpcScale float64 // 1 - lnSpcReduction
  812. Wrap bool
  813. // spcFirstLastPara: the first paragraph's space before and the last
  814. // one's space after count too (PowerPoint drops them otherwise)
  815. SpcFirstLast bool
  816. }
  817. // pptx default text insets, in EMU (0.1" left/right, 0.05" top/bottom)
  818. const (
  819. defaultLIns = 91440
  820. defaultTIns = 45720
  821. )
  822. func (sc *slideCtx) resolveBodyPr(nodes []*xmltree.Node, cm coordMap) bodyProps {
  823. bp := bodyProps{Anchor: "t", FontScale: 1, LnSpcScale: 1, Wrap: true,
  824. LIns: defaultLIns, TIns: defaultTIns, RIns: defaultLIns, BIns: defaultTIns}
  825. for _, n := range nodes {
  826. if n == nil {
  827. continue
  828. }
  829. if v := n.Attr("anchor"); v != "" {
  830. bp.Anchor = v
  831. }
  832. if v := n.Attr("lIns"); v != "" {
  833. bp.LIns = units.AtofDefault(v, defaultLIns)
  834. }
  835. if v := n.Attr("rIns"); v != "" {
  836. bp.RIns = units.AtofDefault(v, defaultLIns)
  837. }
  838. if v := n.Attr("tIns"); v != "" {
  839. bp.TIns = units.AtofDefault(v, defaultTIns)
  840. }
  841. if v := n.Attr("bIns"); v != "" {
  842. bp.BIns = units.AtofDefault(v, defaultTIns)
  843. }
  844. if v := n.Attr("wrap"); v != "" {
  845. bp.Wrap = v != "none"
  846. }
  847. if v := n.Attr("spcFirstLastPara"); v != "" {
  848. bp.SpcFirstLast = v == "1" || v == "true"
  849. }
  850. if na := n.First("normAutofit"); na != nil {
  851. bp.FontScale = units.AtofDefault(na.Attr("fontScale"), 100000) / 100000
  852. bp.LnSpcScale = 1 - units.AtofDefault(na.Attr("lnSpcReduction"), 0)/100000
  853. }
  854. if n.First("noAutofit") != nil || n.First("spAutoFit") != nil {
  855. bp.FontScale = 1
  856. bp.LnSpcScale = 1
  857. }
  858. }
  859. // EMU -> px, using the horizontal / vertical scale of this space
  860. bp.LIns *= cm.kx
  861. bp.RIns *= cm.kx
  862. bp.TIns *= cm.ky
  863. bp.BIns *= cm.ky
  864. return bp
  865. }
  866. func anchorToVAlign(a string) string {
  867. switch a {
  868. case "ctr":
  869. return "middle"
  870. case "b":
  871. return "bottom"
  872. }
  873. return "top"
  874. }
  875. /* ---------------- text bodies ---------------- */
  876. // textResult is everything a txBody contributes to an object
  877. type textResult struct {
  878. HTML string
  879. Plain string
  880. First runStyle
  881. Align string
  882. Empty bool
  883. FontCSS string
  884. LineH float64
  885. FontSize float64
  886. // the whole box is bold / italic / underlined: every run of text is.
  887. // The editor applies these to the box itself, and a descendant cannot
  888. // take an underline off again, so the first run alone must not decide.
  889. Bold, Italic, Underline bool
  890. }
  891. // buildTextBody renders a <p:txBody> into the editor's storage HTML
  892. func (sc *slideCtx) buildTextBody(tx *xmltree.Node, chain []*xmltree.Node, bp bodyProps, cm coordMap) textResult {
  893. res := textResult{Empty: true, Align: "left"}
  894. if tx == nil {
  895. return res
  896. }
  897. // normAutofit's fontScale is not drawn as a fraction: PowerPoint sets
  898. // each run at the scaled size rounded to a whole point (20 pt at 92.5%
  899. // is 19 pt, at 77.5% 16 pt - measured on its own PDFs), so the scale
  900. // goes into the sizes, rounded, rather than into the CSS
  901. scale := cm.fs
  902. fitSize := func(pt float64) float64 {
  903. if bp.FontScale > 0 && bp.FontScale < 1 && pt > 0 {
  904. return math.Max(1, math.Floor(pt*bp.FontScale+0.5))
  905. }
  906. return pt
  907. }
  908. var sb strings.Builder
  909. var plain []string
  910. autoNum := map[int]int{}
  911. firstSet := false
  912. anyText, allBold, allItalic, allUnder := false, true, true, true
  913. paras := tx.All("p")
  914. for pi, p := range paras {
  915. pPr := p.First("pPr")
  916. lvl := int(units.AtofDefault(pPr.Attr("lvl"), 0))
  917. ps := resolveParaStyle(chain, pPr, lvl, &sc.cc)
  918. sc.resolveThemeFonts(&ps.DefRun)
  919. // runs
  920. var runs strings.Builder
  921. var lineText strings.Builder
  922. maxSizePt := 0.0
  923. minSizePt := 0.0
  924. var firstRun, lastRun runStyle
  925. haveRun := false
  926. for _, ch := range paraItems(p) {
  927. switch ch.XMLName.Local {
  928. case "r", "fld":
  929. t := ch.First("t")
  930. if t == nil {
  931. continue
  932. }
  933. rs := ps.DefRun
  934. applyRPr(&rs, ch.First("rPr"), &sc.cc)
  935. rs.SizePt = fitSize(rs.SizePt)
  936. sc.resolveThemeFonts(&rs)
  937. txt := t.Text
  938. // text set in the Symbol font is Greek and maths written
  939. // with Latin codes ("a" is alpha): it goes in as the
  940. // characters it shows, in the paragraph's own font
  941. if strings.EqualFold(strings.TrimSpace(rs.Latin), "symbol") {
  942. txt = fonts.SymbolText(txt)
  943. rs.Latin, rs.EastAsian = ps.DefRun.Latin, ps.DefRun.EastAsian
  944. sc.resolveThemeFonts(&rs)
  945. }
  946. maxSizePt, minSizePt = spanSizes(rs.SizePt, maxSizePt, minSizePt)
  947. if !haveRun {
  948. firstRun = rs
  949. haveRun = true
  950. }
  951. lastRun = rs
  952. if ch.XMLName.Local == "fld" &&
  953. strings.EqualFold(ch.Attr("type"), "slidenum") {
  954. // the stored text is the producer's placeholder glyph
  955. // ("<#>"); what belongs on the slide is its number
  956. txt = strconv.Itoa(sc.slideNum)
  957. }
  958. if txt == "" {
  959. continue
  960. }
  961. anyText = true
  962. allBold = allBold && rs.Bold
  963. allItalic = allItalic && rs.Italic
  964. allUnder = allUnder && rs.Underline
  965. runs.WriteString(`<span style="` + runCSS(rs, scale) + `">` +
  966. xmltree.Escape(txt) + `</span>`)
  967. lineText.WriteString(txt)
  968. case "br":
  969. // a break with no properties of its own opens a line as
  970. // tall as the run before it, not as the box default
  971. rs := ps.DefRun
  972. if haveRun {
  973. rs = lastRun
  974. } else {
  975. rs.SizePt = fitSize(rs.SizePt)
  976. }
  977. if br := ch.First("rPr"); br != nil && br.Attr("sz") != "" {
  978. applyRPr(&rs, br, &sc.cc)
  979. rs.SizePt = fitSize(rs.SizePt)
  980. } else {
  981. applyRPr(&rs, br, &sc.cc)
  982. }
  983. sc.resolveThemeFonts(&rs)
  984. maxSizePt, minSizePt = spanSizes(rs.SizePt, maxSizePt, minSizePt)
  985. runs.WriteString("<br>" + lineSpacerFor(rs, scale))
  986. lineText.WriteString("\n")
  987. }
  988. }
  989. if !haveRun {
  990. // an empty paragraph still occupies a line, sized by endParaRPr
  991. rs := ps.DefRun
  992. applyRPr(&rs, p.First("endParaRPr"), &sc.cc)
  993. rs.SizePt = fitSize(rs.SizePt)
  994. sc.resolveThemeFonts(&rs)
  995. firstRun = rs
  996. maxSizePt, minSizePt = rs.SizePt, rs.SizePt
  997. }
  998. if maxSizePt <= 0 {
  999. maxSizePt = ps.DefRun.SizePt
  1000. }
  1001. if minSizePt <= 0 {
  1002. minSizePt = maxSizePt
  1003. }
  1004. if !firstSet && haveRun {
  1005. res.First = firstRun
  1006. res.Align = algnToCSS(ps.Align)
  1007. res.LineH = lineHeightOf(ps, bp)
  1008. firstSet = true
  1009. }
  1010. if strings.TrimSpace(lineText.String()) != "" {
  1011. res.Empty = false
  1012. }
  1013. plain = append(plain, lineText.String())
  1014. // bullet marker - PowerPoint draws none on an empty paragraph, and
  1015. // does not count one in a numbered list
  1016. bullet := ""
  1017. hasText := strings.TrimSpace(strings.ReplaceAll(lineText.String(), "\u200b", "")) != ""
  1018. if (ps.BuType == "char" || ps.BuType == "autonum") && !hasText {
  1019. // keeps the numbering where it is
  1020. } else if ps.BuType == "char" || ps.BuType == "autonum" {
  1021. marker := ps.BuChar
  1022. if ps.BuType == "autonum" {
  1023. autoNum[lvl]++
  1024. start := ps.BuStartAt
  1025. if start < 1 {
  1026. start = 1
  1027. }
  1028. marker = autoNumMarker(ps.BuAutoNum, autoNum[lvl]+start-1)
  1029. }
  1030. if marker != "" {
  1031. bs := firstRun
  1032. if ps.BuSizePt > 0 {
  1033. bs.SizePt = fitSize(ps.BuSizePt)
  1034. } else if ps.BuSizePct > 0 {
  1035. bs.SizePt = firstRun.SizePt * ps.BuSizePct
  1036. }
  1037. if ps.BuColor != "" {
  1038. bs.Color = ps.BuColor
  1039. }
  1040. // a number is set in the text's font when the marker font
  1041. // is a symbol font (the master's Wingdings bullet font
  1042. // reaching a numbered paragraph): digits in Wingdings are
  1043. // pictographs
  1044. if ps.BuFont != "" && !(ps.BuType == "autonum" && fonts.IsSymbolFont(ps.BuFont)) {
  1045. bs.Latin, bs.EastAsian = ps.BuFont, ps.BuFont
  1046. }
  1047. // a symbol-font marker (Wingdings "l") is a letter in any
  1048. // other font: it goes in as the character it draws, in the
  1049. // text's own font
  1050. if uni, k, ok := fonts.SymbolBullet(ps.BuFont, marker); ok {
  1051. marker = uni
  1052. bs.Latin, bs.EastAsian = firstRun.Latin, firstRun.EastAsian
  1053. bs.SizePt *= k
  1054. }
  1055. // a geometric bullet (● ○ ■) the bullet font has no glyph
  1056. // for is drawn by PowerPoint and Google Slides in Arial,
  1057. // where it is a small shape. Left to the shipped fallbacks
  1058. // it lands on the CJK face, whose full-width circle is twice
  1059. // that size - so Arimo (Arial's metric twin, shipped and
  1060. // embeddable in a PDF) comes right after the bullet font,
  1061. // ahead of any East Asian font the deck names
  1062. if ps.BuType == "char" {
  1063. bs.EastAsian = fonts.BulletFallback
  1064. }
  1065. bs.Underline, bs.Strike, bs.Highlight = false, false, ""
  1066. left := (ps.MarLeft + ps.Indent) * cm.kx
  1067. // the outer span is a line of the paragraph's own text -
  1068. // its size, font and line height - so the marker inside it
  1069. // sits on the first line's baseline whatever its own size
  1070. strut := firstRun
  1071. strut.Bold, strut.Italic, strut.Underline, strut.Strike, strut.Highlight = false, false, false, false, ""
  1072. bullet = `<span style="position:absolute;left:` + units.FmtPx(left) + `;top:0;` +
  1073. `line-height:` + strconv.FormatFloat(units.Round2(lineHeightOf(ps, bp)), 'f', -1, 64) + `;` +
  1074. runCSS(strut, scale) + `"><span style="` + runCSS(bs, scale) + `">` +
  1075. xmltree.Escape(marker) + `</span></span>`
  1076. }
  1077. } else {
  1078. autoNum = map[int]int{}
  1079. }
  1080. // paragraph box
  1081. var css strings.Builder
  1082. css.WriteString("text-align:" + algnToCSS(ps.Align) + ";")
  1083. // a tab goes to the next default stop, an inch apart unless the
  1084. // deck says otherwise (CSS's own default is eight spaces)
  1085. if ps.DefTabSz > 0 && strings.Contains(lineText.String(), "\t") {
  1086. css.WriteString("tab-size:" + units.FmtPx(ps.DefTabSz*cm.kx) + ";")
  1087. }
  1088. lh := lineHeightOf(ps, bp)
  1089. css.WriteString("line-height:" + strconv.FormatFloat(units.Round2(lh), 'f', -1, 64) + ";")
  1090. // PowerPoint scales a whole line with its spacing, so the baseline
  1091. // moves with it; CSS keeps the font's ascent and centres it in the
  1092. // line box instead. Single spacing is made to agree by the fonts
  1093. // themselves (common/fonts.js, the PowerPoint line model); any
  1094. // other spacing leaves every line of the paragraph off by the same
  1095. // amount, which is moved back here
  1096. if haveRun || firstRun.SizePt > 0 {
  1097. sizePx := units.PtToPx(firstRun.SizePt) * scale
  1098. if dy := (model.LineHeightFactor - lh) * (2*ascentRatio(firstRun.Latin) - 1) / 2 * sizePx; math.Abs(dy) > 0.3 {
  1099. if bullet == "" {
  1100. css.WriteString("position:relative;")
  1101. }
  1102. css.WriteString("top:" + units.FmtPx(-dy) + ";")
  1103. }
  1104. }
  1105. // the block's own font size is a floor under every line box in it,
  1106. // so it has to be the paragraph's *smallest* run - otherwise a
  1107. // small line under a big one inherits the big line's height
  1108. css.WriteString("font-size:" + units.FmtPx(units.PtToPx(minSizePt)*scale) + ";")
  1109. // PowerPoint drops the first paragraph's space before and the last
  1110. // one's space after, unless the body says spcFirstLastPara
  1111. if pi > 0 || bp.SpcFirstLast {
  1112. if before := spaceOf(ps.SpcBefPt, ps.SpcBefPct, maxSizePt) * scale; before > 0 {
  1113. css.WriteString("margin-top:" + units.FmtPx(units.PtToPx(before)) + ";")
  1114. }
  1115. }
  1116. if pi < len(paras)-1 || bp.SpcFirstLast {
  1117. if after := spaceOf(ps.SpcAftPt, ps.SpcAftPct, maxSizePt) * scale; after > 0 {
  1118. css.WriteString("margin-bottom:" + units.FmtPx(units.PtToPx(after)) + ";")
  1119. }
  1120. }
  1121. // PowerPoint counts tab stops from the edge of the text box, CSS
  1122. // from the paragraph's content box - which a hanging indent's
  1123. // padding moves. With a tab in the line, the indent is turned
  1124. // round: the content box starts where the first line does and the
  1125. // other lines hang from it (text-indent ... hanging), so the stops
  1126. // land where PowerPoint puts them and the lines where they were.
  1127. hanging := bullet == "" && ps.Indent < 0 && ps.MarLeft+ps.Indent > -0.5 &&
  1128. strings.Contains(lineText.String(), "\t")
  1129. if hanging {
  1130. if first := (ps.MarLeft + ps.Indent) * cm.kx; first > 0.01 {
  1131. css.WriteString("padding-left:" + units.FmtPx(first) + ";")
  1132. }
  1133. } else if ps.MarLeft != 0 {
  1134. css.WriteString("padding-left:" + units.FmtPx(ps.MarLeft*cm.kx) + ";")
  1135. }
  1136. if ps.MarRight != 0 {
  1137. css.WriteString("padding-right:" + units.FmtPx(ps.MarRight*cm.kx) + ";")
  1138. }
  1139. if bullet != "" {
  1140. css.WriteString("position:relative;")
  1141. } else if hanging {
  1142. css.WriteString("text-indent:" + units.FmtPx(-ps.Indent*cm.kx) + " hanging;")
  1143. } else if ps.Indent != 0 {
  1144. css.WriteString("text-indent:" + units.FmtPx(ps.Indent*cm.kx) + ";")
  1145. }
  1146. body := runs.String()
  1147. // PowerPoint's first tab stop in a hanging paragraph is the indent
  1148. // itself, so a leading tab goes there before the default stops; the
  1149. // tab keeps its place in the text inside a box that wide
  1150. if hanging && strings.HasPrefix(lineText.String(), "\t") {
  1151. body = strings.Replace(body, `">`+"\t", `"><span style="display:inline-block;width:`+
  1152. units.FmtPx(-ps.Indent*cm.kx)+`;">`+"\t"+`</span>`, 1)
  1153. }
  1154. if body == "" {
  1155. // nothing to draw, but the line still takes up its own height
  1156. body = lineSpacerFor(firstRun, scale)
  1157. }
  1158. sb.WriteString(`<div style="` + css.String() + `">` + bullet + body + `</div>`)
  1159. }
  1160. // trailing empty paragraphs add nothing but height the source did have,
  1161. // so they are kept - but a body that is entirely empty renders nothing
  1162. res.HTML = sb.String()
  1163. res.Plain = strings.Join(plain, "\n")
  1164. if !firstSet && len(paras) > 0 {
  1165. ps := resolveParaStyle(chain, paras[0].First("pPr"), 0, &sc.cc)
  1166. // no text at all: what the box types in is its endParaRPr
  1167. rs := ps.DefRun
  1168. applyRPr(&rs, paras[0].First("endParaRPr"), &sc.cc)
  1169. sc.resolveThemeFonts(&rs)
  1170. res.First = rs
  1171. res.Align = algnToCSS(ps.Align)
  1172. res.LineH = lineHeightOf(ps, bp)
  1173. }
  1174. if anyText {
  1175. res.Bold, res.Italic, res.Underline = allBold, allItalic, allUnder
  1176. } else {
  1177. res.Bold, res.Italic, res.Underline = res.First.Bold, res.First.Italic, res.First.Underline
  1178. }
  1179. res.FontCSS = fonts.StackFor(res.First.Latin, res.First.EastAsian)
  1180. res.FontSize = units.PtToPx(res.First.SizePt) * scale
  1181. return res
  1182. }
  1183. // resolveThemeFonts expands the +mj-lt / +mn-lt theme font references
  1184. func (sc *slideCtx) resolveThemeFonts(rs *runStyle) {
  1185. fix := func(s string) string {
  1186. switch {
  1187. case strings.HasPrefix(s, "+mj"):
  1188. return sc.majorLatin
  1189. case strings.HasPrefix(s, "+mn"):
  1190. return sc.minorLatin
  1191. }
  1192. return s
  1193. }
  1194. rs.Latin = fix(rs.Latin)
  1195. rs.EastAsian = fix(rs.EastAsian)
  1196. for _, n := range []string{rs.Latin, rs.EastAsian} {
  1197. if n != "" {
  1198. sc.doc.usedFonts[strings.ToLower(n)] = true
  1199. }
  1200. }
  1201. }
  1202. // lineHeightOf converts a paragraph's line spacing into a CSS multiplier
  1203. func lineHeightOf(ps paraStyle, bp bodyProps) float64 {
  1204. if ps.LnSpcPt > 0 {
  1205. // exact spacing: express it relative to the paragraph's own size
  1206. size := ps.DefRun.SizePt
  1207. if size <= 0 {
  1208. size = 18
  1209. }
  1210. return ps.LnSpcPt / size * bp.LnSpcScale
  1211. }
  1212. pct := ps.LnSpcPct
  1213. if pct <= 0 {
  1214. pct = 1
  1215. }
  1216. return pct * model.LineHeightFactor * bp.LnSpcScale
  1217. }
  1218. // spaceOf resolves a paragraph space to points, given the paragraph's
  1219. // largest run size for the percentage form
  1220. func spaceOf(pts, pct, sizePt float64) float64 {
  1221. if pts > 0 {
  1222. return pts
  1223. }
  1224. if pct > 0 {
  1225. // a percentage is of the line, not of the type: 20% before a
  1226. // 28 pt paragraph is 20% of its 33.6 pt single line (measured
  1227. // against PowerPoint's own PDF output)
  1228. return pct * sizePt * model.LineHeightFactor
  1229. }
  1230. return 0
  1231. }
  1232. func algnToCSS(a string) string {
  1233. switch a {
  1234. case "ctr":
  1235. return "center"
  1236. case "r":
  1237. return "right"
  1238. case "just", "justLow", "dist":
  1239. return "justify"
  1240. }
  1241. return "left"
  1242. }
  1243. /* ---------------- shapes ---------------- */
  1244. // parseSp handles p:sp - a text box or a preset-geometry shape
  1245. func (sc *slideCtx) parseSp(node *xmltree.Node, cm coordMap) *model.Object {
  1246. // a shape drawn with a line or connector preset is a line, whatever
  1247. // element it came in - and a straight one is routinely zero wide or
  1248. // zero tall, which the box test below would throw away
  1249. if g := node.Path("spPr", "prstGeom"); g != nil && isLinePreset(g.Attr("prst")) {
  1250. return sc.parseCxnSp(node, cm)
  1251. }
  1252. layoutSp, masterSp := sc.phChain(node)
  1253. // geometry: the shape's own, else the placeholder it inherits from
  1254. box := parseXfrm(node.Path("spPr", "xfrm"), cm)
  1255. if !box.OK && layoutSp != nil {
  1256. box = parseXfrm(layoutSp.Path("spPr", "xfrm"), cm)
  1257. }
  1258. if !box.OK && masterSp != nil {
  1259. box = parseXfrm(masterSp.Path("spPr", "xfrm"), cm)
  1260. }
  1261. if !box.OK || box.W <= 0 || box.H <= 0 {
  1262. return nil
  1263. }
  1264. spPr := node.First("spPr")
  1265. prst := ""
  1266. if g := spPr.First("prstGeom"); g != nil {
  1267. prst = g.Attr("prst")
  1268. } else if spPr.First("custGeom") == nil {
  1269. // no geometry of its own: a placeholder takes the shape its
  1270. // prototype states, and anything else is a plain rectangle
  1271. for _, src := range []*xmltree.Node{layoutSp, masterSp} {
  1272. if g := src.Path("spPr", "prstGeom"); g != nil {
  1273. prst = g.Attr("prst")
  1274. break
  1275. }
  1276. }
  1277. if prst == "" {
  1278. prst = "rect"
  1279. }
  1280. } else if spPr.First("custGeom") != nil {
  1281. // an unfilled freeform made only of straight segments is a
  1282. // polyline, which the editor draws as a line - that is also how
  1283. // this package writes a bent connector back out
  1284. if obj := sc.freeformLine(node, spPr, box, cm); obj != nil {
  1285. return obj
  1286. }
  1287. prst = "custom"
  1288. }
  1289. // a placeholder that states no fill or outline of its own wears its
  1290. // prototype's: a footer bar's colour is set once, on the master
  1291. fillPr, linePr := spPr, spPr
  1292. for _, proto := range []*xmltree.Node{layoutSp, masterSp} {
  1293. if fillPr != nil && hasFillChoice(fillPr) {
  1294. break
  1295. }
  1296. if pp := proto.First("spPr"); pp != nil && hasFillChoice(pp) {
  1297. fillPr = pp
  1298. }
  1299. }
  1300. for _, proto := range []*xmltree.Node{layoutSp, masterSp} {
  1301. if linePr != nil && linePr.First("ln") != nil {
  1302. break
  1303. }
  1304. if pp := proto.First("spPr"); pp != nil && pp.First("ln") != nil {
  1305. linePr = pp
  1306. }
  1307. }
  1308. fill, fillGrad := sc.shapeFill(node, fillPr)
  1309. stroke, strokeW, dash := sc.lineOf(linePr, cm)
  1310. // a shape filled with a picture is a picture in that outline (and the
  1311. // Fallback of an Office-math text box is one: the whole box, drawn)
  1312. if bf := fillPr.First("blipFill"); bf != nil && !hasVisibleText(node.First("txBody")) {
  1313. if obj := sc.pictureFillObject(bf, prst, box, stroke, strokeW, dash); obj != nil {
  1314. return obj
  1315. }
  1316. }
  1317. if stroke == "" {
  1318. if c := sc.styleRefColor(node, "lnRef"); c != "" && c != "none" {
  1319. stroke = c
  1320. if strokeW == 0 {
  1321. strokeW = 1
  1322. }
  1323. }
  1324. }
  1325. // text
  1326. chain := sc.styleChain(node, layoutSp, masterSp)
  1327. bp := sc.resolveBodyPr([]*xmltree.Node{
  1328. masterSp.Path("txBody", "bodyPr"),
  1329. layoutSp.Path("txBody", "bodyPr"),
  1330. node.Path("txBody", "bodyPr"),
  1331. }, cm)
  1332. // Google Slides writes spcFirstLastPara="1" on every shape it exports
  1333. // but never draws the first paragraph's space before (or the last
  1334. // one's space after) itself - its decks would open lower than they
  1335. // were made. PowerPoint does honour the flag, so only Google's own
  1336. // shapes are read the way Google draws them.
  1337. if isGoogleShape(node) {
  1338. bp.SpcFirstLast = false
  1339. }
  1340. tr := sc.buildTextBody(node.First("txBody"), chain, bp, cm)
  1341. kind, known := prstToShapeKind[prst]
  1342. var geom *model.CustomGeom
  1343. if prst == "custom" {
  1344. ext := spPr.Path("xfrm", "ext")
  1345. if geom = parseCustGeom(spPr.First("custGeom"), units.AtofDefault(ext.Attr("cx"), 0), units.AtofDefault(ext.Attr("cy"), 0)); geom != nil {
  1346. kind, known = "custom", true
  1347. }
  1348. }
  1349. if !known {
  1350. kind = "rect"
  1351. }
  1352. hasFill := fill != "" && fill != "none"
  1353. hasLine := stroke != "" && stroke != "none" && strokeW > 0
  1354. // a shape is drawn as a shape when it has a visible body; a bare
  1355. // rectangle with only text in it is a text box
  1356. isShape := hasFill || hasLine || (known && kind != "rect") || !known
  1357. pad := []float64{
  1358. units.Round2(bp.TIns), units.Round2(bp.RIns), units.Round2(bp.BIns), units.Round2(bp.LIns),
  1359. }
  1360. // a SmartArt drawing places a shape's text in a rectangle of its own
  1361. // (dsp:txXfrm) inside the outline: the difference is more inset
  1362. if tx := parseXfrm(node.First("txXfrm"), cm); tx.OK && tx.W > 0 && tx.H > 0 {
  1363. pad[0] = units.Round2(math.Max(0, tx.Y-box.Y) + bp.TIns)
  1364. pad[1] = units.Round2(math.Max(0, box.X+box.W-tx.X-tx.W) + bp.RIns)
  1365. pad[2] = units.Round2(math.Max(0, box.Y+box.H-tx.Y-tx.H) + bp.BIns)
  1366. pad[3] = units.Round2(math.Max(0, tx.X-box.X) + bp.LIns)
  1367. }
  1368. if !isShape {
  1369. role := phRole(node)
  1370. // an empty placeholder is kept: the editor shows its prompt
  1371. if tr.HTML == "" && role == "" {
  1372. return nil
  1373. }
  1374. return &model.Object{
  1375. Type: "text", X: box.X, Y: box.Y, W: box.W, H: box.H, Rot: box.Rot,
  1376. Props: model.Props{
  1377. Ph: role,
  1378. HTML: tr.HTML, FontSize: units.Round2(tr.FontSize), Color: tr.First.Color,
  1379. Align: tr.Align, Bold: tr.Bold, Italic: tr.Italic,
  1380. Underline: tr.Underline, FontFamily: tr.FontCSS,
  1381. VAlign: anchorToVAlign(bp.Anchor), Pad: pad,
  1382. LineHeight: units.Round2(tr.LineH),
  1383. },
  1384. }
  1385. }
  1386. if !hasFill {
  1387. fill, fillGrad = "none", nil
  1388. }
  1389. if !hasLine {
  1390. stroke, strokeW = "", 0
  1391. }
  1392. radius := units.Round2(sc.cornerRadius(spPr, prst, box))
  1393. if kind == "roundRect" && radius <= 0 {
  1394. // adj 0: square corners. A zero radius is not stored (omitempty),
  1395. // and a roundRect without one is drawn with the default rounding
  1396. kind = "rect"
  1397. }
  1398. return &model.Object{
  1399. Type: "shape", X: box.X, Y: box.Y, W: box.W, H: box.H, Rot: box.Rot,
  1400. Props: model.Props{
  1401. Kind: kind, Geom: geom, Fill: fill, FillGrad: fillGrad, Stroke: stroke, StrokeW: units.Round2(strokeW),
  1402. Dash: dash, DashStyle: dashStyleOfLn(spPr), Radius: radius,
  1403. Adj: adjForKind(prst, kind, spPr),
  1404. HTML: tr.HTML, Text: tr.Plain, TextColor: tr.First.Color,
  1405. FontSize: units.Round2(tr.FontSize), FontFamily: tr.FontCSS,
  1406. Bold: tr.Bold, Italic: tr.Italic,
  1407. Align: tr.Align, VAlign: anchorToVAlign(bp.Anchor), Pad: pad,
  1408. LineHeight: units.Round2(tr.LineH),
  1409. },
  1410. }
  1411. }
  1412. // cornerRadius resolves the corner radius of a rounded rectangle, in px
  1413. func (sc *slideCtx) cornerRadius(spPr *xmltree.Node, prst string, box xfrmBox) float64 {
  1414. if !strings.Contains(strings.ToLower(prst), "round") {
  1415. return 0
  1416. }
  1417. adj := 16667.0 // the DrawingML default for roundRect
  1418. // the guide that rounds the corner: roundRect's "adj", a rounded
  1419. // callout's "adj3" (its adj1/adj2 place the tip, and read as a radius
  1420. // they made the corners enormous), adj1 for the other rounded presets
  1421. want := "adj1"
  1422. switch prst {
  1423. case "roundRect":
  1424. want = "adj"
  1425. case "wedgeRoundRectCallout":
  1426. want = "adj3"
  1427. }
  1428. if g := spPr.First("prstGeom"); g != nil {
  1429. if av := g.First("avLst"); av != nil {
  1430. for _, gd := range av.All("gd") {
  1431. if gd.Attr("name") == want {
  1432. if v := strings.TrimPrefix(gd.Attr("fmla"), "val "); v != gd.Attr("fmla") {
  1433. adj = units.AtofDefault(v, adj)
  1434. }
  1435. }
  1436. }
  1437. }
  1438. }
  1439. return math.Min(box.W, box.H) * adj / 100000
  1440. }
  1441. // styleRefColor resolves the colour of a <p:style> fillRef / lnRef, which
  1442. // is how PowerPoint's shape gallery states a theme fill
  1443. func (sc *slideCtx) styleRefColor(node *xmltree.Node, ref string) string {
  1444. st := node.First("style")
  1445. if st == nil {
  1446. return ""
  1447. }
  1448. r := st.First(ref)
  1449. if r == nil {
  1450. return ""
  1451. }
  1452. if r.Attr("idx") == "0" {
  1453. return "none"
  1454. }
  1455. for i := range r.Nodes {
  1456. if c := sc.cc.resolveColor(&r.Nodes[i]); c != "" {
  1457. return c
  1458. }
  1459. }
  1460. return ""
  1461. }
  1462. // dashStyleOfLn is the editor's dash style for an <a:ln> ("" for solid)
  1463. func dashStyleOfLn(spPr *xmltree.Node) string {
  1464. if ln := spPr.First("ln"); ln != nil {
  1465. if d := ln.First("prstDash"); d != nil {
  1466. return dashStyleForPrst(d.Attr("val"))
  1467. }
  1468. }
  1469. return ""
  1470. }
  1471. // lineOf resolves an <a:ln> into colour, width (px) and dash
  1472. func (sc *slideCtx) lineOf(spPr *xmltree.Node, cm coordMap) (string, float64, bool) {
  1473. ln := spPr.First("ln")
  1474. if ln == nil {
  1475. return "", 0, false
  1476. }
  1477. if ln.First("noFill") != nil {
  1478. return "none", 0, false
  1479. }
  1480. color := sc.cc.solidColorOf(ln)
  1481. width := 0.0
  1482. if w := ln.Attr("w"); w != "" {
  1483. width = units.AtofDefault(w, 0) * cm.kx
  1484. }
  1485. if color != "" && width == 0 {
  1486. width = 1 // DrawingML's default hairline
  1487. }
  1488. dash := false
  1489. if d := ln.First("prstDash"); d != nil {
  1490. v := d.Attr("val")
  1491. dash = v != "" && v != "solid"
  1492. }
  1493. return color, width, dash
  1494. }
  1495. // parseCxnSp handles p:cxnSp - connectors, drawn as straight lines
  1496. func (sc *slideCtx) parseCxnSp(node *xmltree.Node, cm coordMap) *model.Object {
  1497. spPr := node.First("spPr")
  1498. if spPr == nil {
  1499. return nil
  1500. }
  1501. box := parseXfrm(spPr.First("xfrm"), cm)
  1502. if !box.OK {
  1503. return nil
  1504. }
  1505. stroke, strokeW, dash := sc.lineOf(spPr, cm)
  1506. if stroke == "" {
  1507. stroke = sc.styleRefColor(node, "lnRef")
  1508. }
  1509. if stroke == "" || stroke == "none" {
  1510. stroke = "#000000"
  1511. }
  1512. if strokeW <= 0 {
  1513. strokeW = 1
  1514. }
  1515. prst := ""
  1516. if g := spPr.First("prstGeom"); g != nil {
  1517. prst = g.Attr("prst")
  1518. }
  1519. pts := connectorPath(prst, spPr, box)
  1520. // the editor stores a line as a start point plus a vector to the far
  1521. // end; anything with a bend carries the full polyline alongside it
  1522. ox, oy := pts[0][0], pts[0][1]
  1523. last := pts[len(pts)-1]
  1524. props := model.Props{Stroke: stroke, StrokeW: units.Round2(strokeW), Dash: dash}
  1525. readLineEnds(spPr.First("ln"), &props)
  1526. if len(pts) > 2 {
  1527. rel := make([][]float64, len(pts))
  1528. for i, p := range pts {
  1529. rel[i] = []float64{units.Round2(p[0] - ox), units.Round2(p[1] - oy)}
  1530. }
  1531. props.Points = rel
  1532. }
  1533. return &model.Object{
  1534. Type: "line", X: ox, Y: oy, W: last[0] - ox, H: last[1] - oy,
  1535. Props: props,
  1536. }
  1537. }
  1538. // isLinePreset reports whether a preset geometry is a line rather than an
  1539. // area: the straight line and every connector
  1540. func isLinePreset(prst string) bool {
  1541. return prst == "line" || prst == "lineInv" || strings.HasSuffix(prst, "Connector1") ||
  1542. strings.HasPrefix(prst, "bentConnector") || strings.HasPrefix(prst, "curvedConnector")
  1543. }
  1544. // connectorPath builds the polyline a connector follows, in absolute
  1545. // editor pixels: the preset's own path, mirrored by the flips and turned
  1546. // by the shape's rotation about the centre of its bounding box.
  1547. func connectorPath(prst string, spPr *xmltree.Node, box xfrmBox) [][2]float64 {
  1548. w, h := box.W, box.H
  1549. var local [][2]float64
  1550. switch prst {
  1551. case "bentConnector2":
  1552. local = [][2]float64{{0, 0}, {w, 0}, {w, h}}
  1553. case "bentConnector3", "bentConnector4", "bentConnector5":
  1554. a := 0.5
  1555. if g := spPr.First("prstGeom"); g != nil {
  1556. if av := g.First("avLst"); av != nil {
  1557. for _, gd := range av.All("gd") {
  1558. if gd.Attr("name") == "adj1" {
  1559. if v := strings.TrimPrefix(gd.Attr("fmla"), "val "); v != gd.Attr("fmla") {
  1560. a = units.AtofDefault(v, 50000) / 100000
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. local = [][2]float64{{0, 0}, {a * w, 0}, {a * w, h}, {w, h}}
  1567. case "lineInv":
  1568. // the other diagonal: bottom left to top right
  1569. local = [][2]float64{{0, h}, {w, 0}}
  1570. default:
  1571. local = [][2]float64{{0, 0}, {w, h}}
  1572. }
  1573. if box.FlipH {
  1574. for i := range local {
  1575. local[i][0] = w - local[i][0]
  1576. }
  1577. }
  1578. if box.FlipV {
  1579. for i := range local {
  1580. local[i][1] = h - local[i][1]
  1581. }
  1582. }
  1583. if box.Rot != 0 {
  1584. rad := box.Rot * math.Pi / 180
  1585. cos, sin := math.Cos(rad), math.Sin(rad)
  1586. cx, cy := w/2, h/2
  1587. for i := range local {
  1588. dx, dy := local[i][0]-cx, local[i][1]-cy
  1589. local[i][0] = cx + dx*cos - dy*sin
  1590. local[i][1] = cy + dx*sin + dy*cos
  1591. }
  1592. }
  1593. out := make([][2]float64, len(local))
  1594. for i := range local {
  1595. out[i] = [2]float64{units.Round2(box.X + local[i][0]), units.Round2(box.Y + local[i][1])}
  1596. }
  1597. return out
  1598. }
  1599. // parsePic handles p:pic - embedded pictures become data URLs
  1600. func (sc *slideCtx) parsePic(node *xmltree.Node, cm coordMap) *model.Object {
  1601. spPr := node.First("spPr")
  1602. if spPr == nil {
  1603. return nil
  1604. }
  1605. box := parseXfrm(spPr.First("xfrm"), cm)
  1606. if !box.OK {
  1607. if layoutSp, masterSp := sc.phChain(node); layoutSp != nil || masterSp != nil {
  1608. box = parseXfrm(firstNonNil(layoutSp, masterSp).Path("spPr", "xfrm"), cm)
  1609. }
  1610. }
  1611. if !box.OK || box.W <= 0 || box.H <= 0 {
  1612. return nil
  1613. }
  1614. blipFill := node.First("blipFill")
  1615. blip := blipFill.First("blip")
  1616. if blip == nil {
  1617. return nil
  1618. }
  1619. rid := blip.AttrNS("relationships", "embed")
  1620. if rid == "" {
  1621. for _, a := range blip.Attrs {
  1622. if a.Name.Local == "embed" {
  1623. rid = a.Value
  1624. }
  1625. }
  1626. }
  1627. target, ok := sc.partRels()[rid]
  1628. if !ok {
  1629. return nil
  1630. }
  1631. mediaPath := xmltree.ResolvePart(sc.partDir(), target)
  1632. data, ok := sc.doc.files[mediaPath]
  1633. if !ok {
  1634. return nil
  1635. }
  1636. ext := strings.TrimPrefix(strings.ToLower(path.Ext(mediaPath)), ".")
  1637. // a Windows metafile (old decks store scans as .wmf) is rendered to a
  1638. // bitmap the browser can show
  1639. data, ext, _ = metafile.BrowserPicture(data, ext)
  1640. props := model.Props{Src: media.EncodeDataURL(data, ext), Fit: "fill"}
  1641. // srcRect crops the source before it is stretched into the frame
  1642. if sr := blipFill.First("srcRect"); sr != nil {
  1643. l := units.AtofDefault(sr.Attr("l"), 0) / 100000
  1644. t := units.AtofDefault(sr.Attr("t"), 0) / 100000
  1645. r := units.AtofDefault(sr.Attr("r"), 0) / 100000
  1646. b := units.AtofDefault(sr.Attr("b"), 0) / 100000
  1647. if l != 0 || t != 0 || r != 0 || b != 0 {
  1648. props.Crop = []float64{units.Round4(l), units.Round4(t), units.Round4(r), units.Round4(b)}
  1649. }
  1650. }
  1651. if blipFill.First("stretch") == nil && blipFill.First("tile") == nil {
  1652. // a blipFill with neither is still stretched by PowerPoint
  1653. props.Fit = "fill"
  1654. }
  1655. prst := ""
  1656. if g := spPr.First("prstGeom"); g != nil {
  1657. prst = g.Attr("prst")
  1658. }
  1659. // a picture drawn through a preset geometry is a shaped crop
  1660. if kind, ok := prstToShapeKind[prst]; ok && kind != "rect" {
  1661. props.Mask = kind
  1662. // the guides it states reshape it, when the editor draws it as
  1663. // itself (roundRect's corner is props.Radius instead)
  1664. if kind == prst && kind != "roundRect" {
  1665. props.Adj = statedAdj(spPr)
  1666. }
  1667. }
  1668. if rad := sc.cornerRadius(spPr, prst, box); rad > 0 {
  1669. props.Radius = units.Round2(rad)
  1670. }
  1671. props.FlipH, props.FlipV = box.FlipH, box.FlipV
  1672. // a frame drawn around the picture (screenshots often carry one)
  1673. if stroke, sw, dash := sc.lineOf(spPr, cm); stroke != "" && stroke != "none" && sw > 0 {
  1674. props.Stroke, props.StrokeW, props.Dash = stroke, units.Round2(sw), dash
  1675. readLineEnds(spPr.First("ln"), &props)
  1676. props.StartHead, props.EndHead, props.ArrowStart, props.ArrowEnd = "", "", false, false
  1677. }
  1678. readPictureEffects(blip, &props)
  1679. // a fill on the picture's frame shows wherever the picture is
  1680. // transparent (or does not reach, under a negative crop)
  1681. if c, g := sc.shapeFill(node, spPr); c != "" && c != "none" {
  1682. props.Fill, props.FillGrad = c, g
  1683. }
  1684. return &model.Object{
  1685. Type: "image", X: box.X, Y: box.Y, W: box.W, H: box.H, Rot: box.Rot,
  1686. Props: props,
  1687. }
  1688. }
  1689. /* ---------------- tables ---------------- */
  1690. // parseGraphicFrame handles p:graphicFrame - tables (charts are skipped)
  1691. func (sc *slideCtx) parseGraphicFrame(node *xmltree.Node, cm coordMap) *model.Object {
  1692. box := parseXfrm(node.First("xfrm"), cm)
  1693. if !box.OK || box.W <= 0 || box.H <= 0 {
  1694. return nil
  1695. }
  1696. gdata := node.Path("graphic", "graphicData")
  1697. tbl := gdata.First("tbl")
  1698. if tbl == nil {
  1699. // the other graphicData the editor can model is a chart
  1700. return sc.parseChartFrame(gdata, box)
  1701. }
  1702. headerRow := false
  1703. tblPr := tbl.First("tblPr")
  1704. if tblPr != nil {
  1705. headerRow = tblPr.Attr("firstRow") == "1"
  1706. }
  1707. flags := readTblFlags(tblPr)
  1708. style := sc.tableStyleFor(tbl)
  1709. // column proportions from the grid definition
  1710. var colW []float64
  1711. var totalW float64
  1712. if grid := tbl.First("tblGrid"); grid != nil {
  1713. var ws []float64
  1714. for _, gc := range grid.All("gridCol") {
  1715. v := units.AtofDefault(gc.Attr("w"), 0)
  1716. ws = append(ws, v)
  1717. totalW += v
  1718. }
  1719. if totalW > 0 && len(ws) > 1 {
  1720. for _, v := range ws {
  1721. colW = append(colW, units.Round2(v/totalW*100.0))
  1722. }
  1723. }
  1724. }
  1725. trs := tbl.All("tr")
  1726. var rowH []float64
  1727. var totalH float64
  1728. for _, tr := range trs {
  1729. totalH += units.AtofDefault(tr.Attr("h"), 0)
  1730. }
  1731. // a table sizes itself from its own grid, not from the frame's ext -
  1732. // Google Slides writes a fixed dummy ext there and PowerPoint ignores it
  1733. if totalW > 0 {
  1734. box.W, _ = cm.size(totalW, 0)
  1735. }
  1736. if totalH > 0 {
  1737. _, box.H = cm.size(0, totalH)
  1738. }
  1739. // table text has no placeholder of its own; it falls back to the
  1740. // master's "other" style, which is where a deck states its table size
  1741. var chain []*xmltree.Node
  1742. if ts := sc.master.Path("txStyles", "otherStyle"); ts != nil {
  1743. chain = append(chain, ts)
  1744. }
  1745. var rows [][]string
  1746. var cellFill [][]string
  1747. var cellPad []float64
  1748. fontSize := 0.0
  1749. color := ""
  1750. var merges [][]int
  1751. var cellAnchor [][]string
  1752. nCols := 0
  1753. for _, tr := range trs {
  1754. if n := len(tr.All("tc")); n > nCols {
  1755. nCols = n
  1756. }
  1757. }
  1758. for ri, tr := range trs {
  1759. if totalH > 0 {
  1760. rowH = append(rowH, units.Round2(units.AtofDefault(tr.Attr("h"), 0)/totalH*100.0))
  1761. }
  1762. var row, fills, anchors []string
  1763. for ci, tc := range tr.All("tc") {
  1764. tcPr := tc.First("tcPr")
  1765. anchors = append(anchors, map[string]string{"ctr": "middle", "b": "bottom"}[tcPr.Attr("anchor")])
  1766. // the table style's look for this cell, then the cell's own fill
  1767. var look cellLook
  1768. if style != nil {
  1769. look = sc.lookOf(styleParts(style, flags, ri, ci, len(trs), nCols))
  1770. }
  1771. fill := look.fill
  1772. if c := sc.cc.fillColorOf(tcPr); c == "none" {
  1773. fill = ""
  1774. } else if c != "" {
  1775. fill = c
  1776. }
  1777. fills = append(fills, fill)
  1778. if cellPad == nil && tcPr != nil {
  1779. cellPad = []float64{
  1780. units.Round2(units.AtofDefault(tcPr.Attr("marT"), 45720) * cm.ky),
  1781. units.Round2(units.AtofDefault(tcPr.Attr("marR"), 91440) * cm.kx),
  1782. units.Round2(units.AtofDefault(tcPr.Attr("marB"), 45720) * cm.ky),
  1783. units.Round2(units.AtofDefault(tcPr.Attr("marL"), 91440) * cm.kx),
  1784. }
  1785. }
  1786. if tc.Attr("hMerge") == "1" || tc.Attr("vMerge") == "1" {
  1787. // covered by a merged cell: kept as an empty cell, which the
  1788. // merge's span draws over
  1789. row = append(row, "")
  1790. continue
  1791. }
  1792. rs := int(units.AtofDefault(tc.Attr("rowSpan"), 1))
  1793. cs := int(units.AtofDefault(tc.Attr("gridSpan"), 1))
  1794. if rs > 1 || cs > 1 {
  1795. merges = append(merges, []int{ri, ci, max(rs, 1), max(cs, 1)})
  1796. }
  1797. bp := sc.resolveBodyPr([]*xmltree.Node{tc.Path("txBody", "bodyPr")}, cm)
  1798. bp.LIns, bp.RIns, bp.TIns, bp.BIns = 0, 0, 0, 0
  1799. cellChain := chain
  1800. if ls := lookTextStyle(look); ls != nil {
  1801. cellChain = append(append([]*xmltree.Node{}, chain...), ls)
  1802. }
  1803. res := sc.buildTextBody(tc.First("txBody"), cellChain, bp, cm)
  1804. if fontSize == 0 && res.FontSize > 0 {
  1805. fontSize = res.FontSize
  1806. }
  1807. if color == "" {
  1808. color = res.First.Color
  1809. }
  1810. row = append(row, res.HTML)
  1811. }
  1812. if len(row) > 0 {
  1813. rows = append(rows, row)
  1814. cellFill = append(cellFill, fills)
  1815. cellAnchor = append(cellAnchor, anchors)
  1816. }
  1817. }
  1818. if len(rows) == 0 {
  1819. return nil
  1820. }
  1821. if fontSize <= 0 {
  1822. fontSize = 16
  1823. }
  1824. if !anyFilled(cellFill) {
  1825. cellFill = nil
  1826. }
  1827. if !anyFilled(cellAnchor) {
  1828. cellAnchor = nil
  1829. }
  1830. props := model.Props{Rows: rows, HeaderRow: headerRow, FontSize: units.Round2(fontSize),
  1831. Color: color, ColW: colW, RowH: rowH,
  1832. CellFill: cellFill, CellPad: cellPad, Merges: merges, CellAnchor: cellAnchor}
  1833. if style != nil {
  1834. // the style is the whole look: the editor's own heading shading and
  1835. // bold heading row stay off, and the rules are the style's
  1836. props.Styled = true
  1837. props.Stroke, props.StrokeW = sc.tableBorder(style, cm)
  1838. if props.Stroke == "" {
  1839. props.Stroke, props.StrokeW = sc.cellBorder(tbl, cm)
  1840. }
  1841. }
  1842. return &model.Object{
  1843. Type: "table", X: box.X, Y: box.Y, W: box.W, H: box.H,
  1844. Props: props,
  1845. }
  1846. }
  1847. // anyFilled reports whether a cell-fill grid states at least one colour
  1848. func anyFilled(grid [][]string) bool {
  1849. for _, row := range grid {
  1850. for _, c := range row {
  1851. if c != "" {
  1852. return true
  1853. }
  1854. }
  1855. }
  1856. return false
  1857. }
  1858. /* ---------------- notes ---------------- */
  1859. // extractNotes pulls the body text of the linked notesSlide part, if any.
  1860. // The slide-number and date placeholders that ride along in the same part
  1861. // are skipped - they are chrome, not the speaker's notes.
  1862. func (sc *slideCtx) extractNotes() string {
  1863. notesPath := relTarget(sc.rels, sc.baseDir, "notesSlide", sc.doc.files)
  1864. if notesPath == "" {
  1865. return ""
  1866. }
  1867. tree := sc.doc.tree(notesPath)
  1868. if tree == nil {
  1869. return ""
  1870. }
  1871. spTree := tree.Path("cSld", "spTree")
  1872. if spTree == nil {
  1873. return ""
  1874. }
  1875. var shapes []*xmltree.Node
  1876. spTree.FindAll("sp", &shapes)
  1877. var lines []string
  1878. for _, sp := range shapes {
  1879. key, isPh := phOf(sp)
  1880. if isPh && key.typ != "body" {
  1881. continue
  1882. }
  1883. tx := sp.First("txBody")
  1884. if tx == nil {
  1885. continue
  1886. }
  1887. for _, p := range tx.All("p") {
  1888. var parts []string
  1889. for i := range p.Nodes {
  1890. ch := &p.Nodes[i]
  1891. if ch.XMLName.Local == "r" || ch.XMLName.Local == "fld" {
  1892. if t := ch.First("t"); t != nil {
  1893. parts = append(parts, t.Text)
  1894. }
  1895. } else if ch.XMLName.Local == "br" {
  1896. parts = append(parts, "\n")
  1897. }
  1898. }
  1899. lines = append(lines, strings.Join(parts, ""))
  1900. }
  1901. }
  1902. for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
  1903. lines = lines[:len(lines)-1]
  1904. }
  1905. return strings.Join(lines, "\n")
  1906. }
  1907. // partRels / partDir name the relationship scope of the part being walked,
  1908. // falling back to the slide's own when nothing else is in scope
  1909. func (sc *slideCtx) partRels() map[string]string {
  1910. if sc.curRels != nil {
  1911. return sc.curRels
  1912. }
  1913. return sc.rels
  1914. }
  1915. func (sc *slideCtx) partDir() string {
  1916. if sc.curDir != "" {
  1917. return sc.curDir
  1918. }
  1919. return sc.baseDir
  1920. }
  1921. // freeformLine turns an unfilled custGeom of straight segments into a line
  1922. // object with its polyline. Returns nil when the shape is anything else.
  1923. func (sc *slideCtx) freeformLine(node, spPr *xmltree.Node, box xfrmBox, cm coordMap) *model.Object {
  1924. if c := sc.cc.fillColorOf(spPr); c != "" && c != "none" {
  1925. return nil
  1926. }
  1927. stroke, strokeW, dash := sc.lineOf(spPr, cm)
  1928. if stroke == "" || stroke == "none" {
  1929. return nil
  1930. }
  1931. pathLst := spPr.Path("custGeom", "pathLst")
  1932. if pathLst == nil {
  1933. return nil
  1934. }
  1935. paths := pathLst.All("path")
  1936. if len(paths) != 1 {
  1937. return nil
  1938. }
  1939. path := paths[0]
  1940. pw := units.AtofDefault(path.Attr("w"), 0)
  1941. ph := units.AtofDefault(path.Attr("h"), 0)
  1942. if pw <= 0 || ph <= 0 {
  1943. return nil
  1944. }
  1945. var pts [][]float64
  1946. for i := range path.Nodes {
  1947. seg := &path.Nodes[i]
  1948. switch seg.XMLName.Local {
  1949. case "moveTo", "lnTo":
  1950. pt := seg.First("pt")
  1951. if pt == nil {
  1952. return nil
  1953. }
  1954. // path coordinates are relative to the path box, which maps
  1955. // onto the shape's own extent
  1956. pts = append(pts, []float64{
  1957. units.Round2(units.AtofDefault(pt.Attr("x"), 0) / pw * box.W),
  1958. units.Round2(units.AtofDefault(pt.Attr("y"), 0) / ph * box.H),
  1959. })
  1960. case "close", "cubicBezTo", "quadBezTo", "arcTo":
  1961. return nil
  1962. }
  1963. }
  1964. if len(pts) < 2 {
  1965. return nil
  1966. }
  1967. // the editor's line origin is the first point, so the polyline it
  1968. // carries is relative to that
  1969. ox, oy := pts[0][0], pts[0][1]
  1970. for i := range pts {
  1971. pts[i][0] = units.Round2(pts[i][0] - ox)
  1972. pts[i][1] = units.Round2(pts[i][1] - oy)
  1973. }
  1974. last := pts[len(pts)-1]
  1975. props := model.Props{Stroke: stroke, StrokeW: units.Round2(strokeW), Dash: dash}
  1976. readLineEnds(spPr.First("ln"), &props)
  1977. if len(pts) > 2 {
  1978. props.Points = pts
  1979. }
  1980. return &model.Object{
  1981. Type: "line",
  1982. X: box.X + ox, Y: box.Y + oy,
  1983. W: last[0], H: last[1],
  1984. Props: props,
  1985. }
  1986. }
  1987. // parseChartFrame resolves a graphicFrame that holds a DrawingML chart
  1988. func (sc *slideCtx) parseChartFrame(gdata *xmltree.Node, box xfrmBox) *model.Object {
  1989. ref := gdata.First("chart")
  1990. if ref == nil {
  1991. return nil
  1992. }
  1993. rid := ref.AttrNS("relationships", "id")
  1994. if rid == "" {
  1995. rid = ref.Attr("id")
  1996. }
  1997. target, ok := sc.partRels()[rid]
  1998. if !ok {
  1999. return nil
  2000. }
  2001. tree := sc.doc.tree(xmltree.ResolvePart(sc.partDir(), target))
  2002. if tree == nil {
  2003. return nil
  2004. }
  2005. spec := sc.parseChartSpec(tree)
  2006. if spec == nil {
  2007. return nil
  2008. }
  2009. return &model.Object{
  2010. Type: "chart", X: box.X, Y: box.Y, W: box.W, H: box.H,
  2011. Props: model.Props{Spec: chartSpecJSON(spec)},
  2012. }
  2013. }
  2014. // readPictureEffects reads the colour effects DrawingML allows on a
  2015. // picture's blip: transparency, a greyscale wash, a duotone tint and the
  2016. // luminance (brightness / contrast) pair. They map onto the editor's
  2017. // re-colour presets and adjustment offsets.
  2018. func readPictureEffects(blip *xmltree.Node, props *model.Props) {
  2019. if blip == nil {
  2020. return
  2021. }
  2022. if am := blip.First("alphaModFix"); am != nil {
  2023. if v := am.Attr("amt"); v != "" {
  2024. if o := clamp01(units.AtofDefault(v, 100000) / 100000); o < 1 {
  2025. props.Opacity = units.Round2(o)
  2026. }
  2027. }
  2028. }
  2029. if blip.First("grayscl") != nil {
  2030. props.Recolor = "gray"
  2031. }
  2032. if blip.First("biLevel") != nil {
  2033. props.Recolor = "black-white"
  2034. }
  2035. if dt := blip.First("duotone"); dt != nil {
  2036. // the second stop is the colour the picture is washed into
  2037. plain := colorCtx{}
  2038. var hexes []string
  2039. for i := range dt.Nodes {
  2040. if c := plain.resolveColor(&dt.Nodes[i]); c != "" {
  2041. hexes = append(hexes, c)
  2042. }
  2043. }
  2044. if len(hexes) > 0 {
  2045. props.Recolor = nearestRecolor(hexes[len(hexes)-1])
  2046. }
  2047. }
  2048. if lum := blip.First("lum"); lum != nil {
  2049. if v := lum.Attr("bright"); v != "" {
  2050. props.Bright = units.Round2(units.AtofDefault(v, 0) / 100000)
  2051. }
  2052. if v := lum.Attr("contrast"); v != "" {
  2053. props.Contrast = units.Round2(units.AtofDefault(v, 0) / 100000)
  2054. }
  2055. }
  2056. }
  2057. // recolorTints is the colour each re-colour preset washes a picture into,
  2058. // shared by the reader (nearest match on a duotone) and the writer
  2059. var recolorTints = map[string]string{
  2060. "blue-light": "#9fc5f8", "blue-dark": "#1c4587", "teal": "#12b5cb",
  2061. "green": "#34a853", "lime": "#b7e1a1", "yellow": "#ffd966",
  2062. "orange": "#f6b26b", "red": "#e06666", "purple": "#8e7cc3",
  2063. "pink": "#ea9999", "sepia": "#b5814f", "washout": "#d9d9d9",
  2064. }
  2065. // nearestRecolor picks the preset whose tint is closest to a colour
  2066. func nearestRecolor(hex string) string {
  2067. r, g, b := hexToRGB(hex)
  2068. best, bestD := "gray", 0.0
  2069. first := true
  2070. for key, tint := range recolorTints {
  2071. tr, tg, tb := hexToRGB(tint)
  2072. d := (r-tr)*(r-tr) + (g-tg)*(g-tg) + (b-tb)*(b-tb)
  2073. if first || d < bestD {
  2074. best, bestD, first = key, d, false
  2075. }
  2076. }
  2077. return best
  2078. }
  2079. /* ---------------- transitions and click links ---------------- */
  2080. // hiddenSlide reports PowerPoint's Hide Slide: <p:sld show="0"> (an
  2081. // xsd:boolean, so "false" says the same), which the slide show skips
  2082. func hiddenSlide(sld *xmltree.Node) bool {
  2083. v := strings.TrimSpace(sld.Attr("show"))
  2084. return v == "0" || v == "false"
  2085. }
  2086. // transitionOf maps a slide's <p:transition> onto the editor's three:
  2087. // fade, slide (anything that moves the slide in) and zoom. PowerPoint 2010
  2088. // and later wrap it in mc:AlternateContent, with a plain fallback.
  2089. func transitionOf(sld *xmltree.Node) string {
  2090. tr := sld.First("transition")
  2091. if tr == nil {
  2092. if ac := sld.First("AlternateContent"); ac != nil {
  2093. if fb := ac.First("Fallback"); fb != nil {
  2094. tr = fb.First("transition")
  2095. }
  2096. if tr == nil {
  2097. if ch := ac.First("Choice"); ch != nil {
  2098. tr = ch.First("transition")
  2099. }
  2100. }
  2101. }
  2102. }
  2103. if tr == nil {
  2104. return ""
  2105. }
  2106. for i := range tr.Nodes {
  2107. switch tr.Nodes[i].XMLName.Local {
  2108. case "fade", "dissolve", "cut":
  2109. return "fade"
  2110. case "push", "cover", "pull", "wipe", "split", "strips", "randomBar", "blinds", "checker", "comb", "wheel", "wedge", "circle", "diamond", "plus", "newsflash", "random", "vortex", "ripple", "flip", "gallery", "cube", "doors", "box", "conveyor", "pan", "glitter", "honeycomb", "flash", "shred", "switch", "ferris", "flythrough", "warp", "reveal", "prism":
  2111. return "slide"
  2112. case "zoom":
  2113. return "zoom"
  2114. case "sndAc", "extLst":
  2115. continue
  2116. default:
  2117. return "fade"
  2118. }
  2119. }
  2120. return ""
  2121. }
  2122. // isGoogleShape reports whether Google Slides made this shape: its export
  2123. // names every one "Google Shape;<id>;<page>", and no other producer does
  2124. func isGoogleShape(node *xmltree.Node) bool {
  2125. for i := range node.Nodes {
  2126. if strings.HasPrefix(node.Nodes[i].XMLName.Local, "nv") {
  2127. if c := node.Nodes[i].First("cNvPr"); c != nil {
  2128. return strings.HasPrefix(c.Attr("name"), "Google Shape;")
  2129. }
  2130. return false
  2131. }
  2132. }
  2133. return false
  2134. }
  2135. // withLink reads a shape's click action into props.link: a jump to another
  2136. // slide becomes "#N", an external address stays as it is (http(s) only)
  2137. func (sc *slideCtx) withLink(node *xmltree.Node, obj *model.Object) *model.Object {
  2138. if obj == nil {
  2139. return nil
  2140. }
  2141. var cNvPr *xmltree.Node
  2142. for i := range node.Nodes {
  2143. if strings.HasPrefix(node.Nodes[i].XMLName.Local, "nv") {
  2144. cNvPr = node.Nodes[i].First("cNvPr")
  2145. break
  2146. }
  2147. }
  2148. hl := cNvPr.First("hlinkClick")
  2149. if hl == nil {
  2150. return obj
  2151. }
  2152. rid := hl.AttrNS("relationships", "id")
  2153. target := sc.partRels()[rid]
  2154. action := hl.Attr("action")
  2155. switch {
  2156. case strings.Contains(action, "hlinksldjump"):
  2157. if n, ok := sc.doc.slideIndex[xmltree.ResolvePart(sc.partDir(), target)]; ok {
  2158. obj.Props.Link = "#" + strconv.Itoa(n)
  2159. }
  2160. case strings.Contains(action, "hlinkshowjump"):
  2161. // first / last / next / previous slide: no absolute target to keep
  2162. case action == "" && target != "":
  2163. low := strings.ToLower(target)
  2164. if strings.HasPrefix(low, "http://") || strings.HasPrefix(low, "https://") {
  2165. obj.Props.Link = target
  2166. }
  2167. }
  2168. return obj
  2169. }