jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
/* ====================================================================
   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.IO;
    using System.Text;
    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.SS.UserModel;
    using HH.WMS.Utils.NPOI.HSSF.Record.Cont;
    using HH.WMS.Utils.NPOI.SS.Formula.PTG;
    using System.Globalization;
 
    public class TextObjectRecord : ContinuableRecord
    {
        HH.WMS.Utils.NPOI.SS.UserModel.IRichTextString _text;
 
        public const short sid = 0x1B6;
 
        private static int FORMAT_RUN_ENCODED_SIZE = 8; // 2 shorts and 4 bytes reserved
 
 
        private BitField _HorizontalTextAlignment = BitFieldFactory.GetInstance(0x000E);
        private BitField _VerticalTextAlignment = BitFieldFactory.GetInstance(0x0070);
        private BitField textLocked = BitFieldFactory.GetInstance(0x200);
 
        public const short TEXT_ORIENTATION_NONE = 0;
        public const short TEXT_ORIENTATION_TOP_TO_BOTTOM = 1;
        public const short TEXT_ORIENTATION_ROT_RIGHT = 2;
        public const short TEXT_ORIENTATION_ROT_LEFT = 3;
 
 
        public const short HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED = 1;
        public const short HORIZONTAL_TEXT_ALIGNMENT_CENTERED = 2;
        public const short HORIZONTAL_TEXT_ALIGNMENT_RIGHT_ALIGNED = 3;
        public const short HORIZONTAL_TEXT_ALIGNMENT_JUSTIFIED = 4;
        public const short VERTICAL_TEXT_ALIGNMENT_TOP = 1;
        public const short VERTICAL_TEXT_ALIGNMENT_CENTER = 2;
        public const short VERTICAL_TEXT_ALIGNMENT_BOTTOM = 3;
        public const short VERTICAL_TEXT_ALIGNMENT_JUSTIFY = 4;
 
        private int field_1_options;
        private int field_2_textOrientation;
        private int field_3_reserved4;
        private int field_4_reserved5;
        private int field_5_reserved6;
        private int field_8_reserved7;
        /*
         * Note - the next three fields are very similar to those on
         * EmbededObjectRefSubRecord(ftPictFmla 0x0009)
         * 
         * some observed values for the 4 bytes preceding the formula: C0 5E 86 03
         * C0 11 AC 02 80 F1 8A 03 D4 F0 8A 03
         */
        private int _unknownPreFormulaInt;
        /** expect tRef, tRef3D, tArea, tArea3D or tName */
        private OperandPtg _linkRefPtg;
        /**
         * Not clear if needed .  Excel seems to be OK if this byte is not present. 
         * Value is often the same as the earlier firstColumn byte. */
        private Byte? _unknownPostFormulaByte;
 
        public TextObjectRecord()
        {
 
        }
 
        public TextObjectRecord(RecordInputStream in1)
        {
 
            field_1_options = in1.ReadUShort();
            field_2_textOrientation = in1.ReadUShort();
            field_3_reserved4 = in1.ReadUShort();
            field_4_reserved5 = in1.ReadUShort();
            field_5_reserved6 = in1.ReadUShort();
            int field_6_textLength = in1.ReadUShort();
            int field_7_formattingDataLength = in1.ReadUShort();
            field_8_reserved7 = in1.ReadInt();
 
            if (in1.Remaining > 0)
            {
                // Text Objects can have simple reference formulas
                // (This bit not mentioned in the MS document)
                if (in1.Remaining < 11)
                {
                    throw new RecordFormatException("Not enough remaining data for a link formula");
                }
                int formulaSize = in1.ReadUShort();
                _unknownPreFormulaInt = in1.ReadInt();
                Ptg[] ptgs = Ptg.ReadTokens(formulaSize, in1);
                if (ptgs.Length != 1)
                {
                    throw new RecordFormatException("Read " + ptgs.Length
                            + " tokens but expected exactly 1");
                }
                _linkRefPtg = (OperandPtg)ptgs[0];
                if (in1.Remaining > 0)
                {
                    _unknownPostFormulaByte = (byte)in1.ReadByte();
                }
                else
                {
                    _unknownPostFormulaByte = null;
                }
            }
            else
            {
                _linkRefPtg = null;
            }
            if (in1.Remaining > 0)
            {
                throw new RecordFormatException("Unused " + in1.Remaining + " bytes at end of record");
            }
 
            String text;
            if (field_6_textLength > 0)
            {
                text = ReadRawString(in1, field_6_textLength);
            }
            else
            {
                text = "";
            }
            _text = new HSSFRichTextString(text);
 
            if (field_7_formattingDataLength > 0)
            {
                ProcessFontRuns(in1, _text, field_7_formattingDataLength);
            }
        }
        private static void ProcessFontRuns(RecordInputStream in1, IRichTextString str,
            int formattingRunDataLength)
        {
            if (formattingRunDataLength % FORMAT_RUN_ENCODED_SIZE != 0)
            {
                throw new RecordFormatException("Bad format run data length " + formattingRunDataLength
                        + ")");
            }
            int nRuns = formattingRunDataLength / FORMAT_RUN_ENCODED_SIZE;
            for (int i = 0; i < nRuns; i++)
            {
                short index = in1.ReadShort();
                short iFont = in1.ReadShort();
                in1.ReadInt(); // skip reserved.
                str.ApplyFont(index, str.Length, iFont);
            }
        }
 
        private int TrailingRecordsSize
        {
            get
            {
                if (_text.Length < 1)
                {
                    return 0;
                }
                int encodedTextSize = 0;
                int textBytesLength = _text.Length * LittleEndianConsts.SHORT_SIZE;
                while (textBytesLength > 0)
                {
                    int chunkSize = Math.Min(RecordInputStream.MAX_RECORD_DATA_SIZE - 2, textBytesLength);
                    textBytesLength -= chunkSize;
 
                    encodedTextSize += 4;           // +4 for ContinueRecord sid+size
                    encodedTextSize += 1 + chunkSize; // +1 for compressed unicode flag, 
                }
 
                int encodedFormatSize = (_text.NumFormattingRuns + 1) * FORMAT_RUN_ENCODED_SIZE
                    + 4;  // +4 for ContinueRecord sid+size
                return encodedTextSize + encodedFormatSize;
            }
        }
        private static byte[] CreateFormatData(IRichTextString str)
        {
            int nRuns = str.NumFormattingRuns;
            byte[] result = new byte[(nRuns + 1) * FORMAT_RUN_ENCODED_SIZE];
            int pos = 0;
            for (int i = 0; i < nRuns; i++)
            {
                LittleEndian.PutUShort(result, pos, str.GetIndexOfFormattingRun(i));
                pos += 2;
                int fontIndex = ((HSSFRichTextString)str).GetFontOfFormattingRun(i);
                LittleEndian.PutUShort(result, pos, fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex);
                pos += 2;
                pos += 4; // skip reserved
            }
            LittleEndian.PutUShort(result, pos, str.Length);
            pos += 2;
            LittleEndian.PutUShort(result, pos, 0);
            pos += 2;
            pos += 4; // skip reserved
 
            return result;
        }
 
        private void SerializeTrailingRecords(ContinuableRecordOutput out1)
        {
            out1.WriteContinue();
            out1.WriteStringData(_text.String);
            out1.WriteContinue();
            WriteFormatData(out1,_text);
        }
 
        private void WriteFormatData(ContinuableRecordOutput out1, IRichTextString str)
        {
            int nRuns = str.NumFormattingRuns;
            for (int i = 0; i < nRuns; i++)
            {
                out1.WriteShort(str.GetIndexOfFormattingRun(i));
                int fontIndex = ((HSSFRichTextString)str).GetFontOfFormattingRun(i);
                out1.WriteShort(fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex);
                out1.WriteInt(0); // skip reserved
            }
            out1.WriteShort(str.Length);
            out1.WriteShort(0);
            out1.WriteInt(0); // skip reserved
        }
 
 
        private int FormattingDataLength
        {
            get
            {
                if (_text.Length < 1)
                {
                    // important - no formatting data if text is empty 
                    return 0;
                }
                return (_text.NumFormattingRuns + 1) * FORMAT_RUN_ENCODED_SIZE;
            }
        }
 
        private void SerializeTXORecord(ContinuableRecordOutput out1)
        {
            out1.WriteShort(field_1_options);
            out1.WriteShort(field_2_textOrientation);
            out1.WriteShort(field_3_reserved4);
            out1.WriteShort(field_4_reserved5);
            out1.WriteShort(field_5_reserved6);
            out1.WriteShort(_text.Length);
            out1.WriteShort(FormattingDataLength);
            out1.WriteInt(field_8_reserved7);
 
            if (_linkRefPtg != null)
            {
                int formulaSize = _linkRefPtg.Size;
                out1.WriteShort(formulaSize);
                out1.WriteInt(_unknownPreFormulaInt);
                _linkRefPtg.Write(out1);
 
                if (_unknownPostFormulaByte != null)
                {
                    out1.WriteByte(Convert.ToByte(_unknownPostFormulaByte, CultureInfo.InvariantCulture));
                }
            }
        }
 
 
        protected override void Serialize(ContinuableRecordOutput out1)
        {
            SerializeTXORecord(out1);
 
            if (_text.String.Length > 0)
            {
                SerializeTrailingRecords(out1);
            }
        }
 
        private void ProcessFontRuns(RecordInputStream in1)
        {
            while (in1.Remaining > 0)
            {
                short index = in1.ReadShort();
                short iFont = in1.ReadShort();
                in1.ReadInt();  // skip reserved.
 
                _text.ApplyFont(index, _text.Length, iFont);
            }
        }
 
 
        private static String ReadRawString(RecordInputStream in1, int textLength)
        {
            byte compressByte = (byte)in1.ReadByte();
            bool isCompressed = (compressByte & 0x01) == 0;
            if (isCompressed)
            {
                return in1.ReadCompressedUnicode(textLength);
            }
            return in1.ReadUnicodeLEString(textLength);
        }
 
        public IRichTextString Str
        {
            get { return _text; }
            set { this._text = value; }
        }
        public override short Sid
        {
            get
            {
                return sid;
            }
        }
 
        /**
         * Get the text orientation field for the TextObjectBase record.
         *
         * @return  One of 
         *        TEXT_ORIENTATION_NONE
         *        TEXT_ORIENTATION_TOP_TO_BOTTOM
         *        TEXT_ORIENTATION_ROT_RIGHT
         *        TEXT_ORIENTATION_ROT_LEFT
         */
        public int TextOrientation
        {
            get { return field_2_textOrientation; }
            set { this.field_2_textOrientation = value; }
        }
 
 
        /**
 * @return the Horizontal text alignment field value.
 */
        public int HorizontalTextAlignment
        {
            get
            {
                return _HorizontalTextAlignment.GetValue(field_1_options);
            }
            set { field_1_options = _HorizontalTextAlignment.SetValue(field_1_options, value); }
        }
        /**
 * @return the Vertical text alignment field value.
 */
        public int VerticalTextAlignment
        {
            get
            {
                return _VerticalTextAlignment.GetValue(field_1_options);
            }
            set { field_1_options = _VerticalTextAlignment.SetValue(field_1_options, value); }
        }
 
        /**
         * Text has been locked
         * @return  the text locked field value.
         */
        public bool IsTextLocked
        {
            get { return textLocked.IsSet(field_1_options); }
            set { field_1_options = textLocked.SetBoolean(field_1_options, value); }
        }
        public Ptg LinkRefPtg
        {
            get
            {
                return _linkRefPtg;
            }
        }
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();
 
            sb.Append("[TXO]\n");
            sb.Append("    .options        = ").Append(HexDump.ShortToHex(field_1_options)).Append("\n");
            sb.Append("         .IsHorizontal = ").Append(HorizontalTextAlignment).Append('\n');
            sb.Append("         .IsVertical   = ").Append(VerticalTextAlignment).Append('\n');
            sb.Append("         .textLocked   = ").Append(IsTextLocked).Append('\n');
            sb.Append("    .textOrientation= ").Append(HexDump.ShortToHex(TextOrientation)).Append("\n");
            sb.Append("    .reserved4      = ").Append(HexDump.ShortToHex(field_3_reserved4)).Append("\n");
            sb.Append("    .reserved5      = ").Append(HexDump.ShortToHex(field_4_reserved5)).Append("\n");
            sb.Append("    .reserved6      = ").Append(HexDump.ShortToHex(field_5_reserved6)).Append("\n");
            sb.Append("    .textLength     = ").Append(HexDump.ShortToHex(_text.Length)).Append("\n");
            sb.Append("    .reserved7      = ").Append(HexDump.IntToHex(field_8_reserved7)).Append("\n");
 
            sb.Append("    .string = ").Append(_text).Append('\n');
 
            for (int i = 0; i < _text.NumFormattingRuns; i++)
            {
                sb.Append("    .textrun = ").Append(((HSSFRichTextString)_text).GetFontOfFormattingRun(i)).Append('\n');
 
            }
            sb.Append("[/TXO]\n");
            return sb.ToString();
        }
 
        public override Object Clone()
        {
 
            TextObjectRecord rec = new TextObjectRecord();
            rec._text = _text;
 
            rec.field_1_options = field_1_options;
            rec.field_2_textOrientation = field_2_textOrientation;
            rec.field_3_reserved4 = field_3_reserved4;
            rec.field_4_reserved5 = field_4_reserved5;
            rec.field_5_reserved6 = field_5_reserved6;
            rec.field_8_reserved7 = field_8_reserved7;
 
            rec._text = _text; // clone needed?
 
            if (_linkRefPtg != null)
            {
                rec._unknownPreFormulaInt = _unknownPreFormulaInt;
                rec._linkRefPtg = _linkRefPtg.Copy();
                rec._unknownPostFormulaByte = _unknownPostFormulaByte;
            }
            return rec;
        }
 
    }
}