chart.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package pptx
  2. /*
  3. chart.go - read a DrawingML chart part into the Slides editor's
  4. chart object.
  5. A chart on a slide is a graphicFrame pointing at a ppt/charts/chartN.xml
  6. part, which carries both a reference to the spreadsheet the numbers came
  7. from and a *cache* of the values as they were last drawn. The cache is
  8. what makes this possible without opening the embedded workbook: it holds
  9. the category labels and every series' numbers, which is exactly the shape
  10. OfficeCharts renders from.
  11. Only the chart kinds the editor can draw are read (bar/column, line,
  12. area, pie, doughnut); anything else - scatter, radar, surface, stock,
  13. 3-D variants with no flat equivalent - is left alone, and its frame is
  14. skipped rather than drawn as something it is not.
  15. */
  16. import (
  17. "encoding/json"
  18. "strconv"
  19. "strings"
  20. "imuslab.com/arozos/mod/office/internal/units"
  21. "imuslab.com/arozos/mod/office/internal/xmltree"
  22. )
  23. // chartSpec mirrors the spec OfficeCharts (common/charts.js) renders
  24. type chartSpec struct {
  25. Type string `json:"type"`
  26. Title string `json:"title,omitempty"`
  27. Labels []string `json:"labels"`
  28. Series []chartSeries `json:"series"`
  29. Options chartSpecOptions `json:"options"`
  30. }
  31. type chartSeries struct {
  32. Name string `json:"name,omitempty"`
  33. Values []float64 `json:"values"`
  34. Color string `json:"color,omitempty"`
  35. }
  36. type chartSpecOptions struct {
  37. Legend bool `json:"legend"`
  38. Gridlines bool `json:"gridlines"`
  39. Stacked bool `json:"stacked,omitempty"`
  40. }
  41. // pptxChartKinds maps the plot element name onto an editor chart type
  42. var pptxChartKinds = []struct{ node, kind string }{
  43. {"barChart", "bar"}, {"bar3DChart", "bar"},
  44. {"lineChart", "line"}, {"line3DChart", "line"},
  45. {"areaChart", "line"}, {"area3DChart", "line"},
  46. {"pieChart", "pie"}, {"pie3DChart", "pie"},
  47. {"doughnutChart", "pie"}, {"ofPieChart", "pie"},
  48. }
  49. // parseChartSpec turns a chartSpace tree into the editor's chart spec.
  50. // Returns nil when the chart is of a kind the editor cannot draw or has
  51. // no cached values to draw.
  52. func (sc *slideCtx) parseChartSpec(tree *xmltree.Node) *chartSpec {
  53. chart := tree.First("chart")
  54. if chart == nil {
  55. return nil
  56. }
  57. plotArea := chart.First("plotArea")
  58. if plotArea == nil {
  59. return nil
  60. }
  61. var plot *xmltree.Node
  62. kind := ""
  63. for _, cand := range pptxChartKinds {
  64. if n := plotArea.First(cand.node); n != nil {
  65. plot, kind = n, cand.kind
  66. break
  67. }
  68. }
  69. if plot == nil {
  70. return nil
  71. }
  72. spec := &chartSpec{Type: kind, Labels: []string{}, Series: []chartSeries{}}
  73. if t := chart.First("title"); t != nil && chart.First("autoTitleDeleted").Attr("val") != "1" {
  74. var texts []string
  75. xmltree.CollectText(t, &texts)
  76. spec.Title = strings.TrimSpace(strings.Join(texts, ""))
  77. }
  78. if g := plot.First("grouping"); g != nil {
  79. v := g.Attr("val")
  80. spec.Options.Stacked = v == "stacked" || v == "percentStacked"
  81. }
  82. spec.Options.Legend = chart.First("legend") != nil
  83. for _, ax := range plotArea.All("valAx") {
  84. if ax.First("majorGridlines") != nil {
  85. spec.Options.Gridlines = true
  86. }
  87. }
  88. for _, ser := range plot.All("ser") {
  89. values := cachedNumbers(ser.First("val"))
  90. if len(values) == 0 {
  91. continue
  92. }
  93. s := chartSeries{Values: values}
  94. if names := cachedStrings(ser.First("tx")); len(names) > 0 {
  95. s.Name = names[0]
  96. }
  97. if c := sc.cc.solidColorOf(ser.First("spPr")); c != "" {
  98. s.Color = c
  99. }
  100. if len(spec.Labels) == 0 {
  101. spec.Labels = cachedStrings(ser.First("cat"))
  102. }
  103. spec.Series = append(spec.Series, s)
  104. }
  105. if len(spec.Series) == 0 {
  106. return nil
  107. }
  108. // a chart with no category cache still needs one label per point
  109. if len(spec.Labels) == 0 {
  110. for i := range spec.Series[0].Values {
  111. spec.Labels = append(spec.Labels, strconv.Itoa(i+1))
  112. }
  113. }
  114. return spec
  115. }
  116. // cachedPoints reads the <c:pt> cache under a chart reference, in index
  117. // order, filling gaps so a sparse cache does not shift the series
  118. func cachedPoints(holder *xmltree.Node) []string {
  119. if holder == nil {
  120. return nil
  121. }
  122. var cache *xmltree.Node
  123. for _, ref := range []string{"strRef", "numRef", "multiLvlStrRef"} {
  124. if r := holder.First(ref); r != nil {
  125. for _, cn := range []string{"strCache", "numCache", "lvl"} {
  126. if c := r.First(cn); c != nil {
  127. cache = c
  128. break
  129. }
  130. }
  131. }
  132. if cache != nil {
  133. break
  134. }
  135. }
  136. if cache == nil {
  137. // literal values, written when the chart has no source range
  138. for _, lit := range []string{"strLit", "numLit"} {
  139. if c := holder.First(lit); c != nil {
  140. cache = c
  141. break
  142. }
  143. }
  144. }
  145. if cache == nil {
  146. return nil
  147. }
  148. count := int(units.AtofDefault(cache.First("ptCount").Attr("val"), 0))
  149. pts := cache.All("pt")
  150. if count <= 0 {
  151. count = len(pts)
  152. }
  153. if count <= 0 {
  154. return nil
  155. }
  156. out := make([]string, count)
  157. for _, pt := range pts {
  158. idx := int(units.AtofDefault(pt.Attr("idx"), -1))
  159. if idx < 0 || idx >= count {
  160. continue
  161. }
  162. if v := pt.First("v"); v != nil {
  163. out[idx] = v.Text
  164. }
  165. }
  166. return out
  167. }
  168. func cachedStrings(holder *xmltree.Node) []string {
  169. return cachedPoints(holder)
  170. }
  171. func cachedNumbers(holder *xmltree.Node) []float64 {
  172. raw := cachedPoints(holder)
  173. if len(raw) == 0 {
  174. return nil
  175. }
  176. out := make([]float64, len(raw))
  177. for i, s := range raw {
  178. out[i] = units.AtofDefault(strings.TrimSpace(s), 0)
  179. }
  180. return out
  181. }
  182. // chartSpecJSON serializes a spec for Props.Spec
  183. func chartSpecJSON(spec *chartSpec) json.RawMessage {
  184. if spec == nil {
  185. return nil
  186. }
  187. b, err := json.Marshal(spec)
  188. if err != nil {
  189. return nil
  190. }
  191. return json.RawMessage(b)
  192. }