zhao
2021-07-02 081df17b8cc4a6e7e4f4e1e1887f24810e3ec2f9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) Under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for Additional information regarding copyright ownership.
   The ASF licenses this file to You Under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed Under the License is distributed on an "AS Is" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations Under the License.
==================================================================== */
 
namespace HH.WMS.Utils.NPOI.HSSF.Record.Aggregates
{
    using System;
    using System.Text;
    using System.Collections;
    using HH.WMS.Utils.NPOI.HSSF.Record;
    using HH.WMS.Utils.NPOI.HSSF.Util;
    using HH.WMS.Utils.NPOI.HSSF.Model;
    using HH.WMS.Utils.NPOI.Util;
    using HH.WMS.Utils.NPOI.SS.Formula;
    using System.Collections.Generic;
    using HH.WMS.Utils.NPOI.SS.Util;
    using HH.WMS.Utils.NPOI.SS.Formula.PTG;
 
    /// <summary>
    /// 
    /// </summary>
    /// CFRecordsAggregate - aggregates Conditional Formatting records CFHeaderRecord
    /// and number of up to three CFRuleRecord records toGether to simplify
    /// access to them.
    /// @author Dmitriy Kumshayev
    public class CFRecordsAggregate : RecordAggregate
    {
        /** Excel allows up to 3 conditional formating rules */
        private const int MAX_CONDTIONAL_FORMAT_RULES = 3;
 
        public const short sid = -2008; // not a real BIFF record
 
        //private static POILogger log = POILogFactory.GetLogger(typeof(CFRecordsAggregate));
 
        private CFHeaderRecord header;
 
        /** List of CFRuleRecord objects */
        private List<CFRuleRecord> rules;
 
        private CFRecordsAggregate(CFHeaderRecord pHeader, CFRuleRecord[] pRules)
        {
            if (pHeader == null)
            {
                throw new ArgumentException("header must not be null");
            }
            if (pRules == null)
            {
                throw new ArgumentException("rules must not be null");
            }
            if (pRules.Length > MAX_CONDTIONAL_FORMAT_RULES)
            {
                throw new ArgumentException("No more than "
                        + MAX_CONDTIONAL_FORMAT_RULES + " rules may be specified");
            }
            header = pHeader;
            rules = new List<CFRuleRecord>(3);
            for (int i = 0; i < pRules.Length; i++)
            {
                rules.Add(pRules[i]);
            }
        }
 
 
        public CFRecordsAggregate(CellRangeAddress[] regions, CFRuleRecord[] rules)
            : this(new CFHeaderRecord(regions, rules.Length), rules)
        {
 
        }
 
        /// <summary>
        /// Create CFRecordsAggregate from a list of CF Records
        /// </summary>
        /// <param name="rs">list of Record objects</param>
        public static CFRecordsAggregate CreateCFAggregate(RecordStream rs)
        {
            Record rec = rs.GetNext();
            if (rec.Sid != CFHeaderRecord.sid)
            {
                throw new InvalidOperationException("next record sid was " + rec.Sid
                        + " instead of " + CFHeaderRecord.sid + " as expected");
            }
 
            CFHeaderRecord header = (CFHeaderRecord)rec;
            int nRules = header.NumberOfConditionalFormats;
 
            CFRuleRecord[] rules = new CFRuleRecord[nRules];
            for (int i = 0; i < rules.Length; i++)
            {
                rules[i] = (CFRuleRecord)rs.GetNext();
            }
 
            return new CFRecordsAggregate(header, rules);
        }
        /// <summary>
        /// Create CFRecordsAggregate from a list of CF Records
        /// </summary>
        /// <param name="recs">list of Record objects</param>
        /// <param name="pOffset">position of CFHeaderRecord object in the list of Record objects</param>
        public static CFRecordsAggregate CreateCFAggregate(IList recs, int pOffset)
        {
            Record rec = (Record)recs[pOffset];
            if (rec.Sid != CFHeaderRecord.sid)
            {
                throw new InvalidOperationException("next record sid was " + rec.Sid
                        + " instead of " + CFHeaderRecord.sid + " as expected");
            }
 
            CFHeaderRecord header = (CFHeaderRecord)rec;
            int nRules = header.NumberOfConditionalFormats;
 
            CFRuleRecord[] rules = new CFRuleRecord[nRules];
            int offset = pOffset;
            int countFound = 0;
            while (countFound < rules.Length)
            {
                offset++;
                if (offset >= recs.Count)
                {
                    break;
                }
                rec = (Record)recs[offset];
                if (rec is CFRuleRecord)
                {
                    rules[countFound] = (CFRuleRecord)rec;
                    countFound++;
                }
                else
                {
                    break;
                }
            }
 
            if (countFound < nRules)
            { // TODO -(MAR-2008) can this ever happen? Write junit 
 
                //if (log.Check(POILogger.DEBUG))
                //{
                //    log.Log(POILogger.DEBUG, "Expected  " + nRules + " Conditional Formats, "
                //            + "but found " + countFound + " rules");
                //}
                header.NumberOfConditionalFormats = (nRules);
                CFRuleRecord[] lessRules = new CFRuleRecord[countFound];
                Array.Copy(rules, 0, lessRules, 0, countFound);
                rules = lessRules;
            }
            return new CFRecordsAggregate(header, rules);
        }
        public override void VisitContainedRecords(RecordVisitor rv)
        {
            rv.VisitRecord(header);
            for (int i = 0; i < rules.Count; i++)
            {
                CFRuleRecord rule = (CFRuleRecord)rules[i];
                rv.VisitRecord(rule);
            }
        }
 
