Example #1
0
 protected void WriteCoordinates(byte[] array, int offset)
 {
     LittleEndian.PutUShort(array, offset + 0, field_1_row);
     LittleEndian.PutUShort(array, offset + 2, field_2_col);
 }
Example #2
0
 /// <summary>
 /// Read the options field from header and return instance part of it.
 /// </summary>
 /// <param name="data">the byte array to read from</param>
 /// <param name="offset">the offset to start reading from</param>
 /// <returns>value of instance part of options field</returns>
 protected static short ReadInstance( byte[] data, int offset )
 {
     short options = LittleEndian.GetShort( data, offset );
     return fInstance.GetShortValue( options );
 }
Example #3
0
        /// <summary>
        /// Creates the lowerlevel escher records for this shape.
        /// </summary>
        /// <param name="hssfShape">The HSSF shape.</param>
        /// <param name="shapeId">The shape id.</param>
        /// <returns></returns>
        private EscherContainerRecord CreateSpContainer(HSSFPolygon hssfShape, int shapeId)
        {
            HSSFShape shape = hssfShape;

            EscherContainerRecord  spContainer = new EscherContainerRecord();
            EscherSpRecord         sp          = new EscherSpRecord();
            EscherOptRecord        opt         = new EscherOptRecord();
            EscherClientDataRecord clientData  = new EscherClientDataRecord();

            spContainer.RecordId = EscherContainerRecord.SP_CONTAINER;
            spContainer.Options  = (short)0x000F;
            sp.RecordId          = EscherSpRecord.RECORD_ID;
            sp.Options           = (short)((EscherAggregate.ST_DONUT << 4) | 0x2);
            sp.ShapeId           = shapeId;
            if (hssfShape.Parent == null)
            {
                sp.Flags = EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE;
            }
            else
            {
                sp.Flags = EscherSpRecord.FLAG_CHILD | EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE;
            }
            opt.RecordId = EscherOptRecord.RECORD_ID;
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.TRANSFORM__ROTATION, false, false, 0));
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, false, false, hssfShape.DrawAreaWidth));
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, false, false, hssfShape.DrawAreaHeight));
            opt.AddEscherProperty(new EscherShapePathProperty(EscherProperties.GEOMETRY__SHAPEPATH, EscherShapePathProperty.COMPLEX));
            EscherArrayProperty verticesProp = new EscherArrayProperty(EscherProperties.GEOMETRY__VERTICES, false, new byte[0]);

            verticesProp.NumberOfElementsInArray  = (hssfShape.XPoints.Length + 1);
            verticesProp.NumberOfElementsInMemory = (hssfShape.XPoints.Length + 1);
            verticesProp.SizeOfElements           = unchecked ((short)0xFFF0);
            for (int i = 0; i < hssfShape.XPoints.Length; i++)
            {
                byte[] data = new byte[4];
                LittleEndian.PutShort(data, 0, (short)hssfShape.XPoints[i]);
                LittleEndian.PutShort(data, 2, (short)hssfShape.YPoints[i]);
                verticesProp.SetElement(i, data);
            }
            int point = hssfShape.XPoints.Length;

            byte[] data1 = new byte[4];
            LittleEndian.PutShort(data1, 0, (short)hssfShape.XPoints[0]);
            LittleEndian.PutShort(data1, 2, (short)hssfShape.YPoints[0]);
            verticesProp.SetElement(point, data1);
            opt.AddEscherProperty(verticesProp);
            EscherArrayProperty segmentsProp = new EscherArrayProperty(EscherProperties.GEOMETRY__SEGMENTINFO, false, null);

            segmentsProp.SizeOfElements           = (0x0002);
            segmentsProp.NumberOfElementsInArray  = (hssfShape.XPoints.Length * 2 + 4);
            segmentsProp.NumberOfElementsInMemory = (hssfShape.XPoints.Length * 2 + 4);
            segmentsProp.SetElement(0, new byte[] { (byte)0x00, (byte)0x40 });
            segmentsProp.SetElement(1, new byte[] { (byte)0x00, (byte)0xAC });
            for (int i = 0; i < hssfShape.XPoints.Length; i++)
            {
                segmentsProp.SetElement(2 + i * 2, new byte[] { (byte)0x01, (byte)0x00 });
                segmentsProp.SetElement(3 + i * 2, new byte[] { (byte)0x00, (byte)0xAC });
            }
            segmentsProp.SetElement(segmentsProp.NumberOfElementsInArray - 2, new byte[] { (byte)0x01, (byte)0x60 });
            segmentsProp.SetElement(segmentsProp.NumberOfElementsInArray - 1, new byte[] { (byte)0x00, (byte)0x80 });
            opt.AddEscherProperty(segmentsProp);
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__FillOK, false, false, 0x00010001));
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINESTARTARROWHEAD, false, false, 0x0));
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEENDARROWHEAD, false, false, 0x0));
            opt.AddEscherProperty(new EscherSimpleProperty(EscherProperties.LINESTYLE__LINEENDCAPSTYLE, false, false, 0x0));

            AddStandardOptions(shape, opt);

            EscherRecord anchor = CreateAnchor(shape.Anchor);

            clientData.RecordId = (EscherClientDataRecord.RECORD_ID);
            clientData.Options  = (short)0x0000;

            spContainer.AddChildRecord(sp);
            spContainer.AddChildRecord(opt);
            spContainer.AddChildRecord(anchor);
            spContainer.AddChildRecord(clientData);

            return(spContainer);
        }
Example #4
0
        /**
         * Constructs a OBJ record and Sets its fields appropriately.
         *
         * @param in the RecordInputstream to Read the record from
         */

        public ObjRecord(RecordInputStream in1)
        {
            // TODO - problems with OBJ sub-records stream
            // MS spec says first sub-record is always CommonObjectDataSubRecord,
            // and last is
            // always EndSubRecord. OOO spec does not mention ObjRecord(0x005D).
            // Existing POI test data seems to violate that rule. Some test data
            // seems to contain
            // garbage, and a crash is only averted by stopping at what looks like
            // the 'EndSubRecord'

            //Check if this can be continued, if so then the
            //following wont work properly
            //int subSize = 0;
            byte[] subRecordData = in1.ReadRemainder();

            if (LittleEndian.GetUShort(subRecordData, 0) != CommonObjectDataSubRecord.sid)
            {
                // seems to occur in just one junit on "OddStyleRecord.xls" (file created by CrystalReports)
                // Excel tolerates the funny ObjRecord, and replaces it with a corrected version
                // The exact logic/reasoning is not yet understood
                _uninterpretedData = subRecordData;
                subrecords         = null;
                return;
            }
            //if (subRecordData.Length % 2 != 0)
            //{
            //    String msg = "Unexpected length of subRecordData : " + HexDump.ToHex(subRecordData);
            //    throw new RecordFormatException(msg);
            //}
            subrecords = new List <SubRecord>();
            using (MemoryStream bais = new MemoryStream(subRecordData))
            {
                LittleEndianInputStream   subRecStream = new LittleEndianInputStream(bais);
                CommonObjectDataSubRecord cmo          = (CommonObjectDataSubRecord)SubRecord.CreateSubRecord(subRecStream, 0);
                subrecords.Add(cmo);
                while (true)
                {
                    SubRecord subRecord = SubRecord.CreateSubRecord(subRecStream, cmo.ObjectType);
                    subrecords.Add(subRecord);
                    if (subRecord.IsTerminating)
                    {
                        break;
                    }
                }
                int nRemainingBytes = subRecStream.Available();
                if (nRemainingBytes > 0)
                {
                    // At present (Oct-2008), most unit test samples have (subRecordData.length % 2 == 0)
                    _isPaddedToQuadByteMultiple = subRecordData.Length % MAX_PAD_ALIGNMENT == 0;
                    if (nRemainingBytes >= (_isPaddedToQuadByteMultiple ? MAX_PAD_ALIGNMENT : NORMAL_PAD_ALIGNMENT))
                    {
                        if (!CanPaddingBeDiscarded(subRecordData, nRemainingBytes))
                        {
                            String msg = "Leftover " + nRemainingBytes
                                         + " bytes in subrecord data " + HexDump.ToHex(subRecordData);
                            throw new RecordFormatException(msg);
                        }
                        _isPaddedToQuadByteMultiple = false;
                    }
                }
                else
                {
                    _isPaddedToQuadByteMultiple = false;
                }
                _uninterpretedData = null;
            }
        }
Example #5
0
        /// <summary>
        /// This method deSerializes the record from a byte array.
        /// </summary>
        /// <param name="data">The byte array containing the escher record information</param>
        /// <param name="offset">The starting offset into data</param>
        /// <param name="recordFactory">May be null since this is not a container record.</param>
        /// <returns>The number of bytes Read from the byte array.</returns>
        public override int FillFields(byte[] data, int offset, EscherRecordFactory recordFactory)
        {
            int bytesRemaining = ReadHeader(data, offset);
            int pos            = offset + 8;
            int size           = 0;

            field_1_shapeIdMax = LittleEndian.GetInt(data, pos + size); size += 4;
            int field_2_numIdClusters = LittleEndian.GetInt(data, pos + size); size += 4;

            field_3_numShapesSaved = LittleEndian.GetInt(data, pos + size); size += 4;
            field_4_drawingsSaved  = LittleEndian.GetInt(data, pos + size); size += 4;
            field_5_fileIdClusters = new FileIdCluster[(bytesRemaining - size) / 8];  // Can't rely on field_2_numIdClusters
            for (int i = 0; i < field_5_fileIdClusters.Length; i++)
            {
                field_5_fileIdClusters[i] = new FileIdCluster(LittleEndian.GetInt(data, pos + size), LittleEndian.GetInt(data, pos + size + 4));
                maxDgId = Math.Max(maxDgId, field_5_fileIdClusters[i].DrawingGroupId);
                size   += 8;
            }
            bytesRemaining -= size;
            if (bytesRemaining != 0)
            {
                throw new RecordFormatException("Expecting no remaining data but got " + bytesRemaining + " byte(s).");
            }
            return(8 + size + bytesRemaining);
        }
