zhao
2021-07-09 0821715ebc11d3934d0594a1cc2c39686d808906
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/* ====================================================================
   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.Model
{
    using System;
    using System.Text;
    using System.Collections;
    using HH.WMS.Utils.NPOI.HSSF.Record;
    using HH.WMS.Utils.NPOI.HSSF.Record.Aggregates;
    using HH.WMS.Utils.NPOI.HSSF.Record.AutoFilter;
    using System.Collections.Generic;
    using HH.WMS.Utils.NPOI.HSSF.Record.PivotTable;
 
    /**
     * Finds correct insert positions for records in workbook streams<p/>
     * 
     * See OOO excelfileformat.pdf sec. 4.2.5 'Record Order in a BIFF8 Workbook Stream'
     * 
     * @author Josh Micich
     */
    public class RecordOrderer
    {
 
        // TODO - simplify logic using a generalised record ordering
 
        private RecordOrderer()
        {
            // no instances of this class
        }
        /**
         * Adds the specified new record in the correct place in sheet records list
         * 
         */
        public static void AddNewSheetRecord(List<RecordBase> sheetRecords, RecordBase newRecord)
        {
            int index = FindSheetInsertPos(sheetRecords, newRecord.GetType());
            sheetRecords.Insert(index, newRecord);
        }
 
        private static int FindSheetInsertPos(List<RecordBase> records, Type recClass)
        {
            if (recClass == typeof(DataValidityTable))
            {
                return FindDataValidationTableInsertPos(records);
            }
            if (recClass == typeof(MergedCellsTable))
            {
                return FindInsertPosForNewMergedRecordTable(records);
            }
            if (recClass == typeof(ConditionalFormattingTable))
            {
                return FindInsertPosForNewCondFormatTable(records);
            }
            if (recClass == typeof(GutsRecord))
            {
                return GetGutsRecordInsertPos(records);
            }
            if (recClass == typeof(PageSettingsBlock))
            {
                return GetPageBreakRecordInsertPos(records);
            }
            if (recClass == typeof(WorksheetProtectionBlock))
            {
                return GetWorksheetProtectionBlockInsertPos(records);
            }
            throw new InvalidOperationException("Unexpected record class (" + recClass.Name + ")");
        }
        /// <summary>
        /// Finds the index where the protection block should be inserted
        /// </summary>
        /// <param name="records">the records for this sheet</param>
        /// <returns></returns>
        /// <remark>
        /// + BOF
        /// o INDEX
        /// o Calculation Settings Block
        /// o PRINTHEADERS
        /// o PRINTGRIDLINES
        /// o GRIDSET
        /// o GUTS
        /// o DEFAULTROWHEIGHT
        /// o SHEETPR
        /// o Page Settings Block
        /// o Worksheet Protection Block
        /// o DEFCOLWIDTH
        /// oo COLINFO
        /// o SORT
        /// + DIMENSION
        /// </remark>
        private static int GetWorksheetProtectionBlockInsertPos(List<RecordBase> records)
        {
            int i = GetDimensionsIndex(records);
            while (i > 0)
            {
                i--;
                Object rb = records[i];
                if (!IsProtectionSubsequentRecord(rb))
                {
                    return i + 1;
                }
            }
            throw new InvalidOperationException("did not find insert pos for protection block");
        }
        /// <summary>
        /// These records may occur between the 'Worksheet Protection Block' and DIMENSION:
        /// </summary>
        /// <param name="rb"></param>
        /// <returns></returns>
        /// <remarks>
        /// o DEFCOLWIDTH
        /// oo COLINFO
        /// o SORT
        /// </remarks>
        private static bool IsProtectionSubsequentRecord(Object rb)
        {
            if (rb is ColumnInfoRecordsAggregate)
            {
                return true; // oo COLINFO
            }
            if (rb is Record)
            {
                Record record = (Record)rb;
                switch (record.Sid)
                {
                    case DefaultColWidthRecord.sid:
                    case UnknownRecord.SORT_0090:
                        return true;
                }
            }
            return false;
        }
        private static int GetPageBreakRecordInsertPos(List<RecordBase> records)
        {
            int dimensionsIndex = GetDimensionsIndex(records);
            int i = dimensionsIndex - 1;
            while (i > 0)
            {
                i--;
                RecordBase rb = records[i];
                if (IsPageBreakPriorRecord(rb))
                {
                    return i + 1;
                }
            }
            throw new InvalidOperationException("Did not Find insert point for GUTS");
        }
        private static bool IsPageBreakPriorRecord(RecordBase rb)
        {
            if (rb is Record)
            {
                Record record = (Record)rb;
                switch (record.Sid)
                {
                    case BOFRecord.sid:
                    case IndexRecord.sid:
                    // calc settings block
                    case UncalcedRecord.sid:
                    case CalcCountRecord.sid:
                    case CalcModeRecord.sid:
                    case PrecisionRecord.sid:
                    case RefModeRecord.sid:
                    case DeltaRecord.sid:
                    case IterationRecord.sid:
                    case DateWindow1904Record.sid:
                    case SaveRecalcRecord.sid:
                    // end calc settings
                    case PrintHeadersRecord.sid:
                    case PrintGridlinesRecord.sid:
                    case GridsetRecord.sid:
                    case DefaultRowHeightRecord.sid:
                    case UnknownRecord.SHEETPR_0081:
                        return true;
                    // next is the 'Worksheet Protection Block'
                }
            }
            return false;
        }
        /// <summary>
        /// Find correct position to add new CFHeader record
        /// </summary>
        /// <param name="records"></param>
        /// <returns></returns>
        private static int FindInsertPosForNewCondFormatTable(List<RecordBase> records)
        {
 
            for (int i = records.Count - 2; i >= 0; i--)
            { // -2 to skip EOF record
                Object rb = records[i];
                if (rb is MergedCellsTable)
                {
                    return i + 1;
                }
                if (rb is DataValidityTable)
                {
                    continue;
                }
                Record rec = (Record)rb;
                switch (rec.Sid)
                {
                    case WindowTwoRecord.sid:
                    case SCLRecord.sid:
                    case PaneRecord.sid:
                    case SelectionRecord.sid:
                    case UnknownRecord.STANDARDWIDTH_0099:
                    // MergedCellsTable usually here 
                    case UnknownRecord.LABELRANGES_015F:
                    case UnknownRecord.PHONETICPR_00EF:
                        // ConditionalFormattingTable goes here
                        return i + 1;
                    // HyperlinkTable (not aggregated by POI yet)
                    // DataValidityTable
                }
            }
            throw new InvalidOperationException("Did not Find Window2 record");
        }
 
        private static int FindInsertPosForNewMergedRecordTable(List<RecordBase> records)
        {
            for (int i = records.Count - 2; i >= 0; i--)
            { // -2 to skip EOF record
                Object rb = records[i];
                if (!(rb is Record))
                {
                    // DataValidityTable, ConditionalFormattingTable, 
                    // even PageSettingsBlock (which doesn't normally appear after 'View Settings')
                    continue;
                }
                Record rec = (Record)rb;
                switch (rec.Sid)
                {
                    // 'View Settings' (4 records) 
                    case WindowTwoRecord.sid:
                    case SCLRecord.sid:
                    case PaneRecord.sid:
                    case SelectionRecord.sid:
 
                    case UnknownRecord.STANDARDWIDTH_0099:
                        return i + 1;
                }
            }
            throw new InvalidOperationException("Did not Find Window2 record");
        }
 
 
        /**
         * Finds the index where the sheet validations header record should be inserted
         * @param records the records for this sheet
         * 
         * + WINDOW2
         * o SCL
         * o PANE
         * oo SELECTION
         * o STANDARDWIDTH
         * oo MERGEDCELLS
         * o LABELRANGES
         * o PHONETICPR
         * o Conditional Formatting Table
         * o Hyperlink Table
         * o Data Validity Table
         * o SHEETLAYOUT
         * o SHEETPROTECTION
         * o RANGEPROTECTION
         * + EOF
         */
        private static int FindDataValidationTableInsertPos(List<RecordBase> records)
        {
            int i = records.Count - 1;
            if (!(records[i] is EOFRecord))
            {
                throw new InvalidOperationException("Last sheet record should be EOFRecord");
            }
            while (i > 0)
            {
                i--;
                RecordBase rb = records[i];
                if (IsDVTPriorRecord(rb))
                {
                    Record nextRec = (Record)records[i + 1];
                    if (!IsDVTSubsequentRecord(nextRec.Sid))
                    {
                        throw new InvalidOperationException("Unexpected (" + nextRec.GetType().Name
                                + ") found after (" + rb.GetType().Name + ")");
                    }
                    return i + 1;
                }
                Record rec = (Record)rb;
                if (!IsDVTSubsequentRecord(rec.Sid))
                {
                    throw new InvalidOperationException("Unexpected (" + rec.GetType().Name
                            + ") while looking for DV Table insert pos");
                }
            }
            return 0;
        }
 
 
        private static bool IsDVTPriorRecord(RecordBase rb)
        {
            if (rb is MergedCellsTable || rb is ConditionalFormattingTable)
            {
                return true;
            }
            short sid = ((Record)rb).Sid;
            switch (sid)
            {
                case WindowTwoRecord.sid:
                case UnknownRecord.SCL_00A0:
                case PaneRecord.sid:
                case SelectionRecord.sid:
                case UnknownRecord.STANDARDWIDTH_0099:
                // MergedCellsTable
                case UnknownRecord.LABELRANGES_015F:
                case UnknownRecord.PHONETICPR_00EF:
                // ConditionalFormattingTable
                case HyperlinkRecord.sid:
                case UnknownRecord.QUICKTIP_0800:
                    return true;
            }
            return false;
        }
 
        private static bool IsDVTSubsequentRecord(short sid)
        {
            switch (sid)
            {
                //case UnknownRecord.SHEETEXT_0862:
                case SheetExtRecord.sid:
                case UnknownRecord.SHEETPROTECTION_0867:
                //case UnknownRecord.RANGEPROTECTION_0868:
                case FeatRecord.sid: 
                case EOFRecord.sid:
                    return true;
            }
            return false;
        }
        /**
         * DIMENSIONS record is always present
         */
        private static int GetDimensionsIndex(List<RecordBase> records)
        {
            int nRecs = records.Count;
            for (int i = 0; i < nRecs; i++)
            {
                if (records[i] is DimensionsRecord)
                {
                    return i;
                }
            }
            // worksheet stream is seriously broken
            throw new InvalidOperationException("DimensionsRecord not found");
        }
 
        private static int GetGutsRecordInsertPos(List<RecordBase> records)
        {
            int dimensionsIndex = GetDimensionsIndex(records);
            int i = dimensionsIndex - 1;
            while (i > 0)
            {
                i--;
                RecordBase rb = records[i];
                if (IsGutsPriorRecord(rb))
                {
                    return i + 1;
                }
            }
            throw new InvalidOperationException("Did not Find insert point for GUTS");
        }
 
        private static bool IsGutsPriorRecord(RecordBase rb)
        {
            if (rb is Record)
            {
                Record record = (Record)rb;
                switch (record.Sid)
                {
                    case BOFRecord.sid:
                    case IndexRecord.sid:
                    // calc settings block
                        case UncalcedRecord.sid:
                        case CalcCountRecord.sid:
                        case CalcModeRecord.sid:
                        case PrecisionRecord.sid:
                        case RefModeRecord.sid:
                        case DeltaRecord.sid:
                        case IterationRecord.sid:
                        case DateWindow1904Record.sid:
                        case SaveRecalcRecord.sid:
                    // end calc settings
                    case PrintHeadersRecord.sid:
                    case PrintGridlinesRecord.sid:
                    case GridsetRecord.sid:
                        return true;
                    // DefaultRowHeightRecord.sid is next
                }
            }
            return false;
        }
        /// <summary>
        /// if the specified record ID terminates a sequence of Row block records
        /// It is assumed that at least one row or cell value record has been found prior to the current 
        /// record
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static bool IsEndOfRowBlock(int sid)
        {
            switch (sid)
            {
                case ViewDefinitionRecord.sid:                // should have been prefixed with DrawingRecord (0x00EC), but bug 46280 seems to allow this
                case DrawingRecord.sid:
                case DrawingSelectionRecord.sid:
                case ObjRecord.sid:
                case TextObjectRecord.sid:
                case GutsRecord.sid:   // see Bugzilla 50426
                case WindowOneRecord.sid:
                // should really be part of workbook stream, but some apps seem to put this before WINDOW2
                case WindowTwoRecord.sid:
                    return true;
 
                case DVALRecord.sid:
                    return true;
                case EOFRecord.sid:
                    // WINDOW2 should always be present, so shouldn't have got this far
                    throw new InvalidOperationException("Found EOFRecord before WindowTwoRecord was encountered");
            }
            return PageSettingsBlock.IsComponentRecord(sid);
        }
        /// <summary>
        /// Whether the specified record id normally appears in the row blocks section of the sheet records
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static bool IsRowBlockRecord(int sid)
        {
            switch (sid)
            {
                case RowRecord.sid:
 
                case BlankRecord.sid:
                case BoolErrRecord.sid:
                case FormulaRecord.sid:
                case LabelRecord.sid:
                case LabelSSTRecord.sid:
                case NumberRecord.sid:
                case RKRecord.sid:
 
                case ArrayRecord.sid:
                case SharedFormulaRecord.sid:
                case TableRecord.sid:
                    return true;
 
            }
            return false;
        }
    }
}