zhao
2021-06-04 c7ec496f9e41c2227103b3ef776e4a3f91bce6b2
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
/*
* 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.Functions
{
    using System;
    using HH.WMS.Utils.NPOI.SS.Formula.Eval;
    using System.Text;
 
    /**
     * Implementation for Excel function OFFSet()<p/>
     * 
     * OFFSet returns an area reference that Is a specified number of rows and columns from a 
     * reference cell or area.<p/>
     * 
     * <b>Syntax</b>:<br/>
     * <b>OFFSet</b>(<b>reference</b>, <b>rows</b>, <b>cols</b>, height, width)<p/>
     * <b>reference</b> Is the base reference.<br/>
     * <b>rows</b> Is the number of rows up or down from the base reference.<br/>
     * <b>cols</b> Is the number of columns left or right from the base reference.<br/>
     * <b>height</b> (default same height as base reference) Is the row Count for the returned area reference.<br/>
     * <b>width</b> (default same width as base reference) Is the column Count for the returned area reference.<br/>
     * 
     * @author Josh Micich
     */
    public class Offset : Function
    {
        // These values are specific to BIFF8
        private static int LAST_VALID_ROW_INDEX = 0xFFFF;
        private static int LAST_VALID_COLUMN_INDEX = 0xFF;
 
 
        /**
         * Exceptions are used within this class to help simplify flow control when error conditions
         * are enCountered 
         */
        [Serializable]
        private class EvalEx : Exception
        {
            private ErrorEval _error;
 
            public EvalEx(ErrorEval error)
            {
                _error = error;
            }
            public ErrorEval GetError()
            {
                return _error;
            }
        }
 
        /** 
         * A one dimensional base + offset.  Represents either a row range or a column range.
         * Two instances of this class toGether specify an area range.
         */
        /* package */
        public class LinearOffsetRange
        {
 
            private int _offset;
            private int _Length;
 
            public LinearOffsetRange(int offset, int length)
            {
                if (length == 0)
                {
                    // handled that condition much earlier
                    throw new ArgumentException("Length may not be zero");
                }
                _offset = offset;
                _Length = length;
            }
 
            public short FirstIndex
            {
                get
                {
                    return (short)_offset;
                }
            }
            public short LastIndex
            {
                get
                {
                    return (short)(_offset + _Length - 1);
                }
            }
            /**
             * Moves the range by the specified translation amount.<p/>
             * 
             * This method also 'normalises' the range: Excel specifies that the width and height 
             * parameters (Length field here) cannot be negative.  However, OFFSet() does produce
             * sensible results in these cases.  That behavior Is replicated here. <p/>
             * 
             * @param translationAmount may be zero negative or positive
             * 
             * @return the equivalent <c>LinearOffsetRange</c> with a positive Length, moved by the
             * specified translationAmount.
             */
            public LinearOffsetRange NormaliseAndTranslate(int translationAmount)
            {
                if (_Length > 0)
                {
                    if (translationAmount == 0)
                    {
                        return this;
                    }
                    return new LinearOffsetRange(translationAmount + _offset, _Length);
                }
                return new LinearOffsetRange(translationAmount + _offset + _Length + 1, -_Length);
            }
 
            public bool IsOutOfBounds(int lowValidIx, int highValidIx)
            {
                if (_offset < lowValidIx)
                {
                    return true;
                }
                if (LastIndex > highValidIx)
                {
                    return true;
                }
                return false;
            }
            public override String ToString()
            {
                StringBuilder sb = new StringBuilder(64);
                sb.Append(GetType().Name).Append(" [");
                sb.Append(_offset).Append("...").Append(LastIndex);
                sb.Append("]");
                return sb.ToString();
            }
        }
 
 
        /**
         * Encapsulates either an area or cell reference which may be 2d or 3d.
         */
        private class BaseRef
        {
            private const int INVALID_SHEET_INDEX = -1;
            private int _firstRowIndex;
            private int _firstColumnIndex;
            private int _width;
            private int _height;
            private RefEval _refEval;
            private AreaEval _areaEval;
 
            public BaseRef(RefEval re)
            {
                _refEval = re;
                _areaEval = null;
                _firstRowIndex = re.Row;
                _firstColumnIndex = re.Column;
                _height = 1;
                _width = 1;
            }
 
            public BaseRef(AreaEval ae)
            {
                _refEval = null;
                _areaEval = ae;
                _firstRowIndex = ae.FirstRow;
                _firstColumnIndex = ae.FirstColumn;
                _height = ae.LastRow - ae.FirstRow + 1;
                _width = ae.LastColumn - ae.FirstColumn + 1;
            }
 
            public int Width
            {
                get
                {
                    return _width;
                }
            }
 
            public int Height
            {
                get
                {
                    return _height;
                }
            }
 
            public int FirstRowIndex
            {
                get
                {
                    return _firstRowIndex;
                }
            }
 
            public int FirstColumnIndex
            {
                get
                {
                    return _firstColumnIndex;
                }
            }
            public AreaEval Offset(int relFirstRowIx, int relLastRowIx,int relFirstColIx, int relLastColIx)
            {
                if (_refEval == null)
                {
                    return _areaEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
                }
                return _refEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
            }
        }
 
        public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol)
        {
 
            if (args.Length < 3 || args.Length > 5)
            {
                return ErrorEval.VALUE_INVALID;
            }
 
            try
            {
                BaseRef baseRef = EvaluateBaseRef(args[0]);
                int rowOffset = EvaluateIntArg(args[1], srcCellRow, srcCellCol);
                int columnOffset = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
                int height = baseRef.Height;
                int width = baseRef.Width;
                switch (args.Length)
                {
                    case 5:
                        width = EvaluateIntArg(args[4], srcCellRow, srcCellCol);
                        break;
                    case 4:
                        height = EvaluateIntArg(args[3], srcCellRow, srcCellCol);
                        break;
                }
                // Zero height or width raises #REF! error
                if (height == 0 || width == 0)
                {
                    return ErrorEval.REF_INVALID;
                }
                LinearOffsetRange rowOffsetRange = new LinearOffsetRange(rowOffset, height);
                LinearOffsetRange colOffsetRange = new LinearOffsetRange(columnOffset, width);
                return CreateOffset(baseRef, rowOffsetRange, colOffsetRange);
            }
            catch (EvaluationException e)
            {
                return e.GetErrorEval();
            }
        }
 
 
 
        private static AreaEval CreateOffset(BaseRef baseRef,
            LinearOffsetRange orRow, LinearOffsetRange orCol)
        {
 
            LinearOffsetRange absRows = orRow.NormaliseAndTranslate(baseRef.FirstRowIndex);
            LinearOffsetRange absCols = orCol.NormaliseAndTranslate(baseRef.FirstColumnIndex);
 
            if (absRows.IsOutOfBounds(0, LAST_VALID_ROW_INDEX))
            {
                throw new EvaluationException(ErrorEval.REF_INVALID);
            }
            if (absCols.IsOutOfBounds(0, LAST_VALID_COLUMN_INDEX))
            {
                throw new EvaluationException(ErrorEval.REF_INVALID);
            }
            return baseRef.Offset(orRow.FirstIndex, orRow.LastIndex, orCol.FirstIndex, orCol.LastIndex);
        }
 
 
        private static BaseRef EvaluateBaseRef(ValueEval eval)
        {
 
            if (eval is RefEval)
            {
                return new BaseRef((RefEval)eval);
            }
            if (eval is AreaEval)
            {
                return new BaseRef((AreaEval)eval);
            }
            if (eval is ErrorEval)
            {
                throw new EvalEx((ErrorEval)eval);
            }
            throw new EvalEx(ErrorEval.VALUE_INVALID);
        }
 
 
        /**
         * OFFSet's numeric arguments (2..5) have similar Processing rules
         */
        public static int EvaluateIntArg(ValueEval eval, int srcCellRow, int srcCellCol)
        {
 
            double d = EvaluateDoubleArg(eval, srcCellRow, srcCellCol);
            return ConvertDoubleToInt(d);
        }
 
        /**
         * Fractional values are silently truncated by Excel.
         * Truncation Is toward negative infinity.
         */
        /* package */
        public static int ConvertDoubleToInt(double d)
        {
            // Note - the standard java type conversion from double to int truncates toward zero.
            // but Math.floor() truncates toward negative infinity
            return (int)Math.Floor(d);
        }
 
 
        private static double EvaluateDoubleArg(ValueEval eval, int srcCellRow, int srcCellCol)
        {
            ValueEval ve = OperandResolver.GetSingleValue(eval, srcCellRow, srcCellCol);
 
            if (ve is NumericValueEval)
            {
                return ((NumericValueEval)ve).NumberValue;
            }
            if (ve is StringEval)
            {
                StringEval se = (StringEval)ve;
                double d = OperandResolver.ParseDouble(se.StringValue);
                if (double.IsNaN(d))
                {
                    throw new EvalEx(ErrorEval.VALUE_INVALID);
                }
                return d;
            }
            if (ve is BoolEval)
            {
                // in the context of OFFSet, bools resolve to 0 and 1.
                if (((BoolEval)ve).BooleanValue)
                {
                    return 1;
                }
                return 0;
            }
            throw new Exception("Unexpected eval type (" + ve.GetType().Name + ")");
        }
    }
}