        /// <summary>
        /// Create a deep Clone of the record
        /// </summary>
        public CFRecordsAggregate CloneCFAggregate()
        {
 
            CFRuleRecord[] newRecs = new CFRuleRecord[rules.Count];
            for (int i = 0; i < newRecs.Length; i++)
            {
                newRecs[i] = (CFRuleRecord)GetRule(i).Clone();
            }
            return new CFRecordsAggregate((CFHeaderRecord)header.Clone(), newRecs);
        }
 
        public override short Sid
        {
            get { return sid; }
        }
 
        /// <summary>
        /// called by the class that is responsible for writing this sucker.
        /// Subclasses should implement this so that their data is passed back in a
        /// byte array.
        /// </summary>
        /// <param name="offset">The offset to begin writing at</param>
        /// <param name="data">The data byte array containing instance data</param>
        /// <returns> number of bytes written</returns>
        public override int Serialize(int offset, byte[] data)
        {
            int nRules = rules.Count;
            header.NumberOfConditionalFormats = (nRules);
 
            int pos = offset;
 
            pos += header.Serialize(pos, data);
            for (int i = 0; i < nRules; i++)
            {
                pos += GetRule(i).Serialize(pos, data);
            }
            return pos - offset;
        }
 
        public CFHeaderRecord Header
        {
            get { return header; }
        }
 
        private void CheckRuleIndex(int idx)
        {
            if (idx < 0 || idx >= rules.Count)
            {
                throw new ArgumentException("Bad rule record index (" + idx
                        + ") nRules=" + rules.Count);
            }
        }
        public CFRuleRecord GetRule(int idx)
        {
            CheckRuleIndex(idx);
            return (CFRuleRecord)rules[idx];
        }
        public void SetRule(int idx, CFRuleRecord r)
        {
            CheckRuleIndex(idx);
            rules[idx] = r;
        }
 
        /**
         * @return <c>false</c> if this whole {@link CFHeaderRecord} / {@link CFRuleRecord}s should be deleted
         */
        public bool UpdateFormulasAfterCellShift(FormulaShifter shifter, int currentExternSheetIx)
        {
            CellRangeAddress[] cellRanges = header.CellRanges;
            bool changed = false;
            ArrayList temp = new ArrayList();
            for (int i = 0; i < cellRanges.Length; i++)
            {
                CellRangeAddress craOld = cellRanges[i];
                CellRangeAddress craNew = ShiftRange(shifter, craOld, currentExternSheetIx);
                if (craNew == null)
                {
                    changed = true;
                    continue;
                }
                temp.Add(craNew);
                if (craNew != craOld)
                {
                    changed = true;
                }
            }
 
            if (changed)
            {
                int nRanges = temp.Count;
                if (nRanges == 0)
                {
                    return false;
                }
                CellRangeAddress[] newRanges = new CellRangeAddress[nRanges];
                newRanges = (CellRangeAddress[])temp.ToArray(typeof(CellRangeAddress));
                header.CellRanges = (newRanges);
            }
 
            for (int i = 0; i < rules.Count; i++)
            {
                CFRuleRecord rule = (CFRuleRecord)rules[i];
                Ptg[] ptgs;
                ptgs = rule.ParsedExpression1;
                if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
                {
                    rule.ParsedExpression1 = (ptgs);
                }
                ptgs = rule.ParsedExpression2;
                if (ptgs != null && shifter.AdjustFormula(ptgs, currentExternSheetIx))
                {
                    rule.ParsedExpression2 = (ptgs);
                }
            }
            return true;
        }
        private static CellRangeAddress ShiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx)
        {
            // FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here
            AreaPtg aptg = new AreaPtg(cra.FirstRow, cra.LastRow, cra.FirstColumn, cra.LastColumn, false, false, false, false);
            Ptg[] ptgs = { aptg, };
 
            if (!shifter.AdjustFormula(ptgs, currentExternSheetIx))
            {
                return cra;
            }
            Ptg ptg0 = ptgs[0];
            if (ptg0 is AreaPtg)
            {
                AreaPtg bptg = (AreaPtg)ptg0;
                return new CellRangeAddress(bptg.FirstRow, bptg.LastRow, bptg.FirstColumn, bptg.LastColumn);
            }
            if (ptg0 is AreaErrPtg)
            {
                return null;
            }
            throw new InvalidCastException("Unexpected shifted ptg class (" + ptg0.GetType().Name + ")");
        }
        public void AddRule(CFRuleRecord r)
        {
            if (rules.Count >= MAX_CONDTIONAL_FORMAT_RULES)
            {
                throw new InvalidOperationException("Cannot have more than "
                        + MAX_CONDTIONAL_FORMAT_RULES + " conditional format rules");
            }
            rules.Add(r);
            header.NumberOfConditionalFormats = (rules.Count);
        }
        public int NumberOfRules
        {
            get { return rules.Count; }
        }
 
        /**
         *  @return sum of sizes of all aggregated records
         */
        public override int RecordSize
        {
            get
            {
                int size = 0;
                if (header != null)
                {
                    size += header.RecordSize;
                }
                if (rules != null)
                {
                    for (IEnumerator irecs = rules.GetEnumerator(); irecs.MoveNext(); )
                    {
                        size += ((Record)irecs.Current).RecordSize;
                    }
                }
                return size;
            }
        }
 
        public override String ToString()
        {
            StringBuilder buffer = new StringBuilder();
 
            buffer.Append("[CF]\n");
            if (header != null)
            {
                buffer.Append(header.ToString());
            }
            for (int i = 0; i < rules.Count; i++)
            {
                CFRuleRecord cfRule = (CFRuleRecord)rules[i];
                if (cfRule != null)
                {
                    buffer.Append(cfRule.ToString());
                }
            }
            buffer.Append("[/CF]\n");
            return buffer.ToString();
        }
    }
}