props.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. package docx
  2. /*
  3. props.go - WordprocessingML formatting properties and the style
  4. inheritance that resolves them.
  5. A paragraph's appearance in Word is almost never stated on the paragraph
  6. itself. It is the sum, lowest priority first, of
  7. docDefaults (rPrDefault / pPrDefault)
  8. the paragraph style, walked up its basedOn chain
  9. the paragraph's own pPr
  10. for a run: the character style chain, then the run's own rPr
  11. and a table adds its table style (and TableNormal behind that) for
  12. borders and cell margins. Every property below is therefore optional -
  13. "not stated" and "stated as off" are different things, and the second
  14. one has to win over an inherited "on". Google Docs writes explicit
  15. w:val="0" for nearly every toggle, which is exactly the case an
  16. "element present = on" reader gets wrong (italic headings, bold body).
  17. */
  18. import (
  19. "strconv"
  20. "strings"
  21. "imuslab.com/arozos/mod/office/internal/xmltree"
  22. )
  23. // optBool is a toggle that may or may not be stated
  24. type optBool struct {
  25. set bool
  26. v bool
  27. }
  28. // optNum is a number that may or may not be stated
  29. type optNum struct {
  30. set bool
  31. v float64
  32. }
  33. func (o *optBool) merge(src optBool) {
  34. if src.set {
  35. *o = src
  36. }
  37. }
  38. func (o *optNum) merge(src optNum) {
  39. if src.set {
  40. *o = src
  41. }
  42. }
  43. // onOff reads a WordprocessingML ST_OnOff element: present without w:val
  44. // means on
  45. func onOff(n *xmltree.Node) optBool {
  46. if n == nil {
  47. return optBool{}
  48. }
  49. switch strings.ToLower(n.Attr("val")) {
  50. case "0", "false", "off", "none":
  51. return optBool{set: true, v: false}
  52. }
  53. return optBool{set: true, v: true}
  54. }
  55. // numAttr reads a numeric attribute (Google Docs writes "100.0")
  56. func numAttr(n *xmltree.Node, name string) optNum {
  57. if n == nil {
  58. return optNum{}
  59. }
  60. s := strings.TrimSpace(n.Attr(name))
  61. if s == "" {
  62. return optNum{}
  63. }
  64. v, err := strconv.ParseFloat(s, 64)
  65. if err != nil {
  66. return optNum{}
  67. }
  68. return optNum{set: true, v: v}
  69. }
  70. /* ---------------- run properties ---------------- */
  71. type docxRPr struct {
  72. b, i, strike, dstrike, caps, smallCaps, vanish optBool
  73. u string // "" = not stated, "none" = off
  74. color string // RRGGBB, "auto", or ""
  75. highlight string // named highlight colour
  76. shd string // RRGGBB fill
  77. sz optNum // half-points
  78. fontASCII, fontEA string
  79. vert string // superscript | subscript | baseline
  80. rStyle string
  81. }
  82. func parseRPr(n *xmltree.Node) docxRPr {
  83. r := docxRPr{}
  84. if n == nil {
  85. return r
  86. }
  87. r.b = onOff(n.First("b"))
  88. r.i = onOff(n.First("i"))
  89. r.strike = onOff(n.First("strike"))
  90. r.dstrike = onOff(n.First("dstrike"))
  91. r.caps = onOff(n.First("caps"))
  92. r.smallCaps = onOff(n.First("smallCaps"))
  93. r.vanish = onOff(n.First("vanish"))
  94. if u := n.First("u"); u != nil {
  95. r.u = u.Attr("val")
  96. if r.u == "" {
  97. r.u = "single"
  98. }
  99. }
  100. if c := n.First("color"); c != nil {
  101. r.color = strings.ToUpper(c.Attr("val"))
  102. }
  103. if h := n.First("highlight"); h != nil {
  104. r.highlight = h.Attr("val")
  105. }
  106. if s := n.First("shd"); s != nil {
  107. if f := strings.ToUpper(s.Attr("fill")); len(f) == 6 {
  108. r.shd = f
  109. } else if f == "AUTO" {
  110. r.shd = "auto"
  111. }
  112. }
  113. r.sz = numAttr(n.First("sz"), "val")
  114. if f := n.First("rFonts"); f != nil {
  115. r.fontASCII = f.Attr("ascii")
  116. if r.fontASCII == "" {
  117. r.fontASCII = f.Attr("hAnsi")
  118. }
  119. r.fontEA = f.Attr("eastAsia")
  120. }
  121. if va := n.First("vertAlign"); va != nil {
  122. r.vert = va.Attr("val")
  123. }
  124. if rs := n.First("rStyle"); rs != nil {
  125. r.rStyle = rs.Attr("val")
  126. }
  127. return r
  128. }
  129. func (r *docxRPr) merge(src docxRPr) {
  130. r.b.merge(src.b)
  131. r.i.merge(src.i)
  132. r.strike.merge(src.strike)
  133. r.dstrike.merge(src.dstrike)
  134. r.caps.merge(src.caps)
  135. r.smallCaps.merge(src.smallCaps)
  136. r.vanish.merge(src.vanish)
  137. if src.u != "" {
  138. r.u = src.u
  139. }
  140. if src.color != "" {
  141. r.color = src.color
  142. }
  143. if src.highlight != "" {
  144. r.highlight = src.highlight
  145. }
  146. if src.shd != "" {
  147. r.shd = src.shd
  148. }
  149. r.sz.merge(src.sz)
  150. if src.fontASCII != "" {
  151. r.fontASCII = src.fontASCII
  152. }
  153. if src.fontEA != "" {
  154. r.fontEA = src.fontEA
  155. }
  156. if src.vert != "" {
  157. r.vert = src.vert
  158. }
  159. }
  160. /* ---------------- paragraph properties ---------------- */
  161. type docxBorder struct {
  162. val string
  163. sz float64 // eighths of a point
  164. color string
  165. space float64 // points
  166. }
  167. // visible reports whether the border draws anything
  168. func (b docxBorder) visible() bool {
  169. switch b.val {
  170. case "", "nil", "none":
  171. return false
  172. }
  173. return true
  174. }
  175. func parseBorder(n *xmltree.Node) (docxBorder, bool) {
  176. if n == nil {
  177. return docxBorder{}, false
  178. }
  179. b := docxBorder{val: n.Attr("val"), color: strings.ToUpper(n.Attr("color"))}
  180. if v := numAttr(n, "sz"); v.set {
  181. b.sz = v.v
  182. }
  183. if v := numAttr(n, "space"); v.set {
  184. b.space = v.v
  185. }
  186. return b, true
  187. }
  188. type docxTab struct {
  189. align string // left | right | center | decimal | clear
  190. pos float64 // twips from the text column's left edge
  191. leader string // none | dot | hyphen | underscore ...
  192. }
  193. type docxPPr struct {
  194. style string
  195. before, after, line optNum
  196. lineRule string
  197. indL, indR, indFirst, indHang optNum
  198. jc string
  199. keepNext, keepLines, pageBreakBefore optBool
  200. widow, contextual optBool
  201. shd string
  202. borders map[string]docxBorder
  203. numID string
  204. numSet bool
  205. ilvl optNum
  206. tabs []docxTab
  207. sect *xmltree.Node
  208. mark docxRPr // paragraph mark run properties
  209. outline optNum
  210. // spacing before / after is Word's "auto" (HTML) spacing
  211. autoBefore, autoAfter optBool
  212. }
  213. func parsePPr(n *xmltree.Node) docxPPr {
  214. p := docxPPr{}
  215. if n == nil {
  216. return p
  217. }
  218. if ps := n.First("pStyle"); ps != nil {
  219. p.style = ps.Attr("val")
  220. }
  221. if sp := n.First("spacing"); sp != nil {
  222. p.before = numAttr(sp, "before")
  223. p.after = numAttr(sp, "after")
  224. p.line = numAttr(sp, "line")
  225. p.lineRule = sp.Attr("lineRule")
  226. // "auto" spacing before/after is Word's HTML-ish 14pt; close enough
  227. if onOff2(sp.Attr("beforeAutospacing")) {
  228. p.before = optNum{set: true, v: 280}
  229. p.autoBefore = optBool{set: true, v: true}
  230. }
  231. if onOff2(sp.Attr("afterAutospacing")) {
  232. p.after = optNum{set: true, v: 280}
  233. p.autoAfter = optBool{set: true, v: true}
  234. }
  235. }
  236. if ind := n.First("ind"); ind != nil {
  237. p.indL = numAttr(ind, "left")
  238. if !p.indL.set {
  239. p.indL = numAttr(ind, "start")
  240. }
  241. p.indR = numAttr(ind, "right")
  242. if !p.indR.set {
  243. p.indR = numAttr(ind, "end")
  244. }
  245. p.indFirst = numAttr(ind, "firstLine")
  246. p.indHang = numAttr(ind, "hanging")
  247. // a stated firstLine clears an inherited hanging indent and vice versa
  248. if p.indFirst.set && !p.indHang.set {
  249. p.indHang = optNum{set: true, v: 0}
  250. }
  251. if p.indHang.set && !p.indFirst.set {
  252. p.indFirst = optNum{set: true, v: 0}
  253. }
  254. }
  255. if jc := n.First("jc"); jc != nil {
  256. p.jc = jc.Attr("val")
  257. }
  258. p.keepNext = onOff(n.First("keepNext"))
  259. p.keepLines = onOff(n.First("keepLines"))
  260. p.pageBreakBefore = onOff(n.First("pageBreakBefore"))
  261. p.widow = onOff(n.First("widowControl"))
  262. p.contextual = onOff(n.First("contextualSpacing"))
  263. if s := n.First("shd"); s != nil {
  264. if f := strings.ToUpper(s.Attr("fill")); len(f) == 6 {
  265. p.shd = f
  266. } else if f == "AUTO" {
  267. p.shd = "auto"
  268. }
  269. }
  270. if bd := n.First("pBdr"); bd != nil {
  271. p.borders = map[string]docxBorder{}
  272. for _, side := range []string{"top", "left", "bottom", "right"} {
  273. if b, ok := parseBorder(bd.First(side)); ok {
  274. p.borders[side] = b
  275. }
  276. }
  277. }
  278. if np := n.First("numPr"); np != nil {
  279. if id := np.First("numId"); id != nil {
  280. p.numID = id.Attr("val")
  281. p.numSet = true
  282. }
  283. p.ilvl = numAttr(np.First("ilvl"), "val")
  284. }
  285. if tabs := n.First("tabs"); tabs != nil {
  286. for _, t := range tabs.All("tab") {
  287. pos := numAttr(t, "pos")
  288. if !pos.set {
  289. continue
  290. }
  291. p.tabs = append(p.tabs, docxTab{align: t.Attr("val"), pos: pos.v, leader: t.Attr("leader")})
  292. }
  293. }
  294. p.sect = n.First("sectPr")
  295. p.mark = parseRPr(n.First("rPr"))
  296. p.outline = numAttr(n.First("outlineLvl"), "val")
  297. return p
  298. }
  299. func onOff2(s string) bool {
  300. switch strings.ToLower(s) {
  301. case "1", "true", "on":
  302. return true
  303. }
  304. return false
  305. }
  306. func (p *docxPPr) merge(src docxPPr) {
  307. if src.style != "" {
  308. p.style = src.style
  309. }
  310. p.before.merge(src.before)
  311. p.after.merge(src.after)
  312. if src.before.set {
  313. p.autoBefore = src.autoBefore
  314. }
  315. if src.after.set {
  316. p.autoAfter = src.autoAfter
  317. }
  318. if src.line.set {
  319. p.line = src.line
  320. p.lineRule = src.lineRule
  321. }
  322. p.indL.merge(src.indL)
  323. p.indR.merge(src.indR)
  324. p.indFirst.merge(src.indFirst)
  325. p.indHang.merge(src.indHang)
  326. if src.jc != "" {
  327. p.jc = src.jc
  328. }
  329. p.keepNext.merge(src.keepNext)
  330. p.keepLines.merge(src.keepLines)
  331. p.pageBreakBefore.merge(src.pageBreakBefore)
  332. p.widow.merge(src.widow)
  333. p.contextual.merge(src.contextual)
  334. if src.shd != "" {
  335. p.shd = src.shd
  336. }
  337. if src.borders != nil {
  338. if p.borders == nil {
  339. p.borders = map[string]docxBorder{}
  340. }
  341. for k, v := range src.borders {
  342. p.borders[k] = v
  343. }
  344. }
  345. if src.numSet {
  346. p.numID = src.numID
  347. p.numSet = true
  348. }
  349. p.ilvl.merge(src.ilvl)
  350. if len(src.tabs) > 0 {
  351. // tab stops accumulate; a "clear" stop removes an inherited one
  352. for _, t := range src.tabs {
  353. kept := p.tabs[:0]
  354. for _, old := range p.tabs {
  355. if absF(old.pos-t.pos) > 1 {
  356. kept = append(kept, old)
  357. }
  358. }
  359. p.tabs = kept
  360. if t.align != "clear" {
  361. p.tabs = append(p.tabs, t)
  362. }
  363. }
  364. }
  365. if src.sect != nil {
  366. p.sect = src.sect
  367. }
  368. p.outline.merge(src.outline)
  369. }
  370. /* ---------------- table properties ---------------- */
  371. type docxTblPr struct {
  372. style string
  373. width optNum
  374. widthType string
  375. ind optNum
  376. jc string
  377. borders map[string]docxBorder // top left bottom right insideH insideV
  378. cellMar map[string]optNum // top left bottom right (twips)
  379. layout string
  380. }
  381. func parseTblPr(n *xmltree.Node) docxTblPr {
  382. t := docxTblPr{}
  383. if n == nil {
  384. return t
  385. }
  386. if s := n.First("tblStyle"); s != nil {
  387. t.style = s.Attr("val")
  388. }
  389. if w := n.First("tblW"); w != nil {
  390. t.width = numAttr(w, "w")
  391. t.widthType = w.Attr("type")
  392. }
  393. if ind := n.First("tblInd"); ind != nil {
  394. t.ind = numAttr(ind, "w")
  395. }
  396. if jc := n.First("jc"); jc != nil {
  397. t.jc = jc.Attr("val")
  398. }
  399. if l := n.First("tblLayout"); l != nil {
  400. t.layout = l.Attr("type")
  401. }
  402. t.borders = parseBorderSet(n.First("tblBorders"))
  403. t.cellMar = parseMarginSet(n.First("tblCellMar"))
  404. return t
  405. }
  406. func parseBorderSet(n *xmltree.Node) map[string]docxBorder {
  407. if n == nil {
  408. return nil
  409. }
  410. out := map[string]docxBorder{}
  411. for _, side := range []string{"top", "left", "bottom", "right", "insideH", "insideV"} {
  412. b, ok := parseBorder(n.First(side))
  413. if !ok {
  414. // start/end are the bidi-neutral spellings of left/right
  415. if side == "left" {
  416. b, ok = parseBorder(n.First("start"))
  417. } else if side == "right" {
  418. b, ok = parseBorder(n.First("end"))
  419. }
  420. }
  421. if ok {
  422. out[side] = b
  423. }
  424. }
  425. return out
  426. }
  427. func parseMarginSet(n *xmltree.Node) map[string]optNum {
  428. if n == nil {
  429. return nil
  430. }
  431. out := map[string]optNum{}
  432. for _, side := range []string{"top", "left", "bottom", "right"} {
  433. m := n.First(side)
  434. if m == nil {
  435. if side == "left" {
  436. m = n.First("start")
  437. } else if side == "right" {
  438. m = n.First("end")
  439. }
  440. }
  441. if v := numAttr(m, "w"); v.set {
  442. out[side] = v
  443. }
  444. }
  445. return out
  446. }
  447. func (t *docxTblPr) merge(src docxTblPr) {
  448. if src.style != "" {
  449. t.style = src.style
  450. }
  451. if src.width.set {
  452. t.width = src.width
  453. t.widthType = src.widthType
  454. }
  455. t.ind.merge(src.ind)
  456. if src.jc != "" {
  457. t.jc = src.jc
  458. }
  459. if src.layout != "" {
  460. t.layout = src.layout
  461. }
  462. if src.borders != nil {
  463. if t.borders == nil {
  464. t.borders = map[string]docxBorder{}
  465. }
  466. for k, v := range src.borders {
  467. t.borders[k] = v
  468. }
  469. }
  470. if src.cellMar != nil {
  471. if t.cellMar == nil {
  472. t.cellMar = map[string]optNum{}
  473. }
  474. for k, v := range src.cellMar {
  475. t.cellMar[k] = v
  476. }
  477. }
  478. }
  479. /* ---------------- style sheet ---------------- */
  480. type docxStyle struct {
  481. id, typ, name, basedOn string
  482. pPr docxPPr
  483. rPr docxRPr
  484. tbl docxTblPr
  485. }
  486. type docxStyleSheet struct {
  487. docP docxPPr
  488. docR docxRPr
  489. styles map[string]*docxStyle
  490. defPara string
  491. defTable string
  492. defChar string
  493. resolvedP map[string]*docxPPr
  494. resolvedR map[string]*docxRPr
  495. resolvedTbl map[string]*docxTblPr
  496. }
  497. func parseStyleSheet(raw []byte) *docxStyleSheet {
  498. ss := &docxStyleSheet{
  499. styles: map[string]*docxStyle{},
  500. resolvedP: map[string]*docxPPr{},
  501. resolvedR: map[string]*docxRPr{},
  502. resolvedTbl: map[string]*docxTblPr{},
  503. }
  504. if raw == nil {
  505. return ss
  506. }
  507. tree, err := xmltree.Parse(raw)
  508. if err != nil {
  509. return ss
  510. }
  511. if dd := tree.First("docDefaults"); dd != nil {
  512. ss.docR = parseRPr(dd.Path("rPrDefault", "rPr"))
  513. ss.docP = parsePPr(dd.Path("pPrDefault", "pPr"))
  514. }
  515. for _, s := range tree.All("style") {
  516. st := &docxStyle{id: s.Attr("styleId"), typ: s.Attr("type")}
  517. if n := s.First("name"); n != nil {
  518. st.name = n.Attr("val")
  519. }
  520. if b := s.First("basedOn"); b != nil {
  521. st.basedOn = b.Attr("val")
  522. }
  523. st.pPr = parsePPr(s.First("pPr"))
  524. st.pPr.style = ""
  525. st.rPr = parseRPr(s.First("rPr"))
  526. st.tbl = parseTblPr(s.First("tblPr"))
  527. ss.styles[st.id] = st
  528. if onOff2(s.Attr("default")) {
  529. switch st.typ {
  530. case "paragraph":
  531. ss.defPara = st.id
  532. case "table":
  533. ss.defTable = st.id
  534. case "character":
  535. ss.defChar = st.id
  536. }
  537. }
  538. }
  539. return ss
  540. }
  541. // chain returns the style and its basedOn ancestors, root first
  542. func (ss *docxStyleSheet) chain(id string) []*docxStyle {
  543. var out []*docxStyle
  544. seen := map[string]bool{}
  545. for id != "" && !seen[id] {
  546. seen[id] = true
  547. st, ok := ss.styles[id]
  548. if !ok {
  549. break
  550. }
  551. out = append([]*docxStyle{st}, out...)
  552. id = st.basedOn
  553. }
  554. return out
  555. }
  556. // paraStyle resolves a paragraph style (the default one when id is empty)
  557. // into the pPr/rPr it contributes on top of docDefaults
  558. func (ss *docxStyleSheet) paraStyle(id string) (*docxPPr, *docxRPr) {
  559. if id == "" || ss.styles[id] == nil {
  560. id = ss.defPara
  561. }
  562. if p, ok := ss.resolvedP[id]; ok {
  563. return p, ss.resolvedR[id]
  564. }
  565. p := ss.docP
  566. p.style = ""
  567. r := ss.docR
  568. for _, st := range ss.chain(id) {
  569. p.merge(st.pPr)
  570. r.merge(st.rPr)
  571. }
  572. ss.resolvedP[id] = &p
  573. ss.resolvedR[id] = &r
  574. return &p, &r
  575. }
  576. // charStyle returns what a character style chain contributes
  577. func (ss *docxStyleSheet) charStyle(id string) docxRPr {
  578. r := docxRPr{}
  579. for _, st := range ss.chain(id) {
  580. r.merge(st.rPr)
  581. }
  582. return r
  583. }
  584. // tableStyle resolves a table style (TableNormal behind it)
  585. func (ss *docxStyleSheet) tableStyle(id string) *docxTblPr {
  586. key := "tbl:" + id
  587. if t, ok := ss.resolvedTbl[key]; ok {
  588. return t
  589. }
  590. t := docxTblPr{}
  591. if ss.defTable != "" && ss.defTable != id {
  592. for _, st := range ss.chain(ss.defTable) {
  593. t.merge(st.tbl)
  594. }
  595. }
  596. for _, st := range ss.chain(id) {
  597. t.merge(st.tbl)
  598. }
  599. ss.resolvedTbl[key] = &t
  600. return &t
  601. }
  602. // headingLevel reports which heading (1-6) a paragraph style is, 0 for none.
  603. // Title and Subtitle come back as -1 and -2.
  604. func (ss *docxStyleSheet) headingLevel(id string) int {
  605. // walk from the style itself towards its roots: a custom style based
  606. // on a heading is that heading
  607. chain := ss.chain(id)
  608. for i := len(chain) - 1; i >= 0; i-- {
  609. if lvl := styleNameLevel(chain[i].id, chain[i].name); lvl != 0 {
  610. return lvl
  611. }
  612. }
  613. if len(chain) == 0 {
  614. return styleNameLevel(id, "")
  615. }
  616. return 0
  617. }
  618. func styleNameLevel(id, name string) int {
  619. n := strings.ToLower(id)
  620. if name != "" {
  621. n = strings.ToLower(name)
  622. }
  623. compact := strings.ReplaceAll(n, " ", "")
  624. switch {
  625. case compact == "title":
  626. return -1
  627. case compact == "subtitle":
  628. return -2
  629. case strings.HasPrefix(compact, "heading") && len(compact) == 8 && compact[7] >= '1' && compact[7] <= '6':
  630. return int(compact[7] - '0')
  631. }
  632. return 0
  633. }