Example #6
0
        public static byte[] CompressCharacterProperty(CharacterProperties newCHP, CharacterProperties oldCHP)
        {
            ArrayList sprmList = new ArrayList();
            int       size     = 0;

            if (newCHP.IsFRMarkDel() != oldCHP.IsFRMarkDel())
            {
                int value = 0;
                if (newCHP.IsFRMarkDel())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0800, value, null, sprmList);
            }
            if (newCHP.IsFRMark() != oldCHP.IsFRMark())
            {
                int value = 0;
                if (newCHP.IsFRMark())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0801, value, null, sprmList);
            }
            if (newCHP.IsFFldVanish() != oldCHP.IsFFldVanish())
            {
                int value = 0;
                if (newCHP.IsFFldVanish())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0802, value, null, sprmList);
            }
            if (newCHP.IsFSpec() != oldCHP.IsFSpec() || newCHP.GetFcPic() != oldCHP.GetFcPic())
            {
                size += SprmUtils.AddSprm((short)0x6a03, newCHP.GetFcPic(), null, sprmList);
            }
            if (newCHP.GetIbstRMark() != oldCHP.GetIbstRMark())
            {
                size += SprmUtils.AddSprm((short)0x4804, newCHP.GetIbstRMark(), null, sprmList);
            }
            if (!newCHP.GetDttmRMark().Equals(oldCHP.GetDttmRMark()))
            {
                byte[] buf = new byte[4];
                newCHP.GetDttmRMark().Serialize(buf, 0);

                size += SprmUtils.AddSprm((short)0x6805, LittleEndian.GetInt(buf), null, sprmList);
            }
            if (newCHP.IsFData() != oldCHP.IsFData())
            {
                int value = 0;
                if (newCHP.IsFData())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0806, value, null, sprmList);
            }
            if (newCHP.IsFSpec() && newCHP.GetFtcSym() != 0)
            {
                byte[] varParam = new byte[4];
                LittleEndian.PutShort(varParam, 0, (short)newCHP.GetFtcSym());
                LittleEndian.PutShort(varParam, 2, (short)newCHP.GetXchSym());

                size += SprmUtils.AddSprm((short)0x6a09, 0, varParam, sprmList);
            }
            if (newCHP.IsFOle2() != newCHP.IsFOle2())
            {
                int value = 0;
                if (newCHP.IsFOle2())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x080a, value, null, sprmList);
            }
            if (newCHP.GetIcoHighlight() != oldCHP.GetIcoHighlight())
            {
                size += SprmUtils.AddSprm((short)0x2a0c, newCHP.GetIcoHighlight(), null, sprmList);
            }
            if (newCHP.GetFcObj() != oldCHP.GetFcObj())
            {
                size += SprmUtils.AddSprm((short)0x680e, newCHP.GetFcObj(), null, sprmList);
            }
            if (newCHP.GetIstd() != oldCHP.GetIstd())
            {
                size += SprmUtils.AddSprm((short)0x4a30, newCHP.GetIstd(), null, sprmList);
            }
            if (newCHP.IsFBold() != oldCHP.IsFBold())
            {
                int value = 0;
                if (newCHP.IsFBold())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0835, value, null, sprmList);
            }
            if (newCHP.IsFItalic() != oldCHP.IsFItalic())
            {
                int value = 0;
                if (newCHP.IsFItalic())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0836, value, null, sprmList);
            }
            if (newCHP.IsFStrike() != oldCHP.IsFStrike())
            {
                int value = 0;
                if (newCHP.IsFStrike())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0837, value, null, sprmList);
            }
            if (newCHP.IsFOutline() != oldCHP.IsFOutline())
            {
                int value = 0;
                if (newCHP.IsFOutline())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0838, value, null, sprmList);
            }
            if (newCHP.IsFShadow() != oldCHP.IsFShadow())
            {
                int value = 0;
                if (newCHP.IsFShadow())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0839, value, null, sprmList);
            }
            if (newCHP.IsFSmallCaps() != oldCHP.IsFSmallCaps())
            {
                int value = 0;
                if (newCHP.IsFSmallCaps())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x083a, value, null, sprmList);
            }
            if (newCHP.IsFCaps() != oldCHP.IsFCaps())
            {
                int value = 0;
                if (newCHP.IsFCaps())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x083b, value, null, sprmList);
            }
            if (newCHP.IsFVanish() != oldCHP.IsFVanish())
            {
                int value = 0;
                if (newCHP.IsFVanish())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x083c, value, null, sprmList);
            }
            if (newCHP.GetKul() != oldCHP.GetKul())
            {
                size += SprmUtils.AddSprm((short)0x2a3e, newCHP.GetKul(), null, sprmList);
            }
            if (newCHP.GetDxaSpace() != oldCHP.GetDxaSpace())
            {
                size += SprmUtils.AddSprm(unchecked ((short)0x8840), newCHP.GetDxaSpace(), null, sprmList);
            }
            if (newCHP.GetIco() != oldCHP.GetIco())
            {
                size += SprmUtils.AddSprm((short)0x2a42, newCHP.GetIco(), null, sprmList);
            }
            if (newCHP.GetHps() != oldCHP.GetHps())
            {
                size += SprmUtils.AddSprm((short)0x4a43, newCHP.GetHps(), null, sprmList);
            }
            if (newCHP.GetHpsPos() != oldCHP.GetHpsPos())
            {
                size += SprmUtils.AddSprm((short)0x4845, newCHP.GetHpsPos(), null, sprmList);
            }
            if (newCHP.GetHpsKern() != oldCHP.GetHpsKern())
            {
                size += SprmUtils.AddSprm((short)0x484b, newCHP.GetHpsKern(), null, sprmList);
            }
            if (newCHP.GetYsr() != oldCHP.GetYsr())
            {
                size += SprmUtils.AddSprm((short)0x484e, newCHP.GetYsr(), null, sprmList);
            }
            if (newCHP.GetFtcAscii() != oldCHP.GetFtcAscii())
            {
                size += SprmUtils.AddSprm((short)0x4a4f, newCHP.GetFtcAscii(), null, sprmList);
            }
            if (newCHP.GetFtcFE() != oldCHP.GetFtcFE())
            {
                size += SprmUtils.AddSprm((short)0x4a50, newCHP.GetFtcFE(), null, sprmList);
            }
            if (newCHP.GetFtcOther() != oldCHP.GetFtcOther())
            {
                size += SprmUtils.AddSprm((short)0x4a51, newCHP.GetFtcOther(), null, sprmList);
            }

            if (newCHP.IsFDStrike() != oldCHP.IsFDStrike())
            {
                int value = 0;
                if (newCHP.IsFDStrike())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x2a53, value, null, sprmList);
            }
            if (newCHP.IsFImprint() != oldCHP.IsFImprint())
            {
                int value = 0;
                if (newCHP.IsFImprint())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0854, value, null, sprmList);
            }
            if (newCHP.IsFSpec() != oldCHP.IsFSpec())
            {
                int value = 0;
                if (newCHP.IsFSpec())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0855, value, null, sprmList);
            }
            if (newCHP.IsFObj() != oldCHP.IsFObj())
            {
                int value = 0;
                if (newCHP.IsFObj())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0856, value, null, sprmList);
            }
            if (newCHP.IsFEmboss() != oldCHP.IsFEmboss())
            {
                int value = 0;
                if (newCHP.IsFEmboss())
                {
                    value = 0x01;
                }
                size += SprmUtils.AddSprm((short)0x0858, value, null, sprmList);
            }
            if (newCHP.GetSfxtText() != oldCHP.GetSfxtText())
            {
                size += SprmUtils.AddSprm((short)0x2859, newCHP.GetSfxtText(), null, sprmList);
            }
            if (newCHP.GetIco24() != oldCHP.GetIco24())
            {
                if (newCHP.GetIco24() != -1) // don't Add a sprm if we're looking at an ico = Auto
                {
                    size += SprmUtils.AddSprm((short)0x6870, newCHP.GetIco24(), null, sprmList);
                }
            }

            return(SprmUtils.GetGrpprl(sprmList, size));
        }
Example #7
0
 public int Write(Stream out1)
 {
     LittleEndian.PutInt(_value.Length, out1);
     out1.Write(_value, 0, _value.Length);
     return(LittleEndian.INT_SIZE + _value.Length);
 }
Example #8
0
        void UnpackV1()
        {
            int width  = (int)m_info.Width;
            int height = (int)m_info.Height;

            m_output = new byte[m_stride * height];

            int x_blocks = width >> 4;

            if (0 != (width & 0xF))
            {
                ++x_blocks;
            }
            int y_blocks = height >> 4;

            if (0 != (height & 0xF))
            {
                ++y_blocks;
            }

            int plane_size = width * height;

            byte[] plane = new byte[plane_size];

            int data1 = LittleEndian.ToInt32(m_input, 0x2C);
            int data2 = LittleEndian.ToInt32(m_input, 0x30);

            for (int channel = 0; channel < m_channels; ++channel)
            {
                int channel_offset = 4 * m_channels;
                for (int i = 0; i < channel; ++i)
                {
                    channel_offset += LittleEndian.ToInt32(m_input, data1 + 4 * i);
                }
                int v21          = data1 + channel_offset;
                int bit_src      = v21 + 12 + LittleEndian.ToInt32(m_input, v21) + LittleEndian.ToInt32(m_input, v21 + 4);
                int channel_size = LittleEndian.ToInt32(m_input, v21 + 8);

                channel_offset = 4 * m_channels;
                for (int i = 0; i < channel; ++i)
                {
                    channel_offset += LittleEndian.ToInt32(m_input, data2 + 4 * i);
                }
                int data_src = data2 + channel_offset;

                LzssResetFrame();
                LzssUnpack(bit_src, data_src, plane, channel_size);

                if (0 == y_blocks || 0 == x_blocks)
                {
                    continue;
                }
                int plane_src = 0;
                bit_src = v21 + 12;
                int bit_mask = 128;
                data_src = bit_src + LittleEndian.ToInt32(m_input, v21);
                int v68 = 16;
                for (int y = 0; y < y_blocks; ++y)
                {
                    int row        = 16 * y;
                    int v66        = 16;
                    int dst_origin = m_stride * row + channel; // within m_output
                    for (int x = 0; x < x_blocks; ++x)
                    {
                        int dst          = dst_origin;
                        int block_width  = v66 > width  ? width - 16 * x : 16;
                        int block_height = v68 > height ? height - row   : 16;
                        if (0 == bit_mask)
                        {
                            ++bit_src;
                            bit_mask = 128;
                        }
                        if (0 != (bit_mask & m_input[bit_src]))
                        {
                            byte b = m_input[data_src++];
                            for (int j = 0; j < block_height; ++j)
                            {
                                int v49 = dst;
                                for (int i = 0; i < block_width; ++i)
                                {
                                    m_output[v49] = b;
                                    v49          += 4;
                                }
                                dst += m_stride;
                            }
                        }
                        else
                        {
                            for (int j = 0; j < block_height; ++j)
                            {
                                int v49 = dst;
                                for (int i = 0; i < block_width; ++i)
                                {
                                    m_output[v49] = plane[plane_src++];
                                    v49          += 4;
                                }
                                dst += m_stride;
                            }
                        }
                        bit_mask  >>= 1;
                        v66        += 16;
                        dst_origin += 64;
                    }
                    v68 += 16;
                }
            }
        }
Example #9
0
        void BlendInput()
        {
            int bit_src      = 0x20 + LittleEndian.ToInt32(m_input, 0xC);
            int data_src     = bit_src + LittleEndian.ToInt32(m_input, 0x2C);
            int overlay_size = LittleEndian.ToInt32(m_input, 0x18);
            var overlay      = new byte[overlay_size];

            LzssUnpack(bit_src, data_src, overlay, overlay_size);

            int width  = (int)m_info.Width;
            int height = (int)m_info.Height;

            bit_src  = 8;                                    // within overlay
            data_src = 8 + LittleEndian.ToInt32(overlay, 0); // within overlay

            int bit_mask = 0x80;
            int x_blocks = width >> 3;

            if (0 != (width & 7))
            {
                ++x_blocks;
            }
            int y_blocks = height >> 3;

            if (0 != (height & 7))
            {
                ++y_blocks;
            }
            if (0 == x_blocks)
            {
                return;
            }
            int h          = 0;
            int dst_origin = 0;

            while (y_blocks > 0)
            {
                int w = 0;
                for (int x = 0; x < x_blocks; ++x)
                {
                    if (0 == bit_mask)
                    {
                        ++bit_src;
                        bit_mask = 0x80;
                    }
                    if (0 == (bit_mask & overlay[bit_src]))
                    {
                        int dst     = 8 * (dst_origin + 4 * x); // within m_output
                        int x_count = Math.Min(8, width - w);
                        int y_count = Math.Min(8, height - h);
                        for (int v30 = y_count; v30 > 0; --v30)
                        {
                            int count = 4 * x_count;
                            Buffer.BlockCopy(overlay, data_src, m_output, dst, count);
                            data_src += count;
                            dst      += m_stride;
                        }
                    }
                    bit_mask >>= 1;
                    w         += 8;
                }
                dst_origin += m_stride;
                h          += 8;
                --y_blocks;
            }
        }
Example #10
0
            private void Unpack5()
            {
                int i   = 0;
                int src = 0;
                int dst = 0;
                int ctl = 1;
                int x   = 0;

                for (;;)
                {
//                    int type = (m_comp0[x/4] >> (x & 3)*2) & 3;
                    if (1 == ctl)
                    {
                        if (x == m_comp0.Length)
                        {
                            break;
                        }
                        ctl = m_comp0[x++] | 0x100;
                    }
                    int type = ctl & 3;
                    ctl >>= 2;

                    int count, off;
                    switch (type)
                    {
                    case 0:
                        m_output[dst++] = m_comp1[src++];
                        break;

                    case 1:
                        count = ((m_comp2[i / 2] >> (4 * (i & 1))) & 0xf) + 2;
                        off   = m_comp1[src++] + 2;
                        Binary.CopyOverlapped(m_output, dst - off, dst, count);
                        dst += count;
                        ++i;
                        break;

                    case 2:
                        count = LittleEndian.ToUInt16(m_comp1, src);
                        if (0 == count)
                        {
                            return;
                        }
                        off   = (count & 0xfff) + 2;
                        count = (count >> 12) + 2;
                        Binary.CopyOverlapped(m_output, dst - off, dst, count);
                        dst += count;
                        src += 2;
                        break;

                    default:
                        off   = (((m_comp2[i / 2] << (4 * (2 - (i & 1)))) & 0xf00) | m_comp1[src]) + 2;
                        count = m_comp1[src + 1] + 18;
                        Binary.CopyOverlapped(m_output, dst - off, dst, count);
                        dst += count;
                        src += 2;
                        ++i;
                        break;
                    }
                }
            }
Example #11
0
        /**
         * Creates a byte array representation of this data structure. Suitable for
         * writing to a Word document.
         *
         * @param fcMin The file offset in the main stream where text begins.
         * @return A byte array representing this data structure.
         */
        internal byte[] ToByteArray(HWPFStream dataStream,
                                    CharIndexTranslator translator)
        {
            byte[] buf          = new byte[512];
            int    size         = _papxList.Count;
            int    grpprlOffset = 0;
            int    bxOffset     = 0;
            int    fcOffset     = 0;

            byte[] lastGrpprl = new byte[0];

            // total size is currently the size of one FC
            int totalSize = FC_SIZE;

            int index = 0;

            for (; index < size; index++)
            {
                byte[] grpprl       = ((PAPX)_papxList[index]).GetGrpprl();
                int    grpprlLength = grpprl.Length;

                // is grpprl huge?
                if (grpprlLength > 488)
                {
                    grpprlLength = 8; // set equal to size of sprmPHugePapx grpprl
                }

                // check to see if we have enough room for an FC, a BX, and the grpprl
                // and the 1 byte size of the grpprl.
                int addition = 0;
                if (!Arrays.Equals(grpprl, lastGrpprl))
                {
                    addition = (FC_SIZE + BX_SIZE + grpprlLength + 1);
                }
                else
                {
                    addition = (FC_SIZE + BX_SIZE);
                }

                totalSize += addition;

                // if size is uneven we will have to add one so the first grpprl falls
                // on a word boundary
                if (totalSize > 511 + (index % 2))
                {
                    totalSize -= addition;
                    break;
                }

                // grpprls must fall on word boundaries
                if (grpprlLength % 2 > 0)
                {
                    totalSize += 1;
                }
                else
                {
                    totalSize += 2;
                }
                lastGrpprl = grpprl;
            }

            // see if we couldn't fit some
            if (index != size)
            {
                _overFlow = new List <PAPX>();
                _overFlow.AddRange(_papxList.GetRange(index, size - index));
            }

            // index should equal number of papxs that will be in this fkp now.
            buf[511] = (byte)index;

            bxOffset     = (FC_SIZE * index) + FC_SIZE;
            grpprlOffset = 511;

            PAPX papx = null;

            lastGrpprl = new byte[0];
            for (int x = 0; x < index; x++)
            {
                papx = _papxList[x];
                byte[] phe    = papx.GetParagraphHeight().ToArray();
                byte[] grpprl = papx.GetGrpprl();

                // is grpprl huge?
                if (grpprl.Length > 488)
                {
                    /*
                     * // if so do we have storage at GetHugeGrpprloffset()
                     * int hugeGrpprlOffset = papx.GetHugeGrpprlOffset();
                     * if (hugeGrpprlOffset == -1) // then we have no storage...
                     * {
                     *  throw new InvalidOperationException(
                     *        "This Paragraph has no dataStream storage.");
                     * }
                     * // we have some storage...
                     *
                     * // get the size of the existing storage
                     * int maxHugeGrpprlSize = LittleEndian.GetUShort(_dataStream, hugeGrpprlOffset);
                     *
                     * if (maxHugeGrpprlSize < grpprl.Length - 2)
                     * { // grpprl.Length-2 because we don't store the istd
                     *  throw new InvalidOperationException(
                     *      "This Paragraph's dataStream storage is too small.");
                     * }
                     *
                     *
                     * // store grpprl at hugeGrpprlOffset
                     * Array.Copy(grpprl, 2, _dataStream, hugeGrpprlOffset + 2,
                     *               grpprl.Length - 2); // grpprl.Length-2 because we don't store the istd
                     * LittleEndian.PutUShort(_dataStream, hugeGrpprlOffset, grpprl.Length - 2);
                     */

                    byte[] hugePapx = new byte[grpprl.Length - 2];
                    System.Array.Copy(grpprl, 2, hugePapx, 0, grpprl.Length - 2);
                    int dataStreamOffset = dataStream.Offset;
                    dataStream.Write(hugePapx);

                    // grpprl = grpprl Containing only a sprmPHugePapx2
                    int istd = LittleEndian.GetUShort(grpprl, 0);
                    grpprl = new byte[8];
                    LittleEndian.PutUShort(grpprl, 0, istd);
                    LittleEndian.PutUShort(grpprl, 2, 0x6646); // sprmPHugePapx2
                    LittleEndian.PutInt(grpprl, 4, dataStreamOffset);
                }

                bool same = Arrays.Equals(lastGrpprl, grpprl);
                if (!same)
                {
                    grpprlOffset -= (grpprl.Length + (2 - grpprl.Length % 2));
                    grpprlOffset -= (grpprlOffset % 2);
                }
                LittleEndian.PutInt(buf, fcOffset, translator.GetByteIndex(papx.Start));
                buf[bxOffset] = (byte)(grpprlOffset / 2);
                Array.Copy(phe, 0, buf, bxOffset + 1, phe.Length);

                // refer to the section on PAPX in the spec. Places a size on the front
                // of the PAPX. Has to do with how the grpprl stays on word
                // boundaries.
                if (!same)
                {
                    int copyOffset = grpprlOffset;
                    if ((grpprl.Length % 2) > 0)
                    {
                        buf[copyOffset++] = (byte)((grpprl.Length + 1) / 2);
                    }
                    else
                    {
                        buf[++copyOffset] = (byte)((grpprl.Length) / 2);
                        copyOffset++;
                    }
                    Array.Copy(grpprl, 0, buf, copyOffset, grpprl.Length);
                    lastGrpprl = grpprl;
                }

                bxOffset += BX_SIZE;
                fcOffset += FC_SIZE;
            }

            LittleEndian.PutInt(buf, fcOffset, translator.GetByteIndex(papx.End));
            return(buf);
        }
Example #12
0
        void UncompressRgba(IBitStream input, byte[] output)
        {
            int stride   = 4 * m_width;
            int q        = CompressInfo[0];
            int b_bits   = CompressInfo[4];
            int g_bits   = CompressInfo[5];
            int r_bits   = CompressInfo[6];
            int b_shift  = 8 - b_bits;
            int g_shift  = 16 - g_bits;
            int r_shift  = 24 - r_bits;
            int dst_pos  = m_y * stride + m_x * 4;
            int baseline = 0xFF >> b_bits | (0xFF >> g_bits | (0xFF >> r_bits << 8)) << 8;
            var line_buf = new int[m_w];

            for (int y = 0; y < m_h; ++y)
            {
                int  alpha        = 0;
                int  rgb          = 0;
                int  repeat_count = 0;
                bool repeat       = true;
                int  dst          = dst_pos + y * stride;
                int  x            = 0;
                int  chunk_size   = 0;
                while (x < m_w)
                {
                    if (0 == chunk_size)
                    {
                        int alpha_inc = 0;
                        if (input.GetNextBit() > 0)
                        {
                            alpha_inc = GetSigned(input);
                        }
                        alpha += alpha_inc;
                        if (0 == alpha || 31 == alpha)
                        {
                            chunk_size = GetInt(input);
                        }
                    }
                    if (alpha != 0)
                    {
                        if (31 == alpha)
                        {
                            --chunk_size;
                        }
                        if (0 == repeat_count)
                        {
                            repeat_count = GetInt(input);
                            repeat       = !repeat;
                        }
                        --repeat_count;
                        if (!repeat)
                        {
                            if (input.GetNextBit() > 0)
                            {
                                rgb = line_buf[x];
                            }
                            else
                            {
                                int g = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    g = GetSigned(input);
                                }
                                int b_inc = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    bool sign = input.GetNextBit() > 0;
                                    int  v    = GetInt(input);
                                    b_inc = tblQuantTransfer[q, v];
                                    if (sign)
                                    {
                                        b_inc = -b_inc;
                                    }
                                }
                                int r_inc = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    bool sign = input.GetNextBit() > 0;
                                    int  v    = GetInt(input);
                                    r_inc = tblQuantTransfer[q, v];
                                    if (sign)
                                    {
                                        r_inc = -r_inc;
                                    }
                                }
                                int c1 = (0xFF >> b_shift) & (int)((uint)rgb >> b_shift);
                                c1 = -c1;
                                if (g >= c1)
                                {
                                    int c2 = (0xFF >> b_shift) + c1;
                                    c1 = g;
                                    if (g > c2)
                                    {
                                        c1 = c2;
                                    }
                                }
                                int b = c1 + b_inc;
                                c1 = (0xFF0000 >> r_shift) & (int)((uint)rgb >> r_shift);
                                c1 = -c1;
                                if (g >= c1)
                                {
                                    int c2 = (0xFF0000 >> r_shift) + c1;
                                    c1 = g;
                                    if (g > c2)
                                    {
                                        c1 = c2;
                                    }
                                }
                                int r = c1 + r_inc;
                                rgb += (b << b_shift) + (r << r_shift) + (g << g_shift);
                            }
                        }
                        uint pixel = (uint)(baseline + rgb);
                        if (31 == alpha)
                        {
                            pixel |= 0xFF000000u;
                        }
                        else
                        {
                            pixel |= (uint)(alpha << 27);
                        }
                        LittleEndian.Pack(pixel, output, dst);
                        dst          += 4;
                        line_buf[x++] = rgb;
                    }
                    else
                    {
                        dst       += 4 * chunk_size;
                        x         += chunk_size;
                        chunk_size = 0;
                    }
                }
            }
        }
Example #13
0
        void UncompressRgb(IBitStream input, byte[] output)
        {
            int  stride    = m_width * 4;
            int  q         = CompressInfo[0];
            int  b_bits    = CompressInfo[4];
            int  g_bits    = CompressInfo[5];
            int  r_bits    = CompressInfo[6];
            bool is_bgr676 = 6 == b_bits && 7 == g_bits && 6 == r_bits;
            int  b_shift   = 8 - b_bits;
            int  g_shift   = 16 - g_bits;
            int  r_shift   = 24 - r_bits;
            int  baseline  = 0xFF >> b_bits | (0xFF >> g_bits | (0xFF >> r_bits | 0xFF00) << 8) << 8;
            {
                for (int y = 0; y < m_height; ++y)
                {
                    int rgb = 0, rgb_ = 0;
                    int dst = y * stride;
                    int x   = 0;
                    while (x < m_width)
                    {
                        int count = GetInt(input);
                        x += count;
                        do
                        {
                            if (input.GetNextBit() > 0)
                            {
                                rgb = LittleEndian.ToInt32(output, dst - stride);
                                if (rgb != 0)
                                {
                                    rgb -= baseline;
                                }
                                rgb_ = rgb;
                            }
                            else
                            {
                                int r = 0, g = 0, b = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    g = GetSigned(input);
                                }
                                int b_inc = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    bool sign = input.GetNextBit() > 0;
                                    int  v    = GetInt(input);
                                    b_inc = tblQuantTransfer[q, v];
                                    if (sign)
                                    {
                                        b_inc = -b_inc;
                                    }
                                }
                                int r_inc = 0;
                                if (input.GetNextBit() > 0)
                                {
                                    bool sign = input.GetNextBit() > 0;
                                    int  v    = GetInt(input);
                                    r_inc = tblQuantTransfer[q, v];
                                    if (sign)
                                    {
                                        r_inc = -r_inc;
                                    }
                                }
                                int gg = g;
                                if (is_bgr676)
                                {
                                    gg >>= 1;
                                }
                                if (CompressInfo[3] != 0)
                                {
                                    int c1 = (0xFF >> b_shift) & (int)((uint)rgb_ >> b_shift);
                                    c1 = -c1;
                                    if (gg >= c1)
                                    {
                                        int c2 = (0xFF >> b_shift) + c1;
                                        c1 = c2;
                                        if (gg <= c2)
                                        {
                                            c1 = gg;
                                        }
                                    }
                                    b  = c1 + b_inc;
                                    c1 = (0xFF0000 >> r_shift) & (int)((uint)rgb_ >> r_shift);
                                    c1 = -c1;
                                    if (gg >= c1)
                                    {
                                        int c2 = (0xFF0000 >> r_shift) + c1;
                                        c1 = c2;
                                        if (gg <= c2)
                                        {
                                            c1 = gg;
                                        }
                                    }
                                    r = c1 + r_inc;
                                }
                                else
                                {
                                    b = gg + b_inc;
                                    r = gg + r_inc;
                                }
                                rgb_ += (b << b_shift) + (r << r_shift) + (g << g_shift);
                                rgb   = rgb_;
                            }
                            if (rgb != 0)
                            {
                                rgb += baseline;
                            }
                            LittleEndian.Pack(rgb, output, dst);
                            dst += 4;
                            --count;
                        }while (count > 0);
                        if (x >= m_width)
                        {
                            break;
                        }

                        count = GetInt(input);
                        x    += count;
                        while (count-- > 0)
                        {
                            LittleEndian.Pack(rgb, output, dst);
                            dst += 4;
                        }
                    }
                }
            }
        }
Example #14
0
        uint DecodeSPB()
        {
            uint width = (uint)Input.ReadByte() << 8;

            width |= (uint)Input.ReadByte();
            uint height = (uint)Input.ReadByte() << 8;

            height |= (uint)Input.ReadByte();

            uint width_pad  = (4 - width * 3 % 4) % 4;
            int  stride     = (int)(width * 3 + width_pad);
            uint total_size = (uint)stride * height + 54;

            if ((uint)m_output.Length < total_size)
            {
                m_output = new byte[total_size];
            }

            /* ---------------------------------------- */
            /* Write header */
            m_output[0] = (byte)'B';
            m_output[1] = (byte)'M';
            LittleEndian.Pack(total_size, m_output, 2);
            m_output[10] = 54; // offset to the body
            m_output[14] = 40; // header size
            LittleEndian.Pack(width, m_output, 18);
            LittleEndian.Pack(height, m_output, 22);
            m_output[26] = 1;  // the number of the plane
            m_output[28] = 24; // bpp

            byte[] decomp_buffer = new byte[width * height * 4];

            for (int i = 0; i < 3; i++)
            {
                uint count = 0;
                int  c     = GetBits(8);
                if (-1 == c)
                {
                    break;
                }
                decomp_buffer[count++] = (byte)c;
                while (count < width * height)
                {
                    int n = GetBits(3);
                    if (0 == n)
                    {
                        decomp_buffer[count++] = (byte)c;
                        decomp_buffer[count++] = (byte)c;
                        decomp_buffer[count++] = (byte)c;
                        decomp_buffer[count++] = (byte)c;
                        continue;
                    }
                    int m;
                    if (7 == n)
                    {
                        m = GetBits(1) + 1;
                    }
                    else
                    {
                        m = n + 2;
                    }

                    for (uint j = 0; j < 4; j++)
                    {
                        if (8 == m)
                        {
                            c = GetBits(8);
                        }
                        else
                        {
                            int k = GetBits(m);
                            if (0 != (k & 1))
                            {
                                c += (k >> 1) + 1;
                            }
                            else
                            {
                                c -= (k >> 1);
                            }
                        }
                        decomp_buffer[count++] = (byte)c;
                    }
                }

                int pbuf  = stride * (int)(height - 1) + i + 54; // in m_output
                int psbuf = 0;                                   // in decomp_buffer

                for (uint j = 0; j < height; j++)
                {
                    if (0 != (j & 1))
                    {
                        for (uint k = 0; k < width; k++, pbuf -= 3)
                        {
                            m_output[pbuf] = decomp_buffer[psbuf++];
                        }
                        pbuf -= stride - 3;
                    }
                    else
                    {
                        for (uint k = 0; k < width; k++, pbuf += 3)
                        {
                            m_output[pbuf] = decomp_buffer[psbuf++];
                        }
                        pbuf -= stride + 3;
                    }
                }
            }
            return(total_size);
        }
Example #15
0
 public void TestUnsignedByteToInt()
 {
     Assert.AreEqual(255, LittleEndian.UByteToInt(unchecked ((byte)255)));
 }
Example #16
0
 /// <summary>
 /// Serializes the simple part of this property.  ie the first 6 bytes.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="pos"></param>
 /// <returns></returns>
 public override int SerializeSimplePart(byte[] data, int pos)
 {
     LittleEndian.PutShort(data, pos, Id);
     LittleEndian.PutInt(data, pos + 2, complexData.Length);
     return(6);
 }
Example #17
0
 public void TestUnsignedShort()
 {
     Assert.AreEqual(0xffff, LittleEndian.GetUShort(new byte[] { unchecked ((byte)0xff), unchecked ((byte)0xff) }, 0));
 }
Example #18
0
            int UnpackLine(byte[] line, int dst)
            {
                int row_pos = 0;

                for (int x = m_width; x > 0 && dst < m_output.Length && row_pos < line.Length;)
                {
                    if (0 != (row_pos & 1))
                    {
                        ++row_pos;
                    }
                    int count = LittleEndian.ToUInt16(line, row_pos);
                    row_pos += 2;
                    int method = count >> 13;
                    int skip   = (count >> 11) & 3;
                    if (0 != skip)
                    {
                        row_pos += skip;
                    }
                    count &= 0x7ff;
                    if (0 == count)
                    {
                        count    = LittleEndian.ToInt32(line, row_pos);
                        row_pos += 4;
                    }
                    if (count > x)
                    {
                        count = x;
                    }
                    x -= count;
                    byte b, g, r, a;

                    switch (method)
                    {
                    case 2:
                        for (int i = 0; i < count && row_pos < line.Length; ++i)
                        {
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = 0xff;
                        }
                        break;

                    case 3:
                        b = line[row_pos++];
                        g = line[row_pos++];
                        r = line[row_pos++];
                        for (int i = 0; i < count; ++i)
                        {
                            m_output[dst++] = b;
                            m_output[dst++] = g;
                            m_output[dst++] = r;
                            m_output[dst++] = 0xff;
                        }
                        break;

                    case 4:
                        for (int i = 0; i < count && row_pos < line.Length; ++i)
                        {
                            a = line[row_pos++];
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = line[row_pos++];
                            m_output[dst++] = a;
                        }
                        break;

                    case 5:
                        a = line[row_pos++];
                        b = line[row_pos++];
                        g = line[row_pos++];
                        r = line[row_pos++];
                        for (int i = 0; i < count; ++i)
                        {
                            m_output[dst++] = b;
                            m_output[dst++] = g;
                            m_output[dst++] = r;
                            m_output[dst++] = a;
                        }
                        break;

                    default:
                        dst += count * 4;
                        break;
                    }
                }
                return(dst);
            }
Example #19
0
            public List <Entry> ReadIndex()
            {
                byte[] title        = m_file.View.ReadBytes(6, 0x40);
                int    title_length = Array.IndexOf <byte> (title, 0);

                if (-1 == title_length)
                {
                    title_length = title.Length;
                }
                string arc_filename = Path.GetFileName(m_file.Name);

                if (0x200 != m_version)
                {
                    arc_filename = arc_filename.ToLowerInvariant();
                }
                string base_filename = Path.GetFileNameWithoutExtension(arc_filename);

                byte[] name_key = GenerateKey(Encodings.cp932.GetBytes(arc_filename));

                uint index_offset = 0x200 + (uint)name_key.Select(x => (int)x).Sum();

                for (int i = 0; i < name_key.Length; ++i)
                {
                    index_offset ^= name_key[i];
                    index_offset  = Binary.RotR(index_offset, 1);
                }
                for (int i = 0; i < name_key.Length; ++i)
                {
                    index_offset ^= name_key[i];
                    index_offset  = Binary.RotR(index_offset, 1);
                }
                index_offset %= 0x401;

                index_offset += 0x4A;
                byte[] index = m_file.View.ReadBytes(index_offset, (uint)(4 * m_count));
                if (index.Length != 4 * m_count)
                {
                    return(null);
                }

                byte[] index_key = new byte[index.Length];
                for (int i = 0; i < index_key.Length; ++i)
                {
                    int v = name_key[(i + 1) % name_key.Length] ^ (name_key[i % name_key.Length] + i);
                    index_key[i] = (byte)(m_count + v);
                }
                Decrypt(index_offset, index_key, index);
                m_data_key = GenerateKey(title, title_length);
                var  dir            = new List <Entry> (m_count);
                int  current_offset = 0;
                uint next_offset    = LittleEndian.ToUInt32(index, current_offset);

                for (int i = 0; i < m_count; ++i)
                {
                    current_offset += 4;
                    uint entry_offset = next_offset;
                    if (entry_offset >= m_file.MaxOffset)
                    {
                        return(null);
                    }
                    if (i + 1 == m_count)
                    {
                        next_offset = (uint)m_file.MaxOffset;
                    }
                    else
                    {
                        next_offset = LittleEndian.ToUInt32(index, current_offset);
                    }
                    uint entry_size = next_offset - entry_offset;
                    var  entry      = ParseEntry(entry_offset, entry_size);
                    if (string.IsNullOrEmpty(entry.Name))
                    {
                        entry.Name = string.Format("{0}#{1:D4}", base_filename, i);
                    }
                    dir.Add(entry);
                }
                return(dir);
            }
Example #20
0
            byte[] ReadLine(uint offset, int repeat)
            {
                m_input.Position = offset;
                int row_length = m_input.ReadUInt16();

                if (0 != (offset & 1))
                {
                    m_input.ReadByte();
                    --row_length;
                }
                var row = new byte[row_length];

                m_input.Read(row, 0, row.Length);
                int row_pos = 0;

                for (int x = m_width; x > 0;)
                {
                    if (0 != (row_pos & 1))
                    {
                        ++row_pos;
                    }
                    int count = LittleEndian.ToUInt16(row, row_pos);
                    row_pos += 2;
                    int method = count >> 13;
                    int skip   = (count >> 11) & 3;
                    if (0 != skip)
                    {
                        row_pos += skip;
                    }
                    count &= 0x7ff;
                    if (0 == count)
                    {
                        count    = LittleEndian.ToInt32(row, row_pos);
                        row_pos += 4;
                    }
                    if (count < 0 || count > x)
                    {
                        count = x;
                    }
                    x -= count;

                    switch (method)
                    {
                    case 2:
                        for (int j = 0; j < repeat; ++j)
                        {
                            for (int i = 3; i < count * 3 && row_pos + i < row.Length; ++i)
                            {
                                row[row_pos + i] += row[row_pos + i - 3];
                            }
                        }
                        row_pos += count * 3;
                        break;

                    case 3:
                        row_pos += 3;
                        break;

                    case 4:
                        for (int j = 0; j < repeat; ++j)
                        {
                            for (int i = 4; i < count * 4 && row_pos + i < row.Length; ++i)
                            {
                                row[row_pos + i] += row[row_pos + i - 4];
                            }
                        }
                        row_pos += count * 4;
                        break;

                    case 5:
                        row_pos += 4;
                        break;

                    default:
                        break;
                    }
                }
                return(row);
            }
Example #21
0
        void TransformState(byte[] state1, byte[] target, int length)
        {
            for (int i = 0; i < 16; ++i)
            {
                tmp[i] = ~LittleEndian.ToUInt32(state1, i * 4);
            }
            if (length > 0)
            {
                for (int count = ((length - 1) >> 1) + 1; count > 0; --count)
                {
                    uint t1 = tmp[4] + tmp[0];
                    uint t2 = Binary.RotL(t1 ^ tmp[12], 16);
                    uint t3 = t2 + tmp[8];
                    uint t4 = Binary.RotL(tmp[4] ^ t3, 12);
                    uint t5 = t4 + t1;
                    uint t6 = Binary.RotL(t5 ^ t2, 8);
                    tmp[12]  = t6;
                    t6      += t3;
                    tmp[4]   = Binary.RotL(t4 ^ t6, 7);
                    t4       = Binary.RotL((tmp[5] + tmp[1]) ^ tmp[13], 16);
                    t3       = Binary.RotL(tmp[5] ^ (t4 + tmp[9]), 12);
                    t2       = t3 + tmp[5] + tmp[1];
                    tmp[13]  = Binary.RotL(t2 ^ t4, 8);
                    tmp[9]  += tmp[13] + t4;
                    tmp[5]   = Binary.RotL(t3 ^ tmp[9], 7);
                    t4       = Binary.RotL((tmp[6] + tmp[2]) ^ tmp[14], 16);
                    tmp[10] += t4;
                    t1       = Binary.RotL(tmp[6] ^ tmp[10], 12);
                    t3       = t1 + tmp[6] + tmp[2];
                    tmp[14]  = Binary.RotL(t3 ^ t4, 8);
                    tmp[6]   = Binary.RotL(t1 ^ (tmp[14] + tmp[10]), 7);
                    tmp[10] += tmp[14];
                    t4       = (tmp[7] + tmp[3]) ^ tmp[15];
                    tmp[3]  += tmp[7];
                    t4       = Binary.RotL(t4, 16);
                    tmp[11] += t4;
                    t1       = Binary.RotL(tmp[7] ^ tmp[11], 12);
                    t4      ^= t1 + tmp[3];
                    tmp[3]  += t1;
                    t4       = Binary.RotL(t4, 8);
                    tmp[11] += t4;
                    t1       = Binary.RotL(t1 ^ tmp[11], 7);
                    t5      += tmp[5];
                    t2      += tmp[6];
                    t4       = Binary.RotL(t5 ^ t4, 16);
                    tmp[10] += t4;
                    tmp[5]   = Binary.RotL(tmp[5] ^ tmp[10], 12);
                    tmp[0]   = tmp[5] + t5;
                    t4       = Binary.RotL(tmp[0] ^ t4, 8);
                    tmp[15]  = t4;
                    tmp[10] += t4;
                    tmp[5]   = Binary.RotL(tmp[5] ^ tmp[10], 7);
                    tmp[12]  = Binary.RotL(tmp[12] ^ t2, 16);
                    tmp[11] += tmp[12];
                    t4       = Binary.RotL(tmp[11] ^ tmp[6], 12);
                    tmp[1]   = t4 + t2;
                    tmp[12]  = Binary.RotL(tmp[12] ^ tmp[1], 8);
                    tmp[11] += tmp[12];
                    tmp[6]   = Binary.RotL(t4 ^ tmp[11], 7);
                    t3      += t1;
                    t4       = Binary.RotL(tmp[13] ^ t3, 16);
                    t2       = t4 + t6;
                    t1       = Binary.RotL(t2 ^ t1, 12);
                    tmp[2]   = t1 + t3;
                    tmp[13]  = Binary.RotL(t4 ^ tmp[2], 8);
                    tmp[8]   = tmp[13] + t2;
                    tmp[7]   = Binary.RotL(tmp[8] ^ t1, 7);
                    t6       = Binary.RotL(tmp[14] ^ (tmp[4] + tmp[3]), 16);
                    t1       = Binary.RotL(tmp[4] ^ (t6 + tmp[9]), 12);
                    tmp[3]  += t1 + tmp[4];
                    t3       = Binary.RotL(t6 ^ tmp[3], 8);
                    tmp[9]  += t3 + t6;
                    tmp[4]   = Binary.RotL(t1 ^ tmp[9], 7);
                    tmp[14]  = t3;
                }
            }
            int pos = 0;

            for (int i = 0; i < 16; ++i)
            {
                uint x = tmp[i] + ~LittleEndian.ToUInt32(state1, pos);
                LittleEndian.Pack(x, target, pos);
                pos += 4;
            }
        }
Example #22
0
        public void PrivateHeaderBlock(byte[] data)
        {
            _data = data;

            long signature = LittleEndian.GetLong(_data, _signature_offset);

            if (signature != _signature)
            {
                if (cmp(POIFSConstants.OOXML_FILE_HEADER, data))
                {
                    throw new OfficeXmlFileException("The supplied data appears to be in the Office 2007+ XML. "
                                                     + "You are calling the part of POI that deals with OLE2 Office Documents. "
                                                     + "You need to call a different part of POI to process this data (eg XSSF instead of HSSF)");
                }

                if (cmp(POIFSConstants.RAW_XML_FILE_HEADER, data))
                {
                    throw new NotOLE2FileException("The supplied data appears to be a raw XML file. "
                                                   + "Formats such as Office 2003 XML are not supported");
                }

                // BIFF2 raw stream
                if (cmp(MAGIC_BIFF2, data))
                {
                    throw new OldExcelFormatException("The supplied data appears to be in BIFF2 format. "
                                                      + "HSSF only supports the BIFF8 format, try OldExcelExtractor");
                }

                // BIFF3 raw stream
                if (cmp(MAGIC_BIFF3, data))
                {
                    throw new OldExcelFormatException("The supplied data appears to be in BIFF3 format. "
                                                      + "HSSF only supports the BIFF8 format, try OldExcelExtractor");
                }

                // BIFF4 raw stream
                if (cmp(MAGIC_BIFF4a, data) || cmp(MAGIC_BIFF4b, data))
                {
                    throw new OldExcelFormatException("The supplied data appears to be in BIFF4 format. "
                                                      + "HSSF only supports the BIFF8 format, try OldExcelExtractor");
                }


                // Give a generic error if the OLE2 signature isn't found
                throw new NotOLE2FileException("Invalid header signature; read "
                                               + new String(HexDump.LongToHex(signature)) + ", expected "
                                               + new String(HexDump.LongToHex(_signature)) + " - Your file appears "
                                               + "not to be a valid OLE2 document");
            }

            if (_data[30] == 12)
            {
                bigBlockSize = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS;
            }
            else if (_data[30] == 9)
            {
                bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
            }
            else
            {
                throw new IOException("Unsupported blocksize  (2^" + _data[30] + "). Expected 2^9 or 2^12.");
            }

            // Setup the fields to read and write the counts and starts
            _bat_count      = new IntegerField(HeaderBlockConstants._bat_count_offset, _data).Value;
            _property_start = new IntegerField(HeaderBlockConstants._property_start_offset, _data).Value;
            _sbat_start     = new IntegerField(HeaderBlockConstants._sbat_start_offset, _data).Value;
            _sbat_count     = new IntegerField(HeaderBlockConstants._sbat_block_count_offset, _data).Value;
            _xbat_start     = new IntegerField(HeaderBlockConstants._xbat_start_offset, _data).Value;
            _xbat_count     = new IntegerField(HeaderBlockConstants._xbat_count_offset, _data).Value;
        }
Example #23
0
        /// <summary>
        /// This version of dump is a translation from the open office escher dump routine.
        /// </summary>
        /// <param name="maxLength">The number of bytes to Read</param>
        /// <param name="in1">An input stream to Read from.</param>
        public void DumpOld(long maxLength, Stream in1)
        {
            long          remainingBytes = maxLength;
            short         options;              // 4 bits for the version and 12 bits for the instance
            short         recordId;
            int           recordBytesRemaining; // including enclosing records
            StringBuilder stringBuf = new StringBuilder();
            short         nDumpSize;
            String        recordName;

            bool atEOF = false;

            while (!atEOF && (remainingBytes > 0))
            {
                stringBuf            = new StringBuilder();
                options              = LittleEndian.ReadShort(in1);
                recordId             = LittleEndian.ReadShort(in1);
                recordBytesRemaining = LittleEndian.ReadInt(in1);

                remainingBytes -= 2 + 2 + 4;

                switch (recordId)
                {
                case unchecked ((short)0xF000):
                    recordName = "MsofbtDggContainer";
                    break;

                case unchecked ((short)0xF006):
                    recordName = "MsofbtDgg";
                    break;

                case unchecked ((short)0xF016):
                    recordName = "MsofbtCLSID";
                    break;

                case unchecked ((short)0xF00B):
                    recordName = "MsofbtOPT";
                    break;

                case unchecked ((short)0xF11A):
                    recordName = "MsofbtColorMRU";
                    break;

                case unchecked ((short)0xF11E):
                    recordName = "MsofbtSplitMenuColors";
                    break;

                case unchecked ((short)0xF001):
                    recordName = "MsofbtBstoreContainer";
                    break;

                case unchecked ((short)0xF007):
                    recordName = "MsofbtBSE";
                    break;

                case unchecked ((short)0xF002):
                    recordName = "MsofbtDgContainer";
                    break;

                case unchecked ((short)0xF008):
                    recordName = "MsofbtDg";
                    break;

                case unchecked ((short)0xF118):
                    recordName = "MsofbtRegroupItem";
                    break;

                case unchecked ((short)0xF120):
                    recordName = "MsofbtColorScheme";
                    break;

                case unchecked ((short)0xF003):
                    recordName = "MsofbtSpgrContainer";
                    break;

                case unchecked ((short)0xF004):
                    recordName = "MsofbtSpContainer";
                    break;

                case unchecked ((short)0xF009):
                    recordName = "MsofbtSpgr";
                    break;

                case unchecked ((short)0xF00A):
                    recordName = "MsofbtSp";
                    break;

                case unchecked ((short)0xF00C):
                    recordName = "MsofbtTextbox";
                    break;

                case unchecked ((short)0xF00D):
                    recordName = "MsofbtClientTextbox";
                    break;

                case unchecked ((short)0xF00E):
                    recordName = "MsofbtAnchor";
                    break;

                case unchecked ((short)0xF00F):
                    recordName = "MsofbtChildAnchor";
                    break;

                case unchecked ((short)0xF010):
                    recordName = "MsofbtClientAnchor";
                    break;

                case unchecked ((short)0xF011):
                    recordName = "MsofbtClientData";
                    break;

                case unchecked ((short)0xF11F):
                    recordName = "MsofbtOleObject";
                    break;

                case unchecked ((short)0xF11D):
                    recordName = "MsofbtDeletedPspl";
                    break;

                case unchecked ((short)0xF005):
                    recordName = "MsofbtSolverContainer";
                    break;

                case unchecked ((short)0xF012):
                    recordName = "MsofbtConnectorRule";
                    break;

                case unchecked ((short)0xF013):
                    recordName = "MsofbtAlignRule";
                    break;

                case unchecked ((short)0xF014):
                    recordName = "MsofbtArcRule";
                    break;

                case unchecked ((short)0xF015):
                    recordName = "MsofbtClientRule";
                    break;

                case unchecked ((short)0xF017):
                    recordName = "MsofbtCalloutRule";
                    break;

                case unchecked ((short)0xF119):
                    recordName = "MsofbtSelection";
                    break;

                case unchecked ((short)0xF122):
                    recordName = "MsofbtUDefProp";
                    break;

                default:
                    if (recordId >= unchecked ((short)0xF018) && recordId <= unchecked ((short)0xF117))
                    {
                        recordName = "MsofbtBLIP";
                    }
                    else if ((options & (short)0x000F) == (short)0x000F)
                    {
                        recordName = "UNKNOWN container";
                    }
                    else
                    {
                        recordName = "UNKNOWN ID";
                    }
                    break;
                }

                stringBuf.Append("  ");
                stringBuf.Append(HexDump.ToHex(recordId));
                stringBuf.Append("  ").Append(recordName).Append(" [");
                stringBuf.Append(HexDump.ToHex(options));
                stringBuf.Append(',');
                stringBuf.Append(HexDump.ToHex(recordBytesRemaining));
                stringBuf.Append("]  instance: ");
                stringBuf.Append(HexDump.ToHex(((short)(options >> 4))));
                Console.WriteLine(stringBuf.ToString());


                if (recordId == (unchecked ((short)0xF007)) && 36 <= remainingBytes && 36 <= recordBytesRemaining)
                {       // BSE, FBSE
                    //                ULONG nP = pIn->GetRecPos();

                    byte n8;
                    //                short n16;
                    //                int n32;

                    stringBuf = new StringBuilder("    btWin32: ");
                    n8        = (byte)in1.ReadByte();
                    stringBuf.Append(HexDump.ToHex(n8));
                    stringBuf.Append(GetBlipType(n8));
                    stringBuf.Append("  btMacOS: ");
                    n8 = (byte)in1.ReadByte();
                    stringBuf.Append(HexDump.ToHex(n8));
                    stringBuf.Append(GetBlipType(n8));
                    Console.WriteLine(stringBuf.ToString());

                    Console.WriteLine("    rgbUid:");
                    HexDump.Dump(in1, 0, 16);

                    Console.Write("    tag: ");
                    OutHex(2, in1);
                    Console.WriteLine();
                    Console.Write("    size: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    cRef: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    offs: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    usage: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    cbName: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    unused2: ");
                    OutHex(4, in1);
                    Console.WriteLine();
                    Console.Write("    unused3: ");
                    OutHex(4, in1);
                    Console.WriteLine();

                    // subtract the number of bytes we've Read
                    remainingBytes -= 36;
                    //n -= pIn->GetRecPos() - nP;
                    recordBytesRemaining = 0;           // loop to MsofbtBLIP
                }
                else if (recordId == unchecked ((short)0xF010) && 0x12 <= remainingBytes && 0x12 <= recordBytesRemaining)
                {       // ClientAnchor
                    //ULONG nP = pIn->GetRecPos();
                    //                short n16;

                    Console.Write("    Flag: ");
                    OutHex(2, in1);
                    Console.WriteLine();
                    Console.Write("    Col1: ");
                    OutHex(2, in1);
                    Console.Write("    dX1: ");
                    OutHex(2, in1);
                    Console.Write("    Row1: ");
                    OutHex(2, in1);
                    Console.Write("    dY1: ");
                    OutHex(2, in1);
                    Console.WriteLine();
                    Console.Write("    Col2: ");
                    OutHex(2, in1);
                    Console.Write("    dX2: ");
                    OutHex(2, in1);
                    Console.Write("    Row2: ");
                    OutHex(2, in1);
                    Console.Write("    dY2: ");
                    OutHex(2, in1);
                    Console.WriteLine();

                    remainingBytes       -= 18;
                    recordBytesRemaining -= 18;
                }
                else if (recordId == unchecked ((short)0xF00B) || recordId == unchecked ((short)0xF122))
                {       // OPT
                    int nComplex = 0;
                    Console.WriteLine("    PROPID        VALUE");
                    while (recordBytesRemaining >= 6 + nComplex && remainingBytes >= 6 + nComplex)
                    {
                        short n16;
                        int   n32;
                        n16 = LittleEndian.ReadShort(in1);
                        n32 = LittleEndian.ReadInt(in1);

                        recordBytesRemaining -= 6;
                        remainingBytes       -= 6;
                        Console.Write("    ");
                        Console.Write(HexDump.ToHex(n16));
                        Console.Write(" (");
                        int propertyId = n16 & (short)0x3FFF;
                        Console.Write(" " + propertyId);
                        if ((n16 & unchecked ((short)0x8000)) == 0)
                        {
                            if ((n16 & (short)0x4000) != 0)
                            {
                                Console.Write(", fBlipID");
                            }
                            Console.Write(")  ");

                            Console.Write(HexDump.ToHex(n32));

                            if ((n16 & (short)0x4000) == 0)
                            {
                                Console.Write(" (");
                                Console.Write(Dec1616(n32));
                                Console.Write(')');
                                Console.Write(" {" + PropertyName((short)propertyId) + "}");
                            }
                            Console.WriteLine();
                        }
                        else
                        {
                            Console.Write(", fComplex)  ");
                            Console.Write(HexDump.ToHex(n32));
                            Console.Write(" - Complex prop len");
                            Console.WriteLine(" {" + PropertyName((short)propertyId) + "}");

                            nComplex += n32;
                        }
                    }
                    // complex property data
                    while ((nComplex & remainingBytes) > 0)
                    {
                        nDumpSize = (nComplex > (int)remainingBytes) ? (short)remainingBytes : (short)nComplex;
                        HexDump.Dump(in1, 0, nDumpSize);
                        nComplex             -= nDumpSize;
                        recordBytesRemaining -= nDumpSize;
                        remainingBytes       -= nDumpSize;
                    }
                }
                else if (recordId == (unchecked ((short)0xF012)))
                {
                    Console.Write("    Connector rule: ");
                    Console.Write(LittleEndian.ReadInt(in1));
                    Console.Write("    ShapeID A: ");
                    Console.Write(LittleEndian.ReadInt(in1));
                    Console.Write("   ShapeID B: ");
                    Console.Write(LittleEndian.ReadInt(in1));
                    Console.Write("    ShapeID connector: ");
                    Console.Write(LittleEndian.ReadInt(in1));
                    Console.Write("   Connect pt A: ");
                    Console.Write(LittleEndian.ReadInt(in1));
                    Console.Write("   Connect pt B: ");
                    Console.WriteLine(LittleEndian.ReadInt(in1));

                    recordBytesRemaining -= 24;
                    remainingBytes       -= 24;
                }
                else if (recordId >= unchecked ((short)0xF018) && recordId < unchecked ((short)0xF117))
                {
                    Console.WriteLine("    Secondary UID: ");
                    HexDump.Dump(in1, 0, 16);
                    Console.WriteLine("    Cache of size: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Boundary top: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Boundary left: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Boundary width: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Boundary height: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    X: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Y: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Cache of saved size: " + HexDump.ToHex(LittleEndian.ReadInt(in1)));
                    Console.WriteLine("    Compression Flag: " + HexDump.ToHex((byte)in1.ReadByte()));
                    Console.WriteLine("    Filter: " + HexDump.ToHex((byte)in1.ReadByte()));
                    Console.WriteLine("    Data (after decompression): ");

                    recordBytesRemaining -= 34 + 16;
                    remainingBytes       -= 34 + 16;

                    nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining;


                    byte[] buf  = new byte[nDumpSize];
                    int    Read = in1.Read(buf, 0, buf.Length);
                    while (Read != -1 && Read < nDumpSize)
                    {
                        Read += in1.Read(buf, Read, buf.Length);
                    }

                    using (MemoryStream bin = new MemoryStream(buf))
                    {
                        Inflater inflater = new Inflater(false);
                        using (InflaterInputStream zIn = new InflaterInputStream(bin, inflater))
                        {
                            int bytesToDump = -1;
                            HexDump.Dump(zIn, 0, bytesToDump);

                            recordBytesRemaining -= nDumpSize;
                            remainingBytes       -= nDumpSize;
                        }
                    }
                }

                bool isContainer = (options & (short)0x000F) == (short)0x000F;
                if (isContainer && remainingBytes >= 0)
                {       // Container
                    if (recordBytesRemaining <= (int)remainingBytes)
                    {
                        Console.WriteLine("            completed within");
                    }
                    else
                    {
                        Console.WriteLine("            continued elsewhere");
                    }
                }
                else if (remainingBytes >= 0)     // -> 0x0000 ... 0x0FFF
                {
                    nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining;

                    if (nDumpSize != 0)
                    {
                        HexDump.Dump(in1, 0, nDumpSize);
                        remainingBytes -= nDumpSize;
                    }
                }
                else
                {
                    Console.WriteLine(" >> OVERRUN <<");
                }
            }
        }
Example #24
0
        public byte[] ToData()
        {
            var timeSeries = m_dataSeries[0].DataPoints
                             .Select(dataPoint => new { Time = dataPoint.Time.Ticks, Compressed = false })
                             .ToList();

            for (int i = 1; i < timeSeries.Count; i++)
            {
                long previousTimestamp = m_dataSeries[0][i - 1].Time.Ticks;
                long timestamp         = timeSeries[i].Time;
                long diff = timestamp - previousTimestamp;

                if (diff >= 0 && diff <= ushort.MaxValue)
                {
                    timeSeries[i] = new { Time = diff, Compressed = true }
                }
                ;
            }

            int timeSeriesByteLength = timeSeries.Sum(obj => obj.Compressed ? sizeof(ushort) : sizeof(int) + sizeof(long));
            int dataSeriesByteLength = sizeof(int) + (2 * sizeof(double)) + (m_samples * sizeof(ushort));
            int totalByteLength      = sizeof(int) + timeSeriesByteLength + (dataSeriesByteLength * m_dataSeries.Count);

            byte[] data   = new byte[totalByteLength];
            int    offset = 0;

            offset += LittleEndian.CopyBytes(m_samples, data, offset);

            List <int> uncompressedIndexes = timeSeries
                                             .Select((obj, Index) => new { obj.Compressed, Index })
                                             .Where(obj => !obj.Compressed)
                                             .Select(obj => obj.Index)
                                             .ToList();

            for (int i = 0; i < uncompressedIndexes.Count; i++)
            {
                int index     = uncompressedIndexes[i];
                int nextIndex = (i + 1 < uncompressedIndexes.Count) ? uncompressedIndexes[i + 1] : timeSeries.Count;

                offset += LittleEndian.CopyBytes(nextIndex - index, data, offset);
                offset += LittleEndian.CopyBytes(timeSeries[index].Time, data, offset);

                for (int j = index + 1; j < nextIndex; j++)
                {
                    offset += LittleEndian.CopyBytes((ushort)timeSeries[j].Time, data, offset);
                }
            }

            foreach (DataSeries dataSeries in m_dataSeries)
            {
                if (dataSeries.Calculated)
                {
                    continue;
                }

                const ushort NaNValue           = ushort.MaxValue;
                const ushort MaxCompressedValue = ushort.MaxValue - 1;
                int          seriesID           = dataSeries.SeriesInfo?.ID ?? 0;
                double       range = dataSeries.Maximum - dataSeries.Minimum;
                double       decompressionOffset = dataSeries.Minimum;
                double       decompressionScale  = range / MaxCompressedValue;
                double       compressionScale    = (decompressionScale != 0.0D) ? 1.0D / decompressionScale : 0.0D;

                offset += LittleEndian.CopyBytes(seriesID, data, offset);
                offset += LittleEndian.CopyBytes(decompressionOffset, data, offset);
                offset += LittleEndian.CopyBytes(decompressionScale, data, offset);

                foreach (DataPoint dataPoint in dataSeries.DataPoints)
                {
                    ushort compressedValue = (ushort)Math.Round((dataPoint.Value - decompressionOffset) * compressionScale);

                    if (compressedValue == NaNValue)
                    {
                        compressedValue--;
                    }

                    if (double.IsNaN(dataPoint.Value))
                    {
                        compressedValue = NaNValue;
                    }

                    offset += LittleEndian.CopyBytes(compressedValue, data, offset);
                }
            }

            byte[] returnArray = GZipStream.CompressBuffer(data);
            returnArray[0] = 0x44;
            returnArray[1] = 0x33;

            return(returnArray);
        }
Example #25
0
        public List <Entry> ReadIndex()
        {
            uint section_size = ReadSectionSize("Fver");

            m_offset    += section_size;
            section_size = ReadSectionSize("Fcdr");

            /*
             * int Mcdr_size;
             * var Mcdr = ZlibUnpack (m_offset, section_size, out Mcdr_size);
             */
            m_offset += section_size;
            uint abmp_size   = ReadSectionSize("ABMP");
            int  max_count   = m_file.View.Read(m_offset, m_size_buffer, 0, Math.Min(10, abmp_size));
            int  size_offset = 0;

            ReadValue(m_size_buffer, ref size_offset, max_count);
            max_count -= size_offset;

            int bmp_unpacked_size = (int)ReadValue(m_size_buffer, ref size_offset, max_count);

            m_offset  += size_offset;
            abmp_size -= (uint)size_offset;
            int index_size;
            var index = ZlibUnpack(m_offset, abmp_size, out index_size, bmp_unpacked_size);

            m_offset    += abmp_size;
            section_size = ReadSectionSize("FGEI");
            if (0 != section_size)
            {
                throw new NotSupportedException();
            }

            int index_offset = 0;

            ReadValue(index, ref index_offset, index_size - index_offset);
            ReadValue(index, ref index_offset, index_size - index_offset);
            int entry_count = (int)ReadValue(index, ref index_offset, index_size - index_offset);

            if (entry_count <= 0 || entry_count > 0xfffff)
            {
                return(null);
            }

            var type_buf = new char[4];
            var dir      = new List <Entry> (entry_count);

            for (int i = 0; i < entry_count; ++i)
            {
                uint id            = ReadValue(index, ref index_offset, index_size - index_offset);
                uint offset        = ReadValue(index, ref index_offset, index_size - index_offset);
                uint size          = ReadValue(index, ref index_offset, index_size - index_offset);
                uint unpacked_size = ReadValue(index, ref index_offset, index_size - index_offset);
                uint flag          = ReadValue(index, ref index_offset, index_size - index_offset);

                if (index_size - index_offset < 4)
                {
                    return(null);
                }
                uint type_id = LittleEndian.ToUInt32(index, index_offset);
                index_offset += 4;
                if (0 == type_id || uint.MaxValue == offset)
                {
                    continue;
                }

                Encoding.ASCII.GetChars(index, index_offset - 4, 4, type_buf, 0);
                var entry = new PackedEntry
                {
                    Name         = CreateName(id, type_buf),
                    Offset       = (long)m_offset + offset,
                    Size         = size,
                    UnpackedSize = unpacked_size,
                    IsPacked     = 0 == flag,
                };
                if (entry.CheckPlacement(m_file.MaxOffset))
                {
                    dir.Add(entry);
                }
            }
            return(dir);
        }
Example #26
0
        public void FromData(Meter meter, byte[] data)
        {
            // If the blob contains the GZip header,
            // use the legacy deserialization algorithm
            if (data[0] == 0x1F && data[1] == 0x8B)
            {
                FromData_Legacy(meter, data);
                return;
            }

            // Restore the GZip header before uncompressing
            data[0] = 0x1F;
            data[1] = 0x8B;

            byte[] uncompressedData = GZipStream.UncompressBuffer(data);
            int    offset           = 0;

            m_samples = LittleEndian.ToInt32(uncompressedData, offset);
            offset   += sizeof(int);

            List <DateTime> times = new List <DateTime>();

            while (times.Count < m_samples)
            {
                int timeValues = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);

                long currentValue = LittleEndian.ToInt64(uncompressedData, offset);
                offset += sizeof(long);
                times.Add(new DateTime(currentValue));

                for (int i = 1; i < timeValues; i++)
                {
                    currentValue += LittleEndian.ToUInt16(uncompressedData, offset);
                    offset       += sizeof(ushort);
                    times.Add(new DateTime(currentValue));
                }
            }

            while (offset < uncompressedData.Length)
            {
                DataSeries dataSeries = new DataSeries();
                int        seriesID   = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);

                if (seriesID > 0 && (object)meter != null)
                {
                    dataSeries.SeriesInfo = GetSeriesInfo(meter, seriesID);
                }

                const ushort NaNValue            = ushort.MaxValue;
                double       decompressionOffset = LittleEndian.ToDouble(uncompressedData, offset);
                double       decompressionScale  = LittleEndian.ToDouble(uncompressedData, offset + sizeof(double));
                offset += 2 * sizeof(double);

                for (int i = 0; i < m_samples; i++)
                {
                    ushort compressedValue = LittleEndian.ToUInt16(uncompressedData, offset);
                    offset += sizeof(ushort);

                    double decompressedValue = decompressionScale * compressedValue + decompressionOffset;

                    if (compressedValue == NaNValue)
                    {
                        decompressedValue = double.NaN;
                    }

                    dataSeries.DataPoints.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = decompressedValue
                    });
                }

                Add(dataSeries);
            }
        }
Example #27
0
        public override ArcFile TryOpen(ArcView file)
        {
            int version = file.View.ReadUInt16(4);

            if (version < 1 || version > 6)
            {
                return(null);
            }
            int count = file.View.ReadInt32(8);

            if (!IsSaneCount(count))
            {
                return(null);
            }
            uint data_offset = file.View.ReadUInt32(12);
            uint index_size  = data_offset - 0x10;
            var  index       = file.View.ReadBytes(0x10, index_size);

            if (6 == version)
            {
                index = ShuffleBlocks(index, file.View.ReadUInt16(6));
            }
            int index_offset = 0;
            var dir          = new List <Entry> (count);

            for (int i = 0; i < count; ++i)
            {
                int name_length;
                if (version > 1)
                {
                    name_length = LittleEndian.ToInt32(index, index_offset);
                    if (0 == name_length)
                    {
                        break;
                    }
                    if (name_length > index_size)
                    {
                        return(null);
                    }
                    index_offset += 5 + name_length;
                }
                name_length = LittleEndian.ToInt32(index, index_offset);
                if (0 == name_length)
                {
                    break;
                }
                if (name_length > index_size)
                {
                    return(null);
                }
                index_offset += 5;
                byte  checksum;
                var   name = DecryptName(index, index_offset, name_length, out checksum);
                Entry entry;
                if (version >= 4)
                {
                    var pcs_entry = FormatCatalog.Instance.Create <PcsEntry> (name);
                    entry         = pcs_entry;
                    pcs_entry.Key = checksum;
                    if (6 == version)
                    {
                        pcs_entry.NameHash = ComputeHash(index, index_offset, name_length - 1);
                    }
                    index_offset += name_length;
                    int c = -1 - checksum;
                    for (int j = 0; j < 4; ++j)
                    {
                        byte key = (byte)((checksum + (17 << j)) & 0x33);
                        index[index_offset + j]     = (byte)(c + key - index[index_offset + j]);
                        index[index_offset + j + 4] = (byte)(c + key - index[index_offset + j + 4]);
                    }
                }
                else
                {
                    index_offset += name_length;
                    entry         = FormatCatalog.Instance.Create <Entry> (name);
                }
                if (index_offset > data_offset)
                {
                    return(null);
                }
                entry.Offset = LittleEndian.ToUInt32(index, index_offset) + data_offset;
                entry.Size   = LittleEndian.ToUInt32(index, index_offset + 4);
                if (!entry.CheckPlacement(file.MaxOffset))
                {
                    return(null);
                }
                dir.Add(entry);
                index_offset += 0x10;
            }
            if (0 == dir.Count)
            {
                return(null);
            }
            return(new PcsArchive(file, this, dir, version));
        }
Example #28
0
        /// <summary>
        /// Reads the dictionary.
        /// </summary>
        /// <param name="src">The byte array containing the bytes making out the dictionary.</param>
        /// <param name="offset">At this offset within src the dictionary starts.</param>
        /// <param name="Length">The dictionary Contains at most this many bytes.</param>
        /// <param name="codepage">The codepage of the string values.</param>
        /// <returns>The dictonary</returns>
        protected IDictionary ReadDictionary(byte[] src, long offset,
                                             int Length, int codepage)
        {
            /* Check whether "offset" points into the "src" array". */
            if (offset < 0 || offset > src.Length)
            {
                throw new HPSFRuntimeException
                          ("Illegal offset " + offset + " while HPSF stream Contains " +
                          Length + " bytes.");
            }
            int o = (int)offset;

            /*
             * Read the number of dictionary entries.
             */
            long nrEntries = LittleEndian.GetUInt(src, o);

            o += LittleEndianConstants.INT_SIZE;

            Hashtable m = new Hashtable((int)nrEntries, (float)1.0);

            try
            {
                for (int i = 0; i < nrEntries; i++)
                {
                    /* The key. */
                    long id = LittleEndian.GetUInt(src, o);
                    o += LittleEndianConstants.INT_SIZE;

                    /* The value (a string). The Length is the either the
                     * number of (two-byte) characters if the character Set is Unicode
                     * or the number of bytes if the character Set is not Unicode.
                     * The Length includes terminating 0x00 bytes which we have To strip
                     * off To Create a Java string. */
                    long sLength = LittleEndian.GetUInt(src, o);
                    o += LittleEndianConstants.INT_SIZE;

                    /* Read the string. */
                    StringBuilder b = new StringBuilder();
                    switch (codepage)
                    {
                    case -1:
                    {
                        /* Without a codepage the Length is equal To the number of
                         * bytes. */
                        b.Append(Encoding.UTF8.GetString(src, o, (int)sLength));
                        break;
                    }

                    case (int)Constants.CP_UNICODE:
                    {
                        /* The Length is the number of characters, i.e. the number
                         * of bytes is twice the number of the characters. */
                        int    nrBytes = (int)(sLength * 2);
                        byte[] h       = new byte[nrBytes];
                        for (int i2 = 0; i2 < nrBytes; i2 += 2)
                        {
                            h[i2]     = src[o + i2 + 1];
                            h[i2 + 1] = src[o + i2];
                        }
                        b.Append(Encoding.GetEncoding(codepage).GetString(h, 0, nrBytes));
                        break;
                    }

                    default:
                    {
                        /* For encodings other than Unicode the Length is the number
                         * of bytes. */
                        b.Append(Encoding.GetEncoding(codepage).GetString(src, o, (int)sLength));
                        break;
                    }
                    }

                    /* Strip 0x00 characters from the end of the string: */
                    while (b.Length > 0 && b[b.Length - 1] == 0x00)
                    {
                        b.Length = b.Length - 1;
                    }
                    if (codepage == (int)Constants.CP_UNICODE)
                    {
                        if (sLength % 2 == 1)
                        {
                            sLength++;
                        }
                        o += (int)(sLength + sLength);
                    }
                    else
                    {
                        o += (int)sLength;
                    }
                    m[id] = b.ToString();
                }
            }
            catch (Exception ex)
            {
                POILogger l = POILogFactory.GetLogger(typeof(Property));
                l.Log(POILogger.WARN,
                      "The property Set's dictionary Contains bogus data. "
                      + "All dictionary entries starting with the one with ID "
                      + id + " will be ignored.", ex);
            }
            return(m);
        }
Example #29
0
        public override ArcFile TryOpen(ArcView file)
        {
            var header = file.View.ReadBytes(0, 0x5C);

            if (header.Length != 0x5C)
            {
                return(null);
            }
            header = HeaderEncryption.Decrypt(header);
            if (!Binary.AsciiEqual(header, "GLibArchiveData2.") || header[0x12] != 0)
            {
                return(null);
            }
            int version = header[0x11] - '0';

            if (version != 0 && version != 1)
            {
                return(null);
            }
            uint index_offset = LittleEndian.ToUInt32(header, 0x54);
            uint index_size   = LittleEndian.ToUInt32(header, 0x58);

            byte[][] encrypted_index = new byte[2][];
            encrypted_index[0] = file.View.ReadBytes(index_offset, index_size);
            if (encrypted_index[0].Length != index_size)
            {
                return(null);
            }
            encrypted_index[1] = new byte[index_size];
            uint[] keys =
            {
                LittleEndian.ToUInt32(header, 0x44),
                LittleEndian.ToUInt32(header, 0x34),
                LittleEndian.ToUInt32(header, 0x24),
                LittleEndian.ToUInt32(header, 0x14),
            };
            int i = 0;

            foreach (var key in keys)
            {
                var decoder = G2MetaScheme.CreateInstance(key);
                decoder.Decrypt(encrypted_index[i], encrypted_index[i ^ 1]);
                i ^= 1;
            }
            byte[] index = encrypted_index[i];
            if (!Binary.AsciiEqual(index, "CDBD"))
            {
                return(null);
            }
            int count          = LittleEndian.ToInt32(index, 4);
            int current_offset = 0x10;
            int info_base      = current_offset + LittleEndian.ToInt32(index, 8);
            int names_base     = current_offset + count * 0x18;
            var dir            = new List <Entry> (count);

            for (i = 0; i < count; ++i)
            {
                int name_offset = names_base + LittleEndian.ToInt32(index, current_offset);
                int parent_dir  = LittleEndian.ToInt32(index, current_offset + 8);
                int attr        = LittleEndian.ToInt32(index, current_offset + 0xC);
                var name        = Binary.GetCString(index, name_offset, info_base - name_offset);
                if (parent_dir != -1)
                {
                    name = Path.Combine(dir[parent_dir].Name, name);
                }
                var entry = new G2Entry {
                    Name = name
                };
                if (0x100 == attr)
                {
                    int info_offset = info_base + LittleEndian.ToInt32(index, current_offset + 0x10);
                    entry.Size   = LittleEndian.ToUInt32(index, info_offset + 8);
                    entry.Offset = LittleEndian.ToUInt32(index, info_offset + 0xC);
                    entry.Type   = FormatCatalog.Instance.GetTypeFromName(name);
                    for (int j = 0; j < 4; ++j)
                    {
                        info_offset  += 0x10;
                        entry.Keys[j] = LittleEndian.ToUInt32(index, info_offset);
                    }
                }
                dir.Add(entry);
                current_offset += 0x18;
            }
            return(new ArcFile(file, this, dir.Where(e => e.Offset != -1).ToList()));
        }
Example #30
0
        void DecryptHelper4(byte[] data, int index, uint[] key_src)
        {
            uint[] buf = new uint[0x50];
            int    i;

            for (i = 0; i < 0x10; ++i)
            {
                buf[i] = BigEndian.ToUInt32(data, index + 40 + 4 * i);
            }
            for (; i < 0x50; ++i)
            {
                uint v = buf[i - 16];
                v     ^= buf[i - 14];
                v     ^= buf[i - 8];
                v     ^= buf[i - 3];
                buf[i] = Binary.RotL(v, 1);
            }
            uint[] key = new uint[10];
            Array.Copy(key_src, key, 5);
            uint k0 = key[0];
            uint k1 = key[1];
            uint k2 = key[2];
            uint k3 = key[3];
            uint k4 = key[4];

            for (int buf_idx = 0; buf_idx < 0x50; ++buf_idx)
            {
                uint f, c;
                if (buf_idx < 0x10)
                {
                    f = k1 ^ k2 ^ k3;
                    c = 0;
                }
                else if (buf_idx < 0x20)
                {
                    f = k1 & k2 | k3 & ~k1;
                    c = 0x5A827999;
                }
                else if (buf_idx < 0x30)
                {
                    f = k3 ^ (k1 | ~k2);
                    c = 0x6ED9EBA1;
                }
                else if (buf_idx < 0x40)
                {
                    f = k1 & k3 | k2 & ~k3;
                    c = 0x8F1BBCDC;
                }
                else
                {
                    f = k1 ^ (k2 | ~k3);
                    c = 0xA953FD4E;
                }
                uint new_k0 = buf[buf_idx] + k4 + f + c + Binary.RotL(k0, 5);
                uint new_k2 = Binary.RotR(k1, 2);
                k1 = k0;
                k4 = k3;
                k3 = k2;
                k2 = new_k2;
                k0 = new_k0;
            }
            key[0] += k0;
            key[1] += k1;
            key[2] += k2;
            key[3] += k3;
            key[4] += k4;
            var ft = new FILETIME {
                DateTimeLow  = key[1],
                DateTimeHigh = key[0] & 0x7FFFFFFF
            };
            var sys_time = new SYSTEMTIME(ft);

            key[5] = (uint)(sys_time.Year | sys_time.Month << 16);
            key[7] = (uint)(sys_time.Hour | sys_time.Minute << 16);
            key[8] = (uint)(sys_time.Second | sys_time.Milliseconds << 16);

            uint flags = LittleEndian.ToUInt32(data, index + 40) | 0x80000000;
            uint rgb   = buf[1] >> 8; // BigEndian.ToUInt32 (data, index+44) >> 8;

            if (0 == (flags & 0x78000000))
            {
                flags |= 0x98000000;
            }
            key[6] = RegionCrc32(m_scheme.Region, flags, rgb);
            key[9] = (uint)(((int)key[2] * (long)(int)key[3]) >> 8);
            if (m_scheme.Version >= 2390)
            {
                key[6] += key[9];
            }
            unsafe
            {
                fixed(byte *data_fixed = data)
                {
                    uint *encoded = (uint *)(data_fixed + index);

                    for (i = 0; i < 10; ++i)
                    {
                        encoded[i] ^= key[i];
                    }
                }
            }
        }