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

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

E-mail: