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

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

E-mail: