You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CFRecordsAggregate.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hssf.record.aggregates;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.function.Supplier;
  20. import org.apache.logging.log4j.LogManager;
  21. import org.apache.logging.log4j.Logger;
  22. import org.apache.poi.common.usermodel.GenericRecord;
  23. import org.apache.poi.hssf.model.RecordStream;
  24. import org.apache.poi.hssf.record.CFHeader12Record;
  25. import org.apache.poi.hssf.record.CFHeaderBase;
  26. import org.apache.poi.hssf.record.CFHeaderRecord;
  27. import org.apache.poi.hssf.record.CFRule12Record;
  28. import org.apache.poi.hssf.record.CFRuleBase;
  29. import org.apache.poi.hssf.record.CFRuleRecord;
  30. import org.apache.poi.hssf.record.Record;
  31. import org.apache.poi.ss.formula.FormulaShifter;
  32. import org.apache.poi.ss.formula.ptg.Ptg;
  33. import org.apache.poi.ss.usermodel.helpers.BaseRowColShifter;
  34. import org.apache.poi.ss.util.CellRangeAddress;
  35. import org.apache.poi.util.GenericRecordJsonWriter;
  36. import org.apache.poi.util.GenericRecordUtil;
  37. import org.apache.poi.util.RecordFormatException;
  38. import static org.apache.logging.log4j.util.Unbox.box;
  39. /**
  40. * <p>CFRecordsAggregate - aggregates Conditional Formatting records CFHeaderRecord
  41. * and number of up CFRuleRecord records together to simplify access to them.</p>
  42. * <p>Note that Excel versions before 2007 can only cope with a maximum of 3
  43. * Conditional Formatting rules per sheet. Excel 2007 or newer can cope with
  44. * unlimited numbers, as can Apache OpenOffice. This is an Excel limitation,
  45. * not a file format one.</p>
  46. */
  47. public final class CFRecordsAggregate extends RecordAggregate implements GenericRecord {
  48. /** Excel 97-2003 allows up to 3 conditional formating rules */
  49. private static final int MAX_97_2003_CONDTIONAL_FORMAT_RULES = 3;
  50. private static final Logger LOG = LogManager.getLogger(CFRecordsAggregate.class);
  51. private final CFHeaderBase header;
  52. /** List of CFRuleRecord objects */
  53. private final List<CFRuleBase> rules = new ArrayList<>();
  54. public CFRecordsAggregate(CFRecordsAggregate other) {
  55. header = other.header.copy();
  56. other.rules.stream().map(t -> t.copy()).forEach(rules::add);
  57. }
  58. private CFRecordsAggregate(CFHeaderBase pHeader, CFRuleBase[] pRules) {
  59. if(pHeader == null) {
  60. throw new IllegalArgumentException("header must not be null");
  61. }
  62. if(pRules == null) {
  63. throw new IllegalArgumentException("rules must not be null");
  64. }
  65. if(pRules.length > MAX_97_2003_CONDTIONAL_FORMAT_RULES) {
  66. LOG.atWarn().log("Excel versions before 2007 require that No more than " +
  67. MAX_97_2003_CONDTIONAL_FORMAT_RULES + " rules may be specified, {} were found, this file will " +
  68. "cause problems with old Excel versions", box(pRules.length));
  69. }
  70. if (pRules.length != pHeader.getNumberOfConditionalFormats()) {
  71. throw new RecordFormatException("Mismatch number of rules");
  72. }
  73. header = pHeader;
  74. for (CFRuleBase pRule : pRules) {
  75. checkRuleType(pRule);
  76. rules.add(pRule);
  77. }
  78. }
  79. public CFRecordsAggregate(CellRangeAddress[] regions, CFRuleBase[] rules) {
  80. this(createHeader(regions, rules), rules);
  81. }
  82. private static CFHeaderBase createHeader(CellRangeAddress[] regions, CFRuleBase[] rules) {
  83. final CFHeaderBase header;
  84. if (rules.length == 0 || rules[0] instanceof CFRuleRecord) {
  85. header = new CFHeaderRecord(regions, rules.length);
  86. } else {
  87. header = new CFHeader12Record(regions, rules.length);
  88. }
  89. // set the "needs recalculate" by default to avoid Excel handling conditional formatting incorrectly
  90. // see bug 52122 for details
  91. header.setNeedRecalculation(true);
  92. return header;
  93. }
  94. /**
  95. * Create CFRecordsAggregate from a list of CF Records
  96. * @param rs - the stream to read from
  97. * @return CFRecordsAggregate object
  98. */
  99. public static CFRecordsAggregate createCFAggregate(RecordStream rs) {
  100. Record rec = rs.getNext();
  101. if (rec.getSid() != CFHeaderRecord.sid &&
  102. rec.getSid() != CFHeader12Record.sid) {
  103. throw new IllegalStateException("next record sid was " + rec.getSid()
  104. + " instead of " + CFHeaderRecord.sid + " or " +
  105. CFHeader12Record.sid + " as expected");
  106. }
  107. CFHeaderBase header = (CFHeaderBase)rec;
  108. int nRules = header.getNumberOfConditionalFormats();
  109. CFRuleBase[] rules = new CFRuleBase[nRules];
  110. for (int i = 0; i < rules.length; i++) {
  111. rules[i] = (CFRuleBase) rs.getNext();
  112. }
  113. return new CFRecordsAggregate(header, rules);
  114. }
  115. /**
  116. * Create a deep clone of the record
  117. *
  118. * @return A new object with the same values as this record
  119. */
  120. public CFRecordsAggregate cloneCFAggregate() {
  121. return new CFRecordsAggregate(this);
  122. }
  123. /**
  124. * @return the header. Never <code>null</code>.
  125. */
  126. public CFHeaderBase getHeader() {
  127. return header;
  128. }
  129. private void checkRuleIndex(int idx) {
  130. if(idx < 0 || idx >= rules.size()) {
  131. throw new IllegalArgumentException("Bad rule record index (" + idx
  132. + ") nRules=" + rules.size());
  133. }
  134. }
  135. private void checkRuleType(CFRuleBase r) {
  136. if (header instanceof CFHeaderRecord &&
  137. r instanceof CFRuleRecord) {
  138. return;
  139. }
  140. if (header instanceof CFHeader12Record &&
  141. r instanceof CFRule12Record) {
  142. return;
  143. }
  144. throw new IllegalArgumentException("Header and Rule must both be CF or both be CF12, can't mix");
  145. }
  146. public CFRuleBase getRule(int idx) {
  147. checkRuleIndex(idx);
  148. return rules.get(idx);
  149. }
  150. public void setRule(int idx, CFRuleBase r) {
  151. if (r == null) {
  152. throw new IllegalArgumentException("r must not be null");
  153. }
  154. checkRuleIndex(idx);
  155. checkRuleType(r);
  156. rules.set(idx, r);
  157. }
  158. public void addRule(CFRuleBase r) {
  159. if (r == null) {
  160. throw new IllegalArgumentException("r must not be null");
  161. }
  162. if(rules.size() >= MAX_97_2003_CONDTIONAL_FORMAT_RULES) {
  163. LOG.atWarn().log("Excel versions before 2007 cannot cope with"
  164. + " any more than " + MAX_97_2003_CONDTIONAL_FORMAT_RULES
  165. + " - this file will cause problems with old Excel versions");
  166. }
  167. checkRuleType(r);
  168. rules.add(r);
  169. header.setNumberOfConditionalFormats(rules.size());
  170. }
  171. public int getNumberOfRules() {
  172. return rules.size();
  173. }
  174. @Override
  175. public Map<String, Supplier<?>> getGenericProperties() {
  176. return GenericRecordUtil.getGenericProperties(
  177. "header", this::getHeader,
  178. "rules", () -> rules
  179. );
  180. }
  181. /**
  182. * String representation of CFRecordsAggregate
  183. */
  184. public String toString() {
  185. return GenericRecordJsonWriter.marshal(this);
  186. }
  187. public void visitContainedRecords(RecordVisitor rv) {
  188. rv.visitRecord(header);
  189. for (CFRuleBase rule : rules) {
  190. rv.visitRecord(rule);
  191. }
  192. }
  193. /**
  194. * @param shifter The {@link FormulaShifter} to use
  195. * @param currentExternSheetIx The index for extern sheets
  196. *
  197. * @return <code>false</code> if this whole {@link CFHeaderRecord} / {@link CFRuleRecord}s should be deleted
  198. */
  199. public boolean updateFormulasAfterCellShift(FormulaShifter shifter, int currentExternSheetIx) {
  200. CellRangeAddress[] cellRanges = header.getCellRanges();
  201. boolean changed = false;
  202. List<CellRangeAddress> temp = new ArrayList<>();
  203. for (CellRangeAddress craOld : cellRanges) {
  204. CellRangeAddress craNew = BaseRowColShifter.shiftRange(shifter, craOld, currentExternSheetIx);
  205. if (craNew == null) {
  206. changed = true;
  207. continue;
  208. }
  209. temp.add(craNew);
  210. if (craNew != craOld) {
  211. changed = true;
  212. }
  213. }
  214. if (changed) {
  215. int nRanges = temp.size();
  216. if (nRanges == 0) {
  217. return false;
  218. }
  219. CellRangeAddress[] newRanges = new CellRangeAddress[nRanges];
  220. temp.toArray(newRanges);
  221. header.setCellRanges(newRanges);
  222. }
  223. for (CFRuleBase rule : rules) {
  224. Ptg[] ptgs;
  225. ptgs = rule.getParsedExpression1();
  226. if (ptgs != null && shifter.adjustFormula(ptgs, currentExternSheetIx)) {
  227. rule.setParsedExpression1(ptgs);
  228. }
  229. ptgs = rule.getParsedExpression2();
  230. if (ptgs != null && shifter.adjustFormula(ptgs, currentExternSheetIx)) {
  231. rule.setParsedExpression2(ptgs);
  232. }
  233. if (rule instanceof CFRule12Record) {
  234. CFRule12Record rule12 = (CFRule12Record)rule;
  235. ptgs = rule12.getParsedExpressionScale();
  236. if (ptgs != null && shifter.adjustFormula(ptgs, currentExternSheetIx)) {
  237. rule12.setParsedExpressionScale(ptgs);
  238. }
  239. }
  240. }
  241. return true;
  242. }
  243. }