Annotation of parser3/src/classes/image.C, revision 1.162

1.1       paf         1: /** @file
                      2:        Parser: @b image parser class.
                      3: 
1.160     moko        4:        Copyright (c) 2001-2017 Art. Lebedev Studio (http://www.artlebedev.com)
1.66      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.73      paf         6: */
1.1       paf         7: 
1.31      parser      8: /*
                      9:        jpegsize: gets the width and height (in pixels) of a jpeg file
                     10:        Andrew Tong, werdna@ugcs.caltech.edu           February 14, 1995
                     11:        modified slightly by alex@ed.ac.uk
                     12:        and further still by rjray@uswest.com
                     13:        optimization and general re-write from tmetro@vl.com
                     14:        from perl by paf@design.ru
1.1       paf        15: */
                     16: 
                     17: #include "pa_config_includes.h"
1.139     moko       18: #include "gif.h"
1.1       paf        19: 
1.91      paf        20: #include "pa_vmethod_frame.h"
1.1       paf        21: #include "pa_common.h"
                     22: #include "pa_request.h"
                     23: #include "pa_vfile.h"
                     24: #include "pa_vimage.h"
1.89      paf        25: #include "pa_vdate.h"
1.91      paf        26: #include "pa_table.h"
1.1       paf        27: 
1.162   ! moko       28: volatile const char * IDENT_IMAGE_C="$Id: image.C,v 1.161 2017/05/11 21:09:42 moko Exp $";
1.139     moko       29: 
1.125     misha      30: // defines
                     31: 
1.126     misha      32: static const String spacebar_width_name("space");
                     33: static const String monospace_width_name("width");
                     34: static const String letter_spacing_name("spacing");
1.125     misha      35: 
1.22      paf        36: // class
                     37: 
1.91      paf        38: class MImage: public Methoded {
1.22      paf        39: public: // VStateless_class
1.130     misha      40:        Value* create_new_value(Pool&) { return new VImage(); }
1.22      paf        41: 
                     42: public:
1.91      paf        43:        MImage();
1.22      paf        44: };
1.1       paf        45: 
1.91      paf        46: // globals
                     47: 
1.151     moko       48: DECLARE_CLASS_VAR(image, new MImage);
1.91      paf        49: 
1.1       paf        50: // helpers
                     51: 
1.118     misha      52: #define EXIF_TAG(tag, name) put(tag, #name);
                     53: 
1.91      paf        54: /// value of exif tag -> it's value
                     55: class EXIF_tag_value2name: public Hash<int, const char*> {
                     56: public:
                     57:        EXIF_tag_value2name() {
                     58:        // image JPEG Exif
                     59:                // Tags used by IFD0 (main image)
                     60:                EXIF_TAG(0x010e,        ImageDescription);
                     61:                EXIF_TAG(0x010f,        Make);
                     62:                EXIF_TAG(0x0110,        Model);
                     63:                EXIF_TAG(0x0112,        Orientation);
                     64:                EXIF_TAG(0x011a,        XResolution);
                     65:                EXIF_TAG(0x011b,        YResolution);
                     66:                EXIF_TAG(0x0128,        ResolutionUnit);
                     67:                EXIF_TAG(0x0131,        Software);
                     68:                EXIF_TAG(0x0132,        DateTime);
                     69:                EXIF_TAG(0x013e,        WhitePoint);
                     70:                EXIF_TAG(0x013f,        PrimaryChromaticities);
                     71:                EXIF_TAG(0x0211,        YCbCrCoefficients);
                     72:                EXIF_TAG(0x0213,        YCbCrPositioning);
                     73:                EXIF_TAG(0x0214,        ReferenceBlackWhite);
                     74:                EXIF_TAG(0x8298,        Copyright);
                     75:                EXIF_TAG(0x8769,        ExifOffset);
                     76:                // Tags used by Exif SubIFD
                     77:                EXIF_TAG(0x829a,        ExposureTime);
                     78:                EXIF_TAG(0x829d,        FNumber);
                     79:                EXIF_TAG(0x8822,        ExposureProgram);
                     80:                EXIF_TAG(0x8827,        ISOSpeedRatings);
                     81:                EXIF_TAG(0x9000,        ExifVersion);
                     82:                EXIF_TAG(0x9003,        DateTimeOriginal);
                     83:                EXIF_TAG(0x9004,        DateTimeDigitized);
                     84:                EXIF_TAG(0x9101,        ComponentsConfiguration);
                     85:                EXIF_TAG(0x9102,        CompressedBitsPerPixel);
                     86:                EXIF_TAG(0x9201,        ShutterSpeedValue);
                     87:                EXIF_TAG(0x9202,        ApertureValue);
                     88:                EXIF_TAG(0x9203,        BrightnessValue);
                     89:                EXIF_TAG(0x9204,        ExposureBiasValue);
                     90:                EXIF_TAG(0x9205,        MaxApertureValue);
                     91:                EXIF_TAG(0x9206,        SubjectDistance);
                     92:                EXIF_TAG(0x9207,        MeteringMode);
                     93:                EXIF_TAG(0x9208,        LightSource);
                     94:                EXIF_TAG(0x9209,        Flash);
                     95:                EXIF_TAG(0x920a,        FocalLength);
                     96:                EXIF_TAG(0x927c,        MakerNote);
                     97:                EXIF_TAG(0x9286,        UserComment);
                     98:                EXIF_TAG(0x9290,        SubsecTime);
                     99:                EXIF_TAG(0x9291,        SubsecTimeOriginal);
                    100:                EXIF_TAG(0x9292,        SubsecTimeDigitized);
                    101:                EXIF_TAG(0xa000,        FlashPixVersion);
                    102:                EXIF_TAG(0xa001,        ColorSpace);
                    103:                EXIF_TAG(0xa002,        ExifImageWidth);
                    104:                EXIF_TAG(0xa003,        ExifImageHeight);
                    105:                EXIF_TAG(0xa004,        RelatedSoundFile);
                    106:                EXIF_TAG(0xa005,        ExifInteroperabilityOffset);
                    107:                EXIF_TAG(0xa20e,        FocalPlaneXResolution);
                    108:                EXIF_TAG(0xa20f,        FocalPlaneYResolution);
                    109:                EXIF_TAG(0xa210,        FocalPlaneResolutionUnit);
                    110:                EXIF_TAG(0xa215,        ExposureIndex);
                    111:                EXIF_TAG(0xa217,        SensingMethod);
                    112:                EXIF_TAG(0xa300,        FileSource);
                    113:                EXIF_TAG(0xa301,        SceneType);
                    114:                EXIF_TAG(0xa302,        CFAPattern);
                    115:                // Misc Tags
                    116:                EXIF_TAG(0x00fe,        NewSubfileType);
                    117:                EXIF_TAG(0x00ff,        SubfileType);
                    118:                EXIF_TAG(0x012d,        TransferFunction);
                    119:                EXIF_TAG(0x013b,        Artist);
                    120:                EXIF_TAG(0x013d,        Predictor);
                    121:                EXIF_TAG(0x0142,        TileWidth);
                    122:                EXIF_TAG(0x0143,        TileLength);
                    123:                EXIF_TAG(0x0144,        TileOffsets);
                    124:                EXIF_TAG(0x0145,        TileByteCounts);
                    125:                EXIF_TAG(0x014a,        SubIFDs);
                    126:                EXIF_TAG(0x015b,        JPEGTables);
                    127:                EXIF_TAG(0x828d,        CFARepeatPatternDim);
                    128:                EXIF_TAG(0x828e,        CFAPattern);
                    129:                EXIF_TAG(0x828f,        BatteryLevel);
                    130:                EXIF_TAG(0x83bb,        IPTC/NAA);
                    131:                EXIF_TAG(0x8773,        InterColorProfile);
                    132:                EXIF_TAG(0x8824,        SpectralSensitivity);
1.118     misha     133:                //EXIF_TAG(0x8825,      GPSInfo);
1.91      paf       134:                EXIF_TAG(0x8828,        OECF);
                    135:                EXIF_TAG(0x8829,        Interlace);
                    136:                EXIF_TAG(0x882a,        TimeZoneOffset);
                    137:                EXIF_TAG(0x882b,        SelfTimerMode);
                    138:                EXIF_TAG(0x920b,        FlashEnergy);
                    139:                EXIF_TAG(0x920c,        SpatialFrequencyResponse);
                    140:                EXIF_TAG(0x920d,        Noise);
                    141:                EXIF_TAG(0x9211,        ImageNumber);
                    142:                EXIF_TAG(0x9212,        SecurityClassification);
                    143:                EXIF_TAG(0x9213,        ImageHistory);
                    144:                EXIF_TAG(0x9214,        SubjectLocation);
                    145:                EXIF_TAG(0x9215,        ExposureIndex);
                    146:                EXIF_TAG(0x9216,        TIFF/EPStandardID);
                    147:                EXIF_TAG(0xa20b,        FlashEnergy);
                    148:                EXIF_TAG(0xa20c,        SpatialFrequencyResponse);
                    149:                EXIF_TAG(0xa214,        SubjectLocation);
1.118     misha     150: 
                    151:                // additional things added by misha@
                    152:                EXIF_TAG(0x0100,        ImageWidth);
                    153:                EXIF_TAG(0x0101,        ImageLength);
                    154:                EXIF_TAG(0x0102,        BitsPerSample);
                    155:                EXIF_TAG(0x0103,        Compression);
                    156:                EXIF_TAG(0x0106,        PhotometricInterpretation);
                    157:                EXIF_TAG(0x010a,        FillOrder);
                    158:                EXIF_TAG(0x010d,        DocumentName);
                    159:                EXIF_TAG(0x0111,        StripOffsets);
                    160:                EXIF_TAG(0x0115,        SamplesPerPixel);
                    161:                EXIF_TAG(0x0116,        RowsPerStrip);
                    162:                EXIF_TAG(0x0117,        StripByteCounts);
                    163:                EXIF_TAG(0x011c,        PlanarConfiguration);
                    164:                EXIF_TAG(0x0156,        TransferRange);
                    165:                EXIF_TAG(0x0200,        JPEGProc);
                    166:                EXIF_TAG(0x0201,        JPEGInterchangeFormat);
                    167:                EXIF_TAG(0x0202,        JPEGInterchangeFormatLength);
                    168:                EXIF_TAG(0x0212,        YCbCrSubSampling);
                    169:                EXIF_TAG(0xa401,        CustomRendered);
                    170:                EXIF_TAG(0xa402,        ExposureMode);
                    171:                EXIF_TAG(0xa403,        WhiteBalance);
                    172:                EXIF_TAG(0xa404,        DigitalZoomRatio);
                    173:                EXIF_TAG(0xa405,        FocalLengthIn35mmFilm);
                    174:                EXIF_TAG(0xa406,        SceneCaptureType);
                    175:                EXIF_TAG(0xa407,        GainControl);
                    176:                EXIF_TAG(0xa408,        Contrast);
                    177:                EXIF_TAG(0xa409,        Saturation);
                    178:                EXIF_TAG(0xa40a,        Sharpness);
                    179:                EXIF_TAG(0xa40b,        DeviceSettingDescription);
                    180:                EXIF_TAG(0xa40c,        SubjectDistanceRange);
                    181:                EXIF_TAG(0xa420,        ImageUniqueID);
1.149     moko      182: 
                    183:                // other tags
                    184:                EXIF_TAG(0xa430,        CameraOwnerName);
                    185:                EXIF_TAG(0xa431,        BodySerialNumber);
                    186:                EXIF_TAG(0xa432,        LensSpecification);
                    187:                EXIF_TAG(0xa433,        LensManufactor);
                    188:                EXIF_TAG(0xa434,        LensModel);
                    189:                EXIF_TAG(0xa435,        LensSerialNumber);
1.91      paf       190:        }
                    191: } exif_tag_value2name;
                    192: 
1.118     misha     193: class EXIF_gps_tag_value2name: public Hash<int, const char*> {
                    194: public:
                    195:                EXIF_gps_tag_value2name() {
                    196:                EXIF_TAG(0x0,   GPSVersionID);
                    197:                EXIF_TAG(0x1,   GPSLatitudeRef);
                    198:                EXIF_TAG(0x2,   GPSLatitude);
                    199:                EXIF_TAG(0x3,   GPSLongitudeRef);
                    200:                EXIF_TAG(0x4,   GPSLongitude);
                    201:                EXIF_TAG(0x5,   GPSAltitudeRef);
                    202:                EXIF_TAG(0x6,   GPSAltitude);
                    203:                EXIF_TAG(0x7,   GPSTimeStamp);
                    204:                EXIF_TAG(0x8,   GPSSatellites);
                    205:                EXIF_TAG(0x9,   GPSStatus);
                    206:                EXIF_TAG(0xA,   GPSMeasureMode);
                    207:                EXIF_TAG(0xB,   GPSDOP);
                    208:                EXIF_TAG(0xC,   GPSSpeedRef);
                    209:                EXIF_TAG(0xD,   GPSSpeed);
                    210:                EXIF_TAG(0xE,   GPSTrackRef);
                    211:                EXIF_TAG(0xF,   GPSTrack);
                    212:                EXIF_TAG(0x10,  GPSImgDirectionRef);
                    213:                EXIF_TAG(0x11,  GPSImgDirection);
                    214:                EXIF_TAG(0x12,  GPSMapDatum);
                    215:                EXIF_TAG(0x13,  GPSDestLatitudeRef);
                    216:                EXIF_TAG(0x14,  GPSDestLatitude);
                    217:                EXIF_TAG(0x15,  GPSDestLongitudeRef);
                    218:                EXIF_TAG(0x16,  GPSDestLongitude);
                    219:                EXIF_TAG(0x17,  GPSDestBearingRef);
                    220:                EXIF_TAG(0x18,  GPSDestBearing);
                    221:                EXIF_TAG(0x19,  GPSDestDistanceRef);
                    222:                EXIF_TAG(0x1A,  GPSDestDistance);
                    223:                EXIF_TAG(0x1B,  GPSProcessingMethod);
                    224:                EXIF_TAG(0x1C,  GPSAreaInformation);
                    225:                EXIF_TAG(0x1D,  GPSDateStamp);
                    226:                EXIF_TAG(0x1E,  GPSDifferential);
                    227:        }
                    228: } exif_gps_tag_value2name;
                    229: 
                    230: #undef EXIF_TAG
1.91      paf       231: 
1.43      parser    232: #ifndef DOXYGEN
1.1       paf       233: class Measure_reader {
                    234: public:
1.91      paf       235:        virtual size_t read(const char* &buf, size_t limit)=0;
1.79      paf       236:        virtual void seek(long value, int whence)=0;
                    237:        virtual long tell()=0;
1.77      paf       238: };
1.1       paf       239: 
1.77      paf       240: class Measure_file_reader: public Measure_reader {
1.152     moko      241:        const String& file_name;
1.91      paf       242:        int f;
                    243: 
1.77      paf       244: public:
1.152     moko      245:        Measure_file_reader(int af, const String& afile_name):
                    246:                file_name(afile_name), f(af) {
1.1       paf       247:        }
                    248: 
1.91      paf       249:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       250:                if(limit==0)
1.1       paf       251:                        return 0;
1.77      paf       252: 
1.91      paf       253:                char* lbuf=new(PointerFreeGC) char[limit];
1.143     moko      254:                ssize_t read_size=::read(f, lbuf, limit);  abuf=lbuf;
                    255:                if(read_size<0)
                    256:                        throw Exception(0, &file_name, "measure read failed: %s (%d)", strerror(errno), errno);
1.1       paf       257:                return read_size;
                    258:        }
                    259: 
1.91      paf       260:        override void seek(long value, int whence) {
1.79      paf       261:                if(lseek(f, value, whence)<0)
1.152     moko      262:                        throw Exception(IMAGE_FORMAT, &file_name, "seek(value=%ld, whence=%d) failed: %s (%d)", value, whence, strerror(errno), errno);
1.77      paf       263:        }
                    264: 
1.91      paf       265:        override long tell() { return lseek(f, 0, SEEK_CUR); }
1.79      paf       266: 
1.77      paf       267: };
                    268: 
                    269: class Measure_buf_reader: public Measure_reader {
1.91      paf       270: 
                    271:        const char* buf; size_t size;
                    272:        const String& file_name; 
                    273: 
                    274:        size_t offset;
                    275: 
1.77      paf       276: public:
1.91      paf       277:        Measure_buf_reader(const char* abuf, size_t asize, const String& afile_name): 
1.77      paf       278:                buf(abuf), size(asize), file_name(afile_name), offset(0) {
                    279:        }
                    280:        
1.91      paf       281:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       282:                size_t to_read=min(limit, size-offset);
1.91      paf       283:                abuf=buf+offset;
1.77      paf       284:                offset+=to_read;
                    285:                return to_read;
                    286:        }
                    287: 
1.91      paf       288:        override void seek(long value, int whence) {
1.79      paf       289:                size_t new_offset;
                    290:                switch(whence) {
                    291:                case SEEK_CUR: new_offset=offset+value; break;
                    292:                case SEEK_SET: new_offset=(size_t)value; break;
1.91      paf       293:                default: 
1.155     moko      294:                        throw Exception(0, 0, "whence #%d not supported", 0, whence); 
1.91      paf       295:                        break; // never
1.79      paf       296:                }
                    297:                
1.77      paf       298:                if((ssize_t)new_offset<0 || new_offset>size)
1.155     moko      299:                        throw Exception(IMAGE_FORMAT, &file_name, "seek(value=%l, whence=%d) failed: out of buffer, new_offset>size (%l>%l) or new_offset<0", 
1.79      paf       300:                                        value, whence, new_offset, size);
1.77      paf       301:                offset=new_offset;
                    302:        }
                    303: 
1.91      paf       304:        override long tell() { return offset; }
1.79      paf       305: 
1.1       paf       306: };
1.77      paf       307: 
1.43      parser    308: #endif
1.1       paf       309: 
1.72      paf       310: /// PNG file header
                    311: struct PNG_Header {
                    312:        char dummy[12];
                    313:        char signature[4]; //< must be "IHDR"
1.80      paf       314:        uchar high_width[2]; //< image width high bytes [we ignore for now]
                    315:        uchar width[2]; //< image width low bytes
                    316:        uchar high_height[2]; //< image height high bytes [we ignore for now]
                    317:        uchar height[4]; //< image height
1.72      paf       318: };
                    319: 
1.21      paf       320: /// GIF file header
1.1       paf       321: struct GIF_Header {
1.72      paf       322:        char       signature[3];         // 'GIF'
1.1       paf       323:        char       version[3];
1.80      paf       324:        uchar       width[2];
                    325:        uchar       height[2];
1.1       paf       326:        char       dif;
                    327:        char       fonColor;
                    328:        char       nulls;
                    329: };
                    330: 
1.31      parser    331: /// JPEG record head
                    332: struct JPG_Segment_head {
1.80      paf       333:        uchar marker;
                    334:        uchar code;
                    335:        uchar length[2];
1.1       paf       336: };
1.21      paf       337: /// JPEG frame header
1.31      parser    338: struct JPG_Size_segment_body {
1.27      parser    339:        char data;                    //< data precision of bits/sample
1.80      paf       340:        uchar height[2];               //< image height
                    341:        uchar width[2];                //< image width
1.27      parser    342:        char numComponents;           //< number of color components
1.1       paf       343: };
                    344: 
1.80      paf       345: /// JPEG Exif TIFF Header
                    346: struct JPG_Exif_TIFF_header {
                    347:        uchar byte_align_identifier[2];
                    348:        char dummy[2]; // always 000A [or 0A00]
                    349:        uchar first_IFD_offset[4]; // Usually the first IFD starts immediately next to TIFF header, so this offset has value '0x00000008'.
                    350: };
                    351: 
                    352: // JPEG Exif IFD start
1.91      paf       353: struct JPG_Exif_IFD_begin {
1.80      paf       354:        uchar directory_entry_count[2]; // the number of directory entry contains in this IFD
                    355: };
                    356: 
                    357: // TTTT ffff NNNNNNNN DDDDDDDD 
                    358: struct JPG_Exif_IFD_entry {
                    359:        uchar tag[2]; // Tag number, this shows a kind of data
                    360:        uchar format[2]; // data format
                    361:        uchar components_count[4]; // number of components
                    362:        uchar value_or_offset_to_it[4]; // data value or offset to data value
                    363: };
                    364: 
                    365: #define JPG_IFD_TAG_EXIF_OFFSET 0x8769
                    366: 
1.118     misha     367: #define JPG_IFD_TAG_EXIF_GPS_OFFSET 0x8825
                    368: 
1.89      paf       369: #define JPEG_EXIF_DATE_CHARS 20
                    370: 
1.162   ! moko      371: 
        !           372: #ifndef DOXYGEN
        !           373: struct Measure_info {
        !           374:        ushort width;
        !           375:        ushort height;
        !           376:        Value** exif;
        !           377:        Value** xmp;
        !           378: };
        !           379: #endif
        !           380: 
1.1       paf       381: //
                    382: 
1.80      paf       383: inline ushort x_endian_to_ushort(uchar b0, uchar b1) {
                    384:        return (ushort)((b1<<8) + b0);
1.33      parser    385: }
                    386: 
1.80      paf       387: inline uint x_endian_to_uint(uchar b0, uchar b1, uchar b2, uchar b3) {
                    388:        return (uint)(((((b3<<8) + b2)<<8)+b1)<<8)+b0;
1.33      parser    389: }
                    390: 
1.80      paf       391: inline ushort endian_to_ushort(bool is_big, const uchar *b/* [2] */) {
                    392:        return is_big?x_endian_to_ushort(b[1], b[0]):
                    393:                x_endian_to_ushort(b[0], b[1]);
1.1       paf       394: }
                    395: 
1.80      paf       396: inline uint endian_to_uint(bool is_big, const uchar *b /* [4] */) {
                    397:        return is_big?x_endian_to_uint(b[3], b[2], b[1], b[0]):
                    398:                x_endian_to_uint(b[0], b[1], b[2], b[3]);
                    399: }
                    400: 
1.152     moko      401: static void measure_gif(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
1.1       paf       402: 
1.91      paf       403:        const char* buf;
1.102     paf       404:        const size_t head_size=sizeof(GIF_Header);
                    405:        if(reader.read(buf, head_size)<head_size)
1.155     moko      406:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - too small");
1.31      parser    407:        GIF_Header *head=(GIF_Header *)buf;
1.1       paf       408: 
1.72      paf       409:        if(strncmp(head->signature, "GIF", 3)!=0)
1.155     moko      410:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - wrong signature");
1.1       paf       411: 
1.80      paf       412:        width=endian_to_ushort(false, head->width);
                    413:        height=endian_to_ushort(false, head->height);
                    414: }
                    415: 
1.155     moko      416: static Value* parse_IFD_entry_formatted_one_value(bool is_big, ushort format, size_t component_size, const uchar *value) {
1.80      paf       417:        switch(format) {
                    418:        case 1: // unsigned byte
1.91      paf       419:                return new VInt((uchar)value[0]);
1.80      paf       420:        case 3: // unsigned short
1.91      paf       421:                return new VInt(endian_to_ushort(is_big, value));
1.80      paf       422:        case 4: // unsigned long
                    423:                 // 'double' because parser's Int is signed
1.91      paf       424:                return new VDouble(endian_to_uint(is_big, value));
1.80      paf       425:        case 5: // unsigned rational
                    426:                {
                    427:                        uint numerator=endian_to_uint(is_big, value); value+=component_size/2;
                    428:                        uint denominator=endian_to_uint(is_big, value);
                    429:                        if(!denominator)
                    430:                                return 0;
1.91      paf       431:                        return new VDouble(((double)numerator)/denominator);
1.80      paf       432:                }
                    433:        case 6: // signed byte
1.91      paf       434:                return new VInt((signed char)value[0]);
1.80      paf       435:        case 8: // signed short
1.91      paf       436:                return new VInt((signed short)endian_to_ushort(is_big, value));
1.80      paf       437:        case 9: // signed long
1.91      paf       438:                return new VInt((signed int)endian_to_uint(is_big, value));
1.80      paf       439:        case 10: // signed rational
                    440:                {
                    441:                        signed int numerator=(signed int)endian_to_uint(is_big, value); value+=component_size/2;
                    442:                        uint denominator=endian_to_uint(is_big, value);
                    443:                        if(!denominator)
                    444:                                return 0;
1.91      paf       445:                        return new VDouble(numerator/denominator);
1.80      paf       446:                }
                    447:                /*
                    448:        case 11: // single float
1.120     misha     449:                @todo
1.80      paf       450:        case 12: // double float
1.120     misha     451:                @todo
1.80      paf       452:                */
                    453:        };      
                    454:        
                    455:        return 0;
                    456: }
                    457: 
1.89      paf       458: // date.C
1.147     moko      459: tm cstr_to_time_t(char *, const char **);
1.89      paf       460: 
1.155     moko      461: static Value* parse_IFD_entry_formatted_value(bool is_big, ushort format, size_t component_size, uint components_count, const uchar *value) {
1.80      paf       462:        if(format==2) { // ascii string, exception: the only type with varying size
1.91      paf       463:                const char* cstr=(const char* )value;
                    464:                size_t length=components_count;
1.89      paf       465:                // Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes
1.155     moko      466:                if(length==JPEG_EXIF_DATE_CHARS && isdigit((unsigned char)cstr[0]) && cstr[length-1]==0) {
                    467:                        char cstr_writable[JPEG_EXIF_DATE_CHARS];
1.89      paf       468:                        strcpy(cstr_writable, cstr);
                    469: 
1.106     paf       470:                        try {
1.147     moko      471:                                tm tmIn=cstr_to_time_t(cstr_writable, 0);
1.146     moko      472:                                return new VDate(tmIn);
1.106     paf       473:                        }
                    474:                        catch(...) { /*ignore bad date times*/ }
1.89      paf       475:                }
                    476: 
1.123     misha     477:                return new VString(*new String(cstr, String::L_TAINTED));
1.80      paf       478:        }
                    479: 
                    480:        if(components_count==1)
1.91      paf       481:                return parse_IFD_entry_formatted_one_value(is_big, format, component_size, value);
1.80      paf       482: 
1.91      paf       483:        VHash* result=new VHash;
                    484:        HashStringValue& hash=result->hash();
1.80      paf       485:        for(uint i=0; i<components_count; i++, value+=component_size) {
1.91      paf       486:                hash.put(
1.93      paf       487:                        String::Body::Format(i),
1.91      paf       488:                        parse_IFD_entry_formatted_one_value(is_big, format, component_size, value));
1.80      paf       489:        }
                    490: 
1.91      paf       491:        return result;
1.80      paf       492: }
                    493: 
1.155     moko      494: static Value* parse_IFD_entry_value(bool is_big, Measure_reader& reader, long tiff_base, JPG_Exif_IFD_entry& entry) {
1.80      paf       495:        size_t format2component_size[]={
                    496:                0, // undefined
                    497:                1, // unsigned byte
                    498:                1, // ascii string
                    499:                2, // unsigned short
                    500:                4, // unsigned long
                    501:                8, // unsigned rational
                    502:                1, // signed byte
                    503:                0, // undefined
                    504:                2, // signed short
                    505:                4, // signed long
                    506:                8, // signed rational
                    507:                /*
                    508:                4, // single float
                    509:                8, // double float
                    510:                */
                    511:        };
                    512: 
                    513:        ushort format=endian_to_ushort(is_big, entry.format);
                    514:        if(format>=sizeof(format2component_size)/sizeof(format2component_size[0]))
                    515:                return 0; // format out of range, ignoring
                    516: 
                    517:        size_t component_size=format2component_size[format];
                    518:        if(component_size==0)
                    519:                return 0; // undefined format
                    520: 
                    521:        // You can get the total data byte length by multiplies 
                    522:        // a 'bytes/components' value (see above chart) by number of components stored 'NNNNNNNN' area
                    523:        uint components_count=endian_to_uint(is_big, entry.components_count);
1.121     misha     524:        uint value_size=component_size*components_count;
1.80      paf       525:        // If its size is over 4bytes, 'DDDDDDDD' contains the offset to data stored address
1.91      paf       526:        Value* result;
1.80      paf       527: 
                    528:        if(value_size<=4)
1.155     moko      529:                result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, entry.value_or_offset_to_it);
1.80      paf       530:        else {
                    531:                long remembered=reader.tell();
                    532:                {
                    533:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.91      paf       534:                        const char* value;
1.156     moko      535:                        if(reader.read(value, value_size)<value_size)
1.80      paf       536:                                return 0;
1.155     moko      537:                        result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, (const uchar*)value);
1.80      paf       538:                }
                    539:                reader.seek(remembered, SEEK_SET);
                    540:        }
                    541: 
                    542:        return result;
                    543: }
                    544: 
1.155     moko      545: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, long tiff_base, bool gps=false);
1.91      paf       546: 
1.155     moko      547: static void parse_IFD_entry(HashStringValue& hash, bool is_big, Measure_reader& reader, long tiff_base, JPG_Exif_IFD_entry& entry, bool gps=false) {
1.80      paf       548:        ushort tag=endian_to_ushort(is_big, entry.tag);
1.118     misha     549: 
                    550:        if(tag==JPG_IFD_TAG_EXIF_OFFSET || tag==JPG_IFD_TAG_EXIF_GPS_OFFSET){
1.80      paf       551:                long remembered=reader.tell();
                    552:                {
                    553:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.118     misha     554:                        parse_IFD(hash, is_big, reader, tiff_base, (tag==JPG_IFD_TAG_EXIF_GPS_OFFSET)?true:gps);
1.80      paf       555:                }
                    556:                reader.seek(remembered, SEEK_SET);
                    557:                return;
                    558:        }
1.118     misha     559: 
1.91      paf       560:        if(Value* value=parse_IFD_entry_value(is_big, reader, tiff_base, entry)) {
1.118     misha     561:                if(const char* name=(gps)?exif_gps_tag_value2name.get(tag):exif_tag_value2name.get(tag))
1.148     moko      562:                        hash.put(name, value);
1.80      paf       563:                else
1.93      paf       564:                        hash.put(String::Body::Format(tag), value);
1.80      paf       565:        }
1.1       paf       566: }
                    567: 
1.155     moko      568: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, long tiff_base, bool gps) {
1.91      paf       569:        const char* buf;
                    570:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
1.80      paf       571:                return;
1.91      paf       572:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
1.80      paf       573: 
                    574:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    575:        for(int i=0; i<directory_entry_count; i++) {
                    576:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    577:                        return;
                    578: 
1.118     misha     579:                parse_IFD_entry(hash, is_big, reader, tiff_base, *(JPG_Exif_IFD_entry *)buf, gps);
1.80      paf       580:        }
                    581:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    582: }
                    583: 
1.162   ! moko      584: static Value* parse_exif(Measure_reader& reader) {
1.91      paf       585:        const char* buf;
1.80      paf       586: 
                    587:        uint tiff_base=reader.tell();
                    588:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    589:                return 0;
                    590: 
                    591:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    592:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    593: 
                    594:        uint first_IFD_offset=endian_to_uint(is_big, head->first_IFD_offset);
                    595:        reader.seek(tiff_base+first_IFD_offset, SEEK_SET);
                    596: 
1.91      paf       597:        VHash* vhash=new VHash;
1.80      paf       598: 
                    599:        // IFD
1.91      paf       600:        parse_IFD(vhash->hash(), is_big, reader, tiff_base);
1.80      paf       601: 
1.91      paf       602:        return vhash;
1.80      paf       603: }
                    604: 
1.162   ! moko      605: static Value* parse_xmp(Measure_reader& reader, ushort xmp_length) {
        !           606:        const char* buf;
        !           607:        if(reader.read(buf, xmp_length)<xmp_length)
        !           608:                return 0;
        !           609:        return new VString(*new String(pa_strdup(buf, xmp_length)));
        !           610: }
        !           611: 
        !           612: static void measure_jpeg(const String& origin_string, Measure_reader& reader, Measure_info &info) {
1.2       paf       613:        // JFIF format markers
1.80      paf       614:        const uchar MARKER=0xFF;
                    615:        const uchar CODE_SIZE_A=0xC0;
                    616:        const uchar CODE_SIZE_B=0xC1;
                    617:        const uchar CODE_SIZE_C=0xC2;
                    618:        const uchar CODE_SIZE_D=0xC3;
1.162   ! moko      619:        const uchar CODE_APP1=0xE1;
1.2       paf       620: 
1.91      paf       621:        const char* buf;
1.18      paf       622:        const size_t prefix_size=2;
1.31      parser    623:        if(reader.read(buf, prefix_size)<prefix_size)
1.155     moko      624:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - too small");
1.80      paf       625:        uchar *signature=(uchar *)buf;
1.1       paf       626:        
1.31      parser    627:        if(!(signature[0]==0xFF && signature[1]==0xD8)) 
1.155     moko      628:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - wrong signature");
1.31      parser    629: 
                    630:        while(true) {
1.80      paf       631:                uint segment_base=reader.tell()+2/*marker,code*/;
1.31      parser    632:                if(reader.read(buf, sizeof(JPG_Segment_head))<sizeof(JPG_Segment_head))
1.79      paf       633:                        break;
1.31      parser    634:                JPG_Segment_head *head=(JPG_Segment_head *)buf;
                    635: 
1.162   ! moko      636:                // Verify that it's a valid segment.
1.31      parser    637:                if(head->marker!=MARKER)
1.155     moko      638:                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - marker not found");
1.79      paf       639: 
1.162   ! moko      640:                ushort segment_length=endian_to_ushort(true, head->length);
        !           641: 
1.79      paf       642:                switch(head->code) {
1.162   ! moko      643:                // http://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_JPEG_files
        !           644:                case CODE_APP1:
        !           645:                        {
        !           646:                                const size_t EXIF_SIG_LEN=6; // Exif\0\0
        !           647:                                const size_t XMP_SIG_LEN=29; // http://ns.adobe.com/xap/1.0/\0
        !           648: 
        !           649:                                if(segment_length<EXIF_SIG_LEN+2 || reader.read(buf, EXIF_SIG_LEN)<EXIF_SIG_LEN)
        !           650:                                        break;
        !           651:                                if(memcmp(buf, "Exif\0\0", EXIF_SIG_LEN)==0){
        !           652:                                        if(info.exif && !*info.exif) // backward compatibility: using first segment
        !           653:                                                *info.exif=parse_exif(reader);
        !           654:                                        break;
        !           655:                                }
        !           656: 
        !           657:                                if(memcmp(buf, "http:/", EXIF_SIG_LEN))
        !           658:                                        break;
        !           659:                                if(segment_length<XMP_SIG_LEN+2 || reader.read(buf, XMP_SIG_LEN-EXIF_SIG_LEN)<XMP_SIG_LEN-EXIF_SIG_LEN)
        !           660:                                        break;
        !           661:                                if(memcmp(buf, "/ns.adobe.com/xap/1.0/\0", XMP_SIG_LEN-EXIF_SIG_LEN)==0){
        !           662:                                        if(info.xmp && !*info.xmp) // backward compatibility: using first segment
        !           663:                                                *info.xmp=parse_xmp(reader, segment_length - XMP_SIG_LEN - 2 /* segment_length */);
        !           664:                                }
        !           665: 
        !           666:                        }
1.1       paf       667:                        break;
1.31      parser    668: 
1.79      paf       669:                case CODE_SIZE_A:
                    670:                case CODE_SIZE_B:
                    671:                case CODE_SIZE_C:
                    672:                case CODE_SIZE_D:
                    673:                        {
                    674:                                // Segments that contain size info
                    675:                                if(reader.read(buf, sizeof(JPG_Size_segment_body))<sizeof(JPG_Size_segment_body))
1.155     moko      676:                                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - can not fully read Size segment");
1.79      paf       677:                                JPG_Size_segment_body *body=(JPG_Size_segment_body *)buf;
                    678:                                
1.162   ! moko      679:                                info.width=endian_to_ushort(true, body->width);
        !           680:                                info.height=endian_to_ushort(true, body->height);
        !           681:                        }
1.80      paf       682:                        return;
1.79      paf       683:                };
                    684: 
1.162   ! moko      685:                reader.seek(segment_base + segment_length, SEEK_SET);
1.31      parser    686:        }
                    687: 
1.155     moko      688:        throw Exception(IMAGE_FORMAT, &origin_string, "broken JPEG file - size frame not found");
1.1       paf       689: }
                    690: 
1.152     moko      691: static void measure_png(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
1.72      paf       692: 
1.91      paf       693:        const char* buf;
1.102     paf       694:        const size_t head_size=sizeof(PNG_Header);
                    695:        if(reader.read(buf, head_size)<head_size)
1.152     moko      696:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - too small");
1.72      paf       697:        PNG_Header *head=(PNG_Header *)buf;
                    698: 
                    699:        if(strncmp(head->signature, "IHDR", 4)!=0)
1.152     moko      700:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - wrong signature");
1.72      paf       701: 
1.80      paf       702:        width=endian_to_ushort(true, head->width);
                    703:        height=endian_to_ushort(true, head->height);
1.72      paf       704: }
                    705: 
1.1       paf       706: // measure center
                    707: 
1.162   ! moko      708: static void measure(const String& file_name, Measure_reader& reader, Measure_info &info) {
1.128     misha     709:        const char* file_name_cstr=file_name.taint_cstr(String::L_FILE_SPEC);
1.91      paf       710:        if(const char* cext=strrchr(file_name_cstr, '.')) {
1.1       paf       711:                cext++;
                    712:                if(strcasecmp(cext, "GIF")==0)
1.162   ! moko      713:                        measure_gif(file_name, reader, info.width, info.height);
1.1       paf       714:                else if(strcasecmp(cext, "JPG")==0 || strcasecmp(cext, "JPEG")==0) 
1.162   ! moko      715:                        measure_jpeg(file_name, reader, info);
1.72      paf       716:                else if(strcasecmp(cext, "PNG")==0)
1.162   ! moko      717:                        measure_png(file_name, reader, info.width, info.height);
1.1       paf       718:                else
1.152     moko      719:                        throw Exception(IMAGE_FORMAT, &file_name, "unhandled image file name extension '%s'", cext);
1.1       paf       720:        } else
1.152     moko      721:                throw Exception(IMAGE_FORMAT, &file_name, "can not determine image type - no file name extension");
1.1       paf       722: }
                    723: 
1.77      paf       724: // methods
1.1       paf       725: 
1.152     moko      726: static void file_measure_action(struct stat& /*finfo*/, int f, const String& file_spec, void *context) {
                    727:        Measure_file_reader reader(f, file_spec);
1.162   ! moko      728:        measure(file_spec, reader, *static_cast<Measure_info *>(context));
1.1       paf       729: }
                    730: 
1.91      paf       731: static void _measure(Request& r, MethodParams& params) {
                    732:        Value& data=params.as_no_junction(0, "data must not be code");
1.1       paf       733: 
1.91      paf       734:        Value* exif=0;
1.162   ! moko      735:        Value* xmp=0;
        !           736:        Measure_info info={ 0, 0, &exif, &xmp };
        !           737: 
1.91      paf       738:        const String* file_name;
1.162   ! moko      739: 
        !           740:        if(file_name=data.get_string()) {
1.152     moko      741:                file_read_action_under_lock(r.absolute(*file_name), "measure", file_measure_action, &info);
1.1       paf       742:        } else {
1.129     misha     743:                VFile* vfile=data.as_vfile(String::L_AS_IS);
1.91      paf       744:                file_name=&vfile->fields().get(name_name)->as_string();
1.162   ! moko      745:                Measure_buf_reader reader(vfile->value_ptr(), vfile->value_size(), *file_name);
        !           746:                measure(*file_name, reader, info);
1.1       paf       747:        }
                    748: 
1.162   ! moko      749:        GET_SELF(r, VImage).set(file_name, info.width, info.height, 0, exif, xmp);
1.1       paf       750: }
                    751: 
1.161     moko      752: static void append_attrib_pair(String &tag, String::Body key, Value* value){
                    753:        // skip border attribute with empty value
                    754:        if(key=="border" && !value->is_defined())
1.4       paf       755:                return;
                    756: 
1.133     misha     757:        // src="a.gif" width="123" ismap[=-1]
1.161     moko      758:        tag << " " << key;
1.91      paf       759:        if(value->is_string() || value->as_int()>=0)
1.161     moko      760:                tag << "=\"" << value->as_string() << "\"";
1.3       paf       761: }
1.161     moko      762: 
1.91      paf       763: static void _html(Request& r, MethodParams& params) {
                    764:        String tag;
1.3       paf       765:        tag << "<img";
1.4       paf       766: 
1.91      paf       767:        const HashStringValue& fields=GET_SELF(r, VImage).fields();
                    768:        HashStringValue* attribs=0;
1.4       paf       769: 
1.91      paf       770:        if(params.count()) {
1.69      paf       771:                // for backward compatibility: someday was ^html{}
1.154     moko      772:                Value& vattribs=r.process(params[0]);
1.145     moko      773:                if(!vattribs.is_string()) { // allow empty
1.100     paf       774:                        if((attribs=vattribs.get_hash())) {
1.161     moko      775:                                for(HashStringValue::Iterator i(*attribs); i; i.next() )
                    776:                                        append_attrib_pair(tag, i.key(), i.value());
1.39      parser    777:                        } else
1.155     moko      778:                                throw Exception(PARSER_RUNTIME, 0, "attributes must be hash");
1.145     moko      779:                }
1.39      parser    780:        }
1.4       paf       781: 
1.161     moko      782:        for(HashStringValue::Iterator i(fields); i; i.next() ){
                    783:                String::Body key=i.key();
                    784:                // skip user-specified attributes
                    785:                if(attribs && attribs->get(key))
                    786:                        continue;
                    787:                // allow only html attributes (to exclude exif, line-*)
                    788:                if(key=="src" || key=="width" || key=="height" || key=="border")
                    789:                        append_attrib_pair(tag, key, i.value());
1.91      paf       790:        }
1.161     moko      791: 
1.6       paf       792:        tag << " />";
1.157     moko      793:        r.write(tag);
1.3       paf       794: }
1.8       paf       795: 
1.68      paf       796: /// @test wrap FILE to auto-object
1.155     moko      797: static gdImage* load(Request& r, const String& file_name){
1.128     misha     798:        const char* file_name_cstr=r.absolute(file_name).taint_cstr(String::L_FILE_SPEC);
1.159     moko      799:        if(FILE *f=pa_fopen(file_name_cstr, "rb")) {
1.91      paf       800:                gdImage* image=new gdImage;
                    801:                bool ok=image->CreateFromGif(f);
1.16      paf       802:                fclose(f);
1.23      paf       803:                if(!ok)
1.155     moko      804:                        throw Exception(IMAGE_FORMAT, &file_name, "is not in GIF format");
1.91      paf       805:                return image;
1.16      paf       806:        } else {
1.155     moko      807:                throw Exception("file.missing", 0, "can not open '%s'", file_name_cstr);
1.16      paf       808:        }
                    809: }
                    810: 
                    811: 
1.91      paf       812: static void _load(Request& r, MethodParams& params) {
1.116     misha     813:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.6       paf       814: 
1.91      paf       815:        gdImage* image=load(r, file_name);
                    816:        GET_SELF(r, VImage).set(&file_name, image->SX(), image->SY(), image);
1.6       paf       817: }
                    818: 
1.91      paf       819: static void _create(Request& r, MethodParams& params) {
                    820:        int width=params.as_int(0, "width must be int", r);
                    821:        int height=params.as_int(1, "height must be int", r);
1.8       paf       822:        int bgcolor_value=0xffFFff;
1.91      paf       823:        if(params.count()>2)
                    824:                bgcolor_value=params.as_int(2, "color must be int", r);
                    825:        gdImage* image=new gdImage;
                    826:        image->Create(width, height);
                    827:        image->FilledRectangle(0, 0, width-1, height-1, image->Color(bgcolor_value));
                    828:        GET_SELF(r, VImage).set(0, width, height, image);
1.6       paf       829: }
                    830: 
1.91      paf       831: static void _gif(Request& r, MethodParams& params) {
1.108     paf       832:        gdImage& image=GET_SELF(r, VImage).image();
1.6       paf       833: 
1.138     misha     834:        const String *file_name=params.count()>0?&params.as_string(0, FILE_NAME_MUST_BE_STRING):0;
1.10      paf       835: 
1.108     paf       836:        gdBuf buf=image.Gif();
1.6       paf       837:        
1.91      paf       838:        VFile& vfile=*new VFile;
1.137     misha     839: 
1.142     moko      840:        vfile.set_binary(false/*not tainted*/, (const char *)buf.ptr, buf.size, file_name, new VString(*new String("image/gif")));
1.137     misha     841: 
1.157     moko      842:        r.write(vfile);
1.6       paf       843: }
                    844: 
1.91      paf       845: static void _line(Request& r, MethodParams& params) {
1.108     paf       846:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       847: 
1.108     paf       848:        image.Line(
1.91      paf       849:                params.as_int(0, "x0 must be int", r), 
                    850:                params.as_int(1, "y0 must be int", r), 
                    851:                params.as_int(2, "x1 must be int", r), 
                    852:                params.as_int(3, "y1 must be int", r), 
1.108     paf       853:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       854: }
                    855: 
1.91      paf       856: static void _fill(Request& r, MethodParams& params) {
1.108     paf       857:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       858: 
1.108     paf       859:        image.Fill(
1.91      paf       860:                params.as_int(0, "x must be int", r), 
                    861:                params.as_int(1, "y must be int", r), 
1.108     paf       862:                image.Color(params.as_int(2, "color must be int", r)));
1.13      paf       863: }
                    864: 
1.91      paf       865: static void _rectangle(Request& r, MethodParams& params) {
1.108     paf       866:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       867: 
1.108     paf       868:        image.Rectangle(
1.91      paf       869:                params.as_int(0, "x0 must be int", r), 
                    870:                params.as_int(1, "y0 must be int", r), 
                    871:                params.as_int(2, "x1 must be int", r), 
                    872:                params.as_int(3, "y1 must be int", r), 
1.108     paf       873:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       874: }
                    875: 
1.91      paf       876: static void _bar(Request& r, MethodParams& params) {
1.108     paf       877:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       878: 
1.108     paf       879:        image.FilledRectangle(
1.91      paf       880:                params.as_int(0, "x0 must be int", r), 
                    881:                params.as_int(1, "y0 must be int", r), 
                    882:                params.as_int(2, "x1 must be int", r), 
                    883:                params.as_int(3, "y1 must be int", r), 
1.108     paf       884:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       885: }
                    886: 
1.44      parser    887: #ifndef DOXYGEN
1.155     moko      888: static void add_point(Table::element_type row, gdImage::Point **p) {
1.110     paf       889:        if(row->count()!=2)
1.155     moko      890:                throw Exception(0, 0, "coordinates table must contain two columns: x and y values");
1.91      paf       891:        (**p).x=row->get(0)->as_int();
                    892:        (**p).y=row->get(1)->as_int();
1.44      parser    893:        (*p)++;
                    894: }
                    895: #endif
1.135     misha     896: #ifndef DOXYGEN
1.155     moko      897: static void add_point(int x, int y, gdImage::Point **p) {
1.135     misha     898:        (**p).x=x;
                    899:        (**p).y=y;
                    900:        (*p)++;
                    901: }
                    902: #endif
1.91      paf       903: static void _replace(Request& r, MethodParams& params) {
1.135     misha     904:        int src_color=params.as_int(0, "src color must be int", r);
                    905:        int dest_color=params.as_int(1, "dest color must be int", r);
                    906: 
1.108     paf       907:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       908: 
1.135     misha     909:        gdImage::Point* all_p=0;
                    910:        size_t count=0;
                    911:        if(params.count() == 3){
1.140     misha     912:                Table* table=params.as_table(2, "coordinates");
1.135     misha     913:                count=table->count();
                    914:                all_p=new(PointerFreeGC) gdImage::Point[count];
                    915:                gdImage::Point* add_p=all_p;
                    916:                table->for_each(add_point, &add_p);
                    917:        } else {
                    918:                int max_x=image.SX()-1;
                    919:                int max_y=image.SY()-1;
                    920:                if(max_x > 0 && max_y > 0){
                    921:                        count=4;
                    922:                        all_p=new(PointerFreeGC) gdImage::Point[count];
                    923:                        gdImage::Point* add_p=all_p;
                    924:                        add_point(0, 0, &add_p);
                    925:                        add_point(max_x, 0, &add_p);
                    926:                        add_point(max_x, max_y, &add_p);
                    927:                        add_point(0, max_y, &add_p);
                    928:                }
                    929:        }
1.13      paf       930: 
1.135     misha     931:        if(count)
                    932:                image.FilledPolygonReplaceColor(all_p, count, image.Color(src_color), image.Color(dest_color));
1.13      paf       933: }
                    934: 
1.91      paf       935: static void _polyline(Request& r, MethodParams& params) {
1.108     paf       936:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       937: 
1.140     misha     938:        Table* table=params.as_table(1, "coordinates");
1.44      parser    939: 
1.92      paf       940:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser    941:        gdImage::Point *add_p=all_p;    
                    942:        table->for_each(add_point, &add_p);
1.108     paf       943:        image.Polygon(all_p, table->count(), 
                    944:                image.Color(params.as_int(0, "color must be int", r)),
1.44      parser    945:                false/*not closed*/);
                    946: }
                    947: 
1.91      paf       948: static void _polygon(Request& r, MethodParams& params) {
1.108     paf       949:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       950: 
1.140     misha     951:        Table* table=(Table*)params.as_table(1, "coordinates");
1.44      parser    952: 
1.92      paf       953:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser    954:        gdImage::Point *add_p=all_p;    
                    955:        table->for_each(add_point, &add_p);
1.108     paf       956:        image.Polygon(all_p, table->count(), 
                    957:                image.Color(params.as_int(0, "color must be int", r)));
1.13      paf       958: }
                    959: 
1.91      paf       960: static void _polybar(Request& r, MethodParams& params) {
1.108     paf       961:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       962: 
1.140     misha     963:        Table* table=(Table*)params.as_table(1, "coordinates");
1.13      paf       964: 
1.92      paf       965:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser    966:        gdImage::Point *add_p=all_p;    
                    967:        table->for_each(add_point, &add_p);
1.108     paf       968:        image.FilledPolygon(all_p, table->count(), 
                    969:                image.Color(params.as_int(0, "color must be int", r)));
1.12      paf       970: }
                    971: 
1.16      paf       972: // font
                    973: 
1.85      paf       974: #define Y(y)(y+index*height)
1.21      paf       975: 
1.91      paf       976: // Font class
                    977: 
1.155     moko      978: Font::Font(Charset& asource_charset, const String& aalphabet, gdImage* aifont, int aheight, int amonospace, int aspacebarspace, int aletterspacing):
1.158     moko      979:        letterspacing(aletterspacing),
1.132     misha     980:        height(aheight),
                    981:        monospace(amonospace),
                    982:        spacebarspace(aspacebarspace),
1.100     paf       983:        ifont(aifont),
1.158     moko      984:        alphabet(aalphabet),
                    985:        fsource_charset(asource_charset){
1.132     misha     986: 
                    987:        if(fsource_charset.isUTF8()){
                    988:                size_t index=0;
                    989:                for(UTF8_string_iterator i(alphabet); i.has_next(); )
                    990:                        fletter2index.put_dont_replace(i.next(), index++);
                    991:        }
1.91      paf       992: }
                    993: 
                    994: /* ******************************** char ********************************** */
                    995: 
                    996: size_t Font::index_of(char ch) {
                    997:        if(ch==' ') return STRING_NOT_FOUND;
                    998:        return alphabet.pos(ch);
                    999: }
                   1000: 
1.132     misha    1001: size_t Font::index_of(XMLCh ch) {
                   1002:        if(ch==' ') return STRING_NOT_FOUND;
                   1003:        return fletter2index.get(ch);
                   1004: }
                   1005: 
1.91      paf      1006: int Font::index_width(size_t index) {
                   1007:        if(index==STRING_NOT_FOUND)
                   1008:                return spacebarspace;
                   1009:        int tr=ifont->GetTransparent();
                   1010:        for(int x=ifont->SX()-1; x>=0; x--) {
                   1011:                for(int y=0; y<height; y++)
                   1012:                        if(ifont->GetPixel(x, Y(y))!=tr) 
                   1013:                                return x+1;
1.16      paf      1014:        }
1.91      paf      1015:        return 0;
                   1016: }
                   1017: 
1.108     paf      1018: void Font::index_display(gdImage& image, int x, int y, size_t index){
1.91      paf      1019:        if(index!=STRING_NOT_FOUND) 
1.108     paf      1020:                ifont->Copy(image, x, y, 0, Y(0), index_width(index), height);
1.91      paf      1021: }
                   1022: 
                   1023: /* ******************************** string ********************************** */
                   1024: 
                   1025: int Font::step_width(int index) {
1.125     misha    1026:        return letterspacing + (monospace ? monospace : index_width(index));
1.91      paf      1027: }
                   1028: 
                   1029: // counts trailing letter_spacing, consider this OK. useful for contiuations
                   1030: int Font::string_width(const String& s){
                   1031:        const char* cstr=s.cstr();
                   1032:        int result=0;
1.132     misha    1033: 
                   1034:        if(fsource_charset.isUTF8()){
                   1035:                for(UTF8_string_iterator i(s); i.has_next(); )
                   1036:                        result+=step_width(index_of(i.next()));
                   1037:        } else {
                   1038:                for(const char* current=cstr; *current; current++)
                   1039:                        result+=step_width(index_of(*current));
                   1040:        }
                   1041: 
1.91      paf      1042:        return result;
                   1043: }
                   1044: 
1.108     paf      1045: void Font::string_display(gdImage& image, int x, int y, const String& s){
1.91      paf      1046:        const char* cstr=s.cstr();
1.132     misha    1047: 
                   1048:        if(fsource_charset.isUTF8()){
                   1049:                for(UTF8_string_iterator i(s); i.has_next(); ){
                   1050:                        size_t index=index_of(i.next());
                   1051:                        index_display(image, x, y, index);
                   1052:                        x+=step_width(index);
                   1053:                }
                   1054:        } else {
                   1055:                for(const char* current=cstr; *current; current++) {
                   1056:                        size_t index=index_of(*current);
                   1057:                        index_display(image, x, y, index);
                   1058:                        x+=step_width(index);
                   1059:                }
1.87      paf      1060:        }
1.91      paf      1061: }
1.87      paf      1062: 
1.91      paf      1063: //
1.35      parser   1064: 
1.16      paf      1065: 
1.91      paf      1066: static void _font(Request& r, MethodParams& params) {
                   1067:        const String& alphabet=params.as_string(0, "alphabet must not be code");
1.131     misha    1068:        size_t alphabet_length=alphabet.length(r.charsets.source());
                   1069:        if(!alphabet_length)
1.155     moko     1070:                throw Exception(PARSER_RUNTIME, 0, "alphabet must not be empty");
1.84      paf      1071: 
1.125     misha    1072:        gdImage* image=load(r, params.as_string(1, FILE_NAME_MUST_NOT_BE_CODE));
                   1073: 
1.126     misha    1074:        int spacebar_width=image->SX();
1.125     misha    1075:        int monospace_width=0; // proportional
                   1076:        int letter_spacing=1;
                   1077:        if(params.count()>2){
1.144     moko     1078:                if(HashStringValue* options=params[2].get_hash()){
1.125     misha    1079:                        // third option is hash
                   1080:                        if(params.count()>3)
1.144     moko     1081:                                throw Exception(PARSER_RUNTIME, 0, "too many params were specified");
1.125     misha    1082:                        int valid_options=0;
                   1083:                        if(Value* vspacebar_width=options->get(spacebar_width_name)){
                   1084:                                valid_options++;
1.153     moko     1085:                                spacebar_width=r.process(*vspacebar_width).as_int();
1.125     misha    1086:                        }
                   1087:                        if(Value* vmonospace_width=options->get(monospace_width_name)){
                   1088:                                valid_options++;
1.153     moko     1089:                                monospace_width=r.process(*vmonospace_width).as_int();
1.125     misha    1090:                                if(!monospace_width)
                   1091:                                        monospace_width=image->SX();
                   1092:                        }
                   1093:                        if(Value* vletter_spacing=options->get(letter_spacing_name)){
                   1094:                                valid_options++;
1.153     moko     1095:                                letter_spacing=r.process(*vletter_spacing).as_int();
1.125     misha    1096:                        }
                   1097:                        if(valid_options!=options->count())
1.134     misha    1098:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.125     misha    1099:                } else {
                   1100:                        // backward
1.144     moko     1101:                        spacebar_width=params.as_int(2, "param must be int or hash", r);
1.125     misha    1102:                        if(params.count()>3) {
                   1103:                                monospace_width=params.as_int(3, "monospace_width must be int", r);
                   1104:                                if(!monospace_width)
                   1105:                                        monospace_width=image->SX();
                   1106:                        }
                   1107:                }
                   1108:        }
                   1109: 
1.131     misha    1110:        if(int remainder=image->SY() % alphabet_length)
1.155     moko     1111:                throw Exception(PARSER_RUNTIME, 0, "font-file height(%d) not divisable by alphabet size(%d), remainder=%d", image->SY(), alphabet_length, remainder);
1.37      parser   1112:        
1.155     moko     1113:        GET_SELF(r, VImage).set_font(new Font(r.charsets.source(), alphabet, image, image->SY() / alphabet_length, monospace_width, spacebar_width, letter_spacing));
1.16      paf      1114: }
                   1115: 
1.91      paf      1116: static void _text(Request& r, MethodParams& params) {
                   1117:        int x=params.as_int(0, "x must be int", r);
                   1118:        int y=params.as_int(1, "y must be int", r);
                   1119:        const String& s=params.as_string(2, "text must not be code");
1.16      paf      1120: 
1.91      paf      1121:        VImage& vimage=GET_SELF(r, VImage);
1.108     paf      1122:        vimage.font().string_display(vimage.image(), x, y, s);
1.16      paf      1123: }
                   1124: 
1.91      paf      1125: static void _length(Request& r, MethodParams& params) {
                   1126:        const String& s=params.as_string(0, "text must not be code");
1.47      parser   1127: 
1.91      paf      1128:        VImage& vimage=GET_SELF(r, VImage);
1.157     moko     1129:        r.write(*new VInt(vimage.font().string_width(s)));
1.47      parser   1130: }
                   1131: 
1.91      paf      1132: static void _arc(Request& r, MethodParams& params) {
1.108     paf      1133:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1134: 
1.108     paf      1135:        image.Arc(
1.91      paf      1136:                params.as_int(0, "center_x must be int", r), 
                   1137:                params.as_int(1, "center_y must be int", r), 
                   1138:                params.as_int(2, "width must be int", r), 
                   1139:                params.as_int(3, "height must be int", r), 
                   1140:                params.as_int(4, "start degrees must be int", r), 
                   1141:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1142:                image.Color(params.as_int(6, "cx must be int", r)));
1.48      parser   1143: }
                   1144: 
1.91      paf      1145: static void _sector(Request& r, MethodParams& params) {
1.108     paf      1146:        gdImage& image=GET_SELF(r, VImage).image();
1.49      parser   1147: 
1.108     paf      1148:        image.Sector(
1.91      paf      1149:                params.as_int(0, "center_x must be int", r), 
                   1150:                params.as_int(1, "center_y must be int", r), 
                   1151:                params.as_int(2, "width must be int", r), 
                   1152:                params.as_int(3, "height must be int", r), 
                   1153:                params.as_int(4, "start degrees must be int", r), 
                   1154:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1155:                image.Color(params.as_int(6, "color must be int", r)));
1.49      parser   1156: }
                   1157: 
1.91      paf      1158: static void _circle(Request& r, MethodParams& params) {
1.108     paf      1159:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1160: 
1.91      paf      1161:        int size=params.as_int(2, "radius must be int", r)*2;
1.108     paf      1162:        image.Arc(
1.91      paf      1163:                params.as_int(0, "center_x must be int", r), 
                   1164:                params.as_int(1, "center_y must be int", r), 
1.50      parser   1165:                size, //w
                   1166:                size, //h
1.48      parser   1167:                0, //s
                   1168:                360, //e
1.108     paf      1169:                image.Color(params.as_int(3, "color must be int", r)));
1.48      parser   1170: }
                   1171: 
1.108     paf      1172: gdImage& as_image(MethodParams& params, int index, const char* msg) {
1.91      paf      1173:        Value& value=params.as_no_junction(index, msg);
1.53      parser   1174: 
1.130     misha    1175:        if(Value* vimage=value.as(VIMAGE_TYPE)) {
1.108     paf      1176:                return static_cast<VImage *>(vimage)->image();
1.75      paf      1177:        } else
1.155     moko     1178:                throw Exception(PARSER_RUNTIME, 0, msg);
1.53      parser   1179: }
                   1180: 
1.91      paf      1181: static void _copy(Request& r, MethodParams& params) {
1.108     paf      1182:        gdImage& dest=GET_SELF(r, VImage).image();
1.53      parser   1183: 
1.108     paf      1184:        gdImage& src=as_image(params, 0, "src must be image");
1.53      parser   1185: 
1.91      paf      1186:        int sx=params.as_int(1, "src_x must be int", r);
                   1187:        int sy=params.as_int(2, "src_y must be int", r);
                   1188:        int sw=params.as_int(3, "src_w must be int", r);
                   1189:        int sh=params.as_int(4, "src_h must be int", r);
                   1190:        int dx=params.as_int(5, "dest_x must be int", r);
                   1191:        int dy=params.as_int(6, "dest_y must be int", r);
                   1192:        if(params.count()>1+2+2+2) {
                   1193:                int dw=params.as_int(1+2+2+2, "dest_w must be int", r);
                   1194:                int dh=(int)(params.count()>1+2+2+2+1?
                   1195:                        params.as_int(1+2+2+2+1, "dest_h must be int", r):sh*(((double)dw)/((double)sw)));
                   1196:                int tolerance=params.count()>1+2+2+2+2?
                   1197:                        params.as_int(1+2+2+2+2, "tolerance must be int", r):150;
1.53      parser   1198: 
1.108     paf      1199:                src.CopyResampled(dest, dx, dy, sx, sy, dw, dh, sw, sh, tolerance);
1.53      parser   1200:        } else
1.108     paf      1201:                src.Copy(dest, dx, dy, sx, sy, sw, sh);
                   1202: }
                   1203: 
                   1204: static void _pixel(Request& r, MethodParams& params) {
                   1205:        gdImage& image=GET_SELF(r, VImage).image();
                   1206: 
1.109     paf      1207:        int x=params.as_int(0, "x must be int", r); 
                   1208:        int y=params.as_int(1, "y must be int", r);
                   1209: 
                   1210:        if(params.count()>2) {
                   1211:                image.SetPixel(x, y, 
                   1212:                        image.Color(params.as_int(2, "color must be int", r)));
                   1213:        } else 
1.157     moko     1214:                r.write(*new VInt(image.DecodeColor(image.GetPixel(x, y))));
1.53      parser   1215: }
                   1216: 
                   1217: 
1.22      paf      1218: // constructor
                   1219: 
1.91      paf      1220: MImage::MImage(): Methoded("image") {
1.1       paf      1221:        // ^image:measure[DATA]
1.22      paf      1222:        add_native_method("measure", Method::CT_DYNAMIC, _measure, 1, 1);
1.3       paf      1223: 
1.25      paf      1224:        // ^image.html[]
                   1225:        // ^image.html[hash]
1.22      paf      1226:        add_native_method("html", Method::CT_DYNAMIC, _html, 0, 1);
1.6       paf      1227: 
1.25      paf      1228:        // ^image.load[background.gif]
1.22      paf      1229:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 1);
1.6       paf      1230: 
1.25      paf      1231:        // ^image.create[width;height] bgcolor=white
                   1232:        // ^image.create[width;height;bgcolor]
1.22      paf      1233:        add_native_method("create", Method::CT_DYNAMIC, _create, 2, 3);
1.6       paf      1234: 
1.25      paf      1235:        // ^image.gif[]
1.95      paf      1236:        add_native_method("gif", Method::CT_DYNAMIC, _gif, 0, 1);
1.12      paf      1237: 
1.25      paf      1238:        // ^image.line(x0;y0;x1;y1;color)
1.22      paf      1239:        add_native_method("line", Method::CT_DYNAMIC, _line, 5, 5);
1.13      paf      1240: 
1.25      paf      1241:        // ^image.fill(x;y;color)
1.22      paf      1242:        add_native_method("fill", Method::CT_DYNAMIC, _fill, 3, 3);
1.13      paf      1243: 
1.25      paf      1244:        // ^image.rectangle(x0;y0;x1;y1;color)
1.22      paf      1245:        add_native_method("rectangle", Method::CT_DYNAMIC, _rectangle, 5, 5);
1.13      paf      1246: 
1.25      paf      1247:        // ^image.bar(x0;y0;x1;y1;color)
1.22      paf      1248:        add_native_method("bar", Method::CT_DYNAMIC, _bar, 5, 5);
1.13      paf      1249: 
1.44      parser   1250:        // ^image.replace(color-source;color-dest)[table x:y]
1.135     misha    1251:        // ^image.replace(color-source;color-dest)
                   1252:        add_native_method("replace", Method::CT_DYNAMIC, _replace, 2, 3);
1.44      parser   1253: 
                   1254:        // ^image.polyline(color)[table x:y]
                   1255:        add_native_method("polyline", Method::CT_DYNAMIC, _polyline, 2, 2);
1.13      paf      1256: 
1.44      parser   1257:        // ^image.polygon(color)[table x:y]
                   1258:        add_native_method("polygon", Method::CT_DYNAMIC, _polygon, 2, 2);
1.13      paf      1259: 
1.44      parser   1260:        // ^image.polybar(color)[table x:y]
                   1261:        add_native_method("polybar", Method::CT_DYNAMIC, _polybar, 2, 2);
1.13      paf      1262: 
1.125     misha    1263:        // ^image.font[alPHAbet;font-file-name.gif]
                   1264:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width)
                   1265:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width;letter_width)
                   1266:        // ^image.font[alPHAbet;font-file-name.gif][$.space-width(.) $.letter-width(.) $.letter-space(.)]
                   1267:        add_native_method("font", Method::CT_DYNAMIC, _font, 2, 4);
1.16      paf      1268: 
1.125     misha    1269:        // ^image.text(x;y)[text]
1.22      paf      1270:        add_native_method("text", Method::CT_DYNAMIC, _text, 3, 3);
1.47      parser   1271:        
1.125     misha    1272:        // ^image.length[text]
1.47      parser   1273:        add_native_method("length", Method::CT_DYNAMIC, _length, 1, 1);
1.16      paf      1274:        
1.48      parser   1275:        // ^image.arc(center x;center y;width;height;start in degrees;end in degrees;color)
                   1276:        add_native_method("arc", Method::CT_DYNAMIC, _arc, 7, 7);
1.49      parser   1277: 
                   1278:        // ^image.sector(center x;center y;width;height;start in degrees;end in degrees;color)
                   1279:        add_native_method("sector", Method::CT_DYNAMIC, _sector, 7, 7);
1.48      parser   1280: 
                   1281:        // ^image.circle(center x;center y;r;color)
                   1282:        add_native_method("circle", Method::CT_DYNAMIC, _circle, 4, 4);
                   1283: 
1.56      parser   1284:        // ^image.copy[source](src x;src y;src w;src h;dst x;dst y[;dest w[;dest h[;tolerance]]])
                   1285:        add_native_method("copy", Method::CT_DYNAMIC, _copy, 1+2+2+2, (1+2+2+2)+2+1);
1.108     paf      1286: 
                   1287:        // ^image.pixel(x;y)[(color)]
1.109     paf      1288:        add_native_method("pixel", Method::CT_DYNAMIC, _pixel, 2, 3);
1.1       paf      1289: }

E-mail: