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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/* ====================================================================
   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
{
    using System;
    using System.Text;
    using HH.WMS.Utils.NPOI.HSSF.Model;
    using HH.WMS.Utils.NPOI.HSSF.Record;
    using HH.WMS.Utils.NPOI.Util;
    using HH.WMS.Utils.NPOI.HSSF.UserModel;
    using HH.WMS.Utils.NPOI.SS.Formula;
    using HH.WMS.Utils.NPOI.HSSF.Record.CF;
    using FR=HH.WMS.Utils.NPOI.SS.Formula;
 
    using HH.WMS.Utils.NPOI.SS.Formula.PTG;
    using HH.WMS.Utils.NPOI.SS.UserModel;
 
    //public enum ComparisonOperator : byte
    //{
    //    NO_COMPARISON = 0,
    //    BETWEEN = 1,
    //    NOT_BETWEEN = 2,
    //    EQUAL = 3,
    //    NOT_EQUAL = 4,
    //    GT = 5,
    //    LT = 6,
    //    GE = 7,
    //    LE = 8
    //}
    /**
     * Conditional Formatting Rule Record.
     * @author Dmitriy Kumshayev
     */
    public class CFRuleRecord : StandardRecord
    {
 
        public const short sid = 0x01B1;
 
 
 
        private byte field_1_condition_type;
        public const byte CONDITION_TYPE_CELL_VALUE_IS = 1;
        public const byte CONDITION_TYPE_FORMULA = 2;
 
        private byte field_2_comparison_operator;
 
        private int field_5_options;
 
        private static BitField modificationBits = bf(0x003FFFFF); // Bits: font,align,bord,patt,prot
        private static BitField alignHor = bf(0x00000001); // 0 = Horizontal alignment modified
        private static BitField alignVer = bf(0x00000002); // 0 = Vertical alignment modified
        private static BitField alignWrap = bf(0x00000004); // 0 = Text wrapped flag modified
        private static BitField alignRot = bf(0x00000008); // 0 = Text rotation modified
        private static BitField alignJustLast = bf(0x00000010); // 0 = Justify last line flag modified
        private static BitField alignIndent = bf(0x00000020); // 0 = Indentation modified
        private static BitField alignShrin = bf(0x00000040); // 0 = Shrink to fit flag modified
        private static BitField notUsed1 = bf(0x00000080); // Always 1
        private static BitField protLocked = bf(0x00000100); // 0 = Cell locked flag modified
        private static BitField protHidden = bf(0x00000200); // 0 = Cell hidden flag modified
        private static BitField bordLeft = bf(0x00000400); // 0 = Left border style and colour modified
        private static BitField bordRight = bf(0x00000800); // 0 = Right border style and colour modified
        private static BitField bordTop = bf(0x00001000); // 0 = Top border style and colour modified
        private static BitField bordBot = bf(0x00002000); // 0 = Bottom border style and colour modified
        private static BitField bordTlBr = bf(0x00004000); // 0 = Top-left to bottom-right border flag modified
        private static BitField bordBlTr = bf(0x00008000); // 0 = Bottom-left to top-right border flag modified
        private static BitField pattStyle = bf(0x00010000); // 0 = Pattern style modified
        private static BitField pattCol = bf(0x00020000); // 0 = Pattern colour modified
        private static BitField pattBgCol = bf(0x00040000); // 0 = Pattern background colour modified
        private static BitField notUsed2 = bf(0x00380000); // Always 111
        private static BitField Undocumented = bf(0x03C00000); // Undocumented bits
        private static BitField fmtBlockBits = bf(0x7C000000); // Bits: font,align,bord,patt,prot
        private static BitField font = bf(0x04000000); // 1 = Record Contains font formatting block
        private static BitField align = bf(0x08000000); // 1 = Record Contains alignment formatting block
        private static BitField bord = bf(0x10000000); // 1 = Record Contains border formatting block
        private static BitField patt = bf(0x20000000); // 1 = Record Contains pattern formatting block
        private static BitField prot = bf(0x40000000); // 1 = Record Contains protection formatting block
        private static BitField alignTextDir = bf(unchecked((int)0x80000000)); // 0 = Text direction modified
 
 
        private static BitField bf(int i)
        {
            return BitFieldFactory.GetInstance(i);
        }
        private short field_6_not_used;
 
        private FontFormatting fontFormatting;
 
        // fix warning CS0414 "never used": private byte field_8_align_text_break;
        // fix warning CS0414 "never used": private byte field_9_align_text_rotation_angle;
        // fix warning CS0414 "never used": private short field_10_align_indentation;
        // fix warning CS0414 "never used": private short field_11_relative_indentation;
        // fix warning CS0414 "never used": private short field_12_not_used;
 
        private BorderFormatting borderFormatting;
 
        private PatternFormatting patternFormatting;
 
        private FR.Formula field_17_formula1;
        private FR.Formula field_18_formula2;
 
        /** Creates new CFRuleRecord */
        private CFRuleRecord(byte conditionType, ComparisonOperator comparisonOperation)
        {
            field_1_condition_type = conditionType;
            field_2_comparison_operator =(byte) comparisonOperation;
 
            // Set modification flags to 1: by default options are not modified
            field_5_options = modificationBits.SetValue(field_5_options, -1);
            // Set formatting block flags to 0 (no formatting blocks)
            field_5_options = fmtBlockBits.SetValue(field_5_options, 0);
            field_5_options = Undocumented.Clear(field_5_options);
 
            //TODO:: check what's this field used for
            field_6_not_used = unchecked((short)0x8002); // Excel seems to Write this value, but it doesn't seem to care what it Reads
            fontFormatting = null;
            //field_8_align_text_break = 0;
            //field_9_align_text_rotation_angle = 0;
            //field_10_align_indentation = 0;
            //field_11_relative_indentation = 0;
            //field_12_not_used = 0;
            borderFormatting = null;
            patternFormatting = null;
            field_17_formula1 = FR.Formula.Create(Ptg.EMPTY_PTG_ARRAY);
            field_18_formula2 = FR.Formula.Create(Ptg.EMPTY_PTG_ARRAY);
        }
 
        private CFRuleRecord(byte conditionType, ComparisonOperator comparisonOperation, Ptg[] formula1, Ptg[] formula2)
            :this(conditionType, comparisonOperation)
        {
            
            //field_1_condition_type = CONDITION_TYPE_CELL_VALUE_IS;
            //field_2_comparison_operator = (byte)comparisonOperation;
            field_17_formula1 = FR.Formula.Create(formula1);
            field_18_formula2 = FR.Formula.Create(formula2);
        }
        /**
         * get the stack of the 1st expression as a list
         *
         * @return list of tokens (casts stack to a list and returns it!)
         * this method can return null is we are unable to create Ptgs from 
         *     existing excel file
         * callers should check for null!
         */
 
        public Ptg[] ParsedExpression1
        {
            get
            {
                return field_17_formula1.Tokens;
            }
            set { field_17_formula1 = FR.Formula.Create(value); }
        }
        /**
 * get the stack of the 2nd expression as a list
 *
 * @return list of tokens (casts stack to a list and returns it!)
 * this method can return null is we are unable to create Ptgs from 
 *     existing excel file
 * callers should check for null!
 */
 
        public Ptg[] ParsedExpression2
        {
            get
            {
                return field_18_formula2.Tokens;
            }
            set { field_18_formula2 = FR.Formula.Create(value); }
        }
 
        /**
         * Creates a new comparison operation rule
         */
        [Obsolete]
        public static CFRuleRecord Create(HSSFWorkbook workbook, String formulaText)
        {
            Ptg[] formula1 = ParseFormula(formulaText, workbook);
            return new CFRuleRecord(CONDITION_TYPE_FORMULA, ComparisonOperator.NO_COMPARISON,
                    formula1, null);
        }
        /**
         * Creates a new comparison operation rule
         */
        [Obsolete]
        public static CFRuleRecord Create(HSSFWorkbook workbook, ComparisonOperator comparisonOperation,
                String formulaText1, String formulaText2)
        {
            Ptg[] formula1 = ParseFormula(formulaText1, workbook);
            Ptg[] formula2 = ParseFormula(formulaText2, workbook);
            return new CFRuleRecord(CONDITION_TYPE_CELL_VALUE_IS, comparisonOperation, formula1, formula2);
        }
        public static CFRuleRecord Create(HSSFSheet sheet, String formulaText)
        {
            Ptg[] formula1 = ParseFormula(formulaText, sheet);
            return new CFRuleRecord(CONDITION_TYPE_FORMULA, ComparisonOperator.NO_COMPARISON,
                    formula1, null);
        }
        /**
         * Creates a new comparison operation rule
         */
        public static CFRuleRecord Create(HSSFSheet sheet, byte comparisonOperation,
                String formulaText1, String formulaText2)
        {
            Ptg[] formula1 = ParseFormula(formulaText1, sheet);
            Ptg[] formula2 = ParseFormula(formulaText2, sheet);
            return new CFRuleRecord(CONDITION_TYPE_CELL_VALUE_IS, (ComparisonOperator)comparisonOperation, formula1, formula2);
        }
        public CFRuleRecord(RecordInputStream in1)
        {
            field_1_condition_type = (byte)in1.ReadByte();
            field_2_comparison_operator = (byte)in1.ReadByte();
            int field_3_formula1_len = in1.ReadUShort();
            int field_4_formula2_len = in1.ReadUShort();
            field_5_options = in1.ReadInt();
            field_6_not_used = in1.ReadShort();
 
            if (ContainsFontFormattingBlock)
            {
                fontFormatting = new FontFormatting(in1);
            }
 
            if (ContainsBorderFormattingBlock)
            {
                borderFormatting = new BorderFormatting(in1);
            }
 
            if (ContainsPatternFormattingBlock)
            {
                patternFormatting = new PatternFormatting(in1);
            }
            field_17_formula1 = FR.Formula.Read(field_3_formula1_len, in1);
            field_18_formula2 = FR.Formula.Read(field_4_formula2_len, in1);
    }
 
        public byte ConditionType
        {
            get { return field_1_condition_type; }
        }
 
        public bool ContainsFontFormattingBlock
        {
            get { return GetOptionFlag(font); }
        }
 
        public FontFormatting FontFormatting
        {
            get
            {
                if (ContainsFontFormattingBlock)
                {
                    return fontFormatting;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                this.fontFormatting = value;
                SetOptionFlag(fontFormatting != null, font);
            }
        }
 
        public bool ContainsAlignFormattingBlock
        {
            get { return GetOptionFlag(align); }
        }
        public void SetAlignFormattingUnChanged()
        {
            SetOptionFlag(false, align);
        }
 
        public bool ContainsBorderFormattingBlock
        {
            get { return GetOptionFlag(bord); }
        }
        public BorderFormatting BorderFormatting
        {
            get
            {
                if (ContainsBorderFormattingBlock)
                {
                    return borderFormatting;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                this.borderFormatting = value;
                SetOptionFlag(borderFormatting != null, bord);
            }
        }
 
        public bool ContainsPatternFormattingBlock
        {
            get { return GetOptionFlag(patt); }
        }
 
        public PatternFormatting PatternFormatting
        {
            get
            {
                if (ContainsPatternFormattingBlock)
                {
                    return patternFormatting;
                }
                else
                {
                    return null;
                }
            }
            set 
            {
                this.patternFormatting = value;
                SetOptionFlag(patternFormatting != null, patt);
            }
        }
 
        public bool ContainsProtectionFormattingBlock
        {
            get { return GetOptionFlag(prot); }
        }
        public void SetProtectionFormattingUnChanged()
        {
            SetOptionFlag(false, prot);
        }
 
        public byte ComparisonOperation
        {
            get { return field_2_comparison_operator; }
            set { field_2_comparison_operator = value; }
        }
 
 
        /**
         * Get the option flags
         *
         * @return bit mask
         */
        public int Options
        {
            get { return field_5_options; }
        }
 
        private bool IsModified(BitField field)
        {
            return !field.IsSet(field_5_options);
        }
 
        private void SetModified(bool modified, BitField field)
        {
            field_5_options = field.SetBoolean(field_5_options, !modified);
        }
 
        public bool IsLeftBorderModified
        {
            get { return IsModified(bordLeft); }
            set { SetModified(value, bordLeft);}
        }
 
        public bool IsRightBorderModified
        {
            get { return IsModified(bordRight); }
            set { SetModified(value, bordRight); }
        }
 
        public bool IsTopBorderModified
        {
            get { return IsModified(bordTop); }
            set { SetModified(value, bordTop);}
        }
 
        public bool IsBottomBorderModified
        {
            get { return IsModified(bordBot); }
            set { SetModified(value, bordBot); }
        }
 
        public bool IsTopLeftBottomRightBorderModified
        {
            get{return IsModified(bordTlBr);}
            set {  SetModified(value, bordTlBr);}
        }
 
        public bool IsBottomLeftTopRightBorderModified
        {
            get { return IsModified(bordBlTr); }
            set { SetModified(value, bordBlTr);}
        }
 
        public bool IsPatternStyleModified
        {
            get { return IsModified(pattStyle); }
            set { SetModified(value, pattStyle);}
        }
 
        public bool IsPatternColorModified
        {
            get { return IsModified(pattCol); }
            set { SetModified(value, pattCol);}
        }
 
        public bool IsPatternBackgroundColorModified
        {
            get { return IsModified(pattBgCol); }
            set {SetModified(value, pattBgCol); }
        }
 
        private bool GetOptionFlag(BitField field)
        {
            return field.IsSet(field_5_options);
        }
 
        private void SetOptionFlag(bool flag, BitField field)
        {
            field_5_options = field.SetBoolean(field_5_options, flag);
        }
 
 
 
        public override short Sid
        {
            get { return sid; }
        }
 
        /**
         * @param ptgs may be <c>null</c>
         * @return encoded size of the formula
         */
        private int GetFormulaSize(FR.Formula formula)
        {
            return formula.EncodedTokenSize;
        }
 
        /**
         * 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.
         *
         * @param offset to begin writing at
         * @param data byte array containing instance data
         * @return number of bytes written
         */
        public override void Serialize(ILittleEndianOutput out1)
        {
            int formula1Len=GetFormulaSize(field_17_formula1);
            int formula2Len=GetFormulaSize(field_18_formula2);
 
            out1.WriteByte(field_1_condition_type);
            out1.WriteByte(field_2_comparison_operator);
            out1.WriteShort(formula1Len);
            out1.WriteShort(formula2Len);
            out1.WriteInt(field_5_options);
            out1.WriteShort(field_6_not_used);
 
            if (ContainsFontFormattingBlock) {
                byte[] fontFormattingRawRecord  = fontFormatting.GetRawRecord();
                out1.Write(fontFormattingRawRecord);
            }
 
            if (ContainsBorderFormattingBlock) {
                borderFormatting.Serialize(out1);
            }
 
            if (ContainsPatternFormattingBlock) {
                patternFormatting.Serialize(out1);
            }
 
            field_17_formula1.SerializeTokens(out1);
            field_18_formula2.SerializeTokens(out1);
        }
 
 
        protected override int DataSize
        {
            get
            {
                int retval = 12 +
                            (ContainsFontFormattingBlock ? fontFormatting.GetRawRecord().Length : 0) +
                            (ContainsBorderFormattingBlock ? 8 : 0) +
                            (ContainsPatternFormattingBlock? 4 : 0) +
                            GetFormulaSize(field_17_formula1) +
                            GetFormulaSize(field_18_formula2)
                            ;
                return retval;
            }
        }
 
 
        public override String ToString()
        {
            StringBuilder buffer = new StringBuilder();
            buffer.Append("[CFRULE]\n");
            buffer.Append("    OPTION FLAGS=0x" + StringUtil.ToHexString(Options));
            /*
            if( ContainsFontFormattingBlock())
            {
                buffer.Append(fontFormatting.ToString());
            }
            if( ContainsBorderFormattingBlock())
            {
                buffer.Append(borderFormatting.ToString());
            }
            if( ContainsPatternFormattingBlock())
            {
                buffer.Append(patternFormatting.ToString());
            }
            buffer.Append("[/CFRULE]\n");*/
            return buffer.ToString();
        }
 
 
        public override Object Clone()
        {
            CFRuleRecord rec = new CFRuleRecord(field_1_condition_type, (ComparisonOperator)field_2_comparison_operator);
            rec.field_5_options = field_5_options;
            rec.field_6_not_used = field_6_not_used;
            if (ContainsFontFormattingBlock)
            {
                rec.fontFormatting = (FontFormatting)fontFormatting.Clone();
            }
            if (ContainsBorderFormattingBlock)
            {
                rec.borderFormatting = (BorderFormatting)borderFormatting.Clone();
            }
            if (ContainsPatternFormattingBlock)
            {
                rec.patternFormatting = (PatternFormatting)patternFormatting.Clone();
            }
            if (field_17_formula1 != null)
            {
                rec.field_17_formula1 = field_17_formula1.Copy();
            }
            if (field_18_formula2 != null)
            {
                rec.field_18_formula2 = field_18_formula2.Copy();
            }
 
            return rec;
        }
 
        /**
         * TODO - Parse conditional format formulas properly i.e. produce tRefN and tAreaN instead of tRef and tArea
         * this call will produce the wrong results if the formula Contains any cell references
         * One approach might be to apply the inverse of SharedFormulaRecord.ConvertSharedFormulas(Stack, int, int)
         * Note - two extra parameters (rowIx &amp;colIx) will be required. They probably come from one of the Region objects.
         * 
         * @return <c>null</c> if <c>formula</c> was null.
         */
        private static Ptg[] ParseFormula(String formula, HSSFWorkbook workbook)
        {
            if (formula == null)
            {
                return null;
            }
            return HSSFFormulaParser.Parse(formula, workbook);
        }
        /**
     * TODO - parse conditional format formulas properly i.e. produce tRefN and tAreaN instead of tRef and tArea
     * this call will produce the wrong results if the formula contains any cell references
     * One approach might be to apply the inverse of SharedFormulaRecord.convertSharedFormulas(Stack, int, int)
     * Note - two extra parameters (rowIx &amp; colIx) will be required. They probably come from one of the Region objects.
     *
     * @return <code>null</code> if <c>formula</c> was null.
     */
        private static Ptg[] ParseFormula(String formula, HSSFSheet sheet)
        {
            if (formula == null)
            {
                return null;
            }
            int sheetIndex = sheet.Workbook.GetSheetIndex(sheet);
            return HSSFFormulaParser.Parse(formula, (HSSFWorkbook)sheet.Workbook, FormulaType.CELL, sheetIndex);
        }
    }
}