zhao
2021-07-19 8347f2fbddbd25369359dcb2da1233ac48a19fdc
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
/* ====================================================================
   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.SS.Formula.PTG
{
 
    using System;
    using System.Text;
    using HH.WMS.Utils.NPOI.Util;
    using HH.WMS.Utils.NPOI.HSSF.Record;
 
 
    using HH.WMS.Utils.NPOI.SS.Util;
    using HH.WMS.Utils.NPOI.SS.Formula.Constant;
 
    /**
     * ArrayPtg - handles arrays
     * 
     * The ArrayPtg is a little weird, the size of the Ptg when parsing initially only
     * includes the Ptg sid and the reserved bytes. The next Ptg in the expression then follows.
     * It is only after the "size" of all the Ptgs is met, that the ArrayPtg data is actually
     * held after this. So Ptg.CreateParsedExpression keeps track of the number of 
     * ArrayPtg elements and need to Parse the data upto the FORMULA record size.
     *  
     * @author Jason Height (jheight at chariot dot net dot au)
     */
    public class ArrayPtg : Ptg
    {
        public const byte sid = 0x20;
 
        private const int RESERVED_FIELD_LEN = 7;
        /** 
 * The size of the plain tArray token written within the standard formula tokens
 * (not including the data which comes after all formula tokens)
 */
        public const int PLAIN_TOKEN_SIZE = 1 + RESERVED_FIELD_LEN;
 
        //private static byte[] DEFAULT_RESERVED_DATA = new byte[RESERVED_FIELD_LEN];
 
        // 7 bytes of data (stored as an int, short and byte here)
        private int _reserved0Int;
        private int _reserved1Short;
        private int _reserved2Byte;
 
        // data from these fields comes after the Ptg data of all tokens in current formula
        private int _nColumns;
        private int _nRows;
        private Object[] _arrayValues;
 
        ArrayPtg(int reserved0, int reserved1, int reserved2, int nColumns, int nRows, Object[] arrayValues)
        {
            _reserved0Int = reserved0;
            _reserved1Short = reserved1;
            _reserved2Byte = reserved2;
            _nColumns = nColumns;
            _nRows = nRows;
            _arrayValues = arrayValues;
        }
        /**
         * @param values2d array values arranged in rows
         */
        public ArrayPtg(Object[][] values2d)
        {
            int nColumns = values2d[0].Length;
            int nRows = values2d.Length;
            // convert 2-d to 1-d array (row by row according to getValueIndex())
            _nColumns = (short)nColumns;
            _nRows = (short)nRows;
 
            Object[] vv = new Object[_nColumns * _nRows];
            for (int r = 0; r < nRows; r++)
            {
                Object[] rowData = values2d[r];
                for (int c = 0; c < nColumns; c++)
                {
                    vv[GetValueIndex(c, r)] = rowData[c];
                }
            }
 
            _arrayValues = vv;
            _reserved0Int = 0;
            _reserved1Short = 0;
            _reserved2Byte = 0;
        }
        public Object[][] GetTokenArrayValues()
        {
            if (_arrayValues == null)
            {
                throw new InvalidOperationException("array values not read yet");
            }
            Object[][] result = new Object[_nRows][];
            for (int r = 0; r < _nRows; r++)
            {
                result[r] = new object[_nColumns];
                for (int c = 0; c < _nColumns; c++)
                {
                    result[r][c] = _arrayValues[GetValueIndex(c, r)];
                }
            }
            return result;
 
        }
 
        public override bool IsBaseToken
        {
            get { return false; }
        }
 
        public override String ToString()
        {
            StringBuilder buffer = new StringBuilder("[ArrayPtg]\n");
 
            buffer.Append("columns = ").Append(ColumnCount).Append("\n");
            buffer.Append("rows = ").Append(RowCount).Append("\n");
            for (int x = 0; x < ColumnCount; x++)
            {
                for (int y = 0; y < RowCount; y++)
                {
                    Object o = _arrayValues.GetValue(GetValueIndex(x, y));
                    buffer.Append("[").Append(x).Append("][").Append(y).Append("] = ").Append(o).Append("\n");
                }
            }
            return buffer.ToString();
        }
 
        /**
         * Note - (2D) array elements are stored column by column 
         * @return the index into the internal 1D array for the specified column and row
         */
        /* package */
        public int GetValueIndex(int colIx, int rowIx)
        {
            if (colIx < 0 || colIx >= _nColumns)
            {
                throw new ArgumentException("Specified colIx (" + colIx
                        + ") is outside the allowed range (0.." + (_nColumns - 1) + ")");
            }
            if (rowIx < 0 || rowIx >= _nRows)
            {
                throw new ArgumentException("Specified rowIx (" + rowIx
                        + ") is outside the allowed range (0.." + (_nRows - 1) + ")");
            }
            return rowIx * _nColumns + colIx;
        }
 
        public override void Write(ILittleEndianOutput out1)
        {
            out1.WriteByte(sid + PtgClass);
            out1.WriteInt(_reserved0Int);
            out1.WriteShort(_reserved1Short);
            out1.WriteByte(_reserved2Byte);
        }
 
        public int WriteTokenValueBytes(ILittleEndianOutput out1)
        {
 
            out1.WriteByte(_nColumns - 1);
            out1.WriteShort(_nRows - 1);
            ConstantValueParser.Encode(out1, _arrayValues);
            return 3 + ConstantValueParser.GetEncodedSize(_arrayValues);
        }
 
        public int RowCount
        {
            get
            {
                return _nRows;
            }
        }
 
        public int ColumnCount
        {
            get
            {
                return _nColumns;
            }
        }
 
        /** This size includes the size of the array Ptg plus the Array Ptg Token value size*/
        public override int Size
        {
            get
            {
                int size = 1 + 7 + 1 + 2;
                size += ConstantValueParser.GetEncodedSize(_arrayValues);
                return size;
            }
        }
 
        public override String ToFormulaString()
        {
            StringBuilder b = new StringBuilder();
            b.Append("{");
            for (int y = 0; y < RowCount; y++)
            {
                if (y > 0)
                {
                    b.Append(";");
                }
                for (int x = 0; x < ColumnCount; x++)
                {
                    if (x > 0)
                    {
                        b.Append(",");
                    }
                    Object o = _arrayValues.GetValue(GetValueIndex(x, y));
                    b.Append(GetConstantText(o));
                }
            }
            b.Append("}");
            return b.ToString();
        }
 
        private static String GetConstantText(Object o)
        {
 
            if (o == null)
            {
                return ""; // TODO - how is 'empty value' represented in formulas?
            }
            if (o is String)
            {
                return "\"" + (String)o + "\"";
            }
            if (o is Double || o is double)
            {
                return NumberToTextConverter.ToText((Double)o);
            }
            if (o is bool || o is Boolean)
            {
                return ((bool)o).ToString().ToUpper();
            }
            if (o is ErrorConstant)
            {
                return ((ErrorConstant)o).Text;
            }
            throw new ArgumentException("Unexpected constant class (" + o.GetType().Name + ")");
        }
 
        public override byte DefaultOperandClass
        {
            get { return Ptg.CLASS_ARRAY; }
        }
 
 
        /**
 * Represents the initial plain tArray token (without the constant data that trails the whole
 * formula).  Objects of this class are only temporary and cannot be used as {@link Ptg}s.
 * These temporary objects get converted to {@link ArrayPtg} by the
 * {@link #finishReading(LittleEndianInput)} method.
 */
        public class Initial : Ptg
        {
            private int _reserved0;
            private int _reserved1;
            private int _reserved2;
 
            public Initial(ILittleEndianInput in1)
            {
                _reserved0 = in1.ReadInt();
                _reserved1 = in1.ReadUShort();
                _reserved2 = in1.ReadUByte();
            }
            private static Exception Invalid()
            {
                throw new InvalidOperationException("This object is a partially initialised tArray, and cannot be used as a Ptg");
            }
            public override byte DefaultOperandClass
            {
                get
                {
                    throw Invalid();
                }
            }
            public override int Size
            {
                get
                {
                    return PLAIN_TOKEN_SIZE;
                }
            }
            public override bool IsBaseToken
            {
                get
                {
                    return false;
                }
            }
            public override String ToFormulaString()
            {
                throw Invalid();
            }
            public override void Write(ILittleEndianOutput out1)
            {
                throw Invalid();
            }
            /**
             * Read in the actual token (array) values. This occurs
             * AFTER the last Ptg in the expression.
             * See page 304-305 of Excel97-2007BinaryFileFormat(xls)Specification.pdf
             */
            public ArrayPtg FinishReading(ILittleEndianInput in1)
            {
                int nColumns = in1.ReadUByte();
                short nRows = in1.ReadShort();
                //The token_1_columns and token_2_rows do not follow the documentation.
                //The number of physical rows and columns is actually +1 of these values.
                //Which is not explicitly documented.
                nColumns++;
                nRows++;
 
                int totalCount = nRows * nColumns;
                Object[] arrayValues = ConstantValueParser.Parse(in1, totalCount);
 
                ArrayPtg result = new ArrayPtg(_reserved0, _reserved1, _reserved2, nColumns, nRows, arrayValues);
                result.PtgClass = this.PtgClass;
                return result;
            }
        }
    }
}