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

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.147   ! moko       28: volatile const char * IDENT_IMAGE_C="$Id: image.C,v 1.146 2015/09/02 21:29:44 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.147   ! moko      462: tm cstr_to_time_t(char *, const char **);
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 {
1.147   ! moko      478:                                tm tmIn=cstr_to_time_t(cstr_writable, 0);
1.146     moko      479:                                return new VDate(tmIn);
1.106     paf       480:                        }
                    481:                        catch(...) { /*ignore bad date times*/ }
1.89      paf       482:                }
                    483: 
1.123     misha     484:                return new VString(*new String(cstr, String::L_TAINTED));
1.80      paf       485:        }
                    486: 
                    487:        if(components_count==1)
1.91      paf       488:                return parse_IFD_entry_formatted_one_value(is_big, format, component_size, value);
1.80      paf       489: 
1.91      paf       490:        VHash* result=new VHash;
                    491:        HashStringValue& hash=result->hash();
1.80      paf       492:        for(uint i=0; i<components_count; i++, value+=component_size) {
1.91      paf       493:                hash.put(
1.93      paf       494:                        String::Body::Format(i),
1.91      paf       495:                        parse_IFD_entry_formatted_one_value(is_big, format, component_size, value));
1.80      paf       496:        }
                    497: 
1.91      paf       498:        return result;
1.80      paf       499: }
                    500: 
1.91      paf       501: static Value* parse_IFD_entry_value(
1.80      paf       502:                                                                        bool is_big, Measure_reader& reader, long tiff_base,
                    503:                                                                        JPG_Exif_IFD_entry& entry) {
                    504:        size_t format2component_size[]={
                    505:                0, // undefined
                    506:                1, // unsigned byte
                    507:                1, // ascii string
                    508:                2, // unsigned short
                    509:                4, // unsigned long
                    510:                8, // unsigned rational
                    511:                1, // signed byte
                    512:                0, // undefined
                    513:                2, // signed short
                    514:                4, // signed long
                    515:                8, // signed rational
                    516:                /*
                    517:                4, // single float
                    518:                8, // double float
                    519:                */
                    520:        };
                    521: 
                    522:        ushort format=endian_to_ushort(is_big, entry.format);
                    523:        if(format>=sizeof(format2component_size)/sizeof(format2component_size[0]))
                    524:                return 0; // format out of range, ignoring
                    525: 
                    526:        size_t component_size=format2component_size[format];
                    527:        if(component_size==0)
                    528:                return 0; // undefined format
                    529: 
                    530:        // You can get the total data byte length by multiplies 
                    531:        // a 'bytes/components' value (see above chart) by number of components stored 'NNNNNNNN' area
                    532:        uint components_count=endian_to_uint(is_big, entry.components_count);
1.121     misha     533:        uint value_size=component_size*components_count;
1.80      paf       534:        // If its size is over 4bytes, 'DDDDDDDD' contains the offset to data stored address
1.91      paf       535:        Value* result;
1.80      paf       536: 
                    537:        if(value_size<=4)
1.91      paf       538:                result=parse_IFD_entry_formatted_value(
1.80      paf       539:                        is_big, format, 
                    540:                        component_size, components_count, 
                    541:                        entry.value_or_offset_to_it);
                    542:        else {
                    543:                long remembered=reader.tell();
                    544:                {
                    545:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.91      paf       546:                        const char* value;
1.80      paf       547:                        if(reader.read(value, value_size)<sizeof(value_size))
                    548:                                return 0;
1.91      paf       549:                        result=parse_IFD_entry_formatted_value(
1.80      paf       550:                                is_big, format, 
                    551:                                component_size, components_count, 
                    552:                                (const uchar*)value);
                    553:                }
                    554:                reader.seek(remembered, SEEK_SET);
                    555:        }
                    556: 
                    557:        return result;
                    558: }
                    559: 
1.91      paf       560: static void parse_IFD(HashStringValue& hash,
1.118     misha     561:                      bool is_big, Measure_reader& reader, long tiff_base, bool gps=false);
1.91      paf       562: 
                    563: static void parse_IFD_entry(HashStringValue& hash,
                    564:                            bool is_big, Measure_reader& reader, long tiff_base,
1.118     misha     565:                            JPG_Exif_IFD_entry& entry, bool gps=false) {
1.80      paf       566:        ushort tag=endian_to_ushort(is_big, entry.tag);
1.118     misha     567: 
                    568:        if(tag==JPG_IFD_TAG_EXIF_OFFSET || tag==JPG_IFD_TAG_EXIF_GPS_OFFSET){
1.80      paf       569:                long remembered=reader.tell();
                    570:                {
                    571:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it), SEEK_SET);
1.118     misha     572:                        parse_IFD(hash, is_big, reader, tiff_base, (tag==JPG_IFD_TAG_EXIF_GPS_OFFSET)?true:gps);
1.80      paf       573:                }
                    574:                reader.seek(remembered, SEEK_SET);
                    575:                return;
                    576:        }
1.118     misha     577: 
1.91      paf       578:        if(Value* value=parse_IFD_entry_value(is_big, reader, tiff_base, entry)) {
1.118     misha     579:                if(const char* name=(gps)?exif_gps_tag_value2name.get(tag):exif_tag_value2name.get(tag))
1.93      paf       580:                        hash.put(String::Body(name), value);
1.80      paf       581:                else
1.93      paf       582:                        hash.put(String::Body::Format(tag), value);
1.80      paf       583:        }
1.1       paf       584: }
                    585: 
1.91      paf       586: static void parse_IFD(
                    587:                      HashStringValue& hash,
1.118     misha     588:                      bool is_big, Measure_reader& reader, long tiff_base, bool gps) {
1.91      paf       589:        const char* buf;
                    590:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
1.80      paf       591:                return;
1.91      paf       592:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
1.80      paf       593: 
                    594:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    595:        for(int i=0; i<directory_entry_count; i++) {
                    596:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    597:                        return;
                    598: 
1.118     misha     599:                parse_IFD_entry(hash, is_big, reader, tiff_base, *(JPG_Exif_IFD_entry *)buf, gps);
1.80      paf       600:        }
                    601:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    602: }
                    603: 
1.91      paf       604: static Value* parse_exif(Measure_reader& reader, const String& origin_string) {
                    605:        const char* buf;
                    606:        if(reader.read(buf, sizeof(JPG_Exif_segment_begin))<sizeof(JPG_Exif_segment_begin))
1.118     misha     607:                throw Exception(IMAGE_FORMAT, 
1.91      paf       608:                        &origin_string, 
1.80      paf       609:                        "not JPEG file - can not fully read Exif segment start");
                    610: 
1.91      paf       611:        JPG_Exif_segment_begin *start=(JPG_Exif_segment_begin *)buf;
1.80      paf       612:        if(memcmp(start->signature, "Exif\0\0", 4+2)!=0) //signature invalid?
                    613:                return 0; // ignore invalid block
                    614: 
                    615:        uint tiff_base=reader.tell();
                    616:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    617:                return 0;
                    618: 
                    619:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    620:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    621: 
                    622:        uint first_IFD_offset=endian_to_uint(is_big, head->first_IFD_offset);
                    623:        reader.seek(tiff_base+first_IFD_offset, SEEK_SET);
                    624: 
1.91      paf       625:        VHash* vhash=new VHash;
1.80      paf       626: 
                    627:        // IFD
1.91      paf       628:        parse_IFD(vhash->hash(), is_big, reader, tiff_base);
1.80      paf       629: 
1.91      paf       630:        return vhash;
1.80      paf       631: }
                    632: 
1.91      paf       633: static void measure_jpeg(const String& origin_string, 
                    634:                         Measure_reader& reader, ushort& width, ushort& height, Value** exif) {
1.2       paf       635:        // JFIF format markers
1.80      paf       636:        const uchar MARKER=0xFF;
                    637:        const uchar CODE_SIZE_A=0xC0;
                    638:        const uchar CODE_SIZE_B=0xC1;
                    639:        const uchar CODE_SIZE_C=0xC2;
                    640:        const uchar CODE_SIZE_D=0xC3;
                    641:        const uchar CODE_EXIF=0xE1;
1.2       paf       642: 
1.91      paf       643:        const char* buf;
1.18      paf       644:        const size_t prefix_size=2;
1.31      parser    645:        if(reader.read(buf, prefix_size)<prefix_size)
1.118     misha     646:                throw Exception(IMAGE_FORMAT, 
1.91      paf       647:                        &origin_string, 
1.34      parser    648:                        "not JPEG file - too small");
1.80      paf       649:        uchar *signature=(uchar *)buf;
1.1       paf       650:        
1.31      parser    651:        if(!(signature[0]==0xFF && signature[1]==0xD8)) 
1.118     misha     652:                throw Exception(IMAGE_FORMAT, 
1.91      paf       653:                        &origin_string, 
1.44      parser    654:                        "not JPEG file - wrong signature");
1.31      parser    655: 
                    656:        while(true) {
1.80      paf       657:                uint segment_base=reader.tell()+2/*marker,code*/;
1.31      parser    658:                if(reader.read(buf, sizeof(JPG_Segment_head))<sizeof(JPG_Segment_head))
1.79      paf       659:                        break;
1.31      parser    660:                JPG_Segment_head *head=(JPG_Segment_head *)buf;
                    661: 
                    662:         // Verify that it's a valid segment.
                    663:                if(head->marker!=MARKER)
1.118     misha     664:                        throw Exception(IMAGE_FORMAT, 
1.91      paf       665:                                &origin_string, 
1.79      paf       666:                                "not JPEG file - marker not found");
                    667: 
                    668:                switch(head->code) {
1.118     misha     669:                // http://park2.wakwak.com/~tsuruzoh/Computer/Digicams/exif-e.html
1.79      paf       670:                case CODE_EXIF:
1.80      paf       671:                        if(exif && !*exif) // seen .jpg with some xml under EXIF tag, after real exif block :)
1.91      paf       672:                                *exif=parse_exif(reader, origin_string);
1.1       paf       673:                        break;
1.31      parser    674: 
1.79      paf       675:                case CODE_SIZE_A:
                    676:                case CODE_SIZE_B:
                    677:                case CODE_SIZE_C:
                    678:                case CODE_SIZE_D:
                    679:                        {
                    680:                                // Segments that contain size info
                    681:                                if(reader.read(buf, sizeof(JPG_Size_segment_body))<sizeof(JPG_Size_segment_body))
1.118     misha     682:                                        throw Exception(IMAGE_FORMAT, 
1.91      paf       683:                                                &origin_string, 
1.79      paf       684:                                                "not JPEG file - can not fully read Size segment");
                    685:                                JPG_Size_segment_body *body=(JPG_Size_segment_body *)buf;
                    686:                                
1.80      paf       687:                                width=endian_to_ushort(true, body->width);
                    688:                                height=endian_to_ushort(true, body->height);
1.79      paf       689:                        }                       
1.80      paf       690:                        return;
1.79      paf       691:                };
                    692: 
1.80      paf       693:                reader.seek(segment_base+endian_to_ushort(true, head->length), SEEK_SET);
1.31      parser    694:        }
                    695: 
1.118     misha     696:        throw Exception(IMAGE_FORMAT, 
1.91      paf       697:                &origin_string, 
1.79      paf       698:                "broken JPEG file - size frame not found");
1.1       paf       699: }
                    700: 
1.91      paf       701: static void measure_png(const String& origin_string, 
1.78      paf       702:                         Measure_reader& reader, ushort& width, ushort& height) {
1.72      paf       703: 
1.91      paf       704:        const char* buf;
1.102     paf       705:        const size_t head_size=sizeof(PNG_Header);
                    706:        if(reader.read(buf, head_size)<head_size)
1.118     misha     707:                throw Exception(IMAGE_FORMAT, 
1.91      paf       708:                        &origin_string, 
1.72      paf       709:                        "not PNG file - too small");
                    710:        PNG_Header *head=(PNG_Header *)buf;
                    711: 
                    712:        if(strncmp(head->signature, "IHDR", 4)!=0)
1.118     misha     713:                throw Exception(IMAGE_FORMAT, 
1.91      paf       714:                        &origin_string, 
1.72      paf       715:                        "not PNG file - wrong signature");      
                    716: 
1.80      paf       717:        width=endian_to_ushort(true, head->width);
                    718:        height=endian_to_ushort(true, head->height);
1.72      paf       719: }
                    720: 
1.1       paf       721: // measure center
                    722: 
1.91      paf       723: static void measure(const String& file_name, 
                    724:                         Measure_reader& reader, ushort& width, ushort& height, Value** exif) {
1.128     misha     725:        const char* file_name_cstr=file_name.taint_cstr(String::L_FILE_SPEC);
1.91      paf       726:        if(const char* cext=strrchr(file_name_cstr, '.')) {
1.1       paf       727:                cext++;
                    728:                if(strcasecmp(cext, "GIF")==0)
1.91      paf       729:                        measure_gif(file_name, reader, width, height);
1.1       paf       730:                else if(strcasecmp(cext, "JPG")==0 || strcasecmp(cext, "JPEG")==0) 
1.91      paf       731:                        measure_jpeg(file_name, reader, width, height, exif);
1.72      paf       732:                else if(strcasecmp(cext, "PNG")==0)
1.91      paf       733:                        measure_png(file_name, reader, width, height);
1.1       paf       734:                else
1.118     misha     735:                        throw Exception(IMAGE_FORMAT, 
1.1       paf       736:                                &file_name, 
                    737:                                "unhandled image file name extension '%s'", cext);
                    738:        } else
1.118     misha     739:                throw Exception(IMAGE_FORMAT, 
1.1       paf       740:                        &file_name, 
                    741:                        "can not determine image type - no file name extension");
                    742: }
                    743: 
1.77      paf       744: // methods
1.1       paf       745: 
1.40      parser    746: #ifndef DOXYGEN
1.77      paf       747: struct File_measure_action_info {
1.91      paf       748:        ushort* width;
                    749:        ushort* height;
                    750:        Value** exif;
                    751:        const String* file_name;
1.1       paf       752: };
1.40      parser    753: #endif
1.91      paf       754: static void file_measure_action(
1.98      paf       755:                                                                struct stat& /*finfo*/, int f, 
                    756:                                                                const String& /*file_spec*/, const char* fname, bool /*as_text*/,
1.77      paf       757:                                                                void *context) {
                    758:        File_measure_action_info& info=*static_cast<File_measure_action_info *>(context);
1.1       paf       759: 
1.91      paf       760:        Measure_file_reader reader(f, *info.file_name, fname);
                    761:        measure(*info.file_name, reader, *info.width, *info.height, info.exif);
1.1       paf       762: }
                    763: 
1.91      paf       764: static void _measure(Request& r, MethodParams& params) {
                    765:        Value& data=params.as_no_junction(0, "data must not be code");
1.1       paf       766: 
1.78      paf       767:        ushort width=0;
                    768:        ushort height=0;
1.91      paf       769:        Value* exif=0;
                    770:        const String* file_name;
1.100     paf       771:        if((file_name=data.get_string())) {
                    772:                File_measure_action_info info={
                    773:                        &width, &height,
                    774:                        &exif,
                    775:                        file_name
                    776:                };
1.91      paf       777:                file_read_action_under_lock(r.absolute(*file_name), 
1.77      paf       778:                        "measure", file_measure_action, &info);
1.1       paf       779:        } else {
1.129     misha     780:                VFile* vfile=data.as_vfile(String::L_AS_IS);
1.91      paf       781:                file_name=&vfile->fields().get(name_name)->as_string();
1.77      paf       782:                Measure_buf_reader reader(
1.91      paf       783:                        vfile->value_ptr(),
                    784:                        vfile->value_size(),
1.77      paf       785:                        *file_name
                    786:                );
1.91      paf       787:                measure(*file_name, reader, width, height, &exif);
1.1       paf       788:        }
                    789: 
1.91      paf       790:        GET_SELF(r, VImage).set(file_name, width, height, 0, exif);
1.1       paf       791: }
                    792: 
1.40      parser    793: #ifndef DOXYGEN
1.4       paf       794: struct Attrib_info {
1.91      paf       795:        String* tag; ///< html tag being constructed
                    796:        HashStringValue* skip; ///< tag attributes not to append to tag string [to skip]
1.4       paf       797: };
1.40      parser    798: #endif
1.91      paf       799: static void append_attrib_pair(
1.133     misha     800:                                HashStringValue::key_type key, 
                    801:                                HashStringValue::value_type value, 
                    802:                                Attrib_info* info) {
                    803:        // skip user-specified, internal(starting with "line-") attributes and border attribute with empty value
                    804:        if(
                    805:                (info->skip && info->skip->get(key))
                    806:                || key.pos("line-")==0
                    807:                || (key=="border" && !value->is_defined())
                    808:        )
1.4       paf       809:                return;
                    810: 
1.133     misha     811:        // src="a.gif" width="123" ismap[=-1]
1.91      paf       812:        *info->tag << " " << key;
                    813:        if(value->is_string() || value->as_int()>=0)
                    814:                *info->tag << "=\"" << value->as_string() << "\"";
1.3       paf       815: }
1.91      paf       816: static void _html(Request& r, MethodParams& params) {
1.3       paf       817: 
1.91      paf       818:        String tag;
1.3       paf       819:        tag << "<img";
1.4       paf       820: 
1.91      paf       821:        const HashStringValue& fields=GET_SELF(r, VImage).fields();
                    822:        HashStringValue* attribs=0;
1.4       paf       823: 
1.91      paf       824:        if(params.count()) {
1.69      paf       825:                // for backward compatibility: someday was ^html{}
1.133     misha     826:                Value& vattribs=r.process_to_value(params[0], false/*don't intercept string*/);
1.145     moko      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");
1.145     moko      835:                }
1.39      parser    836:        }
1.4       paf       837: 
1.91      paf       838:        {
                    839:                Attrib_info info={&tag, attribs};
1.114     paf       840:                fields.for_each<Attrib_info*>(append_attrib_pair, &info);
1.91      paf       841:        }
1.6       paf       842:        tag << " />";
1.3       paf       843:        r.write_pass_lang(tag);
                    844: }
1.8       paf       845: 
1.68      paf       846: /// @test wrap FILE to auto-object
1.91      paf       847: static gdImage* load(Request& r, 
1.16      paf       848:                                         const String& file_name){
1.128     misha     849:        const char* file_name_cstr=r.absolute(file_name).taint_cstr(String::L_FILE_SPEC);
1.16      paf       850:        if(FILE *f=fopen(file_name_cstr, "rb")) {
1.91      paf       851:                gdImage* image=new gdImage;
                    852:                bool ok=image->CreateFromGif(f);
1.16      paf       853:                fclose(f);
1.23      paf       854:                if(!ok)
1.118     misha     855:                        throw Exception(IMAGE_FORMAT, 
1.23      paf       856:                                &file_name,
                    857:                                "is not in GIF format");
1.91      paf       858:                return image;
1.16      paf       859:        } else {
1.68      paf       860:                throw Exception("file.missing", 
1.91      paf       861:                        0, 
1.16      paf       862:                        "can not open '%s'", file_name_cstr);
                    863:        }
                    864: }
                    865: 
                    866: 
1.91      paf       867: static void _load(Request& r, MethodParams& params) {
1.116     misha     868:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.6       paf       869: 
1.91      paf       870:        gdImage* image=load(r, file_name);
                    871:        GET_SELF(r, VImage).set(&file_name, image->SX(), image->SY(), image);
1.6       paf       872: }
                    873: 
1.91      paf       874: static void _create(Request& r, MethodParams& params) {
                    875:        int width=params.as_int(0, "width must be int", r);
                    876:        int height=params.as_int(1, "height must be int", r);
1.8       paf       877:        int bgcolor_value=0xffFFff;
1.91      paf       878:        if(params.count()>2)
                    879:                bgcolor_value=params.as_int(2, "color must be int", r);
                    880:        gdImage* image=new gdImage;
                    881:        image->Create(width, height);
                    882:        image->FilledRectangle(0, 0, width-1, height-1, image->Color(bgcolor_value));
                    883:        GET_SELF(r, VImage).set(0, width, height, image);
1.6       paf       884: }
                    885: 
1.91      paf       886: static void _gif(Request& r, MethodParams& params) {
1.108     paf       887:        gdImage& image=GET_SELF(r, VImage).image();
1.6       paf       888: 
1.138     misha     889:        const String *file_name=params.count()>0?&params.as_string(0, FILE_NAME_MUST_BE_STRING):0;
1.10      paf       890: 
1.108     paf       891:        gdBuf buf=image.Gif();
1.6       paf       892:        
1.91      paf       893:        VFile& vfile=*new VFile;
1.137     misha     894: 
1.142     moko      895:        vfile.set_binary(false/*not tainted*/, (const char *)buf.ptr, buf.size, file_name, new VString(*new String("image/gif")));
1.137     misha     896: 
1.6       paf       897:        r.write_no_lang(vfile);
                    898: }
                    899: 
1.91      paf       900: static void _line(Request& r, MethodParams& params) {
1.108     paf       901:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       902: 
1.108     paf       903:        image.Line(
1.91      paf       904:                params.as_int(0, "x0 must be int", r), 
                    905:                params.as_int(1, "y0 must be int", r), 
                    906:                params.as_int(2, "x1 must be int", r), 
                    907:                params.as_int(3, "y1 must be int", r), 
1.108     paf       908:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       909: }
                    910: 
1.91      paf       911: static void _fill(Request& r, MethodParams& params) {
1.108     paf       912:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf       913: 
1.108     paf       914:        image.Fill(
1.91      paf       915:                params.as_int(0, "x must be int", r), 
                    916:                params.as_int(1, "y must be int", r), 
1.108     paf       917:                image.Color(params.as_int(2, "color must be int", r)));
1.13      paf       918: }
                    919: 
1.91      paf       920: static void _rectangle(Request& r, MethodParams& params) {
1.108     paf       921:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       922: 
1.108     paf       923:        image.Rectangle(
1.91      paf       924:                params.as_int(0, "x0 must be int", r), 
                    925:                params.as_int(1, "y0 must be int", r), 
                    926:                params.as_int(2, "x1 must be int", r), 
                    927:                params.as_int(3, "y1 must be int", r), 
1.108     paf       928:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       929: }
                    930: 
1.91      paf       931: static void _bar(Request& r, MethodParams& params) {
1.108     paf       932:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       933: 
1.108     paf       934:        image.FilledRectangle(
1.91      paf       935:                params.as_int(0, "x0 must be int", r), 
                    936:                params.as_int(1, "y0 must be int", r), 
                    937:                params.as_int(2, "x1 must be int", r), 
                    938:                params.as_int(3, "y1 must be int", r), 
1.108     paf       939:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf       940: }
                    941: 
1.44      parser    942: #ifndef DOXYGEN
1.91      paf       943: static void add_point(Table::element_type row, 
                    944:                                          gdImage::Point **p) {
1.110     paf       945:        if(row->count()!=2)
                    946:                throw Exception(0,
                    947:                        0,
                    948:                        "coordinates table must contain two columns: x and y values");
1.91      paf       949:        (**p).x=row->get(0)->as_int();
                    950:        (**p).y=row->get(1)->as_int();
1.44      parser    951:        (*p)++;
                    952: }
                    953: #endif
1.135     misha     954: #ifndef DOXYGEN
                    955: static void add_point(int x, int y, 
                    956:                                          gdImage::Point **p) {
                    957:        (**p).x=x;
                    958:        (**p).y=y;
                    959:        (*p)++;
                    960: }
                    961: #endif
1.91      paf       962: static void _replace(Request& r, MethodParams& params) {
1.135     misha     963:        int src_color=params.as_int(0, "src color must be int", r);
                    964:        int dest_color=params.as_int(1, "dest color must be int", r);
                    965: 
1.108     paf       966:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       967: 
1.135     misha     968:        gdImage::Point* all_p=0;
                    969:        size_t count=0;
                    970:        if(params.count() == 3){
1.140     misha     971:                Table* table=params.as_table(2, "coordinates");
1.135     misha     972:                count=table->count();
                    973:                all_p=new(PointerFreeGC) gdImage::Point[count];
                    974:                gdImage::Point* add_p=all_p;
                    975:                table->for_each(add_point, &add_p);
                    976:        } else {
                    977:                int max_x=image.SX()-1;
                    978:                int max_y=image.SY()-1;
                    979:                if(max_x > 0 && max_y > 0){
                    980:                        count=4;
                    981:                        all_p=new(PointerFreeGC) gdImage::Point[count];
                    982:                        gdImage::Point* add_p=all_p;
                    983:                        add_point(0, 0, &add_p);
                    984:                        add_point(max_x, 0, &add_p);
                    985:                        add_point(max_x, max_y, &add_p);
                    986:                        add_point(0, max_y, &add_p);
                    987:                }
                    988:        }
1.13      paf       989: 
1.135     misha     990:        if(count)
                    991:                image.FilledPolygonReplaceColor(all_p, count, image.Color(src_color), image.Color(dest_color));
1.13      paf       992: }
                    993: 
1.91      paf       994: static void _polyline(Request& r, MethodParams& params) {
1.108     paf       995:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf       996: 
1.140     misha     997:        Table* table=params.as_table(1, "coordinates");
1.44      parser    998: 
1.92      paf       999:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1000:        gdImage::Point *add_p=all_p;    
                   1001:        table->for_each(add_point, &add_p);
1.108     paf      1002:        image.Polygon(all_p, table->count(), 
                   1003:                image.Color(params.as_int(0, "color must be int", r)),
1.44      parser   1004:                false/*not closed*/);
                   1005: }
                   1006: 
1.91      paf      1007: static void _polygon(Request& r, MethodParams& params) {
1.108     paf      1008:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1009: 
1.140     misha    1010:        Table* table=(Table*)params.as_table(1, "coordinates");
1.44      parser   1011: 
1.92      paf      1012:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1013:        gdImage::Point *add_p=all_p;    
                   1014:        table->for_each(add_point, &add_p);
1.108     paf      1015:        image.Polygon(all_p, table->count(), 
                   1016:                image.Color(params.as_int(0, "color must be int", r)));
1.13      paf      1017: }
                   1018: 
1.91      paf      1019: static void _polybar(Request& r, MethodParams& params) {
1.108     paf      1020:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1021: 
1.140     misha    1022:        Table* table=(Table*)params.as_table(1, "coordinates");
1.13      paf      1023: 
1.92      paf      1024:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1025:        gdImage::Point *add_p=all_p;    
                   1026:        table->for_each(add_point, &add_p);
1.108     paf      1027:        image.FilledPolygon(all_p, table->count(), 
                   1028:                image.Color(params.as_int(0, "color must be int", r)));
1.12      paf      1029: }
                   1030: 
1.16      paf      1031: // font
                   1032: 
1.85      paf      1033: #define Y(y)(y+index*height)
1.21      paf      1034: 
1.91      paf      1035: // Font class
                   1036: 
1.132     misha    1037: Font::Font(
                   1038:        Charset& asource_charset, 
1.91      paf      1039:        const String& aalphabet, 
1.125     misha    1040:        gdImage* aifont, int aheight, int amonospace, int aspacebarspace, int aletterspacing):
1.132     misha    1041:        fsource_charset(asource_charset),
                   1042:        height(aheight),
                   1043:        monospace(amonospace),
                   1044:        spacebarspace(aspacebarspace),
1.125     misha    1045:        letterspacing(aletterspacing),
1.100     paf      1046:        ifont(aifont),
                   1047:        alphabet(aalphabet)     {
1.132     misha    1048: 
                   1049:        if(fsource_charset.isUTF8()){
                   1050:                size_t index=0;
                   1051:                for(UTF8_string_iterator i(alphabet); i.has_next(); )
                   1052:                        fletter2index.put_dont_replace(i.next(), index++);
                   1053:        }
1.91      paf      1054: }
                   1055: 
                   1056: /* ******************************** char ********************************** */
                   1057: 
                   1058: size_t Font::index_of(char ch) {
                   1059:        if(ch==' ') return STRING_NOT_FOUND;
                   1060:        return alphabet.pos(ch);
                   1061: }
                   1062: 
1.132     misha    1063: size_t Font::index_of(XMLCh ch) {
                   1064:        if(ch==' ') return STRING_NOT_FOUND;
                   1065:        return fletter2index.get(ch);
                   1066: }
                   1067: 
1.91      paf      1068: int Font::index_width(size_t index) {
                   1069:        if(index==STRING_NOT_FOUND)
                   1070:                return spacebarspace;
                   1071:        int tr=ifont->GetTransparent();
                   1072:        for(int x=ifont->SX()-1; x>=0; x--) {
                   1073:                for(int y=0; y<height; y++)
                   1074:                        if(ifont->GetPixel(x, Y(y))!=tr) 
                   1075:                                return x+1;
1.16      paf      1076:        }
1.91      paf      1077:        return 0;
                   1078: }
                   1079: 
1.108     paf      1080: void Font::index_display(gdImage& image, int x, int y, size_t index){
1.91      paf      1081:        if(index!=STRING_NOT_FOUND) 
1.108     paf      1082:                ifont->Copy(image, x, y, 0, Y(0), index_width(index), height);
1.91      paf      1083: }
                   1084: 
                   1085: /* ******************************** string ********************************** */
                   1086: 
                   1087: int Font::step_width(int index) {
1.125     misha    1088:        return letterspacing + (monospace ? monospace : index_width(index));
1.91      paf      1089: }
                   1090: 
                   1091: // counts trailing letter_spacing, consider this OK. useful for contiuations
                   1092: int Font::string_width(const String& s){
                   1093:        const char* cstr=s.cstr();
                   1094:        int result=0;
1.132     misha    1095: 
                   1096:        if(fsource_charset.isUTF8()){
                   1097:                for(UTF8_string_iterator i(s); i.has_next(); )
                   1098:                        result+=step_width(index_of(i.next()));
                   1099:        } else {
                   1100:                for(const char* current=cstr; *current; current++)
                   1101:                        result+=step_width(index_of(*current));
                   1102:        }
                   1103: 
1.91      paf      1104:        return result;
                   1105: }
                   1106: 
1.108     paf      1107: void Font::string_display(gdImage& image, int x, int y, const String& s){
1.91      paf      1108:        const char* cstr=s.cstr();
1.132     misha    1109: 
                   1110:        if(fsource_charset.isUTF8()){
                   1111:                for(UTF8_string_iterator i(s); i.has_next(); ){
                   1112:                        size_t index=index_of(i.next());
                   1113:                        index_display(image, x, y, index);
                   1114:                        x+=step_width(index);
                   1115:                }
                   1116:        } else {
                   1117:                for(const char* current=cstr; *current; current++) {
                   1118:                        size_t index=index_of(*current);
                   1119:                        index_display(image, x, y, index);
                   1120:                        x+=step_width(index);
                   1121:                }
1.87      paf      1122:        }
1.91      paf      1123: }
1.87      paf      1124: 
1.91      paf      1125: //
1.35      parser   1126: 
1.16      paf      1127: 
1.91      paf      1128: static void _font(Request& r, MethodParams& params) {
                   1129:        const String& alphabet=params.as_string(0, "alphabet must not be code");
1.131     misha    1130:        size_t alphabet_length=alphabet.length(r.charsets.source());
                   1131:        if(!alphabet_length)
1.115     misha    1132:                throw Exception(PARSER_RUNTIME,
1.91      paf      1133:                        0,
1.37      parser   1134:                        "alphabet must not be empty");
1.84      paf      1135: 
1.125     misha    1136:        gdImage* image=load(r, params.as_string(1, FILE_NAME_MUST_NOT_BE_CODE));
                   1137: 
1.126     misha    1138:        int spacebar_width=image->SX();
1.125     misha    1139:        int monospace_width=0; // proportional
                   1140:        int letter_spacing=1;
                   1141:        if(params.count()>2){
1.144     moko     1142:                if(HashStringValue* options=params[2].get_hash()){
1.125     misha    1143:                        // third option is hash
                   1144:                        if(params.count()>3)
1.144     moko     1145:                                throw Exception(PARSER_RUNTIME, 0, "too many params were specified");
1.125     misha    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
1.144     moko     1165:                        spacebar_width=params.as_int(2, "param must be int or hash", r);
1.125     misha    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: