bool SkPNGImageDecoder::onDecode(SkStream* sk_stream, SkBitmap* decodedBitmap,
                                 Mode mode) {
    png_structp png_ptr;
    png_infop info_ptr;

    if (onDecodeInit(sk_stream, &png_ptr, &info_ptr) == false) {
        return false;
    }

    if (setjmp(png_jmpbuf(png_ptr))) {
        return false;
    }

    PNGAutoClean autoClean(png_ptr, info_ptr);

    png_uint_32 origWidth, origHeight;
    int bit_depth, color_type, interlace_type;
    png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bit_depth,
            &color_type, &interlace_type, int_p_NULL, int_p_NULL);

    SkBitmap::Config    config;
    bool                hasAlpha = false;
    bool                doDither = this->getDitherImage();
    SkPMColor           theTranspColor = 0; // 0 tells us not to try to match

    if (getBitmapConfig(png_ptr, info_ptr, &config, &hasAlpha,
                &doDither, &theTranspColor) == false) {
        return false;
    }

    const int sampleSize = this->getSampleSize();
    SkScaledBitmapSampler sampler(origWidth, origHeight, sampleSize);

    decodedBitmap->setConfig(config, sampler.scaledWidth(),
                             sampler.scaledHeight(), 0);
    if (SkImageDecoder::kDecodeBounds_Mode == mode) {
        return true;
    }

    // from here down we are concerned with colortables and pixels

    // we track if we actually see a non-opaque pixels, since sometimes a PNG sets its colortype
    // to |= PNG_COLOR_MASK_ALPHA, but all of its pixels are in fact opaque. We care, since we
    // draw lots faster if we can flag the bitmap has being opaque
    bool reallyHasAlpha = false;
    SkColorTable* colorTable = NULL;

    if (color_type == PNG_COLOR_TYPE_PALETTE) {
        decodePalette(png_ptr, info_ptr, &hasAlpha,
                &reallyHasAlpha, &colorTable);
    }

    SkAutoUnref aur(colorTable);

    if (!this->allocPixelRef(decodedBitmap,
                             SkBitmap::kIndex8_Config == config ?
                                colorTable : NULL)) {
        return false;
    }

    SkAutoLockPixels alp(*decodedBitmap);

    /* Add filler (or alpha) byte (before/after each RGB triplet) */
    if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY) {
        png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
    }

    /* Turn on interlace handling.  REQUIRED if you are not using
    * png_read_image().  To see how to handle interlacing passes,
    * see the png_read_row() method below:
    */
    const int number_passes = interlace_type != PNG_INTERLACE_NONE ?
                        png_set_interlace_handling(png_ptr) : 1;

    /* Optional call to gamma correct and add the background to the palette
    * and update info structure.  REQUIRED if you are expecting libpng to
    * update the palette for you (ie you selected such a transform above).
    */
    png_read_update_info(png_ptr, info_ptr);

    if (SkBitmap::kIndex8_Config == config && 1 == sampleSize) {
        for (int i = 0; i < number_passes; i++) {
            for (png_uint_32 y = 0; y < origHeight; y++) {
                uint8_t* bmRow = decodedBitmap->getAddr8(0, y);
                png_read_rows(png_ptr, &bmRow, png_bytepp_NULL, 1);
            }
        }
    } else {
        SkScaledBitmapSampler::SrcConfig sc;
        int srcBytesPerPixel = 4;

        if (colorTable != NULL) {
            sc = SkScaledBitmapSampler::kIndex;
            srcBytesPerPixel = 1;
        } else if (hasAlpha) {
            sc = SkScaledBitmapSampler::kRGBA;
        } else {
            sc = SkScaledBitmapSampler::kRGBX;
        }

        /*  We have to pass the colortable explicitly, since we may have one
            even if our decodedBitmap doesn't, due to the request that we
            upscale png's palette to a direct model
         */
        SkAutoLockColors ctLock(colorTable);
        if (!sampler.begin(decodedBitmap, sc, doDither, ctLock.colors())) {
            return false;
        }
        const int height = decodedBitmap->height();

        if (number_passes > 1) {
            SkAutoMalloc storage(origWidth * origHeight * srcBytesPerPixel);
            uint8_t* base = (uint8_t*)storage.get();
            size_t rb = origWidth * srcBytesPerPixel;

            for (int i = 0; i < number_passes; i++) {
                uint8_t* row = base;
                for (png_uint_32 y = 0; y < origHeight; y++) {
                    uint8_t* bmRow = row;
                    png_read_rows(png_ptr, &bmRow, png_bytepp_NULL, 1);
                    row += rb;
                }
            }
            // now sample it
            base += sampler.srcY0() * rb;
            for (int y = 0; y < height; y++) {
                reallyHasAlpha |= sampler.next(base);
                base += sampler.srcDY() * rb;
            }
        } else {
            SkAutoMalloc storage(origWidth * srcBytesPerPixel);
            uint8_t* srcRow = (uint8_t*)storage.get();
            skip_src_rows(png_ptr, srcRow, sampler.srcY0());

            for (int y = 0; y < height; y++) {
                uint8_t* tmp = srcRow;
                png_read_rows(png_ptr, &tmp, png_bytepp_NULL, 1);
                reallyHasAlpha |= sampler.next(srcRow);
                if (y < height - 1) {
                    skip_src_rows(png_ptr, srcRow, sampler.srcDY() - 1);
                }
            }

            // skip the rest of the rows (if any)
            png_uint_32 read = (height - 1) * sampler.srcDY() +
                               sampler.srcY0() + 1;
            SkASSERT(read <= origHeight);
            skip_src_rows(png_ptr, srcRow, origHeight - read);
        }
    }

    /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
    png_read_end(png_ptr, info_ptr);

    if (0 != theTranspColor) {
        reallyHasAlpha |= substituteTranspColor(decodedBitmap, theTranspColor);
    }
    decodedBitmap->setIsOpaque(!reallyHasAlpha);
    return true;
}
Ejemplo n.º 2
0
MetaData::typed_data::typed_data(const typed_data &from)
    : mType(from.mType),
      mSize(0) {
    allocateStorage(from.mSize);
    memcpy(storage(), from.storage(), mSize);
}
Ejemplo n.º 3
0
void OrthoBuilder::LUsolve( vector<vector<PL_NUM>>& AA, vector<PL_NUM>& ff, vector<PL_NUM>* xx )
{
	if( AA.size() < 1 )
	{
		cout << "ERROR in LUsolve: AA.size() is less than 1\n";
		return;
	}
	int AAsize = AA.size();

	vector<PL_NUM> storage( AAsize, 0.0 );
	PL_NUM tmpNum = 0;

	int nzRow = 0;
	if( fabs( AA[0][0] ) < ALMOST_ZERO )		//TODO may be I can join this and the next block. I mean the checks on AA[i][j] != 0
	{
		//make AA[0][0] nonzero by changing the order of rows 
		int nzFound = false;
		for( nzRow; nzRow < AAsize; ++nzRow )
		{
			if( fabs( AA[nzRow][0] ) > ALMOST_ZERO )			//CHECK, may be it is better to put != 0 here
			{
				nzFound = true;
				break;
			}
		}
		if( nzFound == false )
		{
			cout << "ERROR in LUsolve: no nonzero elements found\n";
			return;
		}

		for( int col = 0; col < AAsize; ++col )
		{
			storage[col] = AA[nzRow][col];
			AA[nzRow][col] = AA[0][col];
			AA[0][col] = storage[col];
		}
		tmpNum = ff[nzRow];
		ff[nzRow] = ff[0];
		ff[0] = tmpNum;
	}
	for( int i = 0; i < AAsize; ++i )
	{
		if( fabs( AA[i][i] ) < ALMOST_ZERO )				//TODO may be there should be fabs( ) < DELTA?
		{
			for( int row = i + 1; row < AAsize; ++row )
			{
				if( fabs( AA[row][i] ) > ALMOST_ZERO )			//TODO may be there should be fabs( ) > DELTA?
				{
					for( int col = 0; col < AAsize; ++col )
					{
						storage[col] = AA[row][col];			//TODO may be we don't need a whole vector here, just single number. (I mean storage)
						AA[row][col] = AA[i][col];
						AA[i][col] = storage[col];
					}
					tmpNum = ff[row];
					ff[row] = ff[i];
					ff[i] = tmpNum;
					break;
				}
			}
		}
	}

	for( int i = 0; i < AAsize; ++i )
	{
		if( fabs( AA[i][i] ) < ALMOST_ZERO )
		{
			cout << "alert! UFO detected!\n";
		}
	}

	vector<vector<PL_NUM>> LL( AAsize, vector<PL_NUM>( AAsize, 0.0 ) );			//TODO here we can use less memory, UU and LL are trialgular
	vector<vector<PL_NUM>> UU( AAsize, vector<PL_NUM>( AAsize, 0.0 ) );			//TODO initialization of arrays is slow

	//Crout's algorithm, theory is in book: Kincaid, Cheney - Numerical analysis: mathematics of scientific computing
	for( int k = 0; k < AAsize; ++k )
	{
		UU[k][k] = 1;
		for( int i = k; i < AAsize; ++i )
		{
			LL[i][k] = AA[i][k];
			for( int s = 0; s <= k - 1; ++s )
			{
				LL[i][k] -= LL[i][s] * UU[s][k];
			}
		}
		for( int j = k + 1; j < AAsize; ++j )
		{
			UU[k][j] = AA[k][j];
			for( int s = 0; s <= k - 1; ++s )
			{
				UU[k][j] -= LL[k][s] * UU[s][j];
			}
			UU[k][j] /= LL[k][k];
		}
	}

	//now we can find xx, by solving LL * zz = ff and then UU * x = zz; for theory look at the same book as for LU decomposition
	for( int i = 0; i < AAsize; ++i )
	{
		(*xx)[i] = ff[i];
		for( int  j = 0; j <= i - 1; ++j )
		{
			(*xx)[i] -= LL[i][j] * (*xx)[j];
		}
		(*xx)[i] /= LL[i][i];
	}
	for( int i = AAsize - 1; i >= 0; --i )
	{
		for( int  j = i + 1; j < AAsize; ++j )
		{
			(*xx)[i] -= UU[i][j] * (*xx)[j];
		}
	}
}
Ejemplo n.º 4
0
void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
    const GlyphBuffer& glyphBuffer, unsigned from, unsigned numGlyphs,
    const FloatPoint& point, const FloatRect& textRect) const
{
    SkScalar x = SkFloatToScalar(point.x());
    SkScalar y = SkFloatToScalar(point.y());

    const OpenTypeVerticalData* verticalData = font->verticalData();
    if (font->platformData().orientation() == Vertical && verticalData) {
        SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
        SkPoint* pos = storage.get();

        AffineTransform savedMatrix = gc->getCTM();
        gc->concatCTM(AffineTransform(0, -1, 1, 0, point.x(), point.y()));
        gc->concatCTM(AffineTransform(1, 0, 0, 1, -point.x(), -point.y()));

        const unsigned kMaxBufferLength = 256;
        Vector<FloatPoint, kMaxBufferLength> translations;

        const FontMetrics& metrics = font->fontMetrics();
        SkScalar verticalOriginX = SkFloatToScalar(point.x() + metrics.floatAscent() - metrics.floatAscent(IdeographicBaseline));
        float horizontalOffset = point.x();

        unsigned glyphIndex = 0;
        while (glyphIndex < numGlyphs) {
            unsigned chunkLength = std::min(kMaxBufferLength, numGlyphs - glyphIndex);

            const Glyph* glyphs = glyphBuffer.glyphs(from + glyphIndex);
            translations.resize(chunkLength);
            verticalData->getVerticalTranslationsForGlyphs(font, &glyphs[0], chunkLength, reinterpret_cast<float*>(&translations[0]));

            x = verticalOriginX;
            y = SkFloatToScalar(point.y() + horizontalOffset - point.x());

            float currentWidth = 0;
            for (unsigned i = 0; i < chunkLength; ++i, ++glyphIndex) {
                pos[i].set(
                    x + SkIntToScalar(lroundf(translations[i].x())),
                    y + -SkIntToScalar(-lroundf(currentWidth - translations[i].y())));
                currentWidth += glyphBuffer.advanceAt(from + glyphIndex);
            }
            horizontalOffset += currentWidth;
            paintGlyphs(gc, font, glyphs, chunkLength, pos, textRect);
        }

        gc->setCTM(savedMatrix);
        return;
    }

    if (!glyphBuffer.hasOffsets()) {
        SkAutoSTMalloc<64, SkScalar> storage(numGlyphs);
        SkScalar* xpos = storage.get();
        const float* adv = glyphBuffer.advances(from);
        for (unsigned i = 0; i < numGlyphs; i++) {
            xpos[i] = x;
            x += SkFloatToScalar(adv[i]);
        }
        const Glyph* glyphs = glyphBuffer.glyphs(from);
        paintGlyphsHorizontal(gc, font, glyphs, numGlyphs, xpos, SkFloatToScalar(y), textRect);
        return;
    }

    // FIXME: text rendering speed:
    // Android has code in their WebCore fork to special case when the
    // GlyphBuffer has no advances other than the defaults. In that case the
    // text drawing can proceed faster. However, it's unclear when those
    // patches may be upstreamed to WebKit so we always use the slower path
    // here.
    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
    SkPoint* pos = storage.get();
    const FloatSize* offsets = glyphBuffer.offsets(from);
    const float* advances = glyphBuffer.advances(from);
    SkScalar advanceSoFar = SkFloatToScalar(0);
    for (unsigned i = 0; i < numGlyphs; i++) {
        pos[i].set(
            x + SkFloatToScalar(offsets[i].width()) + advanceSoFar,
            y + SkFloatToScalar(offsets[i].height()));
        advanceSoFar += SkFloatToScalar(advances[i]);
    }

    const Glyph* glyphs = glyphBuffer.glyphs(from);
    paintGlyphs(gc, font, glyphs, numGlyphs, pos, textRect);
}
Ejemplo n.º 5
0
DTC::LiveStreamInfo *Content::AddLiveStream( const QString   &sStorageGroup,
                                             const QString   &sFileName,
                                             const QString   &sHostName,
                                             int              nMaxSegments,
                                             int              nWidth,
                                             int              nHeight,
                                             int              nBitrate,
                                             int              nAudioBitrate,
                                             int              nSampleRate )
{
    QString sGroup = sStorageGroup;

    if (sGroup.isEmpty())
    {
        LOG(VB_UPNP, LOG_WARNING,
            "AddLiveStream - StorageGroup missing... using 'Default'");
        sGroup = "Default";
    }

    if (sFileName.isEmpty())
    {
        QString sMsg ( "AddLiveStream - FileName missing." );

        LOG(VB_UPNP, LOG_ERR, sMsg);

        throw sMsg;
    }

    // ------------------------------------------------------------------
    // Search for the filename
    // ------------------------------------------------------------------

    QString sFullFileName;
    if (sHostName.isEmpty() || sHostName == gCoreContext->GetHostName())
    {
        StorageGroup storage( sGroup );
        sFullFileName = storage.FindFile( sFileName );

        if (sFullFileName.isEmpty())
        {
            LOG(VB_UPNP, LOG_ERR,
                QString("AddLiveStream - Unable to find %1.").arg(sFileName));

            return NULL;
        }
    }
    else
    {
        sFullFileName =
            gCoreContext->GenMythURL(sHostName, 0, sFileName, sStorageGroup);
    }

    HTTPLiveStream *hls = new
        HTTPLiveStream(sFullFileName, nWidth, nHeight, nBitrate, nAudioBitrate,
                       nMaxSegments, 10, 32000, nSampleRate);

    if (!hls)
    {
        LOG(VB_UPNP, LOG_ERR,
            "AddLiveStream - Unable to create HTTPLiveStream.");
        return NULL;
    }

    DTC::LiveStreamInfo *lsInfo = hls->StartStream();

    delete hls;

    return lsInfo;
}
Ejemplo n.º 6
0
static void draw_nine_clipped(const SkMask& mask, const SkIRect& outerR,
                              const SkIPoint& center, bool fillCenter,
                              const SkIRect& clipR, SkBlitter* blitter) {
    int cx = center.x();
    int cy = center.y();
    SkMask m;

    // top-left
    m.fBounds = mask.fBounds;
    m.fBounds.fRight = cx;
    m.fBounds.fBottom = cy;
    if (m.fBounds.width() > 0 && m.fBounds.height() > 0) {
        extractMaskSubset(mask, &m);
        m.fBounds.offsetTo(outerR.left(), outerR.top());
        blitClippedMask(blitter, m, m.fBounds, clipR);
    }

    // top-right
    m.fBounds = mask.fBounds;
    m.fBounds.fLeft = cx + 1;
    m.fBounds.fBottom = cy;
    if (m.fBounds.width() > 0 && m.fBounds.height() > 0) {
        extractMaskSubset(mask, &m);
        m.fBounds.offsetTo(outerR.right() - m.fBounds.width(), outerR.top());
        blitClippedMask(blitter, m, m.fBounds, clipR);
    }

    // bottom-left
    m.fBounds = mask.fBounds;
    m.fBounds.fRight = cx;
    m.fBounds.fTop = cy + 1;
    if (m.fBounds.width() > 0 && m.fBounds.height() > 0) {
        extractMaskSubset(mask, &m);
        m.fBounds.offsetTo(outerR.left(), outerR.bottom() - m.fBounds.height());
        blitClippedMask(blitter, m, m.fBounds, clipR);
    }

    // bottom-right
    m.fBounds = mask.fBounds;
    m.fBounds.fLeft = cx + 1;
    m.fBounds.fTop = cy + 1;
    if (m.fBounds.width() > 0 && m.fBounds.height() > 0) {
        extractMaskSubset(mask, &m);
        m.fBounds.offsetTo(outerR.right() - m.fBounds.width(),
                           outerR.bottom() - m.fBounds.height());
        blitClippedMask(blitter, m, m.fBounds, clipR);
    }

    SkIRect innerR;
    innerR.set(outerR.left() + cx - mask.fBounds.left(),
               outerR.top() + cy - mask.fBounds.top(),
               outerR.right() + (cx + 1 - mask.fBounds.right()),
               outerR.bottom() + (cy + 1 - mask.fBounds.bottom()));
    if (fillCenter) {
        blitClippedRect(blitter, innerR, clipR);
    }

    const int innerW = innerR.width();
    size_t storageSize = (innerW + 1) * (sizeof(int16_t) + sizeof(uint8_t));
    SkAutoSMalloc<4*1024> storage(storageSize);
    int16_t* runs = (int16_t*)storage.get();
    uint8_t* alpha = (uint8_t*)(runs + innerW + 1);

    SkIRect r;
    // top
    r.set(innerR.left(), outerR.top(), innerR.right(), innerR.top());
    if (r.intersect(clipR)) {
        int startY = SkMax32(0, r.top() - outerR.top());
        int stopY = startY + r.height();
        int width = r.width();
        for (int y = startY; y < stopY; ++y) {
            runs[0] = width;
            runs[width] = 0;
            alpha[0] = *mask.getAddr8(cx, mask.fBounds.top() + y);
            blitter->blitAntiH(r.left(), outerR.top() + y, alpha, runs);
        }
    }
    // bottom
    r.set(innerR.left(), innerR.bottom(), innerR.right(), outerR.bottom());
    if (r.intersect(clipR)) {
        int startY = outerR.bottom() - r.bottom();
        int stopY = startY + r.height();
        int width = r.width();
        for (int y = startY; y < stopY; ++y) {
            runs[0] = width;
            runs[width] = 0;
            alpha[0] = *mask.getAddr8(cx, mask.fBounds.bottom() - y - 1);
            blitter->blitAntiH(r.left(), outerR.bottom() - y - 1, alpha, runs);
        }
    }
    // left
    r.set(outerR.left(), innerR.top(), innerR.left(), innerR.bottom());
    if (r.intersect(clipR)) {
        int startX = r.left() - outerR.left();
        int stopX = startX + r.width();
        int height = r.height();
        for (int x = startX; x < stopX; ++x) {
            blitter->blitV(outerR.left() + x, r.top(), height,
                           *mask.getAddr8(mask.fBounds.left() + x, mask.fBounds.top() + cy));
        }
    }
    // right
    r.set(innerR.right(), innerR.top(), outerR.right(), innerR.bottom());
    if (r.intersect(clipR)) {
        int startX = outerR.right() - r.right();
        int stopX = startX + r.width();
        int height = r.height();
        for (int x = startX; x < stopX; ++x) {
            blitter->blitV(outerR.right() - x - 1, r.top(), height,
                           *mask.getAddr8(mask.fBounds.right() - x - 1, mask.fBounds.top() + cy));
        }
    }
}
Ejemplo n.º 7
0
SkCodec::Result SkScaledCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
                                           size_t rowBytes, const Options& options,
                                           SkPMColor ctable[], int* ctableCount) {

    if (options.fSubset) {
        // Subsets are not supported.
        return kUnimplemented;
    } 

    Result result = fScanlineDecoder->start(requestedInfo, &options, ctable, ctableCount);
    if (kSuccess == result) {
        // native decode supported
        return fScanlineDecoder->getScanlines(dst, requestedInfo.height(), rowBytes);

    }

    if (kInvalidScale != result) {
        // no scaling requested
        return result;
    }
    
    // scaling requested
    int sampleX;
    int sampleY;
    if (!scaling_supported(requestedInfo, fScanlineDecoder->getInfo(), &sampleX, &sampleY)) {
        return kInvalidScale;
    }
    // set first sample pixel in y direction
    int Y0 = sampleY >> 1;

    int dstHeight = requestedInfo.height();
    int srcHeight = fScanlineDecoder->getInfo().height();
    
    SkImageInfo info = requestedInfo;
    // use original height as scanlineDecoder does not support y sampling natively
    info = info.makeWH(requestedInfo.width(), srcHeight);

    // update scanlineDecoder with new info
    result = fScanlineDecoder->start(info, &options, ctable, ctableCount);
    if (kSuccess != result) {
        return result;
    }
    
    const bool requiresPostYSampling = fScanlineDecoder->requiresPostYSampling();

    if (requiresPostYSampling) {
        SkAutoMalloc storage(srcHeight * rowBytes);
        uint8_t* storagePtr = static_cast<uint8_t*>(storage.get());
        result = fScanlineDecoder->getScanlines(storagePtr, srcHeight, rowBytes);
        if (kSuccess != result) {
            return result;
        }
        storagePtr += Y0 * rowBytes;
        for (int y = 0; y < dstHeight; y++) {
            memcpy(dst, storagePtr, rowBytes);
            storagePtr += sampleY * rowBytes;
            dst = SkTAddOffset<void>(dst, rowBytes);
        }
    } else {
        // does not require post y sampling
        result = fScanlineDecoder->skipScanlines(Y0);
        if (kSuccess != result) {
            return result;
        }
        for (int y = 0; y < dstHeight; y++) {
            result = fScanlineDecoder->getScanlines(dst, 1, rowBytes);
            if (kSuccess != result) {
                return result;
            }
            if (y < dstHeight - 1) {
                result = fScanlineDecoder->skipScanlines(sampleY - 1);
                if (kSuccess != result) {
                    return result;
                }
            }
            dst = SkTAddOffset<void>(dst, rowBytes);
        }
    }
    return kSuccess;
}
Ejemplo n.º 8
0
GLuint SkGL::BindNewTexture(const SkBitmap& origBitmap, SkPoint* max) {
    SkBitmap tmpBitmap;
    const SkBitmap* bitmap = &origBitmap;

    if (needToPromoteTo32bit(origBitmap)) {
        origBitmap.copyTo(&tmpBitmap, SkBitmap::kARGB_8888_Config);
        // now bitmap points to our temp, which has been promoted to 32bits
        bitmap = &tmpBitmap;
    }

    GLenum format, type;
    if (!canBeTexture(*bitmap, &format, &type)) {
        return 0;
    }

    SkAutoLockPixels alp(*bitmap);
    if (!bitmap->readyToDraw()) {
        return 0;
    }

    GLuint  textureName;
    glGenTextures(1, &textureName);

    glBindTexture(GL_TEXTURE_2D, textureName);

    // express rowbytes as a number of pixels for ow
    int ow = bitmap->rowBytesAsPixels();
    int oh = bitmap->height();
    int nw = SkNextPow2(ow);
    int nh = SkNextPow2(oh);

    glPixelStorei(GL_UNPACK_ALIGNMENT, bitmap->bytesPerPixel());

    // check if we need to scale to create power-of-2 dimensions
#ifdef SK_GL_SUPPORT_COMPRESSEDTEXIMAGE2D
    if (SkBitmap::kIndex8_Config == bitmap->config()) {
        size_t imagesize = bitmap->getSize() + SK_GL_SIZE_OF_PALETTE;
        SkAutoMalloc storage(imagesize);

        build_compressed_data(storage.get(), *bitmap);
        // we only support POW2 here (GLES 1.0 restriction)
        SkASSERT(ow == nw);
        SkASSERT(oh == nh);
        glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, ow, oh, 0,
                               imagesize, storage.get());
    } else  // fall through to non-compressed logic
#endif
    {
        if (ow != nw || oh != nh) {
            glTexImage2D(GL_TEXTURE_2D, 0, format, nw, nh, 0,
                         format, type, NULL);
            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, ow, oh,
                            format, type, bitmap->getPixels());
        } else {
            // easy case, the bitmap is already pow2
            glTexImage2D(GL_TEXTURE_2D, 0, format, ow, oh, 0,
                         format, type, bitmap->getPixels());
        }
    }

#ifdef TRACE_TEXTURE_CREATION
    SkDebugf("--- new texture [%d] size=(%d %d) bpp=%d\n", textureName, ow, oh,
             bitmap->bytesPerPixel());
#endif

    if (max) {
        max->fX = SkFixedToScalar(bitmap->width() << (16 - SkNextLog2(nw)));
        max->fY = SkFixedToScalar(oh << (16 - SkNextLog2(nh)));
    }
    return textureName;
}
Ejemplo n.º 9
0
MainWindow::MainWindow(OCContext* context, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStorageInfo storage(qApp->applicationDirPath());
    qDebug() << storage.rootPath();
    if (storage.isReadOnly())
        qDebug() << "isReadOnly:" << storage.isReadOnly();

    qDebug() << "name:" << storage.name();
    qDebug() << "fileSystemType:" << storage.fileSystemType();
    qDebug() << "size:" << storage.bytesTotal()/1000/1000 << "MB";
    qDebug() << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";



    QList<QStorageInfo> drives = QStorageInfo::mountedVolumes();

    for(auto& drive : drives)
    {
       qDebug() << drive.rootPath();
       if (drive.isReadOnly())
           qDebug() << "isReadOnly:" << drive.isReadOnly();

       qDebug() << "name:" << drive.name();
       qDebug() << "fileSystemType:" << drive.fileSystemType();
       qDebug() << "size:" << drive.bytesTotal()/1000/1000 << "MB";
       qDebug() << "availableSize:" << drive.bytesAvailable()/1000/1000 << "MB";
    }
    _context = context;

    MediaExplorerPresenter* mediaExplorerPresenter = new MediaExplorerPresenter(_context);
    PlaybackPresenter* playbackPresenter = new PlaybackPresenter(_context);

    //Add preview pane
    //ui->gridLayout_3->addWidget(new PreviewPane(playbackPresenter));

    //Set Media Explorer widget
    //ui->dockWidget_3->setWidget(new MediaExplorerView(mediaExplorerPresenter));

    //QGridLayout* layout = new QGridLayout();
    //layout->addWidget(new PlaybackSlider(playbackPresenter)), ui->widget->setLayout(layout);

    stdout = freopen("output_file", "w", stdout);

    QFile f;
    f.open(stderr, QIODevice::ReadOnly);
    QByteArray output = f.readAll();
    QString out(output);

    /*ui->label_2->setText(out);
    ui->textBrowser->setText(out);

    ui->textBrowser->append("TEST\n");
    ui->textBrowser->append("12345\n");
*/
    BackupPresenter* backupPresenter = new BackupPresenter(context);
    ui->stackedWidget->addWidget(new BackupLayout(this, *backupPresenter));

    ui->stackedWidget->addWidget(new ClipProcessorLayout());

    //ui->buttonGroup->addButton(new QPushButton("Test", this));

    connect(ui->buttonGroup, SIGNAL(buttonClicked(int)), SLOT(on_pushButton_7_clicked(int)));

    /*QMenu* importMenu = new QMenu();
    QAction* testAction = new QAction("test menu item", this);
    connect(testAction,SIGNAL(triggered()), SLOT(SelectImportFolder()));
    importMenu->addAction(testAction);*/
}
Ejemplo n.º 10
0
static PyObject * THPStorage_(pynew)(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
  HANDLE_TH_ERRORS
  Py_ssize_t num_args = args ? PyTuple_Size(args) : 0;

  THPStoragePtr self((THPStorage *)type->tp_alloc(type, 0));
  THPUtils_assert(self, "failed to allocate a " THPStorageStr " object");
  THAllocator* allocator = NULL;

  // Internally we allow constructing with a keywoard only argument cdata
  if (kwargs != NULL) {
    PyObject *allocator_ptr = PyDict_GetItemString(kwargs, "allocator");
    if (allocator_ptr) {
      THPUtils_assert(THPUtils_checkLong(allocator_ptr), "invalid allocator");
      allocator = (THAllocator*) PyLong_AsVoidPtr(allocator_ptr);
      PyDict_DelItemString(kwargs, "allocator");
    }

    Py_ssize_t num_kwargs = PyDict_Size(kwargs);
    if (num_args == 0) {
      PyObject *cdata_ptr = PyDict_GetItemString(kwargs, "cdata");
      if (num_kwargs == 1 && cdata_ptr && THPUtils_checkLong(cdata_ptr)) {
        THStorage *ptr = (THStorage*)PyLong_AsVoidPtr(cdata_ptr);
        self->cdata = ptr;
        return (PyObject*)self.release();
      }
    }
    THPUtils_assert(num_kwargs == 0, THPStorageStr "(): invalid keyword arguments");
  }

  // torch.Storage()
  if (num_args == 0) {
    if (allocator) {
      self->cdata = THPStorage_(newWithAllocator)(0, allocator);
    } else {
      self->cdata = THStorage_(new)(LIBRARY_STATE_NOARGS);
    }
    return (PyObject*)self.release();
  }

  PyObject *first_arg = PyTuple_GET_ITEM(args, 0);

  // torch.Storage(size)
  if (num_args == 1 && THPUtils_checkLong(first_arg)) {
    int64_t size = THPUtils_unpackLong(first_arg);
    if (allocator) {
      self->cdata = THPStorage_(newWithAllocator)(size, allocator);
    } else {
      self->cdata = THStorage_(newWithSize)(LIBRARY_STATE size);
    }
    return (PyObject*)self.release();
  }

  // torch.Storage(view_source, [offset, [size]])
  if (num_args < 4 && THPStorage_(Check)(first_arg)) {
#ifdef THD_GENERIC_FILE
    THPUtils_setError("distributed storages don't support storage views");
    return NULL;
#else
    THPStorage *storage_arg = (THPStorage *)first_arg;
    int64_t numel = storage_arg->cdata->size;
    int64_t offset = 0;

    if (num_args >= 2) {
      PyObject *second_arg = PyTuple_GET_ITEM(args, 1);
      if (!THPUtils_checkLong(second_arg))
        goto invalid_arguments;
      offset = THPUtils_unpackLong(second_arg);
    }

    int64_t size = numel - offset;
    if (num_args >= 3) {
      PyObject *third_arg = PyTuple_GET_ITEM(args, 2);
      if (!THPUtils_checkLong(third_arg))
        goto invalid_arguments;
      size = THPUtils_unpackLong(third_arg);
    }

    THPUtils_assert(offset >= 0 && offset <= numel, "specified an offset of "
        "%" PRId64 ", but the viewed storage has only %" PRId64 " element(s)", offset, numel);
    THPUtils_assert(size >= 1 && size <= numel - offset, "specified a size of "
        "%" PRId64 ", but the viewed storage has only %" PRId64 " element(s) after offset %" PRId64,
        size, numel - offset, offset);

    real *data_ptr = THStorage_(data)(LIBRARY_STATE storage_arg->cdata) + offset;
    THStoragePtr storage(THStorage_(newWithData)(LIBRARY_STATE data_ptr, size));
    storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_VIEW;
    storage->view = storage_arg->cdata;
    THStorage_(retain)(LIBRARY_STATE storage_arg->cdata);
    self->cdata = storage.release();
    return (PyObject*)self.release();
#endif
  }

  // torch.Storage(sequence)
  if (num_args == 1 && PySequence_Check(first_arg)) {
#ifdef THD_GENERIC_FILE
    THPUtils_setError("distributed storages don't support construction from a sequence");
#else
    Py_ssize_t length = PySequence_Length(first_arg);
    THPUtils_assert(length >= 0, "couldn't obtain the length of %s",
        THPUtils_typename(first_arg));
    self->cdata = THStorage_(newWithSize)(LIBRARY_STATE length);
    THPObjectPtr item;
    try {
      for (Py_ssize_t i = 0; i < length; i++) {
        item = PySequence_GetItem(first_arg, i);
        real value = THPUtils_(unpackReal)(item.get());
#if !defined(THC_GENERIC_FILE)
        self->cdata->unsafe_data<real>()[i] = value;
#else
        // TODO: this might be slow - consider batched updates?
        THCStorage_(set)(LIBRARY_STATE self->cdata, i, value);
#endif
      }
    } catch (std::runtime_error &e) {
      THPUtils_setError("tried to construct a storage from a sequence (%s), "
          "but one of the items was of type %s instead of %s",
          THPUtils_typename(first_arg),
          THPUtils_typename(item.get()),
          THPUtils_typeTraits<real>::python_type_str);
      return NULL;
    }
    return (PyObject*)self.release();
#endif
  }

#ifndef THD_GENERIC_FILE
invalid_arguments:
#endif
  THPUtils_invalidArguments(args, kwargs, THPStorageStr " constructor", 6,
          "no arguments",
          "(int size)",
          "(Sequence data)",
          "(" THPStorageStr " view_source)",
          "(" THPStorageStr " view_source, int offset)",
          "(" THPStorageStr " view_source, int offset, int size)");
  return NULL;
  END_HANDLE_TH_ERRORS
}
Ejemplo n.º 11
0
SkShader* Gradient::platformGradient()
{
    if (m_gradient)
        return m_gradient;

    sortStopsIfNecessary();
    ASSERT(m_stopsSorted);

    size_t countUsed = totalStopsNeeded(m_stops.data(), m_stops.size());
    ASSERT(countUsed >= 2);
    ASSERT(countUsed >= m_stops.size());

    // FIXME: Why is all this manual pointer math needed?!
    SkAutoMalloc storage(countUsed * (sizeof(SkColor) + sizeof(SkScalar)));
    SkColor* colors = (SkColor*)storage.get();
    SkScalar* pos = (SkScalar*)(colors + countUsed);

    fillStops(m_stops.data(), m_stops.size(), pos, colors);

    SkShader::TileMode tile = SkShader::kClamp_TileMode;
    switch (m_spreadMethod) {
    case SpreadMethodReflect:
        tile = SkShader::kMirror_TileMode;
        break;
    case SpreadMethodRepeat:
        tile = SkShader::kRepeat_TileMode;
        break;
    case SpreadMethodPad:
        tile = SkShader::kClamp_TileMode;
        break;
    }

    if (m_radial) {
        // Since the two-point radial gradient is slower than the plain radial,
        // only use it if we have to.
        if (m_p0 == m_p1 && m_r0 <= 0.0f) {
            // The radius we give to Skia must be positive (and non-zero).  If
            // we're given a zero radius, just ask for a very small radius so
            // Skia will still return an object.
            SkScalar radius = m_r1 > 0 ? WebCoreFloatToSkScalar(m_r1) : WebCoreFloatToSkScalar(FLT_EPSILON);
            m_gradient = SkGradientShader::CreateRadial(m_p1, radius, colors, pos, static_cast<int>(countUsed), tile);
        } else {
            // The radii we give to Skia must be positive.  If we're given a 
            // negative radius, ask for zero instead.
            SkScalar radius0 = m_r0 >= 0.0f ? WebCoreFloatToSkScalar(m_r0) : 0;
            SkScalar radius1 = m_r1 >= 0.0f ? WebCoreFloatToSkScalar(m_r1) : 0;
            m_gradient = SkGradientShader::CreateTwoPointRadial(m_p0, radius0, m_p1, radius1, colors, pos, static_cast<int>(countUsed), tile);
        }

        if (aspectRatio() != 1) {
            // CSS3 elliptical gradients: apply the elliptical scaling at the
            // gradient center point.
            m_gradientSpaceTransformation.translate(m_p0.x(), m_p0.y());
            m_gradientSpaceTransformation.scale(1, 1 / aspectRatio());
            m_gradientSpaceTransformation.translate(-m_p0.x(), -m_p0.y());
            ASSERT(m_p0 == m_p1);
        }
    } else {
        SkPoint pts[2] = { m_p0, m_p1 };
        m_gradient = SkGradientShader::CreateLinear(pts, colors, pos, static_cast<int>(countUsed), tile);
    }

    ASSERT(m_gradient);
    SkMatrix matrix = m_gradientSpaceTransformation;
    m_gradient->setLocalMatrix(matrix);
    return m_gradient;
}
Ejemplo n.º 12
0
    static void drawBitmapMesh(JNIEnv* env, jobject, SkCanvas* canvas,
                          const SkBitmap* bitmap, int meshWidth, int meshHeight,
                          jfloatArray jverts, int vertIndex, jintArray jcolors,
                          int colorIndex, const SkPaint* paint) {

        const int ptCount = (meshWidth + 1) * (meshHeight + 1);
        const int indexCount = meshWidth * meshHeight * 6;

        AutoJavaFloatArray  vertA(env, jverts, vertIndex + (ptCount << 1));
        AutoJavaIntArray    colorA(env, jcolors, colorIndex + ptCount);
        
        /*  Our temp storage holds 2 or 3 arrays.
            texture points [ptCount * sizeof(SkPoint)]
            optionally vertex points [ptCount * sizeof(SkPoint)] if we need a
                copy to convert from float to fixed
            indices [ptCount * sizeof(uint16_t)]
        */
        ssize_t storageSize = ptCount * sizeof(SkPoint); // texs[]
#ifdef SK_SCALAR_IS_FIXED
        storageSize += ptCount * sizeof(SkPoint);  // storage for verts
#endif
        storageSize += indexCount * sizeof(uint16_t);  // indices[]

        SkAutoMalloc storage(storageSize);
        SkPoint* texs = (SkPoint*)storage.get();
        SkPoint* verts;
        uint16_t* indices;
#ifdef SK_SCALAR_IS_FLOAT
        verts = (SkPoint*)(vertA.ptr() + vertIndex);
        indices = (uint16_t*)(texs + ptCount);
#else
        verts = texs + ptCount;
        indices = (uint16_t*)(verts + ptCount);
        // convert floats to fixed
        {
            const float* src = vertA.ptr() + vertIndex;
            for (int i = 0; i < ptCount; i++) {
                verts[i].set(SkFloatToFixed(src[0]), SkFloatToFixed(src[1]));
                src += 2;
            }
        }
#endif

        // cons up texture coordinates and indices
        {
            const SkScalar w = SkIntToScalar(bitmap->width());
            const SkScalar h = SkIntToScalar(bitmap->height());
            const SkScalar dx = w / meshWidth;
            const SkScalar dy = h / meshHeight;
            
            SkPoint* texsPtr = texs;
            SkScalar y = 0;
            for (int i = 0; i <= meshHeight; i++) {
                if (i == meshHeight) {
                    y = h;  // to ensure numerically we hit h exactly
                }
                SkScalar x = 0;
                for (int j = 0; j < meshWidth; j++) {
                    texsPtr->set(x, y);
                    texsPtr += 1;
                    x += dx;
                }
                texsPtr->set(w, y);
                texsPtr += 1;
                y += dy;
            }
            SkASSERT(texsPtr - texs == ptCount);
        }
        
        // cons up indices
        {
            uint16_t* indexPtr = indices;
            int index = 0;
            for (int i = 0; i < meshHeight; i++) {
                for (int j = 0; j < meshWidth; j++) {
                    // lower-left triangle
                    *indexPtr++ = index;
                    *indexPtr++ = index + meshWidth + 1;
                    *indexPtr++ = index + meshWidth + 2;
                    // upper-right triangle
                    *indexPtr++ = index;
                    *indexPtr++ = index + meshWidth + 2;
                    *indexPtr++ = index + 1;
                    // bump to the next cell
                    index += 1;
                }
                // bump to the next row
                index += 1;
            }
            SkASSERT(indexPtr - indices == indexCount);
            SkASSERT((char*)indexPtr - (char*)storage.get() == storageSize);
        }

        // double-check that we have legal indices
#ifdef SK_DEBUG
        {
            for (int i = 0; i < indexCount; i++) {
                SkASSERT((unsigned)indices[i] < (unsigned)ptCount);
            }
        }
#endif

        // cons-up a shader for the bitmap
        SkPaint tmpPaint;
        if (paint) {
            tmpPaint = *paint;
        }
        SkShader* shader = SkShader::CreateBitmapShader(*bitmap,
                        SkShader::kClamp_TileMode, SkShader::kClamp_TileMode);
        tmpPaint.setShader(shader)->safeUnref();

        canvas->drawVertices(SkCanvas::kTriangles_VertexMode, ptCount, verts,
                             texs, (const SkColor*)colorA.ptr(), NULL, indices,
                             indexCount, tmpPaint);
    }
Ejemplo n.º 13
0
 static qr_type *qr_create(length_type n, length_type m, storage_type s) 
 {
   qr_type *qr = vsip_cqrd_create_f(n, m, storage(s));
   if (!qr) VSIP_IMPL_THROW(std::bad_alloc());
   return qr;
 }
bool SkFPDFEMBImageDecoder::onDecode(SkStream* stream, SkBitmap* bm,
                                 SkBitmap::Config prefConfig, Mode mode) {

    FPDFEMB_RESULT result;
#ifdef USE_FIXED_MEM
    SkAutoMalloc storage(USE_FIXED_MEM);
    result = FPDFEMB_InitFixedMemory(storage.get(), USE_FIXED_MEM,
                                     pdf_oom_handler);
#else
    FPDFEMB_MEMMGR  memmgr;
    memmgr.Alloc = pdf_alloc;
    memmgr.AllocNL = pdf_alloc_nl;
    memmgr.Realloc = pdf_realloc;
    memmgr.Free = pdf_free;

    result = FPDFEMB_Init(&memmgr);
#endif
    SkDebugf("----- SkImageDecoder_FPDFEMB_Factory init %d, streamLen = %d\n", result, stream->getLength());

    FPDFEMB_FILE_ACCESS file;
    file.GetSize = file_getsize;
    file.ReadBlock = file_readblock;
    file.user = stream;

    FPDFEMB_DOCUMENT document;
    result = FPDFEMB_StartLoadDocument(&file, NULL, &document, NULL);
    SkDebugf("----- SkImageDecoder_FPDFEMB_Factory open %d %p\n", result, document);

    int pageCount = FPDFEMB_GetPageCount(document);
    SkDebugf("----- SkImageDecoder_FPDFEMB_Factory pageCount %d\n", pageCount);

    if (pageCount > 0) {
        FPDFEMB_PAGE page;
        result = FPDFEMB_LoadPage(document, 0, &page);
        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory load page %d\n", result);

        int width, height;
        result = FPDFEMB_GetPageSize(page, &width, &height);
        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory page size %d [%d %d]\n", result, width, height);

        FPDFEMB_RECT rect;
        result = FPDFEMB_GetPageBBox(page, &rect);
        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory page rect %d [%d %d %d %d]\n", result,
                 rect.left, rect.top, rect.right, rect.bottom);

        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory begin page parse...\n");
        result = FPDFEMB_StartParse(page, false, NULL);
        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory page parse %d\n", result);

        if (0 == result) {
            this->render(page, rect, bm, prefConfig, mode);
        }

        result = FPDFEMB_ClosePage(page);
        SkDebugf("----- SkImageDecoder_FPDFEMB_Factory close page %d\n", result);
    }
    
    result = FPDFEMB_CloseDocument(document);
    SkDebugf("----- SkImageDecoder_FPDFEMB_Factory close %d\n", result);

 //   FPDFEMB_Exit();

    return true;    
}
Ejemplo n.º 15
0
void testTrainICAAMColor()
{
    std::cout << "trainICTest testTrainICAAMColor" << std::endl;
    aam::AppearanceDataIC model;
    aam::TrainModelLoader loader;
    loader.useGrayImages(false);

    for (int i = 0; i < TRIANGLES_COUNT; i++)
    {
        model.triangles.push_back(cv::Vec3i(trianglesData[i * 3],
                trianglesData[i * 3 + 1], trianglesData[i * 3 + 2]));
    }

    try
    {
        std::vector<std::string> fileNames =
                boost::assign::list_of<std::string>
                ("107_0764.bmp")  /*("107_0766.bmp")*/  ("107_0779.bmp")
                ("107_0780.bmp")  ("107_0781.bmp")  ("107_0782.bmp")
                ("107_0783.bmp")  ("107_0784.bmp")  ("107_0785.bmp")
                ("107_0786.bmp")  ("107_0787.bmp")  ("107_0788.bmp")
                ("107_0789.bmp")  ("107_0790.bmp")  ("107_0791.bmp")
                ("107_0792.bmp")  ("107_0793.bmp")  ("107_0794.bmp")
                ("107_0795.bmp")  ("107_0798.bmp")  ("107_0799.bmp")
                ("107_0800.bmp")  ("108_0801.bmp")  ("108_0802.bmp")
                ("108_0803.bmp")  ("108_0804.bmp");

        for (int i = 0; i < fileNames.size(); i++)
        {
            std::ostringstream stream;

            stream << "data/cootes/" << fileNames[i] << ".mat.dat";
            std::string markupFile = stream.str();

            stream.str(std::string());

            stream << "data/cootes/" << fileNames[i];
            std::string imageFile = stream.str();

            loader.load(markupFile, imageFile);
        }

        std::vector<aam::TrainModelInfo> trainData = loader.getModels();
        aam::AAMFunctions2D::trainModelIC(0.98, trainData, model);

        cv::FileStorage storage("output/aam_ic_c_test.xml",
                cv::FileStorage::WRITE);
        storage << "R" << model.R;
        storage << "s" << model.s;
        storage << "s_star" << model.sStar;
        storage << "s0" << model.s0;
        storage << "A0" << model.A0;
        storage << "mask" << model.mask;
        storage << "triangles" << model.triangles;

        cv::Mat1i tmp(2, 1);
        tmp(0, 0) = model.textureSize.width;
        tmp(1, 0) = model.textureSize.height;
        storage << "texture_size" << tmp;
        storage.release();

        for (int i = 0; i < model.R.rows; i++)
        {
            cv::Mat img;
            aam::AAMFunctions2D::vector2Appearance(model.R.t().col(i),
                    model.mask,
                    model.textureSize, img);

            cv::normalize(img, img, 1, 0, cv::NORM_MINMAX);
            cv::imshow("test", img);
            cv::waitKey(500);
        }
        cv::waitKey(0);
    }
    catch (std::exception& e)
    {
        std::cout << "%TEST_FAILED% time=0 testname=testTrainICAAMColor (trainICTest) message=Exception occured: " <<
                e.what() << std::endl;
    }
}
Ejemplo n.º 16
0
void SkGLDevice::drawVertices(const SkDraw& draw, SkCanvas::VertexMode vmode,
                              int vertexCount, const SkPoint vertices[],
                              const SkPoint texs[], const SkColor colors[],
                              SkXfermode* xmode,
                              const uint16_t indices[], int indexCount,
                              const SkPaint& paint) {

    if (false) {
        SkRect bounds;
        SkIRect ibounds;
        
        bounds.set(vertices, vertexCount);
        bounds.round(&ibounds);
        
        SkDebugf("---- drawverts: %d pts, texs=%d colors=%d indices=%d bounds [%d %d]\n",
                 vertexCount, texs!=0, colors!=0, indexCount, ibounds.width(), ibounds.height());
    }
    
    SkGLClipIter* iter = this->updateMatrixClip();
    
    SkGL::SetPaint(paint);
    
    const SkGLVertex* glVerts;
    const SkGLVertex* glTexs = NULL;
    
#if GLSCALAR_IS_SCALAR
    glVerts = (const SkGLVertex*)vertices;
#else
    SkAutoSTMalloc<32, SkGLVertex> storage(vertexCount);
    storage.get()->setPoints(vertices, vertexCount);
    glVerts = storage.get();
#endif
    
    uint8_t* colorArray = NULL;
    if (colors) {
        colorArray = (uint8_t*)sk_malloc_throw(vertexCount*4);
        SkGL::SetRGBA(colorArray, colors, vertexCount);
    }
    SkAutoFree afca(colorArray);
    
    SkGLVertex* texArray = NULL;
    TexCache* cache = NULL;

    if (texs && paint.getShader()) {
        SkShader* shader = paint.getShader();
        
        //        if (!shader->setContext(this->accessBitmap(), paint, *draw.fMatrix)) {
        if (!shader->setContext(*draw.fBitmap, paint, *draw.fMatrix)) {
            goto DONE;
        }
        
        SkBitmap bitmap;
        SkMatrix matrix;
        SkShader::TileMode tileModes[2];
        if (shader->asABitmap(&bitmap, &matrix, tileModes)) {
            SkPoint max;
            GLuint name;
            cache = SkGLDevice::LockTexCache(bitmap, &name, &max);
            if (NULL == cache) {
                return;
            }

            matrix.postScale(max.fX / bitmap.width(), max.fY / bitmap.height());
            glMatrixMode(GL_TEXTURE);
            SkGL::LoadMatrix(matrix);
            glMatrixMode(GL_MODELVIEW);
            
#if GLSCALAR_IS_SCALAR
            glTexs = (const SkGLVertex*)texs;
#else
            texArray = (SkGLVertex*)sk_malloc_throw(vertexCount * sizeof(SkGLVertex));
            texArray->setPoints(texs, vertexCount);
            glTexs = texArray;
#endif
            
            SkGL::SetPaintAlpha(paint);
            SkGL::SetTexParams(paint.isFilterBitmap(),
                               tileModes[0], tileModes[1]);
        }
    }
DONE:
    SkAutoFree aftex(texArray);
    
    SkGL::DrawVertices(indices ? indexCount : vertexCount,
                       gVertexModeToGL[vmode],
                       glVerts, glTexs, colorArray, indices, iter);
    
    if (cache) {
        SkGLDevice::UnlockTexCache(cache);
    }
}
Ejemplo n.º 17
0
void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
                      const FloatPoint& point) const
{
    // compile-time assert
    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t));

    SkPaint paint;
    if (!setupForText(&paint, gc, font)) {
        return;
    }
    
    SkScalar                    x = SkFloatToScalar(point.x());
    SkScalar                    y = SkFloatToScalar(point.y());
    const GlyphBufferGlyph*     glyphs = glyphBuffer.glyphs(from);
    const GlyphBufferAdvance*   adv = glyphBuffer.advances(from);
    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
    SkPoint*                    pos = storage.get();
    
    SkCanvas* canvas = gc->platformContext()->mCanvas;

    /*  We need an array of [x,y,x,y,x,y,...], but webkit is giving us
        point.xy + [width, height, width, height, ...], so we have to convert
     */

    if (EmojiFont::IsAvailable()) {
        // set filtering, to make scaled images look nice(r)
        paint.setFilterBitmap(true);
        
        int localIndex = 0;
        int localCount = 0;
        for (int i = 0; i < numGlyphs; i++) {
            if (EmojiFont::IsEmojiGlyph(glyphs[i])) {
                if (localCount)
                    canvas->drawPosText(&glyphs[localIndex],
                                        localCount * sizeof(uint16_t),
                                        &pos[localIndex], paint);
                EmojiFont::Draw(canvas, glyphs[i], x, y, paint);
                // reset local index/count track for "real" glyphs
                localCount = 0;
                localIndex = i + 1;
            } else {
                pos[i].set(x, y);
                localCount += 1;
            }
            x += SkFloatToScalar(adv[i].width());
            y += SkFloatToScalar(adv[i].height());
        }
        // draw the last run of glyphs (if any)
        if (localCount)
            canvas->drawPosText(&glyphs[localIndex],
                                localCount * sizeof(uint16_t),
                                &pos[localIndex], paint);
    } else {
        for (int i = 0; i < numGlyphs; i++) {
            pos[i].set(x, y);
            x += SkFloatToScalar(adv[i].width());
            y += SkFloatToScalar(adv[i].height());
        }
        canvas->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, paint);
    }
}
Ejemplo n.º 18
0
// ****************************************************************************
//
//  Function Name:	RMergeData::OpenFile( )
//
//  Description:		Make this MergeData takes its values from the given file
//							if bCompatibleMode == TRUE the file is a PSD4 file
//
//  Returns:			Nothing
//
//  Exceptions:		None
//
// ****************************************************************************
//
BOOLEAN RMergeData::OpenFile( const RMBCString& fileName, BOOL bCompatibleMode )
	{
	uBYTE*			pBuffer			= ::GetGlobalBuffer( );
	BOOLEAN			fReturnValue	= FALSE;
	try
		{
		RStorage	storage( fileName, kRead );

		//	Quick validate a that we are possible using a text file.
		YStreamLength	current		= storage.GetPosition( );
		YStreamLength	readAmt		= ::GetGlobalBufferSize( );
		try
		{
			storage.Read( readAmt, pBuffer );
		}
		catch( YException exception )
		{
			if ( exception != kEndOfFile )
				throw;
			readAmt	= storage.GetPosition( ) - current;
		}
		for (YStreamLength iCnt = 0; iCnt < readAmt; ++iCnt )
			if ( pBuffer[iCnt] == '\0' )	//	If null, this can't be a text file...
				throw kDataFormatInvalid;
		//
		//		Reset to beginning of file.
		storage.SeekAbsolute( current );
		//	delete the entries, and empty the list
		::DeleteAllItems( m_MergeData );
		m_MergeData.Empty( );

		//	Now, merge the new list if there is actually data
		if ( readAmt > 0 )
		{
			if ( bCompatibleMode == FALSE )
			{
				MergeStorage( storage );
		
				//	Remember the new file name
				m_FileName		= fileName;
			}
			else
				MergeCompatibleStorage( storage );
		}

		//	We succeeded
		fReturnValue	= TRUE;
		}
	catch( YException exception )
		{
		if ( exception == kEndOfFile )
			{
			::DeleteAllItems( m_MergeData );
			m_MergeData.Empty( );
			m_FileName		= fileName;
			fReturnValue	= TRUE;
			}
		else
			::ReportException( exception );
		}
	catch( ... )
		{
		::ReportException( kUnknownError );
		}

	::ReleaseGlobalBuffer( pBuffer );
	return fReturnValue;
	}
Ejemplo n.º 19
0
void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
                      const FloatPoint& point) const {
    SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert

    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
    SkScalar x = SkFloatToScalar(point.x());
    SkScalar y = SkFloatToScalar(point.y());

    // FIXME: text rendering speed:
    // Android has code in their WebCore fork to special case when the
    // GlyphBuffer has no advances other than the defaults. In that case the
    // text drawing can proceed faster. However, it's unclear when those
    // patches may be upstreamed to WebKit so we always use the slower path
    // here.
    const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs), storage2(numGlyphs), storage3(numGlyphs);
    SkPoint* pos = storage.get();
    SkPoint* vPosBegin = storage2.get();
    SkPoint* vPosEnd = storage3.get();

    bool isVertical = font->platformData().orientation() == Vertical;
    for (int i = 0; i < numGlyphs; i++) {
        SkScalar myWidth = SkFloatToScalar(adv[i].width());
        pos[i].set(x, y);
        if (isVertical) {
            vPosBegin[i].set(x + myWidth, y);
            vPosEnd[i].set(x + myWidth, y - myWidth);
        }
        x += myWidth;
        y += SkFloatToScalar(adv[i].height());
    }

    gc->platformContext()->prepareForSoftwareDraw();

    SkCanvas* canvas = gc->platformContext()->canvas();
    TextDrawingModeFlags textMode = gc->platformContext()->getTextDrawingMode();

    // We draw text up to two times (once for fill, once for stroke).
    if (textMode & TextModeFill) {
        SkPaint paint;
        gc->platformContext()->setupPaintForFilling(&paint);
        font->platformData().setupPaint(&paint);
        adjustTextRenderMode(&paint, gc->platformContext());
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
        paint.setColor(gc->fillColor().rgb());

        if (isVertical) {
            SkPath path;
            for (int i = 0; i < numGlyphs; ++i) {
                path.reset();
                path.moveTo(vPosBegin[i]);
                path.lineTo(vPosEnd[i]);
                canvas->drawTextOnPath(glyphs + i, 2, path, 0, paint);
            }
        } else
            canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);
    }

    if ((textMode & TextModeStroke)
        && gc->platformContext()->getStrokeStyle() != NoStroke
        && gc->platformContext()->getStrokeThickness() > 0) {

        SkPaint paint;
        gc->platformContext()->setupPaintForStroking(&paint, 0, 0);
        font->platformData().setupPaint(&paint);
        adjustTextRenderMode(&paint, gc->platformContext());
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
        paint.setColor(gc->strokeColor().rgb());

        if (textMode & TextModeFill) {
            // If we also filled, we don't want to draw shadows twice.
            // See comment in FontChromiumWin.cpp::paintSkiaText() for more details.
            SkSafeUnref(paint.setLooper(0));
        }

        if (isVertical) {
            SkPath path;
            for (int i = 0; i < numGlyphs; ++i) {
                path.reset();
                path.moveTo(vPosBegin[i]);
                path.lineTo(vPosEnd[i]);
                canvas->drawTextOnPath(glyphs + i, 2, path, 0, paint);
            }
        } else
            canvas->drawPosText(glyphs, numGlyphs << 1, pos, paint);
    }
}
Ejemplo n.º 20
0
QFileInfo Guide::GetChannelIcon( int nChanId,
                                 int nWidth  /* = 0 */,
                                 int nHeight /* = 0 */ )
{
    // Get Icon file path

    QString sFileName = ChannelUtil::GetIcon( nChanId );

    if (sFileName.isEmpty())
        return QFileInfo();

    // ------------------------------------------------------------------
    // Search for the filename
    // ------------------------------------------------------------------

    StorageGroup storage( "ChannelIcons" );
    QString sFullFileName = storage.FindFile( sFileName );

    if (sFullFileName.isEmpty())
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("GetImageFile - Unable to find %1.").arg(sFileName));

        return QFileInfo();
    }

    // ----------------------------------------------------------------------
    // check to see if the file (still) exists
    // ----------------------------------------------------------------------

    if ((nWidth == 0) && (nHeight == 0))
    {
        if (QFile::exists( sFullFileName ))
        {
            return QFileInfo( sFullFileName );
        }

        LOG(VB_UPNP, LOG_ERR,
            QString("GetImageFile - File Does not exist %1.").arg(sFullFileName));

        return QFileInfo();
    }
    // -------------------------------------------------------------------

    QString sNewFileName = QString( "%1.%2x%3.png" )
                              .arg( sFullFileName )
                              .arg( nWidth    )
                              .arg( nHeight   );

    // ----------------------------------------------------------------------
    // check to see if image is already created.
    // ----------------------------------------------------------------------

    if (QFile::exists( sNewFileName ))
        return QFileInfo( sNewFileName );

    // ----------------------------------------------------------------------
    // We need to create it...
    // ----------------------------------------------------------------------

    float fAspect = 0.0;

    QImage *pImage = new QImage( sFullFileName );

    if (!pImage)
        return QFileInfo();

    if (fAspect <= 0)
           fAspect = (float)(pImage->width()) / pImage->height();

    if (fAspect == 0)
    {
        delete pImage;
        return QFileInfo();
    }

    if ( nWidth == 0 )
        nWidth = (int)rint(nHeight * fAspect);

    if ( nHeight == 0 )
        nHeight = (int)rint(nWidth / fAspect);

    QImage img = pImage->scaled( nWidth, nHeight, Qt::IgnoreAspectRatio,
                                Qt::SmoothTransformation);

    img.save( sNewFileName, "PNG" );

    delete pImage;

    return QFileInfo( sNewFileName );
}
Ejemplo n.º 21
0
void auth_init()
{
	FILE *fp;
	static char uname[USERNAME_LEN+1];
	static char dir[DIR_LEN+1];
	static char per[DIR_LEN+1];

	printf("*** AUTH SYSTEM INIT START ***\n");
	pthread_mutex_init(&auth_lock,0);

	fp=fopen(passwd_file,"r");
	if (fp==0) printf("passwd NOT EXISTS\n");
	else
	{
		//printf("USER:\n");
		while (!feof(fp))
		{
			MALLOC(struct auth_profile,p);

			fscanf(fp,"%s",uname);
			if (feof(fp)) break;

			fscanf(fp,"%s",p->pass);
			
			p->uid=uid_alloc();

			map_insert(uname,(int)p);
			//printf("%s %s\n",uname,p->pass);
		}

		printf("passwd READ COMPLETE\n");
		fclose(fp);
	}

	fp=fopen(permission_file,"r");
	if (fp==0) printf("permission NOT EXISTS\n");
	else
	{
		while (!feof(fp))
		{
			fscanf(fp,"%s",dir);
			if (feof(fp)) break;
			
			fix_dir(dir);

			while (1)
			{
				int uid;

				fscanf(fp,"%s",uname);
				if (auth_strcmp(uname,"[end]")) break;

				fscanf(fp,"%s",per);
				
				uid=get_uid_by_name(uname);
				if (uid>0)
				{
					uint_8 mask=give_permission_mask(per);

					map_insert(storage(dir,uid),mask);
					//printf("DIR:%s %s %x\n",dir,per,mask);
				}
			}
		}
		printf("permission READ COMPLETE\n");
		fclose(fp);
	}
	printf("*** AUTH SYSTEM INIT COMPLETE ***\n\n");
}
Ejemplo n.º 22
0
// TODO: This needs to be split into helper functions to better scope the
// inputs/outputs, and reduce duplicate code.
// This issue is tracked in https://bugs.webkit.org/show_bug.cgi?id=62989
void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
                      const GlyphBuffer& glyphBuffer,  int from, int numGlyphs,
                      const FloatPoint& point) const {
    COMPILE_ASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t), GlyphBufferGlyphSize_equals_uint16_t);

    bool shouldSmoothFonts = true;
    bool shouldAntialias = true;
    
    switch (fontDescription().fontSmoothing()) {
    case Antialiased:
        shouldSmoothFonts = false;
        break;
    case SubpixelAntialiased:
        break;
    case NoSmoothing:
        shouldAntialias = false;
        shouldSmoothFonts = false;
        break;
    case AutoSmoothing:
        // For the AutoSmooth case, don't do anything! Keep the default settings.
        break; 
    }
    
    if (!shouldUseSmoothing() || PlatformSupport::layoutTestMode())
        shouldSmoothFonts = false;

    const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
    SkScalar x = SkFloatToScalar(point.x());
    SkScalar y = SkFloatToScalar(point.y());

    if (font->platformData().orientation() == Vertical)
        y += SkFloatToScalar(font->fontMetrics().floatAscent(IdeographicBaseline) - font->fontMetrics().floatAscent());
    // FIXME: text rendering speed:
    // Android has code in their WebCore fork to special case when the
    // GlyphBuffer has no advances other than the defaults. In that case the
    // text drawing can proceed faster. However, it's unclear when those
    // patches may be upstreamed to WebKit so we always use the slower path
    // here.
    const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
    SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
    SkPoint* pos = storage.get();

    for (int i = 0; i < numGlyphs; i++) {
        pos[i].set(x, y);
        x += SkFloatToScalar(adv[i].width);
        y += SkFloatToScalar(adv[i].height);
    }

    SkCanvas* canvas = gc->platformContext()->canvas();
    if (font->platformData().orientation() == Vertical) {
        canvas->save();
        canvas->rotate(-90);
        SkMatrix rotator;
        rotator.reset();
        rotator.setRotate(90);
        rotator.mapPoints(pos, numGlyphs);
    }
    TextDrawingModeFlags textMode = gc->platformContext()->getTextDrawingMode();

    // We draw text up to two times (once for fill, once for stroke).
    if (textMode & TextModeFill) {
        SkPaint paint;
        gc->platformContext()->setupPaintForFilling(&paint);
        setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts);
        gc->platformContext()->adjustTextRenderMode(&paint);
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);

        canvas->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, paint);
    }

    if ((textMode & TextModeStroke)
        && gc->platformContext()->getStrokeStyle() != NoStroke
        && gc->platformContext()->getStrokeThickness() > 0) {

        SkPaint paint;
        gc->platformContext()->setupPaintForStroking(&paint, 0, 0);
        setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts);
        gc->platformContext()->adjustTextRenderMode(&paint);
        paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);

        if (textMode & TextModeFill) {
            // If we also filled, we don't want to draw shadows twice.
            // See comment in FontChromiumWin.cpp::paintSkiaText() for more details.
            paint.setLooper(0);
        }

        canvas->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, paint);
    }
    if (font->platformData().orientation() == Vertical)
        canvas->restore();
}
Ejemplo n.º 23
0
QFileInfo Content::GetImageFile( const QString &sStorageGroup,
                            const QString &sFileName,
                            int nWidth,
                            int nHeight)
{
    QString sGroup = sStorageGroup;

    if (sGroup.isEmpty())
    {
        LOG(VB_UPNP, LOG_WARNING,
            "GetFile - StorageGroup missing... using 'Default'");
        sGroup = "Default";
    }

    if (sFileName.isEmpty())
    {
        QString sMsg ( "GetFile - FileName missing." );

        LOG(VB_UPNP, LOG_ERR, sMsg);

        throw sMsg;
    }

    // ------------------------------------------------------------------
    // Search for the filename
    // ------------------------------------------------------------------

    StorageGroup storage( sGroup );
    QString sFullFileName = storage.FindFile( sFileName );

    if (sFullFileName.isEmpty())
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("GetImageFile - Unable to find %1.").arg(sFileName));

        return QFileInfo();
    }

    // ----------------------------------------------------------------------
    // check to see if the file (still) exists
    // ----------------------------------------------------------------------

    if ((nWidth == 0) && (nHeight == 0))
    {
        if (QFile::exists( sFullFileName ))
        {
            return QFileInfo( sFullFileName );
        }

        LOG(VB_UPNP, LOG_ERR,
            QString("GetImageFile - File Does not exist %1.").arg(sFullFileName));

        return QFileInfo();
    }

    QString sNewFileName = QString( "%1.%2x%3.jpg" )
                              .arg( sFullFileName )
                              .arg( nWidth    )
                              .arg( nHeight   );

    // ----------------------------------------------------------------------
    // check to see if image is already created.
    // ----------------------------------------------------------------------

    if (QFile::exists( sNewFileName ))
        return QFileInfo( sNewFileName );

    // ----------------------------------------------------------------------
    // Must generate Generate Image and save.
    // ----------------------------------------------------------------------

    float fAspect = 0.0;

    QImage *pImage = new QImage( sFullFileName);

    if (!pImage)
        return QFileInfo();

    if (fAspect <= 0)
           fAspect = (float)(pImage->width()) / pImage->height();

    if ( nWidth == 0 )
        nWidth = (int)rint(nHeight * fAspect);

    if ( nHeight == 0 )
        nHeight = (int)rint(nWidth / fAspect);

    QImage img = pImage->scaled( nWidth, nHeight, Qt::KeepAspectRatio,
                                Qt::SmoothTransformation);

    QByteArray fname = sNewFileName.toLatin1();
    img.save( fname.constData(), "JPG", 60 );

    delete pImage;

    return QFileInfo( sNewFileName );
}
Ejemplo n.º 24
0
FormMessage::FormMessage (QWidget* parent, bool is_reply, const AMessageInfoGUI& info, int edit_id) : FormMessageUI (parent)
{
	m_text_changed = false;

	if (edit_id != 0)
		is_reply = false;

	m_edit_id = edit_id;

	connect(m_text_view->View->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(link_clicked(const QUrl&)));
	connect(m_text_view->View->page(), SIGNAL(linkHovered(const QString&, const QString&, const QString&)), this, SLOT(link_hover(const QString&, const QString&, const QString&)));

	m_forum_tree = NULL;
	m_main_form  = NULL;

	m_info = info;

	if (m_edit_id == 0)
	{
		m_info.IDParent = m_info.ID;
		m_info.ID = 0;
	}

	// получение информации о форуме сообщения
	// работает "по тихому", т.к. если возникнет ошибка, то это не сильно принципиально
	// и можно продолжать нормальную работу, а не пугать пользователя
	// https://rsdn.ru/forum/janus/3315591.1

	std::auto_ptr<IAStorage> storage(AStorageFactory::getStorage());

	if (storage.get() != NULL)
	{
		AForumInfo forum_info;

		if (storage->getForumInfo(m_info.IDForum, forum_info) != false)
			m_forum_info = forum_info;
	}

	// формирование текста при ответе
	if (is_reply == true)
	{
		QString subject = m_info.Subject;
		QString body    = m_info.Message;

		//
		// корректировка темы
		//

		if (subject.length() > 3 && subject.mid(0, 4) == "Re: ")
			subject.insert(2, "[2]");
		else if (subject.length() > 3 && subject.mid(0, 3) == "Re[")
		{
			int pos = subject.indexOf("]");

			if (pos != -1)
			{
				int num = subject.mid(3, pos - 3).toInt();

				if (num == 0)
					subject = "Re: " + subject;
				else
				{
					subject.remove(3, pos - 3);
					subject.insert(3, QString::number(num + 1));
				}
			}
			else
				subject = "Re: " + subject;
		}
		else
			subject = "Re: " + subject;

		m_info.Subject = subject;

		//
		// корректировка тела сообщения
		//

		body = AFormatter::normalizeBody(body, info.UserNick).trimmed();

		if (body.length() > 0)
			body += "\r\n\r\n";

		if (info.IDUser == 0)
			body = QString::fromUtf8("Здравствуйте, Аноним, Вы писали:\r\n\r\n") + body;
		else
			body = QString::fromUtf8("Здравствуйте, ") + info.UserNick + QString::fromUtf8(", Вы писали:\r\n\r\n") + body;

		m_info.Message = body;

	}   // if (is_reply == true)
	else
	{
		// замена HTML спец-символов
		m_info.Message.replace("&gt;",  ">");
		m_info.Message.replace("&lt;",  "<");
		m_info.Message.replace("&amp;", "&");
	}

	// удаление таглайнов
	QRegExp tagline("\\[tagline\\](.+)\\[/tagline\\]");
	tagline.setMinimal(true);
	m_info.Message.replace(tagline, "");
	//m_info.Message = m_info.Message.trimmed();

	// установка остальных полей
	m_text_subject->setText(m_info.Subject);
	m_text_source->setPlainText(m_info.Message);
	text_subject_text_changed(m_info.Subject);

	if (is_reply == true)
	{
		QIcon icon;
		icon.addFile(":/icons/reply16.png",  QSize(16, 16));
		icon.addFile(":/icons/reply22.png",  QSize(22, 22));
		icon.addFile(":/icons/reply32.png",  QSize(32, 32));
		icon.addFile(":/icons/reply48.png",  QSize(48, 48));
		setWindowIcon(icon);

		m_text_source->setFocus();

		m_text_source->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
	}
	else if (m_edit_id != 0)
	{
		QIcon icon;
		icon.addFile(":/icons/edit16.png",  QSize(16, 16));
		icon.addFile(":/icons/edit22.png",  QSize(22, 22));
		icon.addFile(":/icons/edit32.png",  QSize(32, 32));
		icon.addFile(":/icons/edit48.png",  QSize(48, 48));
		icon.addFile(":/icons/edit64.png",  QSize(64, 64));
		setWindowIcon(icon);

		m_text_source->setFocus();

		m_text_source->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
	}
	else
	{
		m_text_subject->setFocus();
		m_text_subject->selectAll();
	}

	// установка обработчиков формы
	connect(m_button_send,  SIGNAL(triggered()),                 this, SLOT(button_send_triggered()));
	connect(m_button_draft, SIGNAL(triggered()),                 this, SLOT(button_draft_triggered()));
	connect(m_text_subject, SIGNAL(textChanged(const QString&)), this, SLOT(text_subject_text_changed(const QString&)));
	connect(m_tab_message,  SIGNAL(currentChanged(int)),         this, SLOT(tab_changed(int)));
	connect(m_text_source,  SIGNAL(textChanged()),               this, SLOT(text_changed()));
}
Ejemplo n.º 25
0
 static Distribution* get_object_p()
 {
     return static_cast<Distribution*>(storage());
 }
Ejemplo n.º 26
0
void EventArchiver::archiveIncidences( Calendar* calendar, const QDate& /*limitDate*/, QWidget* widget, const Incidence::List& incidences, bool /*withGUI*/)
{
  FileStorage storage( calendar );

  // Save current calendar to disk
  KTempFile tmpFile;
  tmpFile.setAutoDelete(true);
  storage.setFileName( tmpFile.name() );
  if ( !storage.save() ) {
    kdDebug(5850) << "EventArchiver::archiveEvents(): Can't save calendar to temp file" << endl;
    return;
  }

  // Duplicate current calendar by loading in new calendar object
  CalendarLocal archiveCalendar( KOPrefs::instance()->mTimeZoneId );

  FileStorage archiveStore( &archiveCalendar );
  archiveStore.setFileName( tmpFile.name() );
  if (!archiveStore.load()) {
    kdDebug(5850) << "EventArchiver::archiveEvents(): Can't load calendar from temp file" << endl;
    return;
  }

  // Strip active events from calendar so that only events to be archived
  // remain. This is not really efficient, but there is no other easy way.
  QStringList uids;
  Incidence::List allIncidences = archiveCalendar.rawIncidences();
  Incidence::List::ConstIterator it;
  for( it = incidences.begin(); it != incidences.end(); ++it ) {
    uids << (*it)->uid();
  }
  for( it = allIncidences.begin(); it != allIncidences.end(); ++it ) {
    if ( !uids.contains( (*it)->uid() ) ) {
      archiveCalendar.deleteIncidence( *it );
    }
  }

  // Get or create the archive file
  KURL archiveURL( KOPrefs::instance()->mArchiveFile );
  QString archiveFile;

  if ( KIO::NetAccess::exists( archiveURL, true, widget ) ) {
    if( !KIO::NetAccess::download( archiveURL, archiveFile, widget ) ) {
      kdDebug(5850) << "EventArchiver::archiveEvents(): Can't download archive file" << endl;
      return;
    }
    // Merge with events to be archived.
    archiveStore.setFileName( archiveFile );
    if ( !archiveStore.load() ) {
      kdDebug(5850) << "EventArchiver::archiveEvents(): Can't merge with archive file" << endl;
      return;
    }
  } else {
    archiveFile = tmpFile.name();
  }

  // Save archive calendar
  if ( !archiveStore.save() ) {
    KMessageBox::error(widget,i18n("Cannot write archive file %1.").arg( archiveStore.fileName() ));
    return;
  }

  // Upload if necessary
  KURL srcUrl;
  srcUrl.setPath(archiveFile);
  if (srcUrl != archiveURL) {
    if ( !KIO::NetAccess::upload( archiveFile, archiveURL, widget ) ) {
      KMessageBox::error(widget,i18n("Cannot write archive to final destination."));
      return;
    }
  }

  KIO::NetAccess::removeTempFile(archiveFile);

  // Delete archived events from calendar
  for( it = incidences.begin(); it != incidences.end(); ++it ) {
    calendar->deleteIncidence( *it );
  }
  emit eventsDeleted();
}
Ejemplo n.º 27
0
void MetaData::typed_data::getData(
        uint32_t *type, const void **data, size_t *size) const {
    *type = mType;
    *size = mSize;
    *data = storage();
}
Ejemplo n.º 28
0
void testTrainICAAMGray()
{
    std::cout << "trainICTest testTrainICAAMGray" << std::endl;
    aam::AppearanceDataIC model;
    aam::TrainModelLoader loader;
    loader.useGrayImages(true);

    for (int i = 0; i < TRIANGLES_COUNT; i++)
    {
        model.triangles.push_back(cv::Vec3i(trianglesData[i * 3],
                trianglesData[i * 3 + 1], trianglesData[i * 3 + 2]));
    }

    try
    {
        std::vector<std::string> fileNames =
                boost::assign::list_of<std::string>
                ("107_0764.bmp")  /*("107_0766.bmp")*/  ("107_0779.bmp")
                ("107_0780.bmp")  ("107_0781.bmp")  ("107_0782.bmp")
                ("107_0783.bmp")  ("107_0784.bmp")  ("107_0785.bmp")
                ("107_0786.bmp")  ("107_0787.bmp")  ("107_0788.bmp")
                ("107_0789.bmp")  ("107_0790.bmp")  ("107_0791.bmp")
                ("107_0792.bmp")  ("107_0793.bmp")  ("107_0794.bmp")
                ("107_0795.bmp")  ("107_0798.bmp")  ("107_0799.bmp")
                ("107_0800.bmp")  ("108_0801.bmp")  ("108_0802.bmp")
                ("108_0803.bmp")  ("108_0804.bmp");
        
        for (int i = 0; i < fileNames.size(); i++)
        {
            std::ostringstream stream;

            stream << "data/cootes/" << fileNames[i] << ".mat.dat";
            std::string markupFile = stream.str();

            stream.str(std::string());

            stream << "data/cootes/" << fileNames[i];
            std::string imageFile = stream.str();

            loader.load(markupFile, imageFile);
        }

        std::vector<aam::TrainModelInfo> trainData = loader.getModels();
        aam::AAMFunctions2D::trainModelIC(0.95, trainData, model);

        if (!boost::filesystem::exists("output"))
        {
            boost::filesystem::create_directory("output");
        }

        cv::FileStorage storage("output/aam_ic_test.xml",
                cv::FileStorage::WRITE);
        storage << "R" << model.R;
        storage << "s" << model.s;
        storage << "s_star" << model.sStar;
        storage << "s0" << model.s0;
        storage << "A0" << model.A0;
        storage << "mask" << model.mask;
        storage << "triangles" << model.triangles;

        cv::Mat1i tmp(2, 1);
        tmp(0, 0) = model.textureSize.width;
        tmp(1, 0) = model.textureSize.height;
        storage << "texture_size" << tmp;
        storage.release();

        aam::RealMatrix targetR;
        if (!loadVector("data/aam_r_vectors.raw", model.nPixels, 20,
                targetR))
        {
            std::cout << "%TEST_FAILED% time=0 testname=testTrainICAAMGray (trainICTest) message=Can't reference R matrix" << std::endl;
            return;
        }

        aam::RealMatrix targetA;
        if (!loadVector("data/aam_a_vectors.raw", model.nPixels, 22,
                targetA))
        {
            std::cout << "%TEST_FAILED% time=0 testname=testTrainICAAMGray (trainICTest) message=Can't reference A matrix" << std::endl;
            return;
        }

        cv::Mat m, s;
        cv::meanStdDev(model.A, m, s);
        std::cout << m << std::endl;
        std::cout << s << std::endl;

        cv::meanStdDev(targetA, m, s);
        std::cout << m << std::endl;
        std::cout << s << std::endl;

        aam::RealMatrix Rsum, Rsum2;
        cv::reduce(model.R.t(), Rsum, 1, CV_REDUCE_SUM);
        cv::reduce(targetR, Rsum2, 1, CV_REDUCE_SUM);
        
            cv::Mat img, img2;
            aam::AAMFunctions2D::vector2Appearance(Rsum,
                    model.mask,
                    model.textureSize, img);
            aam::AAMFunctions2D::vector2Appearance(Rsum2,
                    model.mask,
                    model.textureSize, img2);

            cv::normalize(img2, img, 1, 0, cv::NORM_MINMAX);
            cv::imshow("test", img);
            cv::waitKey(0);
    }
    catch (std::exception& e)
    {
        std::cout << "%TEST_FAILED% time=0 testname=testTrainICAAMGray (trainICTest) message=Exception occured: " <<
                e.what() << std::endl;
    }
}
SkColorSpaceXform_A2B::SkColorSpaceXform_A2B(SkColorSpace_A2B* srcSpace,
                                             SkColorSpace_XYZ* dstSpace)
    : fLinearDstGamma(kLinear_SkGammaNamed == dstSpace->gammaNamed()) {
#if (SkCSXformPrintfDefined)
    static const char* debugGammaNamed[4] = {
        "Linear", "SRGB", "2.2", "NonStandard"
    };
    static const char* debugGammas[5] = {
        "None", "Named", "Value", "Table", "Param"
    };
#endif
    int currentChannels;
    switch (srcSpace->iccType()) {
        case SkColorSpace_Base::kRGB_ICCTypeFlag:
            currentChannels = 3;
            break;
        case SkColorSpace_Base::kCMYK_ICCTypeFlag:
            currentChannels = 4;
            // CMYK images from JPEGs (the only format that supports it) are actually
            // inverted CMYK, so we need to invert every channel.
            // TransferFn is y = -x + 1 for x < 1.f, otherwise 0x + 0, ie y = 1 - x for x in [0,1]
            this->addTransferFns({1.f, 0.f, 0.f, -1.f, 1.f, 0.f, 1.f}, 4);
            break;
        default:
            currentChannels = 0;
            SkASSERT(false);
    }
    // add in all input color space -> PCS xforms
    for (int i = 0; i < srcSpace->count(); ++i) {
        const SkColorSpace_A2B::Element& e = srcSpace->element(i);
        SkASSERT(e.inputChannels() == currentChannels);
        currentChannels = e.outputChannels();
        switch (e.type()) {
            case SkColorSpace_A2B::Element::Type::kGammaNamed:
                if (kLinear_SkGammaNamed == e.gammaNamed()) {
                    break;
                }

                // take the fast path for 3-channel named gammas
                if (3 == currentChannels) {
                    if (k2Dot2Curve_SkGammaNamed == e.gammaNamed()) {
                        SkCSXformPrintf("fast path from 2.2\n");
                        fElementsPipeline.append(SkRasterPipeline::from_2dot2);
                        break;
                    } else if (kSRGB_SkGammaNamed == e.gammaNamed()) {
                        SkCSXformPrintf("fast path from sRGB\n");
                        // Images should always start the pipeline as unpremul
                        fElementsPipeline.append_from_srgb(kUnpremul_SkAlphaType);
                        break;
                    }
                }

                SkCSXformPrintf("Gamma stage added: %s\n", debugGammaNamed[(int)e.gammaNamed()]);
                SkColorSpaceTransferFn fn;
                SkAssertResult(named_to_parametric(&fn, e.gammaNamed()));
                this->addTransferFns(fn, currentChannels);
                break;
            case SkColorSpace_A2B::Element::Type::kGammas: {
                const SkGammas& gammas = e.gammas();
                SkCSXformPrintf("Gamma stage added:");
                for (int channel = 0; channel < gammas.channels(); ++channel) {
                    SkCSXformPrintf("  %s", debugGammas[(int)gammas.type(channel)]);
                }
                SkCSXformPrintf("\n");
                bool gammaNeedsRef = false;
                for (int channel = 0; channel < gammas.channels(); ++channel) {
                    if (SkGammas::Type::kTable_Type == gammas.type(channel)) {
                        SkTableTransferFn table = {
                                gammas.table(channel),
                                gammas.data(channel).fTable.fSize,
                        };

                        this->addTableFn(table, channel);
                        gammaNeedsRef = true;
                    } else {
                        SkColorSpaceTransferFn fn;
                        SkAssertResult(gamma_to_parametric(&fn, gammas, channel));
                        this->addTransferFn(fn, channel);
                    }
                }
                if (gammaNeedsRef) {
                    fGammaRefs.push_back(sk_ref_sp(&gammas));
                }
                break;
            }
            case SkColorSpace_A2B::Element::Type::kCLUT:
                SkCSXformPrintf("CLUT (%d -> %d) stage added\n", e.colorLUT().inputChannels(),
                                                                 e.colorLUT().outputChannels());
                fCLUTs.push_back(sk_ref_sp(&e.colorLUT()));
                fElementsPipeline.append(SkRasterPipeline::color_lookup_table,
                                         fCLUTs.back().get());
                break;
            case SkColorSpace_A2B::Element::Type::kMatrix:
                if (!e.matrix().isIdentity()) {
                    SkCSXformPrintf("Matrix stage added\n");
                    addMatrix(e.matrix());
                }
                break;
        }
    }

    // Lab PCS -> XYZ PCS
    if (SkColorSpace_A2B::PCS::kLAB == srcSpace->pcs()) {
        SkCSXformPrintf("Lab -> XYZ element added\n");
        fElementsPipeline.append(SkRasterPipeline::lab_to_xyz);
    }

    // we should now be in XYZ PCS
    SkASSERT(3 == currentChannels);

    // and XYZ PCS -> output color space xforms
    if (!dstSpace->fromXYZD50()->isIdentity()) {
        addMatrix(*dstSpace->fromXYZD50());
    }

    switch (dstSpace->gammaNamed()) {
        case kLinear_SkGammaNamed:
            // do nothing
            break;
        case k2Dot2Curve_SkGammaNamed:
            fElementsPipeline.append(SkRasterPipeline::to_2dot2);
            break;
        case kSRGB_SkGammaNamed:
            fElementsPipeline.append(SkRasterPipeline::to_srgb);
            break;
        case kNonStandard_SkGammaNamed: {
            for (int channel = 0; channel < 3; ++channel) {
                const SkGammas& gammas = *dstSpace->gammas();
                if (SkGammas::Type::kTable_Type == gammas.type(channel)) {
                    static constexpr int kInvTableSize = 256;
                    std::vector<float> storage(kInvTableSize);
                    invert_table_gamma(storage.data(), nullptr, storage.size(),
                                       gammas.table(channel),
                                       gammas.data(channel).fTable.fSize);
                    SkTableTransferFn table = {
                            storage.data(),
                            (int) storage.size(),
                    };
                    fTableStorage.push_front(std::move(storage));

                    this->addTableFn(table, channel);
                } else {
                    SkColorSpaceTransferFn fn;
                    SkAssertResult(gamma_to_parametric(&fn, gammas, channel));
                    this->addTransferFn(fn.invert(), channel);
                }
            }
        }
        break;
    }
}
Ejemplo n.º 30
0
void GroundProgramBuilder::add()
{
	switch(stack_->type)
	{
		case LIT:
		{
			stack_->lits.push_back(Lit::create(stack_->type, stack_->vals.size() - stack_->n - 1, stack_->n));
			break;
		}
		case TERM:
		{
			if(stack_->n > 0)
			{
				ValVec vals;
				std::copy(stack_->vals.end() - stack_->n, stack_->vals.end(), std::back_inserter(vals));
				stack_->vals.resize(stack_->vals.size() - stack_->n);
				uint32_t name = stack_->vals.back().index;
				stack_->vals.back()  = Val::func(storage()->index(Func(storage(), name, vals)));
			}
			break;
		}
		case AGGR_SUM:
		case AGGR_COUNT:
		case AGGR_AVG:
		case AGGR_MIN:
		case AGGR_MAX:
		case AGGR_EVEN:
		case AGGR_EVEN_SET:
		case AGGR_ODD:
		case AGGR_ODD_SET:
		case AGGR_DISJUNCTION:
		{
			assert(stack_->type != AGGR_DISJUNCTION || stack_->n > 0);
			std::copy(stack_->lits.end() - stack_->n, stack_->lits.end(), std::back_inserter(stack_->aggrLits));
			stack_->lits.resize(stack_->lits.size() - stack_->n);
			stack_->lits.push_back(Lit::create(stack_->type, stack_->n ? stack_->aggrLits.size() - stack_->n : stack_->vals.size() - 2, stack_->n));
			break;
		}
		case STM_RULE:
		case STM_CONSTRAINT:
		{
			Rule::Printer *printer = output_->printer<Rule::Printer>();
			printer->begin();
			if(stack_->type == STM_RULE)             { printLit(printer, stack_->lits.size() - stack_->n - 1, true); }
			printer->endHead();
			for(uint32_t i = stack_->n; i >= 1; i--) { printLit(printer, stack_->lits.size() - i, false); }
			printer->end();
			pop(stack_->n + (stack_->type == STM_RULE));
			break;
		}
		case STM_SHOW:
		case STM_HIDE:
		{
			Display::Printer *printer = output_->printer<Display::Printer>();
			printLit(printer, stack_->lits.size() - 1, stack_->type == STM_SHOW);
			pop(1);
			break;
		}
		case STM_EXTERNAL:
		{
			External::Printer *printer = output_->printer<External::Printer>();
			printLit(printer, stack_->lits.size() - 1, true);
			pop(1);
			break;
		}
		#pragma message "reimplement this"
		/*
		case STM_MINIMIZE:
		case STM_MAXIMIZE:
		case STM_MINIMIZE_SET:
		case STM_MAXIMIZE_SET:
		{
			Optimize::Printer *printer = output_->printer<Optimize::Printer>();
			bool maximize = (stack_->type == STM_MAXIMIZE || stack_->type == STM_MAXIMIZE_SET);
			bool set = (stack_->type == STM_MINIMIZE_SET || stack_->type == STM_MAXIMIZE_SET);
			printer->begin(maximize, set);
			for(uint32_t i = stack_->n; i >= 1; i--)
			{

				Lit &a     = stack_->lits[stack_->lits.size() - i];
				Val prio   = stack_->vals[a.offset + a.n + 2];
				Val weight = stack_->vals[a.offset + a.n + 1];
				printer->print(predLitRep(a), weight.num, prio.num);
			}
			printer->end();
			pop(stack_->n);
			break;
		}
		*/
		case STM_COMPUTE:
		{
			Compute::Printer *printer = output_->printer<Compute::Printer>();
			for(uint32_t i = stack_->n; i >= 1; i--)
			{
				Lit &a = stack_->lits[stack_->lits.size() - i];
				printer->print(predLitRep(a));
			}
			pop(stack_->n);
			break;
		}
#pragma message "reimplement me!"
		//case META_SHOW:
		//case META_HIDE:
//		case META_EXTERNAL:
//		{
//			Val num = stack_->vals.back();
//			stack_->vals.pop_back();
//			Val id  = stack_->vals.back();
//			stack_->vals.pop_back();
//			assert(id.type == Val::ID);
//			assert(num.type == Val::NUM);
//			storage()->newDomain(id.index, num.num);
//			if(stack_->type == META_EXTERNAL) { output_->external(id.index, num.num); }
//			//else { output_->show(id.index, num.num, stack_->type == META_SHOW); }
//			break;
//		}
#pragma message "reimplement me!"
		//case META_GLOBALSHOW:
		case META_GLOBALHIDE:
		{
			output_->hideAll();
			break;
		}
		default: {
			doAdd();
		}
	}
}