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

1.1       paf         1: /** @file
                      2:        Parser: @b image parser class.
                      3: 
1.120     misha       4:        Copyright(c) 2001-2009 ArtLebedev Group (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.123   ! misha       8: static const char * const IDENT_IMAGE_C="$Date: 2009-05-13 07:36:05 $";
1.31      parser      9: 
                     10: /*
                     11:        jpegsize: gets the width and height (in pixels) of a jpeg file
                     12:        Andrew Tong, werdna@ugcs.caltech.edu           February 14, 1995
                     13:        modified slightly by alex@ed.ac.uk
                     14:        and further still by rjray@uswest.com
                     15:        optimization and general re-write from tmetro@vl.com
                     16:        from perl by paf@design.ru
1.1       paf        17: */
                     18: 
                     19: #include "pa_config_includes.h"
                     20: 
1.91      paf        21: #include "pa_vmethod_frame.h"
                     22: 
1.8       paf        23: #include "gif.h"
1.6       paf        24: 
1.1       paf        25: #include "pa_common.h"
                     26: #include "pa_request.h"
                     27: #include "pa_vfile.h"
                     28: #include "pa_vimage.h"
1.89      paf        29: #include "pa_vdate.h"
1.91      paf        30: #include "pa_table.h"
1.1       paf        31: 
1.22      paf        32: // class
                     33: 
1.91      paf        34: class MImage: public Methoded {
1.22      paf        35: public: // VStateless_class
1.112     paf        36:        Value* create_new_value(Pool&, HashStringValue&) { return new VImage(); }
1.22      paf        37: 
                     38: public:
1.91      paf        39:        MImage();
1.24      paf        40: 
                     41: public: // Methoded
1.22      paf        42:        bool used_directly() { return true; }
                     43: 
                     44: };
1.1       paf        45: 
1.91      paf        46: // globals
                     47: 
                     48: DECLARE_CLASS_VAR(image, new MImage, 0);
                     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.91      paf       182:        }
                    183: } exif_tag_value2name;
                    184: 
1.118     misha     185: class EXIF_gps_tag_value2name: public Hash<int, const char*> {
                    186: public:
                    187:                EXIF_gps_tag_value2name() {
                    188:                EXIF_TAG(0x0,   GPSVersionID);
                    189:                EXIF_TAG(0x1,   GPSLatitudeRef);
                    190:                EXIF_TAG(0x2,   GPSLatitude);
                    191:                EXIF_TAG(0x3,   GPSLongitudeRef);
                    192:                EXIF_TAG(0x4,   GPSLongitude);
                    193:                EXIF_TAG(0x5,   GPSAltitudeRef);
                    194:                EXIF_TAG(0x6,   GPSAltitude);
                    195:                EXIF_TAG(0x7,   GPSTimeStamp);
                    196:                EXIF_TAG(0x8,   GPSSatellites);
                    197:                EXIF_TAG(0x9,   GPSStatus);
                    198:                EXIF_TAG(0xA,   GPSMeasureMode);
                    199:                EXIF_TAG(0xB,   GPSDOP);
                    200:                EXIF_TAG(0xC,   GPSSpeedRef);
                    201:                EXIF_TAG(0xD,   GPSSpeed);
                    202:                EXIF_TAG(0xE,   GPSTrackRef);
                    203:                EXIF_TAG(0xF,   GPSTrack);
                    204:                EXIF_TAG(0x10,  GPSImgDirectionRef);
                    205:                EXIF_TAG(0x11,  GPSImgDirection);
                    206:                EXIF_TAG(0x12,  GPSMapDatum);
                    207:                EXIF_TAG(0x13,  GPSDestLatitudeRef);
                    208:                EXIF_TAG(0x14,  GPSDestLatitude);
                    209:                EXIF_TAG(0x15,  GPSDestLongitudeRef);
                    210:                EXIF_TAG(0x16,  GPSDestLongitude);
                    211:                EXIF_TAG(0x17,  GPSDestBearingRef);
                    212:                EXIF_TAG(0x18,  GPSDestBearing);
                    213:                EXIF_TAG(0x19,  GPSDestDistanceRef);
                    214:                EXIF_TAG(0x1A,  GPSDestDistance);
                    215:                EXIF_TAG(0x1B,  GPSProcessingMethod);
                    216:                EXIF_TAG(0x1C,  GPSAreaInformation);
                    217:                EXIF_TAG(0x1D,  GPSDateStamp);
                    218:                EXIF_TAG(0x1E,  GPSDifferential);
                    219:        }
                    220: } exif_gps_tag_value2name;
                    221: 
                    222: #undef EXIF_TAG
1.91      paf       223: 
1.43      parser    224: #ifndef DOXYGEN
1.1       paf       225: class Measure_reader {
                    226: public:
1.91      paf       227:        virtual size_t read(const char* &buf, size_t limit)=0;
1.79      paf       228:        virtual void seek(long value, int whence)=0;
                    229:        virtual long tell()=0;
1.77      paf       230: };
1.1       paf       231: 
1.77      paf       232: class Measure_file_reader: public Measure_reader {
1.91      paf       233:        const String& file_name; const char* fname;
                    234:        int f;
                    235: 
1.77      paf       236: public:
1.91      paf       237:        Measure_file_reader(int af, const String& afile_name, const char* afname): 
                    238:                file_name(afile_name), fname(afname), f(af) {
1.1       paf       239:        }
                    240: 
1.91      paf       241:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       242:                if(limit==0)
1.1       paf       243:                        return 0;
1.77      paf       244: 
1.91      paf       245:                char* lbuf=new(PointerFreeGC) char[limit];
1.77      paf       246:                size_t read_size=(size_t)::read(f, lbuf, limit);  abuf=lbuf;
                    247:                if(ssize_t(read_size)<0 || read_size>limit)
                    248:                        throw Exception(0,
                    249:                                &file_name, 
1.104     paf       250:                                "measure failed: actually read %u bytes count not in [0..%u] valid range", 
1.77      paf       251:                        read_size, limit);
                    252: 
1.1       paf       253:                return read_size;
                    254:        }
                    255: 
1.91      paf       256:        override void seek(long value, int whence) {
1.79      paf       257:                if(lseek(f, value, whence)<0)
1.118     misha     258:                        throw Exception(IMAGE_FORMAT,
1.77      paf       259:                                &file_name, 
1.79      paf       260:                                "seek(value=%ld, whence=%d) failed: %s (%d), actual filename '%s'", 
                    261:                                        value, whence, strerror(errno), errno, fname);
1.77      paf       262:        }
                    263: 
1.91      paf       264:        override long tell() { return lseek(f, 0, SEEK_CUR); }
1.79      paf       265: 
1.77      paf       266: };
                    267: 
                    268: class Measure_buf_reader: public Measure_reader {
1.91      paf       269: 
                    270:        const char* buf; size_t size;
                    271:        const String& file_name; 
                    272: 
                    273:        size_t offset;
                    274: 
1.77      paf       275: public:
1.91      paf       276:        Measure_buf_reader(const char* abuf, size_t asize, const String& afile_name): 
1.77      paf       277:                buf(abuf), size(asize), file_name(afile_name), offset(0) {
                    278:        }
                    279:        
1.91      paf       280:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       281:                size_t to_read=min(limit, size-offset);
1.91      paf       282:                abuf=buf+offset;
1.77      paf       283:                offset+=to_read;
                    284:                return to_read;
                    285:        }
                    286: 
1.91      paf       287:        override void seek(long value, int whence) {
1.79      paf       288:                size_t new_offset;
                    289:                switch(whence) {
                    290:                case SEEK_CUR: new_offset=offset+value; break;
                    291:                case SEEK_SET: new_offset=(size_t)value; break;
1.91      paf       292:                default: 
                    293:                        throw Exception(0, 
                    294:                                0, 
                    295:                                "whence #%d not supported", 0, whence); 
                    296:                        break; // never
1.79      paf       297:                }
                    298:                
1.77      paf       299:                if((ssize_t)new_offset<0 || new_offset>size)
1.118     misha     300:                        throw Exception(IMAGE_FORMAT,
1.77      paf       301:                                &file_name, 
1.79      paf       302:                                "seek(value=%l, whence=%d) failed: out of buffer, new_offset>size (%l>%l) or new_offset<0", 
                    303:                                        value, whence, new_offset, size);
1.77      paf       304:                offset=new_offset;
                    305:        }
                    306: 
1.91      paf       307:        override long tell() { return offset; }
1.79      paf       308: 
1.1       paf       309: };
1.77      paf       310: 
1.43      parser    311: #endif
1.1       paf       312: 
1.72      paf       313: /// PNG file header
                    314: struct PNG_Header {
                    315:        char dummy[12];
                    316:        char signature[4]; //< must be "IHDR"
1.80      paf       317:        uchar high_width[2]; //< image width high bytes [we ignore for now]
                    318:        uchar width[2]; //< image width low bytes
                    319:        uchar high_height[2]; //< image height high bytes [we ignore for now]
                    320:        uchar height[4]; //< image height
1.72      paf       321: };
                    322: 
1.21      paf       323: /// GIF file header
1.1       paf       324: struct GIF_Header {
1.72      paf       325:        char       signature[3];         // 'GIF'
1.1       paf       326:        char       version[3];
1.80      paf       327:        uchar       width[2];
                    328:        uchar       height[2];
1.1       paf       329:        char       dif;
                    330:        char       fonColor;
                    331:        char       nulls;
                    332: };
                    333: 
1.31      parser    334: /// JPEG record head
                    335: struct JPG_Segment_head {
1.80      paf       336:        uchar marker;
                    337:        uchar code;
                    338:        uchar length[2];
1.1       paf       339: };
1.21      paf       340: /// JPEG frame header
1.31      parser    341: struct JPG_Size_segment_body {
1.27      parser    342:        char data;                    //< data precision of bits/sample
1.80      paf       343:        uchar height[2];               //< image height
                    344:        uchar width[2];                //< image width
1.27      parser    345:        char numComponents;           //< number of color components
1.1       paf       346: };
                    347: 
1.79      paf       348: /// JPEG frame header
1.91      paf       349: struct JPG_Exif_segment_begin {
1.79      paf       350:        char signature[6]; // Exif\0\0
                    351: };
                    352: 
1.80      paf       353: /// JPEG Exif TIFF Header
                    354: struct JPG_Exif_TIFF_header {
                    355:        uchar byte_align_identifier[2];
                    356:        char dummy[2]; // always 000A [or 0A00]
                    357:        uchar first_IFD_offset[4]; // Usually the first IFD starts immediately next to TIFF header, so this offset has value '0x00000008'.
                    358: };
                    359: 
                    360: // JPEG Exif IFD start
1.91      paf       361: struct JPG_Exif_IFD_begin {
1.80      paf       362:        uchar directory_entry_count[2]; // the number of directory entry contains in this IFD
                    363: };
                    364: 
                    365: // TTTT ffff NNNNNNNN DDDDDDDD 
                    366: struct JPG_Exif_IFD_entry {
                    367:        uchar tag[2]; // Tag number, this shows a kind of data
                    368:        uchar format[2]; // data format
                    369:        uchar components_count[4]; // number of components
                    370:        uchar value_or_offset_to_it[4]; // data value or offset to data value
                    371: };
                    372: 
                    373: #define JPG_IFD_TAG_EXIF_OFFSET 0x8769
                    374: 
1.118     misha     375: #define JPG_IFD_TAG_EXIF_GPS_OFFSET 0x8825
                    376: 
1.89      paf       377: #define JPEG_EXIF_DATE_CHARS 20
                    378: 
1.1       paf       379: //
                    380: 
1.80      paf       381: inline ushort x_endian_to_ushort(uchar b0, uchar b1) {
                    382:        return (ushort)((b1<<8) + b0);
1.33      parser    383: }
                    384: 
1.80      paf       385: inline uint x_endian_to_uint(uchar b0, uchar b1, uchar b2, uchar b3) {
                    386:        return (uint)(((((b3<<8) + b2)<<8)+b1)<<8)+b0;
1.33      parser    387: }
                    388: 
1.80      paf       389: inline ushort endian_to_ushort(bool is_big, const uchar *b/* [2] */) {
                    390:        return is_big?x_endian_to_ushort(b[1], b[0]):
                    391:                x_endian_to_ushort(b[0], b[1]);
1.1       paf       392: }
                    393: 
1.80      paf       394: inline uint endian_to_uint(bool is_big, const uchar *b /* [4] */) {
                    395:        return is_big?x_endian_to_uint(b[3], b[2], b[1], b[0]):
                    396:                x_endian_to_uint(b[0], b[1], b[2], b[3]);
                    397: }
                    398: 
1.91      paf       399: static void measure_gif(const String& origin_string, 
1.78      paf       400:                         Measure_reader& reader, ushort& width, ushort& height) {
1.1       paf       401: 
1.91      paf       402:        const char* buf;
1.102     paf       403:        const size_t head_size=sizeof(GIF_Header);
                    404:        if(reader.read(buf, head_size)<head_size)
1.118     misha     405:                throw Exception(IMAGE_FORMAT, 
1.91      paf       406:                        &origin_string, 
1.34      parser    407:                        "not GIF file - too small");
1.31      parser    408:        GIF_Header *head=(GIF_Header *)buf;
1.1       paf       409: 
1.72      paf       410:        if(strncmp(head->signature, "GIF", 3)!=0)
1.118     misha     411:                throw Exception(IMAGE_FORMAT, 
1.91      paf       412:                        &origin_string, 
1.44      parser    413:                        "not GIF file - wrong signature");      
1.1       paf       414: 
1.80      paf       415:        width=endian_to_ushort(false, head->width);
                    416:        height=endian_to_ushort(false, head->height);
                    417: }
                    418: 
1.91      paf       419: static Value* parse_IFD_entry_formatted_one_value(
1.80      paf       420:                                                                                                  bool is_big,
                    421:                                                                                                  ushort format, 
                    422:                                                                                                  size_t component_size, 
                    423:                                                                                                  const uchar *value) {
                    424:        switch(format) {
                    425:        case 1: // unsigned byte
1.91      paf       426:                return new VInt((uchar)value[0]);
1.80      paf       427:        case 3: // unsigned short
1.91      paf       428:                return new VInt(endian_to_ushort(is_big, value));
1.80      paf       429:        case 4: // unsigned long
                    430:                 // 'double' because parser's Int is signed
1.91      paf       431:                return new VDouble(endian_to_uint(is_big, value));
1.80      paf       432:        case 5: // unsigned rational
                    433:                {
                    434:                        uint numerator=endian_to_uint(is_big, value); value+=component_size/2;
                    435:                        uint denominator=endian_to_uint(is_big, value);
                    436:                        if(!denominator)
                    437:                                return 0;
1.91      paf       438:                        return new VDouble(((double)numerator)/denominator);
1.80      paf       439:                }
                    440:        case 6: // signed byte
1.91      paf       441:                return new VInt((signed char)value[0]);
1.80      paf       442:        case 8: // signed short
1.91      paf       443:                return new VInt((signed short)endian_to_ushort(is_big, value));
1.80      paf       444:        case 9: // signed long
1.91      paf       445:                return new VInt((signed int)endian_to_uint(is_big, value));
1.80      paf       446:        case 10: // signed rational
                    447:                {
                    448:                        signed int numerator=(signed int)endian_to_uint(is_big, value); value+=component_size/2;
                    449:                        uint denominator=endian_to_uint(is_big, value);
                    450:                        if(!denominator)
                    451:                                return 0;
1.91      paf       452:                        return new VDouble(numerator/denominator);
1.80      paf       453:                }
                    454:                /*
                    455:        case 11: // single float
1.120     misha     456:                @todo
1.80      paf       457:        case 12: // double float
1.120     misha     458:                @todo
1.80      paf       459:                */
                    460:        };      
                    461:        
                    462:        return 0;
                    463: }
                    464: 
1.89      paf       465: // date.C
1.107     paf       466: tm cstr_to_time_t(char *cstr);
1.89      paf       467: 
1.91      paf       468: static Value* parse_IFD_entry_formatted_value(bool is_big, ushort format, 
                    469:                                              size_t component_size, uint components_count, 
                    470:                                              const uchar *value) {
1.80      paf       471:        if(format==2) { // ascii string, exception: the only type with varying size
1.91      paf       472:                const char* cstr=(const char* )value;
                    473:                size_t length=components_count;
1.89      paf       474:                // Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes
1.91      paf       475:                if(length==JPEG_EXIF_DATE_CHARS 
1.111     paf       476:                        && isdigit((unsigned char)cstr[0])
1.91      paf       477:                        && cstr[length-1]==0) {
1.89      paf       478:                        char cstr_writable[JPEG_EXIF_DATE_CHARS]; 
                    479:                        strcpy(cstr_writable, cstr);
                    480: 
1.106     paf       481:                        try {
                    482:                                return new VDate(cstr_to_time_t(cstr_writable));
                    483:                        }
                    484:                        catch(...) { /*ignore bad date times*/ }
1.89      paf       485:                }
                    486: 
1.123   ! misha     487:                return new VString(*new String(cstr, String::L_TAINTED));
1.80      paf       488:        }
                    489: 
                    490:        if(components_count==1)
1.91      paf       491:                return parse_IFD_entry_formatted_one_value(is_big, format, component_size, value);
1.80      paf       492: 
1.91      paf       493:        VHash* result=new VHash;
                    494:        HashStringValue& hash=result->hash();
1.80      paf       495:        for(uint i=0; i<components_count; i++, value+=component_size) {
1.91      paf       496:                hash.put(
1.93      paf       497:                        String::Body::Format(i),
1.91      paf       498:                        parse_IFD_entry_formatted_one_value(is_big, format, component_size, value));
1.80      paf       499:        }
                    500: 
1.91      paf       501:        return result;
1.80      paf       502: }
                    503: 
1.91      paf       504: static Value* parse_IFD_entry_value(
1.80      paf       505:                                                                        bool is_big, Measure_reader& reader, long tiff_base,
                    506:                                                                        JPG_Exif_IFD_entry& entry) {
                    507:        size_t format2component_size[]={
                    508:                0, // undefined
                    509:                1, // unsigned byte
                    510:                1, // ascii string
                    511:                2, // unsigned short
                    512:                4, // unsigned long
                    513:                8, // unsigned rational
                    514:                1, // signed byte
                    515:                0, // undefined
                    516:                2, // signed short
                    517:                4, // signed long
                    518:                8, // signed rational
                    519:                /*
                    520:                4, // single float
                    521:                8, // double float
                    522:                */
                    523:        };
                    524: 
                    525:        ushort format=endian_to_ushort(is_big, entry.format);
                    526:        if(format>=sizeof(format2component_size)/sizeof(format2component_size[0]))
                    527:                return 0; // format out of range, ignoring
                    528: 
                    529:        size_t component_size=format2component_size[format];
                    530:        if(component_size==0)
                    531:                return 0; // undefined format
                    532: 
                    533:        // You can get the total data byte length by multiplies 
                    534:        // a 'bytes/components' value (see above chart) by number of components stored 'NNNNNNNN' area
                    535:        uint components_count=endian_to_uint(is_big, entry.components_count);
1.121     misha     536:        uint value_size=component_size*components_count;
1.80      paf       537:        // If its size is over 4bytes, 'DDDDDDDD' contains the offset to data stored address
1.91      paf       538:        Value* result;
1.80      paf       539: 
                    540:        if(value_size<=4)
1.91      paf       541:                result=parse_IFD_entry_formatted_value(
1.80      paf       542:                        is_big, format, 
                    543:                        component_size, components_count, 
                    544:                        entry.value_or_offset_to_it);
                    545:        else {
                    546:                long remembered=reader.tell();
                    547:                {
                    548:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.91      paf       549:                        const char* value;
1.80      paf       550:                        if(reader.read(value, value_size)<sizeof(value_size))
                    551:                                return 0;
1.91      paf       552:                        result=parse_IFD_entry_formatted_value(
1.80      paf       553:                                is_big, format, 
                    554:                                component_size, components_count, 
                    555:                                (const uchar*)value);
                    556:                }
                    557:                reader.seek(remembered, SEEK_SET);
                    558:        }
                    559: 
                    560:        return result;
                    561: }
                    562: 
1.91      paf       563: static void parse_IFD(HashStringValue& hash,
1.118     misha     564:                      bool is_big, Measure_reader& reader, long tiff_base, bool gps=false);
1.91      paf       565: 
                    566: static void parse_IFD_entry(HashStringValue& hash,
                    567:                            bool is_big, Measure_reader& reader, long tiff_base,
1.118     misha     568:                            JPG_Exif_IFD_entry& entry, bool gps=false) {
1.80      paf       569:        ushort tag=endian_to_ushort(is_big, entry.tag);
1.118     misha     570: 
                    571:        if(tag==JPG_IFD_TAG_EXIF_OFFSET || tag==JPG_IFD_TAG_EXIF_GPS_OFFSET){
1.80      paf       572:                long remembered=reader.tell();
                    573:                {
                    574:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.118     misha     575:                        parse_IFD(hash, is_big, reader, tiff_base, (tag==JPG_IFD_TAG_EXIF_GPS_OFFSET)?true:gps);
1.80      paf       576:                }
                    577:                reader.seek(remembered, SEEK_SET);
                    578:                return;
                    579:        }
1.118     misha     580: 
1.91      paf       581:        if(Value* value=parse_IFD_entry_value(is_big, reader, tiff_base, entry)) {
1.118     misha     582:                if(const char* name=(gps)?exif_gps_tag_value2name.get(tag):exif_tag_value2name.get(tag))
1.93      paf       583:                        hash.put(String::Body(name), value);
1.80      paf       584:                else
1.93      paf       585:                        hash.put(String::Body::Format(tag), value);
1.80      paf       586:        }
1.1       paf       587: }
                    588: 
1.91      paf       589: static void parse_IFD(
                    590:                      HashStringValue& hash,
1.118     misha     591:                      bool is_big, Measure_reader& reader, long tiff_base, bool gps) {
1.91      paf       592:        const char* buf;
                    593:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
1.80      paf       594:                return;
1.91      paf       595:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
1.80      paf       596: 
                    597:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    598:        for(int i=0; i<directory_entry_count; i++) {
                    599:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    600:                        return;
                    601: 
1.118     misha     602:                parse_IFD_entry(hash, is_big, reader, tiff_base, *(JPG_Exif_IFD_entry *)buf, gps);
1.80      paf       603:        }
                    604:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    605: }
                    606: 
1.91      paf       607: static Value* parse_exif(Measure_reader& reader, const String& origin_string) {
                    608:        const char* buf;
                    609:        if(reader.read(buf, sizeof(JPG_Exif_segment_begin))<sizeof(JPG_Exif_segment_begin))
1.118     misha     610:                throw Exception(IMAGE_FORMAT, 
1.91      paf       611:                        &origin_string, 
1.80      paf       612:                        "not JPEG file - can not fully read Exif segment start");
                    613: 
1.91      paf       614:        JPG_Exif_segment_begin *start=(JPG_Exif_segment_begin *)buf;
1.80      paf       615:        if(memcmp(start->signature, "Exif\0\0", 4+2)!=0) //signature invalid?
                    616:                return 0; // ignore invalid block
                    617: 
                    618:        uint tiff_base=reader.tell();
                    619:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    620:                return 0;
                    621: 
                    622:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    623:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    624: 
                    625:        uint first_IFD_offset=endian_to_uint(is_big, head->first_IFD_offset);
                    626:        reader.seek(tiff_base+first_IFD_offset, SEEK_SET);
                    627: 
1.91      paf       628:        VHash* vhash=new VHash;
1.80      paf       629: 
                    630:        // IFD
1.91      paf       631:        parse_IFD(vhash->hash(), is_big, reader, tiff_base);
1.80      paf       632: 
1.91      paf       633:        return vhash;
1.80      paf       634: }
                    635: 
1.91      paf       636: static void measure_jpeg(const String& origin_string, 
                    637:                         Measure_reader& reader, ushort& width, ushort& height, Value** exif) {
1.2       paf       638:        // JFIF format markers
1.80      paf       639:        const uchar MARKER=0xFF;
                    640:        const uchar CODE_SIZE_A=0xC0;
                    641:        const uchar CODE_SIZE_B=0xC1;
                    642:        const uchar CODE_SIZE_C=0xC2;
                    643:        const uchar CODE_SIZE_D=0xC3;
                    644:        const uchar CODE_EXIF=0xE1;
1.2       paf       645: 
1.91      paf       646:        const char* buf;
1.18      paf       647:        const size_t prefix_size=2;
1.31      parser    648:        if(reader.read(buf, prefix_size)<prefix_size)
1.118     misha     649:                throw Exception(IMAGE_FORMAT, 
1.91      paf       650:                        &origin_string, 
1.34      parser    651:                        "not JPEG file - too small");
1.80      paf       652:        uchar *signature=(uchar *)buf;
1.1       paf       653:        
1.31      parser    654:        if(!(signature[0]==0xFF && signature[1]==0xD8)) 
1.118     misha     655:                throw Exception(IMAGE_FORMAT, 
1.91      paf       656:                        &origin_string, 
1.44      parser    657:                        "not JPEG file - wrong signature");
1.31      parser    658: 
                    659:        while(true) {
1.80      paf       660:                uint segment_base=reader.tell()+2/*marker,code*/;
1.31      parser    661:                if(reader.read(buf, sizeof(JPG_Segment_head))<sizeof(JPG_Segment_head))
1.79      paf       662:                        break;
1.31      parser    663:                JPG_Segment_head *head=(JPG_Segment_head *)buf;
                    664: 
                    665:         // Verify that it's a valid segment.
                    666:                if(head->marker!=MARKER)
1.118     misha     667:                        throw Exception(IMAGE_FORMAT, 
1.91      paf       668:                                &origin_string, 
1.79      paf       669:                                "not JPEG file - marker not found");
                    670: 
                    671:                switch(head->code) {
1.118     misha     672:                // http://park2.wakwak.com/~tsuruzoh/Computer/Digicams/exif-e.html
1.79      paf       673:                case CODE_EXIF:
1.80      paf       674:                        if(exif && !*exif) // seen .jpg with some xml under EXIF tag, after real exif block :)
1.91      paf       675:                                *exif=parse_exif(reader, origin_string);
1.1       paf       676:                        break;
1.31      parser    677: 
1.79      paf       678:                case CODE_SIZE_A:
                    679:                case CODE_SIZE_B:
                    680:                case CODE_SIZE_C:
                    681:                case CODE_SIZE_D:
                    682:                        {
                    683:                                // Segments that contain size info
                    684:                                if(reader.read(buf, sizeof(JPG_Size_segment_body))<sizeof(JPG_Size_segment_body))
1.118     misha     685:                                        throw Exception(IMAGE_FORMAT, 
1.91      paf       686:                                                &origin_string, 
1.79      paf       687:                                                "not JPEG file - can not fully read Size segment");
                    688:                                JPG_Size_segment_body *body=(JPG_Size_segment_body *)buf;
                    689:                                
1.80      paf       690:                                width=endian_to_ushort(true, body->width);
                    691:                                height=endian_to_ushort(true, body->height);
1.79      paf       692:                        }                       
1.80      paf       693:                        return;
1.79      paf       694:                };
                    695: 
1.80      paf       696:                reader.seek(segment_base+endian_to_ushort(true, head->length), SEEK_SET);
1.31      parser    697:        }
                    698: 
1.118     misha     699:        throw Exception(IMAGE_FORMAT, 
1.91      paf       700:                &origin_string, 
1.79      paf       701:                "broken JPEG file - size frame not found");
1.1       paf       702: }
                    703: 
1.91      paf       704: static void measure_png(const String& origin_string, 
1.78      paf       705:                         Measure_reader& reader, ushort& width, ushort& height) {
1.72      paf       706: 
1.91      paf       707:        const char* buf;
1.102     paf       708:        const size_t head_size=sizeof(PNG_Header);
                    709:        if(reader.read(buf, head_size)<head_size)
1.118     misha     710:                throw Exception(IMAGE_FORMAT, 
1.91      paf       711:                        &origin_string, 
1.72      paf       712:                        "not PNG file - too small");
                    713:        PNG_Header *head=(PNG_Header *)buf;
                    714: 
                    715:        if(strncmp(head->signature, "IHDR", 4)!=0)
1.118     misha     716:                throw Exception(IMAGE_FORMAT, 
1.91      paf       717:                        &origin_string, 
1.72      paf       718:                        "not PNG file - wrong signature");      
                    719: 
1.80      paf       720:        width=endian_to_ushort(true, head->width);
                    721:        height=endian_to_ushort(true, head->height);
1.72      paf       722: }
                    723: 
1.1       paf       724: // measure center
                    725: 
1.91      paf       726: static void measure(const String& file_name, 
                    727:                         Measure_reader& reader, ushort& width, ushort& height, Value** exif) {
                    728:        const char* file_name_cstr=file_name.cstr(String::L_FILE_SPEC);
                    729:        if(const char* cext=strrchr(file_name_cstr, '.')) {
1.1       paf       730:                cext++;
                    731:                if(strcasecmp(cext, "GIF")==0)
1.91      paf       732:                        measure_gif(file_name, reader, width, height);
1.1       paf       733:                else if(strcasecmp(cext, "JPG")==0 || strcasecmp(cext, "JPEG")==0) 
1.91      paf       734:                        measure_jpeg(file_name, reader, width, height, exif);
1.72      paf       735:                else if(strcasecmp(cext, "PNG")==0)
1.91      paf       736:                        measure_png(file_name, reader, width, height);
1.1       paf       737:                else
1.118     misha     738:                        throw Exception(IMAGE_FORMAT, 
1.1       paf       739:                                &file_name, 
                    740:                                "unhandled image file name extension '%s'", cext);
                    741:        } else
1.118     misha     742:                throw Exception(IMAGE_FORMAT, 
1.1       paf       743:                        &file_name, 
                    744:                        "can not determine image type - no file name extension");
                    745: }
                    746: 
1.77      paf       747: // methods
1.1       paf       748: 
1.40      parser    749: #ifndef DOXYGEN
1.77      paf       750: struct File_measure_action_info {
1.91      paf       751:        ushort* width;
                    752:        ushort* height;
                    753:        Value** exif;
                    754:        const String* file_name;
1.1       paf       755: };
1.40      parser    756: #endif
1.91      paf       757: static void file_measure_action(
1.98      paf       758:                                                                struct stat& /*finfo*/, int f, 
                    759:                                                                const String& /*file_spec*/, const char* fname, bool /*as_text*/,
1.77      paf       760:                                                                void *context) {
                    761:        File_measure_action_info& info=*static_cast<File_measure_action_info *>(context);
1.1       paf       762: 
1.91      paf       763:        Measure_file_reader reader(f, *info.file_name, fname);
                    764:        measure(*info.file_name, reader, *info.width, *info.height, info.exif);
1.1       paf       765: }
                    766: 
1.91      paf       767: static void _measure(Request& r, MethodParams& params) {
                    768:        Value& data=params.as_no_junction(0, "data must not be code");
1.1       paf       769: 
1.78      paf       770:        ushort width=0;
                    771:        ushort height=0;
1.91      paf       772:        Value* exif=0;
                    773:        const String* file_name;
1.100     paf       774:        if((file_name=data.get_string())) {
                    775:                File_measure_action_info info={
                    776:                        &width, &height,
                    777:                        &exif,
                    778:                        file_name
                    779:                };
1.91      paf       780:                file_read_action_under_lock(r.absolute(*file_name), 
1.77      paf       781:                        "measure", file_measure_action, &info);
1.1       paf       782:        } else {
1.91      paf       783:                VFile* vfile=data.as_vfile();
                    784:                file_name=&vfile->fields().get(name_name)->as_string();
1.77      paf       785:                Measure_buf_reader reader(
1.91      paf       786:                        vfile->value_ptr(),
                    787:                        vfile->value_size(),
1.77      paf       788:                        *file_name
                    789:                );
1.91      paf       790:                measure(*file_name, reader, width, height, &exif);
1.1       paf       791:        }
                    792: 
1.91      paf       793:        GET_SELF(r, VImage).set(file_name, width, height, 0, exif);
1.1       paf       794: }
                    795: 
1.40      parser    796: #ifndef DOXYGEN
1.4       paf       797: struct Attrib_info {
1.91      paf       798:        String* tag; ///< html tag being constructed
                    799:        HashStringValue* skip; ///< tag attributes not to append to tag string [to skip]
1.4       paf       800: };
1.40      parser    801: #endif
1.91      paf       802: static void append_attrib_pair(
                    803:                               HashStringValue::key_type key, 
                    804:                               HashStringValue::value_type value, 
                    805:                               Attrib_info* info) {
1.49      parser    806:        // skip user-specified and internal(starting with "line-") attributes 
1.91      paf       807:        if(info->skip && info->skip->get(key) || key.pos("line-")==0)
1.4       paf       808:                return;
                    809: 
1.3       paf       810:        // src="a.gif" width=123 ismap[=-1]
1.91      paf       811:        *info->tag << " " << key;
                    812:        if(value->is_string() || value->as_int()>=0)
                    813:                *info->tag << "=\"" << value->as_string() << "\"";
1.3       paf       814: }
1.91      paf       815: static void _html(Request& r, MethodParams& params) {
1.3       paf       816: 
1.91      paf       817:        String tag;
1.3       paf       818:        tag << "<img";
1.4       paf       819: 
1.91      paf       820:        const HashStringValue& fields=GET_SELF(r, VImage).fields();
                    821:        HashStringValue* attribs=0;
1.4       paf       822: 
1.91      paf       823:        if(params.count()) {
1.69      paf       824:                // for backward compatibility: someday was ^html{}
1.91      paf       825:                Value& vattribs=r.process_to_value(params[0],
1.52      parser    826:                        false/*don't intercept string*/);
1.82      paf       827:                if(!vattribs.is_string()) // allow empty
1.100     paf       828:                        if((attribs=vattribs.get_hash())) {
                    829:                                Attrib_info info={&tag, 0};
1.114     paf       830:                                attribs->for_each<Attrib_info*>(append_attrib_pair, &info);
1.39      parser    831:                        } else
1.115     misha     832:                                throw Exception(PARSER_RUNTIME, 
1.91      paf       833:                                        0, 
1.39      parser    834:                                        "attributes must be hash");
                    835:        }
1.4       paf       836: 
1.91      paf       837:        {
                    838:                Attrib_info info={&tag, attribs};
1.114     paf       839:                fields.for_each<Attrib_info*>(append_attrib_pair, &info);
1.91      paf       840:        }
1.6       paf       841:        tag << " />";
1.3       paf       842:        r.write_pass_lang(tag);
                    843: }
1.8       paf       844: 
1.68      paf       845: /// @test wrap FILE to auto-object
1.91      paf       846: static gdImage* load(Request& r, 
1.16      paf       847:                                         const String& file_name){
1.91      paf       848:        const char* file_name_cstr=r.absolute(file_name).cstr(String::L_FILE_SPEC);
1.16      paf       849:        if(FILE *f=fopen(file_name_cstr, "rb")) {
1.91      paf       850:                gdImage* image=new gdImage;
                    851:                bool ok=image->CreateFromGif(f);
1.16      paf       852:                fclose(f);
1.23      paf       853:                if(!ok)
1.118     misha     854:                        throw Exception(IMAGE_FORMAT, 
1.23      paf       855:                                &file_name,
                    856:                                "is not in GIF format");
1.91      paf       857:                return image;
1.16      paf       858:        } else {
1.68      paf       859:                throw Exception("file.missing", 
1.91      paf       860:                        0, 
1.16      paf       861:                        "can not open '%s'", file_name_cstr);
                    862:        }
                    863: }
                    864: 
                    865: 
1.91      paf       866: static void _load(Request& r, MethodParams& params) {
1.116     misha     867:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.6       paf       868: 
1.91      paf       869:        gdImage* image=load(r, file_name);
                    870:        GET_SELF(r, VImage).set(&file_name, image->SX(), image->SY(), image);
1.6       paf       871: }
                    872: 
1.91      paf       873: static void _create(Request& r, MethodParams& params) {
                    874:        int width=params.as_int(0, "width must be int", r);
                    875:        int height=params.as_int(1, "height must be int", r);
1.8       paf       876:        int bgcolor_value=0xffFFff;
1.91      paf       877:        if(params.count()>2)
                    878:                bgcolor_value=params.as_int(2, "color must be int", r);
                    879:        gdImage* image=new gdImage;
                    880:        image->Create(width, height);
                    881:        image->FilledRectangle(0, 0, width-1, height-1, image->Color(bgcolor_value));
                    882:        GET_SELF(r, VImage).set(0, width, height, image);
1.6       paf       883: }
                    884: 
1.91      paf       885: static void _gif(Request& r, MethodParams& params) {
1.108     paf       886:        gdImage& image=GET_SELF(r, VImage).image();
1.6       paf       887: 
1.95      paf       888:        const String *file_name=0;
                    889:        if(params.count()>0)
1.116     misha     890:                file_name=&params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.10      paf       891: 
1.108     paf       892:        gdBuf buf=image.Gif();
1.6       paf       893:        
1.91      paf       894:        VFile& vfile=*new VFile;
                    895:        Value* content_type=new VString(*new String("image/gif"));
1.20      paf       896:        vfile.set(false/*not tainted*/, 
1.95      paf       897:                (const char*)buf.ptr, buf.size, 
                    898:                file_name? file_name->cstr(String::L_FILE_SPEC): 0, 
                    899:                content_type);
1.6       paf       900: 
                    901:        r.write_no_lang(vfile);
                    902: }
                    903: 
1.91      paf       904: static void _line(Request& r, MethodParams& params) {
1.108     paf       905:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       906: 
1.108     paf       907:        image.Line(
1.91      paf       908:                params.as_int(0, "x0 must be int", r), 
                    909:                params.as_int(1, "y0 must be int", r), 
                    910:                params.as_int(2, "x1 must be int", r), 
                    911:                params.as_int(3, "y1 must be int", r), 
1.108     paf       912:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       913: }
                    914: 
1.91      paf       915: static void _fill(Request& r, MethodParams& params) {
1.108     paf       916:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       917: 
1.108     paf       918:        image.Fill(
1.91      paf       919:                params.as_int(0, "x must be int", r), 
                    920:                params.as_int(1, "y must be int", r), 
1.108     paf       921:                image.Color(params.as_int(2, "color must be int", r)));
1.13      paf       922: }
                    923: 
1.91      paf       924: static void _rectangle(Request& r, MethodParams& params) {
1.108     paf       925:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       926: 
1.108     paf       927:        image.Rectangle(
1.91      paf       928:                params.as_int(0, "x0 must be int", r), 
                    929:                params.as_int(1, "y0 must be int", r), 
                    930:                params.as_int(2, "x1 must be int", r), 
                    931:                params.as_int(3, "y1 must be int", r), 
1.108     paf       932:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       933: }
                    934: 
1.91      paf       935: static void _bar(Request& r, MethodParams& params) {
1.108     paf       936:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       937: 
1.108     paf       938:        image.FilledRectangle(
1.91      paf       939:                params.as_int(0, "x0 must be int", r), 
                    940:                params.as_int(1, "y0 must be int", r), 
                    941:                params.as_int(2, "x1 must be int", r), 
                    942:                params.as_int(3, "y1 must be int", r), 
1.108     paf       943:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       944: }
                    945: 
1.44      parser    946: #ifndef DOXYGEN
1.91      paf       947: static void add_point(Table::element_type row, 
                    948:                                          gdImage::Point **p) {
1.110     paf       949:        if(row->count()!=2)
                    950:                throw Exception(0,
                    951:                        0,
                    952:                        "coordinates table must contain two columns: x and y values");
1.91      paf       953:        (**p).x=row->get(0)->as_int();
                    954:        (**p).y=row->get(1)->as_int();
1.44      parser    955:        (*p)++;
                    956: }
                    957: #endif
1.91      paf       958: static void _replace(Request& r, MethodParams& params) {
1.108     paf       959:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       960: 
1.116     misha     961:        Table* table=params.as_no_junction(2, COORDINATES_MUST_NOT_BE_CODE).get_table();
1.44      parser    962:        if(!table) 
1.119     misha     963:                throw Exception(PARSER_RUNTIME,
1.91      paf       964:                        0,
1.44      parser    965:                        "coordinates must be table");
1.13      paf       966: 
1.92      paf       967:        gdImage::Point *all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser    968:        gdImage::Point *add_p=all_p;    
                    969:        table->for_each(add_point, &add_p);
1.108     paf       970:        image.FilledPolygonReplaceColor(all_p, table->count(), 
                    971:                image.Color(params.as_int(0, "src color must be int", r)),
                    972:                image.Color(params.as_int(1, "dest color must be int", r)));
1.13      paf       973: }
                    974: 
1.91      paf       975: static void _polyline(Request& r, MethodParams& params) {
1.108     paf       976:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       977: 
1.116     misha     978:        Table* table=params.as_no_junction(1, COORDINATES_MUST_NOT_BE_CODE).get_table();
1.44      parser    979:        if(!table) 
1.119     misha     980:                throw Exception(PARSER_RUNTIME,
1.91      paf       981:                        0,
1.44      parser    982:                        "coordinates must be table");
                    983: 
1.92      paf       984:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser    985:        gdImage::Point *add_p=all_p;    
                    986:        table->for_each(add_point, &add_p);
1.108     paf       987:        image.Polygon(all_p, table->count(), 
                    988:                image.Color(params.as_int(0, "color must be int", r)),
1.44      parser    989:                false/*not closed*/);
                    990: }
                    991: 
1.91      paf       992: static void _polygon(Request& r, MethodParams& params) {
1.108     paf       993:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       994: 
1.116     misha     995:        Table* table=params.as_no_junction(1, COORDINATES_MUST_NOT_BE_CODE).get_table();
1.44      parser    996:        if(!table) 
1.119     misha     997:                throw Exception(PARSER_RUNTIME,
1.91      paf       998:                        0,
1.44      parser    999:                        "coordinates must be table");
                   1000: 
1.92      paf      1001:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1002:        gdImage::Point *add_p=all_p;    
                   1003:        table->for_each(add_point, &add_p);
1.108     paf      1004:        image.Polygon(all_p, table->count(), 
                   1005:                image.Color(params.as_int(0, "color must be int", r)));
1.13      paf      1006: }
                   1007: 
1.91      paf      1008: static void _polybar(Request& r, MethodParams& params) {
1.108     paf      1009:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1010: 
1.116     misha    1011:        Table* table=params.as_no_junction(1, COORDINATES_MUST_NOT_BE_CODE).get_table();
1.44      parser   1012:        if(!table) 
1.115     misha    1013:                throw Exception(PARSER_RUNTIME,
1.91      paf      1014:                        0,
1.44      parser   1015:                        "coordinates must be table");
1.13      paf      1016: 
1.92      paf      1017:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1018:        gdImage::Point *add_p=all_p;    
                   1019:        table->for_each(add_point, &add_p);
1.108     paf      1020:        image.FilledPolygon(all_p, table->count(), 
                   1021:                image.Color(params.as_int(0, "color must be int", r)));
1.12      paf      1022: }
                   1023: 
1.16      paf      1024: // font
                   1025: 
1.85      paf      1026: #define Y(y)(y+index*height)
1.21      paf      1027: 
1.91      paf      1028: // Font class
                   1029: 
                   1030: const int Font::letter_spacing=1;
                   1031: 
                   1032: Font::Font(//, 
                   1033:        const String& aalphabet, 
                   1034:        gdImage* aifont, int aheight, int amonospace, int aspacebarspace):
                   1035:        height(aheight), monospace(amonospace),  spacebarspace(aspacebarspace),
1.100     paf      1036:        ifont(aifont),
                   1037:        alphabet(aalphabet)     {
1.91      paf      1038: }
                   1039: 
                   1040: /* ******************************** char ********************************** */
                   1041: 
                   1042: size_t Font::index_of(char ch) {
                   1043:        if(ch==' ') return STRING_NOT_FOUND;
                   1044:        return alphabet.pos(ch);
                   1045: }
                   1046: 
                   1047: int Font::index_width(size_t index) {
                   1048:        if(index==STRING_NOT_FOUND)
                   1049:                return spacebarspace;
                   1050:        int tr=ifont->GetTransparent();
                   1051:        for(int x=ifont->SX()-1; x>=0; x--) {
                   1052:                for(int y=0; y<height; y++)
                   1053:                        if(ifont->GetPixel(x, Y(y))!=tr) 
                   1054:                                return x+1;
1.16      paf      1055:        }
1.91      paf      1056:        return 0;
                   1057: }
                   1058: 
1.108     paf      1059: void Font::index_display(gdImage& image, int x, int y, size_t index){
1.91      paf      1060:        if(index!=STRING_NOT_FOUND) 
1.108     paf      1061:                ifont->Copy(image, x, y, 0, Y(0), index_width(index), height);
1.91      paf      1062: }
                   1063: 
                   1064: /* ******************************** string ********************************** */
                   1065: 
                   1066: int Font::step_width(int index) {
                   1067:        return letter_spacing + (monospace ? monospace : index_width(index));
                   1068: }
                   1069: 
                   1070: // counts trailing letter_spacing, consider this OK. useful for contiuations
                   1071: int Font::string_width(const String& s){
                   1072:        const char* cstr=s.cstr();
                   1073:        int result=0;
                   1074:        for(const char* current=cstr; *current; current++)
                   1075:                result+=step_width(index_of(*current));
                   1076:        return result;
                   1077: }
                   1078: 
1.108     paf      1079: void Font::string_display(gdImage& image, int x, int y, const String& s){
1.91      paf      1080:        const char* cstr=s.cstr();
                   1081:        for(const char* current=cstr; *current; current++) {
                   1082:                size_t index=index_of(*current);
                   1083:                index_display(image, x, y, index);
                   1084:                x+=step_width(index);
1.87      paf      1085:        }
1.91      paf      1086: }
1.87      paf      1087: 
1.91      paf      1088: //
1.35      parser   1089: 
1.16      paf      1090: 
1.91      paf      1091: static void _font(Request& r, MethodParams& params) {
                   1092:        const String& alphabet=params.as_string(0, "alphabet must not be code");
1.117     misha    1093:        gdImage* image=load(r, params.as_string(1, FILE_NAME_MUST_NOT_BE_CODE));
1.91      paf      1094:        int spacebar_width=params.as_int(2, "spacebar_width must be int", r);
1.37      parser   1095:        int monospace_width;
1.91      paf      1096:        if(params.count()>3) {
                   1097:                monospace_width=params.as_int(3, "monospace_width must be int", r);
1.37      parser   1098:                if(!monospace_width)
1.91      paf      1099:                        monospace_width=image->SX();
1.37      parser   1100:        } else
                   1101:                monospace_width=0;
1.16      paf      1102: 
1.91      paf      1103:        if(!alphabet.length())
1.115     misha    1104:                throw Exception(PARSER_RUNTIME,
1.91      paf      1105:                        0,
1.37      parser   1106:                        "alphabet must not be empty");
1.84      paf      1107: 
1.91      paf      1108:        if(int remainder=image->SY() % alphabet.length())
1.115     misha    1109:                throw Exception(PARSER_RUNTIME,
1.91      paf      1110:                        0,
1.84      paf      1111:                        "font-file height(%d) not divisable by alphabet size(%d), remainder=%d",
1.91      paf      1112:                                image->SY(), alphabet.length(), remainder);
1.37      parser   1113:        
1.108     paf      1114:        GET_SELF(r, VImage).set_font(new Font(
1.37      parser   1115:                alphabet, 
1.36      parser   1116:                image, 
1.108     paf      1117:                image->SY() / alphabet.length(), monospace_width, spacebar_width));
1.16      paf      1118: }
                   1119: 
1.91      paf      1120: static void _text(Request& r, MethodParams& params) {
                   1121:        int x=params.as_int(0, "x must be int", r);
                   1122:        int y=params.as_int(1, "y must be int", r);
                   1123:        const String& s=params.as_string(2, "text must not be code");
1.16      paf      1124: 
1.91      paf      1125:        VImage& vimage=GET_SELF(r, VImage);
1.108     paf      1126:        vimage.font().string_display(vimage.image(), x, y, s);
1.16      paf      1127: }
                   1128: 
1.91      paf      1129: static void _length(Request& r, MethodParams& params) {
                   1130:        const String& s=params.as_string(0, "text must not be code");
1.47      parser   1131: 
1.91      paf      1132:        VImage& vimage=GET_SELF(r, VImage);
1.108     paf      1133:        r.write_no_lang(*new VInt(vimage.font().string_width(s)));
1.47      parser   1134: }
                   1135: 
1.91      paf      1136: static void _arc(Request& r, MethodParams& params) {
1.108     paf      1137:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1138: 
1.108     paf      1139:        image.Arc(
1.91      paf      1140:                params.as_int(0, "center_x must be int", r), 
                   1141:                params.as_int(1, "center_y must be int", r), 
                   1142:                params.as_int(2, "width must be int", r), 
                   1143:                params.as_int(3, "height must be int", r), 
                   1144:                params.as_int(4, "start degrees must be int", r), 
                   1145:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1146:                image.Color(params.as_int(6, "cx must be int", r)));
1.48      parser   1147: }
                   1148: 
1.91      paf      1149: static void _sector(Request& r, MethodParams& params) {
1.108     paf      1150:        gdImage& image=GET_SELF(r, VImage).image();
1.49      parser   1151: 
1.108     paf      1152:        image.Sector(
1.91      paf      1153:                params.as_int(0, "center_x must be int", r), 
                   1154:                params.as_int(1, "center_y must be int", r), 
                   1155:                params.as_int(2, "width must be int", r), 
                   1156:                params.as_int(3, "height must be int", r), 
                   1157:                params.as_int(4, "start degrees must be int", r), 
                   1158:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1159:                image.Color(params.as_int(6, "color must be int", r)));
1.49      parser   1160: }
                   1161: 
1.91      paf      1162: static void _circle(Request& r, MethodParams& params) {
1.108     paf      1163:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1164: 
1.91      paf      1165:        int size=params.as_int(2, "radius must be int", r)*2;
1.108     paf      1166:        image.Arc(
1.91      paf      1167:                params.as_int(0, "center_x must be int", r), 
                   1168:                params.as_int(1, "center_y must be int", r), 
1.50      parser   1169:                size, //w
                   1170:                size, //h
1.48      parser   1171:                0, //s
                   1172:                360, //e
1.108     paf      1173:                image.Color(params.as_int(3, "color must be int", r)));
1.48      parser   1174: }
                   1175: 
1.108     paf      1176: gdImage& as_image(MethodParams& params, int index, const char* msg) {
1.91      paf      1177:        Value& value=params.as_no_junction(index, msg);
1.53      parser   1178: 
1.91      paf      1179:        if(Value* vimage=value.as(VIMAGE_TYPE, false)) {
1.108     paf      1180:                return static_cast<VImage *>(vimage)->image();
1.75      paf      1181:        } else
1.115     misha    1182:                throw Exception(PARSER_RUNTIME, 
1.91      paf      1183:                        0, 
1.53      parser   1184:                        msg);
                   1185: }
                   1186: 
1.91      paf      1187: static void _copy(Request& r, MethodParams& params) {
1.108     paf      1188:        gdImage& dest=GET_SELF(r, VImage).image();
1.53      parser   1189: 
1.108     paf      1190:        gdImage& src=as_image(params, 0, "src must be image");
1.53      parser   1191: 
1.91      paf      1192:        int sx=params.as_int(1, "src_x must be int", r);
                   1193:        int sy=params.as_int(2, "src_y must be int", r);
                   1194:        int sw=params.as_int(3, "src_w must be int", r);
                   1195:        int sh=params.as_int(4, "src_h must be int", r);
                   1196:        int dx=params.as_int(5, "dest_x must be int", r);
                   1197:        int dy=params.as_int(6, "dest_y must be int", r);
                   1198:        if(params.count()>1+2+2+2) {
                   1199:                int dw=params.as_int(1+2+2+2, "dest_w must be int", r);
                   1200:                int dh=(int)(params.count()>1+2+2+2+1?
                   1201:                        params.as_int(1+2+2+2+1, "dest_h must be int", r):sh*(((double)dw)/((double)sw)));
                   1202:                int tolerance=params.count()>1+2+2+2+2?
                   1203:                        params.as_int(1+2+2+2+2, "tolerance must be int", r):150;
1.53      parser   1204: 
1.108     paf      1205:                src.CopyResampled(dest, dx, dy, sx, sy, dw, dh, sw, sh, tolerance);
1.53      parser   1206:        } else
1.108     paf      1207:                src.Copy(dest, dx, dy, sx, sy, sw, sh);
                   1208: }
                   1209: 
                   1210: static void _pixel(Request& r, MethodParams& params) {
                   1211:        gdImage& image=GET_SELF(r, VImage).image();
                   1212: 
1.109     paf      1213:        int x=params.as_int(0, "x must be int", r); 
                   1214:        int y=params.as_int(1, "y must be int", r);
                   1215: 
                   1216:        if(params.count()>2) {
                   1217:                image.SetPixel(x, y, 
                   1218:                        image.Color(params.as_int(2, "color must be int", r)));
                   1219:        } else 
                   1220:                r.write_no_lang(*new VInt(image.DecodeColor(image.GetPixel(x, y))));
1.53      parser   1221: }
                   1222: 
                   1223: 
1.22      paf      1224: // constructor
                   1225: 
1.91      paf      1226: MImage::MImage(): Methoded("image") {
1.1       paf      1227:        // ^image:measure[DATA]
1.22      paf      1228:        add_native_method("measure", Method::CT_DYNAMIC, _measure, 1, 1);
1.3       paf      1229: 
1.25      paf      1230:        // ^image.html[]
                   1231:        // ^image.html[hash]
1.22      paf      1232:        add_native_method("html", Method::CT_DYNAMIC, _html, 0, 1);
1.6       paf      1233: 
1.25      paf      1234:        // ^image.load[background.gif]
1.22      paf      1235:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 1);
1.6       paf      1236: 
1.25      paf      1237:        // ^image.create[width;height] bgcolor=white
                   1238:        // ^image.create[width;height;bgcolor]
1.22      paf      1239:        add_native_method("create", Method::CT_DYNAMIC, _create, 2, 3);
1.6       paf      1240: 
1.25      paf      1241:        // ^image.gif[]
1.95      paf      1242:        add_native_method("gif", Method::CT_DYNAMIC, _gif, 0, 1);
1.12      paf      1243: 
1.25      paf      1244:        // ^image.line(x0;y0;x1;y1;color)
1.22      paf      1245:        add_native_method("line", Method::CT_DYNAMIC, _line, 5, 5);
1.13      paf      1246: 
1.25      paf      1247:        // ^image.fill(x;y;color)
1.22      paf      1248:        add_native_method("fill", Method::CT_DYNAMIC, _fill, 3, 3);
1.13      paf      1249: 
1.25      paf      1250:        // ^image.rectangle(x0;y0;x1;y1;color)
1.22      paf      1251:        add_native_method("rectangle", Method::CT_DYNAMIC, _rectangle, 5, 5);
1.13      paf      1252: 
1.25      paf      1253:        // ^image.bar(x0;y0;x1;y1;color)
1.22      paf      1254:        add_native_method("bar", Method::CT_DYNAMIC, _bar, 5, 5);
1.13      paf      1255: 
1.44      parser   1256:        // ^image.replace(color-source;color-dest)[table x:y]
                   1257:        add_native_method("replace", Method::CT_DYNAMIC, _replace, 3, 3);
                   1258: 
                   1259:        // ^image.polyline(color)[table x:y]
                   1260:        add_native_method("polyline", Method::CT_DYNAMIC, _polyline, 2, 2);
1.13      paf      1261: 
1.44      parser   1262:        // ^image.polygon(color)[table x:y]
                   1263:        add_native_method("polygon", Method::CT_DYNAMIC, _polygon, 2, 2);
1.13      paf      1264: 
1.44      parser   1265:        // ^image.polybar(color)[table x:y]
                   1266:        add_native_method("polybar", Method::CT_DYNAMIC, _polybar, 2, 2);
1.13      paf      1267: 
1.36      parser   1268:     // ^image.font[alPHAbet;font-file-name.gif](spacebar_width)
                   1269:     // ^image.font[alPHAbet;font-file-name.gif](spacebar_width;width)
                   1270:        add_native_method("font", Method::CT_DYNAMIC, _font, 3, 4);
1.16      paf      1271: 
1.25      paf      1272:     // ^image.text(x;y)[text]
1.22      paf      1273:        add_native_method("text", Method::CT_DYNAMIC, _text, 3, 3);
1.47      parser   1274:        
                   1275:     // ^image.ngth[text]
                   1276:        add_native_method("length", Method::CT_DYNAMIC, _length, 1, 1);
1.16      paf      1277:        
1.48      parser   1278:        // ^image.arc(center x;center y;width;height;start in degrees;end in degrees;color)
                   1279:        add_native_method("arc", Method::CT_DYNAMIC, _arc, 7, 7);
1.49      parser   1280: 
                   1281:        // ^image.sector(center x;center y;width;height;start in degrees;end in degrees;color)
                   1282:        add_native_method("sector", Method::CT_DYNAMIC, _sector, 7, 7);
1.48      parser   1283: 
                   1284:        // ^image.circle(center x;center y;r;color)
                   1285:        add_native_method("circle", Method::CT_DYNAMIC, _circle, 4, 4);
                   1286: 
1.56      parser   1287:        // ^image.copy[source](src x;src y;src w;src h;dst x;dst y[;dest w[;dest h[;tolerance]]])
                   1288:        add_native_method("copy", Method::CT_DYNAMIC, _copy, 1+2+2+2, (1+2+2+2)+2+1);
1.108     paf      1289: 
                   1290:        // ^image.pixel(x;y)[(color)]
1.109     paf      1291:        add_native_method("pixel", Method::CT_DYNAMIC, _pixel, 2, 3);
1.1       paf      1292: }

E-mail: