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

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

E-mail: