Ejemplo n.º 1
0
void MainWindow::process() {
    m_dirty = false;
    QImage qsrc = m_player->image();
    if (qsrc.isNull()) {
        m_result[0] = m_result[1] = m_result[2] = qsrc;
        imageChanged(image());
        return;
    }

    gpu_image<float4> src = gpu_image_from_qimage<float4>(qsrc);
    if (input_gamma == "linear-rgb") {
        src = gpu_linear2srgb(src);
    }

    gpu_image<float4> lab = gpu_rgb2lab(src);

    gpu_image<float4> st;
    if (st_type == "central-diff") {
        st = gpu_st_central_diff(gpu_rgb2gray(src));
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else if (st_type == "sobel-rgb") {
        st = gpu_st_sobel(src);
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else if (st_type == "sobel-lab") {
        st = gpu_st_sobel(lab);
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else if (st_type == "sobel-L") {
        st = gpu_st_sobel(gpu_shuffle(lab,0));
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else  if (st_type == "scharr-rgb") {
        st = gpu_st_scharr(src);
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else  if (st_type == "scharr-lab") {
        st = gpu_st_scharr(lab);
        st = gpu_gauss_filter_xy(st, sigma_c, precision_sigma_c);
    }
    else if (st_type == "etf-full") {
        gpu_image<float2> tfm = gpu_etf_full(gpu_rgb2gray(src), sigma_c, etf_N);
        st = gpu_st_from_tangent(tfm);
    }
    else if (st_type == "etf-xy") {
        gpu_image<float2> tfm = gpu_etf_xy(gpu_rgb2gray(src), sigma_c, etf_N);
        st = gpu_st_from_tangent(tfm);
    }
    else if (st_type == "gaussian-deriv") {
        st = gpu_st_gaussian(gpu_rgb2gray(src), sqrtf(0.433f*0.433f + sigma_c*sigma_c));
    }
    else {
        assert(0);
    }

    gpu_image<float4> lfm = gpu_st_lfm(st, bf_alpha);

    gpu_image<float> flow;
    if (!m_noise.is_valid() || (m_noise.size() != src.size())) {
        m_noise = gpu_noise_random(st.w(), st.h(), -1, 2);
    }
    flow = m_noise;
    flow = gpu_stgauss2_filter(flow, st, 6, 22.5f, false, true, true, 2, 1.0f, 2);
    flow = gpu_stgauss2_filter(flow, st, 1, 22.5, false, true, true, 2, 1.0f, 2 );

    gpu_image<float4> img = lab;
    gpu_image<float4> Ie = img;
    gpu_image<float4> Ia = img;

    if (enable_bf) {
        int N = std::max(n_e, n_a);
        for (int i = 0; i < N; ++i) {
            if (filter_type == "oa") {
                img = gpu_oabf_1d(img, lfm, sigma_dg, sigma_rg, false, precision_g);
                img = gpu_oabf_1d(img, lfm, sigma_dt, sigma_rt, true, precision_t);
            } else if (filter_type == "xy") {
                img = gpu_bilateral_filter_xy(img, sigma_dg, sigma_rg);
            } else if (filter_type == "fbl") {
                img = gpu_oabf_1d(img, lfm, sigma_dg, sigma_rg, false, precision_g);
                img = gpu_stbf2_filter(img, st, sigma_dt, sigma_rt, precision_t, 90.0f, false, true, true, 2, 1);
            } else {
                img = gpu_bilateral_filter(img, sigma_dg, sigma_rg);
            }
            if (i == (n_e - 1)) Ie = img;
            if (i == (n_a - 1)) Ia = img;
        }
    }

    gpu_image<float> L;
    if (output != "fill") {
        L = gpu_shuffle(Ie, 0);
        if (dog_type == "flow-based") {
            if (!dog_reparam)
                L = gpu_gradient_dog( L, lfm, sigma_e, dog_k, dog_tau, precision_e );
            else
                L = gpu_gradient_dog2( L, lfm, sigma_e, dog_k, dog_p, precision_e );

            if (dog_fgauss == "euler") {
                L = gpu_stgauss2_filter(L, st, sigma_m, 90, false, false, false, 1, step_m, precision_m);
            } else if (dog_fgauss == "rk2-nn") {
                L = gpu_stgauss2_filter(L, st, sigma_m, 90, false, false, false, 2, step_m, precision_m);
            } else if (dog_fgauss == "rk2") {
                L = gpu_stgauss2_filter(L, st, sigma_m, 90, false, true, true, 2, step_m, precision_m);
            } else if (dog_fgauss == "rk4") {
                L = gpu_stgauss2_filter(L, st, sigma_m, 90, false, true, true, 4, step_m, precision_m);
            }
        } else {
            if (!dog_reparam)
                L = gpu_isotropic_dog( L, sigma_e, dog_k, dog_tau, precision_e );
            else
                L = gpu_isotropic_dog2( L, sigma_e, dog_k, dog_p, precision_e );

        }

        {
            float eps, phi;
            if (!dog_reparam) {
                eps = dog_eps;
                phi = dog_phi;
            } else {
                eps = dog_eps_p;

#ifndef ANGLE_PHI
                phi = dog_phi_p;
#else
                phi = .tan( M_PI*(dog_phi_p/180) );
                //phi = .01*tan( M_PI*(dog_phi_p/180) );
#endif
            }

            if (dog_adj_func == "smoothstep")  {
                L = gpu_dog_threshold_smoothstep(L, eps, phi);
            } else {
                L = gpu_dog_threshold_tanh(L, eps, phi);
            }
        }
    }
Ejemplo n.º 2
0
/*!
  \brief Draw the raster data
  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rectangle of the plot canvas
*/
void QwtPlotRasterItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( canvasRect.isEmpty() || d_data->alpha == 0 )
        return;

    const bool doCache = qwtUseCache( d_data->cache.policy, painter );

    const QwtInterval xInterval = interval( Qt::XAxis );
    const QwtInterval yInterval = interval( Qt::YAxis );

    /*
        Scaling an image always results in a loss of
        precision/quality. So we always render the image in
        paint device resolution.
    */

    QwtScaleMap xxMap, yyMap;
    qwtTransformMaps( painter->transform(), xMap, yMap, xxMap, yyMap );

    QRectF paintRect = painter->transform().mapRect( canvasRect );
    QRectF area = QwtScaleMap::invTransform( xxMap, yyMap, paintRect );

    const QRectF br = boundingRect();
    if ( br.isValid() && !br.contains( area ) )
    {
        area &= br;
        if ( !area.isValid() )
            return;

        paintRect = QwtScaleMap::transform( xxMap, yyMap, area );
    }

    QRectF imageRect;
    QImage image;

    QRectF pixelRect = pixelHint(area);
    if ( !pixelRect.isEmpty() )
    {
        // one pixel of the target device in plot coordinates
        const double dx = qAbs( xxMap.invTransform( 1 ) - xxMap.invTransform( 0 ) );
        const double dy = qAbs( yyMap.invTransform( 1 ) - yyMap.invTransform( 0 ) );

        if ( dx > pixelRect.width() && dy > pixelRect.height() )
        {
            /*
              When the resolution of the data pixels is higher than
              the resolution of the target device we render in
              target device resolution.
             */
            pixelRect = QRectF();
        }
        else
        {
            /*
              If only one dimension is of the data pixel is higher
              we expand the pixel rect to the resolution of the target device.
             */

            if ( dx > pixelRect.width() )
                pixelRect.setWidth( dx );

            if ( dy > pixelRect.height() )
                pixelRect.setHeight( dy );
        }
    }

    if ( pixelRect.isEmpty() )
    {
        if ( QwtPainter::roundingAlignment( painter ) )
        {
            // we want to have maps, where the boundaries of
            // the aligned paint rectangle exactly match the area

            paintRect = qwtAlignRect(paintRect);
            qwtAdjustMaps(xxMap, yyMap, area, paintRect);
        }

        // When we have no information about position and size of
        // data pixels we render in resolution of the paint device.

        image = compose(xxMap, yyMap,
            area, paintRect, paintRect.size().toSize(), doCache);
        if ( image.isNull() )
            return;

        // Remove pixels at the boundaries, when explicitly
        // excluded in the intervals

        imageRect = qwtStripRect(paintRect, area,
            xxMap, yyMap, xInterval, yInterval);

        if ( imageRect != paintRect )
        {
            const QRect r(
                qRound( imageRect.x() - paintRect.x()),
                qRound( imageRect.y() - paintRect.y() ),
                qRound( imageRect.width() ),
                qRound( imageRect.height() ) );

            image = image.copy(r);
        }
    }
    else
    {
        if ( QwtPainter::roundingAlignment( painter ) )
            paintRect = qwtAlignRect(paintRect);

        // align the area to the data pixels
        QRectF imageArea = qwtExpandToPixels(area, pixelRect);

        if ( imageArea.right() == xInterval.maxValue() &&
            !( xInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, pixelRect.width(), 0);
        }
        if ( imageArea.bottom() == yInterval.maxValue() &&
            !( yInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, 0, pixelRect.height() );
        }

        QSize imageSize;
        imageSize.setWidth( qRound( imageArea.width() / pixelRect.width() ) );
        imageSize.setHeight( qRound( imageArea.height() / pixelRect.height() ) );

        image = compose(xxMap, yyMap,
            imageArea, paintRect, imageSize, doCache );

        if ( image.isNull() )
            return;

        imageRect = qwtStripRect(paintRect, area,
            xxMap, yyMap, xInterval, yInterval);

        if ( ( image.width() > 1 || image.height() > 1 ) &&
            testPaintAttribute( PaintInDeviceResolution ) )
        {
            // Because of rounding errors the pixels
            // need to be expanded manually to rectangles of
            // different sizes

            image = qwtExpandImage(image, xxMap, yyMap,
                imageArea, area, paintRect, xInterval, yInterval );
        }
    }

    painter->save();
    painter->setWorldTransform( QTransform() );

    QwtPainter::drawImage( painter, imageRect, image );

    painter->restore();
}
Ejemplo n.º 3
0
void QMapboxGL::addImage(const QString &name, const QImage &sprite)
{
    if (sprite.isNull()) return;

    d_ptr->mapObj->addImage(name.toStdString(), toSpriteImage(sprite));
}
Ejemplo n.º 4
0
static
void read_jpeg_image(QImageIO* iio)
{
    QImage image;

    struct jpeg_decompress_struct cinfo;

    struct my_jpeg_source_mgr *iod_src = new my_jpeg_source_mgr(iio);
    struct my_error_mgr jerr;

    jpeg_create_decompress(&cinfo);

    cinfo.src = iod_src;

    cinfo.err = jpeg_std_error(&jerr);
    jerr.error_exit = my_error_exit;

    if (!setjmp(jerr.setjmp_buffer)) {
#if defined(_OS_UNIXWARE7_)
        (void) jpeg_read_header(&cinfo, B_TRUE);
#else
        (void) jpeg_read_header(&cinfo, TRUE);
#endif

        (void) jpeg_start_decompress(&cinfo);

        if ( cinfo.output_components == 3 || cinfo.output_components == 4) {
            image.create( cinfo.output_width, cinfo.output_height, 32 );
        } else if ( cinfo.output_components == 1 ) {
            image.create( cinfo.output_width, cinfo.output_height, 8, 256 );
            for (int i=0; i<256; i++)
                image.setColor(i, qRgb(i,i,i));
        } else {
            // Unsupported format
        }

        if (!image.isNull()) {
            uchar** lines = image.jumpTable();
            while (cinfo.output_scanline < cinfo.output_height)
                (void) jpeg_read_scanlines(&cinfo,
                                           lines + cinfo.output_scanline,
                                           cinfo.output_height);
            (void) jpeg_finish_decompress(&cinfo);
        }

        if ( cinfo.output_components == 3 ) {
            // Expand 24->32 bpp.
            for (uint j=0; j<cinfo.output_height; j++) {
                uchar *in = image.scanLine(j) + cinfo.output_width * 3;
                QRgb *out = (QRgb*)image.scanLine(j);

                for (uint i=cinfo.output_width; i--; ) {
                    in-=3;
                    out[i] = qRgb(in[0], in[1], in[2]);
                }
            }
        }
        iio->setImage(image);
        iio->setStatus(0);
    }

    jpeg_destroy_decompress(&cinfo);
    delete iod_src;
}
Ejemplo n.º 5
0
void GSVWrapper::processQueue()
{
    if (requestQueue.isEmpty()) {
        qDebug() <<  "GSVWrapper::processQueue(): requestQueue is empty";
        return;
    } else {
        qDebug() << "GSVWrapper::processQueue()";
        printRequests(); // Debug
    }

    foreach(QSharedPointer<Request> req, requestQueue) {
        switch (req->state()) {
        case Request::Unready:
            req->setState(Request::Running);
            switch (req->type()) {
            case Request::Pano: {
                    qDebug() << "Requesting panorama" << req->lat << req->lng;
                    if (req->getMetadata() != 0) {
                        // Metadata is already fetched
                        QVector2D v = getZoomLevel(req->zoomLevel);
                        qDebug() << QString("Zoomlevel %1 max x = %2 and max y = %3").arg(req->zoomLevel).arg(v.x()).arg(v.y());

                        // Here is tile logic
                        for (int x = 0; x < v.x(); x++) {
                            for (int y = 0; y < v.y(); y++) {

                                QImage tile = filehandler.getTile(req->getMetadata()->lat.toDouble(),
                                                                  req->getMetadata()->lng.toDouble(),
                                                                  x, y, req->zoomLevel);
                                if (tile.isNull()) { // Must get tile from network
                                    networkhandler.getTile(req->id,
                                                           req->getMetadata()->pano_id,
                                                           req->zoomLevel,
                                                           x, y, req->priority);
                                } else { // Tile found from cache
                                    // Save tile to current panorama
                                    Tile *t = new Tile(x, y, req->zoomLevel, tile);
                                    req->getPanorama()->addTile(*t);

                                    emit tileReady(tile, req->lat, req->lng, x, y, req->zoomLevel);
                                }
                            }
                        }

                    } else { // Panorama request, but must fetch first metadata
                        qDebug() << "Get metadata first for" << req->id;
                        getMeta(req);
                    }
                }
                break;
            case Request::Meta:
                qDebug() << "Requesting metafield" << req->fieldName;
                networkhandler.getMeta(req->id, req->lat, req->lng);
                break;
            default:
                qDebug() << "GSVWrapper::handleMetadata: Error: Unkown request type";
                break;
            }
            break;
            case Request::Running:
            break;
            case Request::Ready:
            break;
            default:
            qDebug() << "Unknown request state";
            break;
        }
    }

    removeReadyRequests();
}
Ejemplo n.º 6
0
void GeometryPainter::drawPolygon(QPainter& pt, const OGRPolygon* polygon, const QMatrix& m)
{
  QPen pen = pt.pen();
  QBrush brush = pt.brush();

  if (polygon->getNumInteriorRings() > 0)
  {
    QPainter* lpt = NULL;
    QImage* image = new QImage(pt.window().size(), QImage::Format_ARGB32);
    if (image->isNull() == true)
    {
      delete image;
      throw Exception("Internal Error: GeometryPainter::drawPolygon "
                      "Error allocating image.");
    }
    image->fill(qRgba(0, 0, 0, 0));
    lpt = new QPainter(image);
    lpt->setMatrix(pt.matrix());
    lpt->setPen(pen);
    lpt->setBrush(brush);

    const OGRLinearRing* ring = polygon->getExteriorRing();
    QPolygonF qp;
    _convertRingToQPolygon(ring, qp, m);

    lpt->setPen(Qt::NoPen);
    lpt->setBrush(brush);
    lpt->drawPolygon(qp, Qt::WindingFill);

    lpt->setPen(pen);
    lpt->setBrush(Qt::NoBrush);
    lpt->drawPolygon(qp);
    for (int i = 0; i < polygon->getNumInteriorRings(); i++)
    {
      ring = polygon->getInteriorRing(i);

      // draw the appropriate border around the section we erased.
      _convertRingToQPolygon(ring, qp, m);

      // clear out the hole
      lpt->setPen(Qt::NoPen);
      lpt->setBrush(QColor(0, 0, 0, 0));
      lpt->setCompositionMode(QPainter::CompositionMode_Clear);
      lpt->drawPolygon(qp, Qt::WindingFill);

      lpt->setPen(pen);
      lpt->setBrush(Qt::NoBrush);
      lpt->setCompositionMode(QPainter::CompositionMode_SourceOver);
      lpt->drawPolygon(qp, Qt::WindingFill);
    }

    lpt->end();

    QMatrix m = pt.matrix();
    pt.resetMatrix();
    pt.drawImage(pt.window(), *image);
    pt.setMatrix(m);

    delete lpt;
    delete image;
  }
  else
  {
    const OGRLinearRing* ring = polygon->getExteriorRing();
    QPolygonF qp;
    _convertRingToQPolygon(ring, qp, m);

    pt.setPen(Qt::NoPen);
    pt.setBrush(brush);
    pt.drawPolygon(qp, Qt::WindingFill);

    pt.setPen(pen);
    pt.setBrush(Qt::NoBrush);
    pt.drawPolygon(qp);
  }
}
Ejemplo n.º 7
0
void burnDialog::on_BurnFlashButton_clicked()
{
  if (hexType==FLASH_FILE_TYPE) {
    QString fileName=ui->FWFileName->text();
    if (!fileName.isEmpty()) {
      g.flashDir( QFileInfo(fileName).dir().absolutePath() );
      if (!ui->useFwImageCB->isChecked()) {
        QImage image = ui->imageLabel->pixmap()->toImage().scaled(ui->imageLabel->width(), ui->imageLabel->height());
        if (!image.isNull()) {
          QString tempDir = QDir::tempPath();
          QString tempFile;
          if (getFileType(fileName) == FILE_TYPE_HEX)
            tempFile = tempDir + "/flash.hex";
          else
            tempFile = tempDir + "/flash.bin";
          FlashInterface flash(fileName);
          flash.setSplash(image);
          if (flash.saveFlash(tempFile) > 0) {
            hexfileName->clear();
            hexfileName->append(tempFile);
          } else {
            hexfileName->clear();
            QMessageBox::critical(this, tr("Warning"), tr("Cannot save customized firmware"));
          }
        }
        else {
          hexfileName->clear();
          QMessageBox::critical(this, tr("Warning"), tr("Custom image not found"));
        }
      }
      else {
        hexfileName->clear();
        hexfileName->append(fileName);
      }
    }
    else {
      QMessageBox::critical(this, tr("Warning"), tr("No firmware selected"));
      hexfileName->clear();     
    }
  }
  if (hexType==EEPROM_FILE_TYPE) {
    QString calib = g.profile[g.id()].stickPotCalib();
    QString trainercalib = g.profile[g.id()].trainerCalib();
    int potsnum=GetCurrentFirmware()->getCapability(Pots);
    int8_t vBatCalib=(int8_t) g.profile[g.id()].vBatCalib();
    int8_t currentCalib=(int8_t) g.profile[g.id()].currentCalib();
    int8_t PPM_Multiplier=(int8_t) g.profile[g.id()].ppmMultiplier();
    uint8_t GSStickMode=(uint8_t) g.profile[g.id()].gsStickMode();
    uint8_t vBatWarn=(uint8_t) g.profile[g.id()].vBatWarn();
    
    QString DisplaySet= g.profile[g.id()].display();
    QString BeeperSet= g.profile[g.id()].beeper();
    QString HapticSet= g.profile[g.id()].haptic();
    QString SpeakerSet= g.profile[g.id()].speaker();
    bool patch=false;
    if (ui->patchcalib_CB->isChecked()) {
      if ((calib.length()==(NUM_STICKS+potsnum)*12) && (trainercalib.length()==16)) {
        QString Byte;
        int16_t byte16;
        bool ok;
        for (int i=0; i<(NUM_STICKS+potsnum); i++) {
          Byte=calib.mid(i*12,4);
          byte16=(int16_t)Byte.toInt(&ok,16);
          if (ok)
            radioData.generalSettings.calibMid[i]=byte16;
          Byte=calib.mid(4+i*12,4);
          byte16=(int16_t)Byte.toInt(&ok,16);
          if (ok)
            radioData.generalSettings.calibSpanNeg[i]=byte16;
          Byte=calib.mid(8+i*12,4);
          byte16=(int16_t)Byte.toInt(&ok,16);
          if (ok)
            radioData.generalSettings.calibSpanPos[i]=byte16;
        }
        for (int i=0; i<4; i++) {
          Byte=trainercalib.mid(i*4,4);
          byte16=(int16_t)Byte.toInt(&ok,16);
          if (ok)
            radioData.generalSettings.trainer.calib[i]=byte16;
        }
        radioData.generalSettings.currentCalib=currentCalib;
        radioData.generalSettings.vBatCalib=vBatCalib;
        radioData.generalSettings.PPM_Multiplier=PPM_Multiplier;
        patch=true;
      } else {
        QMessageBox::critical(this, tr("Warning"), tr("Wrong radio calibration data in profile, Settings not patched"));
      }
    }
    if (ui->patchhw_CB->isChecked()) {
      if ((DisplaySet.length()==6) && (BeeperSet.length()==4) && (HapticSet.length()==6) && (SpeakerSet.length()==6)) {
        radioData.generalSettings.vBatWarn=vBatWarn;
        radioData.generalSettings.stickMode=GSStickMode;
        uint8_t byte8u;
        int8_t byte8;
        bool ok;
        byte8=(int8_t)DisplaySet.mid(0,2).toInt(&ok,16);
        if (ok)
          radioData.generalSettings.optrexDisplay=(byte8==1 ? true : false);
        byte8u=(uint8_t)DisplaySet.mid(2,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.contrast=byte8u;

        byte8u=(uint8_t)DisplaySet.mid(4,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.backlightBright=byte8u;

        byte8u=(uint8_t)BeeperSet.mid(0,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.beeperMode=(BeeperMode)byte8u;

        byte8=(int8_t)BeeperSet.mid(2,2).toInt(&ok,16);
        if (ok)
          radioData.generalSettings.beeperLength=byte8;

        byte8u=(uint8_t)HapticSet.mid(0,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.hapticMode=(BeeperMode)byte8u;

        byte8u=(uint8_t)HapticSet.mid(2,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.hapticStrength=byte8u;

        byte8=(int8_t)HapticSet.mid(4,2).toInt(&ok,16);
        if (ok)
          radioData.generalSettings.hapticLength=byte8;

        byte8u=(uint8_t)SpeakerSet.mid(0,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.speakerMode=byte8u;

        byte8u=(uint8_t)SpeakerSet.mid(2,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.speakerPitch=byte8u;

        byte8u=(uint8_t)SpeakerSet.mid(4,2).toUInt(&ok,16);
        if (ok)
          radioData.generalSettings.speakerVolume=byte8u;
        patch=true;
      } else {
        QMessageBox::critical(this, tr("Warning"), tr("Wrong radio setting data in profile, Settings not patched"));
      }
    
      QString fileName;
      if (patch) {
        QString tempDir    = QDir::tempPath();
        fileName = tempDir + "/temp.bin";
        QFile file(fileName);

        uint8_t *eeprom = (uint8_t*)malloc(GetEepromInterface()->getEEpromSize());
        int eeprom_size = 0;

        eeprom_size = GetEepromInterface()->save(eeprom, radioData, GetCurrentFirmwareVariant());
        if (!eeprom_size) {
          QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(fileName).arg(file.errorString()));
          hexfileName->clear();
        }

        if (!file.open(QIODevice::WriteOnly)) {
          QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(fileName).arg(file.errorString()));
          hexfileName->clear();
        }

        QTextStream outputStream(&file);

        long result = file.write((char*)eeprom, eeprom_size);
        if(result!=eeprom_size) {
          QMessageBox::warning(this, tr("Error"),tr("Error writing file %1:\n%2.").arg(fileName).arg(file.errorString()));
          hexfileName->clear();
        }
        hexfileName->clear();
        hexfileName->append(fileName);
      } else {
        hexfileName->clear();
        hexfileName->append(ui->FWFileName->text());        
      }
    } else {
      hexfileName->clear();
      hexfileName->append(ui->FWFileName->text());        
    }
  }
  this->close();
}
Ejemplo n.º 8
0
/**
 * Program entrypoint.
 */
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QWidget window;

    unsigned char *raw_data;
    unsigned char *buf;
    int *color_freqs;
    int *unique_pals;
    int unique_pals_count;
    int *pal_indexes;
    unsigned char *pal_data;
    int *pal_sizes;
    unsigned char *tile_data;
    int tile_data_sz;
    unsigned char *attrib_data;
    int attrib_data_sz;
    const char *input_filename = 0;
    const char *chr_output_filename = 0;
    const char *pal_output_filename = 0;
    const char *attrib_output_filename = 0;
    int width = -1;
    int height = -1;

    /* Process arguments. */
    if (!process_args(argv, &input_filename, &chr_output_filename, &pal_output_filename,
                      &attrib_output_filename, &width, &height)) {
        return(-1);
    }

    /* check arguments */
    if (!input_filename) {
        fprintf(stderr, "img2nes: no filename given\n");
        return(-1);
    }
#if 0
    if (width == -1 || height == -1) {
        fprintf(stderr, "img2nes: please specify width and height of image\n");
        return(-1);
    }
    if (width % 16 || height % 16) {
        fprintf(stderr, "img2nes: width and height must be multiples of 16\n");
        return(-1);
    }
#endif

    QImage originalImage = QImage(input_filename).convertToFormat(QImage::Format_RGB32);
    if (originalImage.isNull()) {
        fprintf(stderr, "img2nes: unable to read image '%s'\n", input_filename);
        return(-1);
    }
    width = originalImage.width();
    height = originalImage.height();

    /* allocate some buffers */
    raw_data = (unsigned char *)malloc(width * height * 3);
    buf = (unsigned char *)malloc(width * height);
    tile_data_sz = (height / 8) * (width / 8) * 16 * sizeof(unsigned char);
    tile_data = (unsigned char *)malloc(tile_data_sz);
    if (!raw_data || !buf || !tile_data) {
        fprintf(stderr, "img2nes: failed to allocate memory for image data\n");
        return(0);
    }

#if 0
    /* read input image */
    if (!read_image(input_filename, width, height, /*has_alpha=*/0, raw_data))
        return(-1);
#endif

    /* convert raw RGB to nes palette indices */
    convert_to_nes_colors(originalImage.bits(), width, height, /*has_alpha=*/1, buf);

    QImage originalNesImage = to_qimage(buf, width, height);

    QImage reducedColorsImage;
    QImage reducedPalettesImage;

    /* that was the easy part */
    {
        int i, j;
        int cw = width / 16;
        int ch = height / 16;
        color_freqs = (int*)calloc(cw * ch,  64 * sizeof(int));
        pal_data = (unsigned char *)malloc(cw * ch * 4 * sizeof(unsigned char));
        pal_sizes = (int*)malloc(cw * ch * sizeof(int));
        /* process all 16x16 blocks */
        for (i = 0; i < ch; ++i) {
            for (j = 0; j < cw; ++j) {
                int num_colors;
                unsigned char pal[64];
                int *f = &color_freqs[(i*cw+j)*64];
                /* count frequency of colors */
                count_nes_color_frequencies(&buf[i*16*width+(j*16)], 16, 16, width, f);
                f[0x0F] = INT_MAX;

                /* record the colors that are actually used */
                nes_palette_from_color_frequencies(f, pal, &num_colors);

#if 0
                {
                    printf("palette: ");
                    for (int k = 0; k < num_colors; ++k) {
                        printf("%.2X ", pal[k]);
                    }
                    printf("\n");
                }
#endif

                /* reduce number of colors if necessary */
                reduce_colors(&buf[i*16*width+(j*16)], 16, 16, width, f, pal, &num_colors);

                /* sort the palette so that different palettes can be easily compared */
                qsort(pal, num_colors, sizeof(unsigned char), compare_nes_colors);
#if 0
                {
                    printf("sorted palette: ");
                    for (int k = 0; k < num_colors; ++k) {
                        printf("%.2X ", pal[k]);
                    }
                    printf("\n");
                }
#endif

                /* store the final palette for this 16x16 block */
                assert(num_colors <= 4);
                memcpy(&pal_data[(i*cw+j)*4], pal, num_colors * sizeof(unsigned char));
                pal_sizes[i*cw+j] = num_colors;
            }
        }

        reducedColorsImage = to_qimage(buf, width, height);

        /* now each 16x16 block uses max 4 unique colors
           the next step is to reduce the number of 4-color palettes, if necessary */
        unique_pals = (int*)malloc(cw * ch * sizeof(int));
        unique_pals_count = 0;
        pal_indexes = (int*)malloc(cw * ch * sizeof(int));
        /* find unique palettes and record their usage */
        find_unique_palettes(pal_data, cw * ch, pal_sizes, unique_pals, &unique_pals_count, pal_indexes);

        /*	    printf("unique palettes: %d\n", unique_pals_count); */
        /* reduce number of palettes used if necessary */
        reduce_palettes(buf, width, height, pal_data, pal_sizes, unique_pals, &unique_pals_count, pal_indexes);

        reducedPalettesImage = to_qimage(buf, width, height);

        /* encode tiles */
        encode_nes_tiles(buf, width, height, pal_data, pal_sizes, unique_pals, pal_indexes, tile_data);

        /* write tiles */
        write_tiles(chr_output_filename, tile_data, tile_data_sz);

        /* write palette data */
        write_palettes(pal_output_filename, pal_data, pal_sizes, unique_pals, unique_pals_count);

        /* encode attribute data */
        attrib_data_sz = (cw/2)*(ch/2);
        attrib_data = (unsigned char *)malloc(attrib_data_sz);
        encode_nes_attributes(cw, ch, pal_indexes, attrib_data);

        /* write attribute data */
        write_attributes(attrib_output_filename, attrib_data, attrib_data_sz);
    }

    QHBoxLayout *box = new QHBoxLayout(&window);
    box->addWidget(create_label(originalImage));
    box->addWidget(create_label(originalNesImage));
    box->addWidget(create_label(reducedColorsImage));
    box->addWidget(create_label(reducedPalettesImage));
    window.show();
    app.exec();

    /* Cleanup */
    free(raw_data);
    free(buf);
    free(tile_data);
    free(pal_data);
    free(pal_sizes);
    free(unique_pals);
    free(pal_indexes);
    free(color_freqs);
    free(attrib_data);

    /* All done. */
    return 0;
}
Ejemplo n.º 9
0
/**
 * Loads the thumbnail from the metadata.
 * If no thumbnail is embedded, the whole image
 * is loaded and downsampled in a fast manner.
 * @param file the file to be loaded
 * @param ba the file buffer (can be empty)
 * @param forceLoad the loading flag (e.g. exiv only)
 * @param maxThumbSize the maximal thumbnail size to be loaded
 * @param minThumbSize the minimal thumbnail size to be loaded
 * @return QImage the loaded image. Null if no image
 * could be loaded at all.
 **/ 
QImage DkThumbNail::computeIntern(const QString& filePath, const QSharedPointer<QByteArray> ba, 
								  int forceLoad, int maxThumbSize, int minThumbSize) {
	
	DkTimer dt;
	//qDebug() << "[thumb] file: " << file.absoluteFilePath();

	// see if we can read the thumbnail from the exif data
	QImage thumb;
	DkMetaDataT metaData;

	QSharedPointer<QByteArray> baZip = QSharedPointer<QByteArray>();
#ifdef WITH_QUAZIP
	if (QFileInfo(mFile).dir().path().contains(DkZipContainer::zipMarker())) 
		baZip = DkZipContainer::extractImage(DkZipContainer::decodeZipFile(filePath), DkZipContainer::decodeImageFile(filePath));
#endif
	try {
		if (baZip && !baZip->isEmpty())	
			metaData.readMetaData(filePath, baZip);
		else if (!ba || ba->isEmpty())
			metaData.readMetaData(filePath);
		else
			metaData.readMetaData(filePath, ba);

		// read the full image if we want to create new thumbnails
		if (forceLoad != force_save_thumb)
			thumb = metaData.getThumbnail();
	}
	catch(...) {
		// do nothing - we'll load the full file
	}
	removeBlackBorder(thumb);

	if (thumb.isNull() && forceLoad == force_exif_thumb)
		return QImage();

	bool exifThumb = !thumb.isNull();

	int orientation = metaData.getOrientation();
	int imgW = thumb.width();
	int imgH = thumb.height();
	int tS = minThumbSize;

	// as found at: http://olliwang.com/2010/01/30/creating-thumbnail-images-in-qt/
	QFileInfo fInfo(filePath);
	QString lFilePath = fInfo.isSymLink() ? fInfo.symLinkTarget() : filePath;
	fInfo = lFilePath;

	QImageReader* imageReader = 0;
	
	if (!ba || ba->isEmpty())
		imageReader = new QImageReader(lFilePath);
	else {
		QBuffer buffer;
		buffer.setData(ba->data());
		buffer.open(QIODevice::ReadOnly);
		imageReader = new QImageReader(&buffer, fInfo.suffix().toStdString().c_str());
		buffer.close();
	}

	if (thumb.isNull() || (thumb.width() < tS && thumb.height() < tS)) {

		imgW = imageReader->size().width();		// crash detected: unhandled exception at 0x66850E9A (msvcr110d.dll) in nomacs.exe: 0xC0000005: Access violation reading location 0x0000C788.
		imgH = imageReader->size().height();	// locks the file!
	}
	
	if (forceLoad != DkThumbNailT::force_exif_thumb && (imgW > maxThumbSize || imgH > maxThumbSize)) {
		if (imgW > imgH) {
			imgH = qRound((float)maxThumbSize / imgW * imgH);
			imgW = maxThumbSize;
		} 
		else if (imgW < imgH) {
			imgW = qRound((float)maxThumbSize / imgH * imgW);
			imgH = maxThumbSize;
		}
		else {
			imgW = maxThumbSize;
			imgH = maxThumbSize;
		}
	}

	bool rescale = forceLoad == force_save_thumb;

	if (forceLoad != force_exif_thumb && (thumb.isNull() || thumb.width() < tS && thumb.height() < tS || forceLoad == force_full_thumb || forceLoad == force_save_thumb)) { // braces
		
		// flip size if the image is rotated by 90°
		if (metaData.isTiff() && abs(orientation) == 90) {
			int tmpW = imgW;
			imgW = imgH;
			imgH = tmpW;
			qDebug() << "EXIF size is flipped...";
		}

		QSize initialSize = imageReader->size();

		imageReader->setScaledSize(QSize(imgW, imgH));
		thumb = imageReader->read();

		// try to read the image
		if (thumb.isNull()) {
			DkBasicLoader loader;
			
			if (baZip && !baZip->isEmpty())	{
				if (loader.loadGeneral(lFilePath, baZip, true, true))
				thumb = loader.image();
			}
			else {
				if (loader.loadGeneral(lFilePath, ba, true, true))
					thumb = loader.image();
			}
		}

		// the image is not scaled correctly yet
		if (rescale && !thumb.isNull() && (imgW == -1 || imgH == -1)) {
			imgW = thumb.width();
			imgH = thumb.height();

			if (imgW > maxThumbSize || imgH > maxThumbSize) {
				if (imgW > imgH) {
					imgH = qRound((float)maxThumbSize / imgW * imgH);
					imgW = maxThumbSize;
				} 
				else if (imgW < imgH) {
					imgW = qRound((float)maxThumbSize / imgH * imgW);
					imgH = maxThumbSize;
				}
				else {
					imgW = maxThumbSize;
					imgH = maxThumbSize;
				}
			}

			thumb = thumb.scaled(QSize(imgW*2, imgH*2), Qt::KeepAspectRatio, Qt::FastTransformation);
			thumb = thumb.scaled(QSize(imgW, imgH), Qt::KeepAspectRatio, Qt::SmoothTransformation);
		}

		// is there a nice solution to do so??
		imageReader->setFileName("josef");	// image reader locks the file -> but there should not be one so we just set it to another file...
	}
	else if (rescale) {
		thumb = thumb.scaled(QSize(imgW, imgH), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
	}

	if (imageReader)
		delete imageReader;

	if (orientation != -1 && orientation != 0 && (metaData.isJpg() || metaData.isRaw())) {
		QTransform rotationMatrix;
		rotationMatrix.rotate((double)orientation);
		thumb = thumb.transformed(rotationMatrix);
	}

	// save the thumbnail if the caller either forces it, or the save thumb is requested and the image did not have any before
	if (rescale || (forceLoad == save_thumb && !exifThumb)) {
		
		try {

			QImage sThumb = thumb.copy();
			if (orientation != -1 && orientation != 0) {
				QTransform rotationMatrix;
				rotationMatrix.rotate(-(double)orientation);
				sThumb = sThumb.transformed(rotationMatrix);
			}

			metaData.setThumbnail(sThumb);

			if (!ba || ba->isEmpty())
				metaData.saveMetaData(lFilePath);
			else
				metaData.saveMetaData(lFilePath, ba);

			qDebug() << "[thumb] saved to exif data";
		}
		catch(...) {
			qDebug() << "Sorry, I could not save the metadata";
		}
	}


	if (!thumb.isNull())
		qDebug() << "[thumb] " << fInfo.fileName() << "(" << thumb.width() << " x " << thumb.height() << ") loaded in: " << dt.getTotal() << ((exifThumb) ? " from EXIV" : " from File");

	return thumb;
}
Ejemplo n.º 10
0
void DialogCameraView::DownloadPicture()
{
    string u;

    if (camera->get_param("type") == "axis")
    {
        string cam = "1";
        if (camera->get_param("model") != "") cam = camera->get_param("model").c_str();
        u = "http://" + camera->get_param("host") + ":" + camera->get_param("port") + "/axis-cgi/jpg/image.cgi?camera=" + cam;
    }
    else if (camera->get_param("type") == "gadspot")
    {
        u = "http://" + camera->get_param("host") + ":" + camera->get_param("port") + "/Jpeg/CamImg.jpg";
    }
    else if (camera->get_param("type") == "planet")
    {
        if (camera->get_param("model") == "ICA-300" ||
            camera->get_param("model") == "ICA-302" ||
            camera->get_param("model") == "ICA-500")
        {
            u = "http://" + camera->get_param("host") + ":" + camera->get_param("port") + "/Jpeg/CamImg.jpg";
        }
        else
        {
            u = "http://" + camera->get_param("host") + ":" + camera->get_param("port") + "/goform/video2";
        }
    }
    else if (camera->get_param("type") == "standard_mjpeg")
    {
        u = camera->get_param("url_jpeg");
    }

    qDebug() << u.c_str();

    QNetworkAccessManager *netmanager = new QNetworkAccessManager(this);
    connect(netmanager, &QNetworkAccessManager::finished, [=](QNetworkReply *reply) {

        if (reply->error() != QNetworkReply::NoError)
        {
            QMessageBox::warning(this, "Calaos Installer", tr("Calaos Installer: Erreur !"), reply->errorString());

            return;
        }

        qDebug() << QImageReader::supportedImageFormats();

        QByteArray res = reply->readAll();
        QImage img = QImage::fromData(res);
        reply->deleteLater();
        netmanager->deleteLater();

        if (img.isNull())
            QMessageBox::warning(this, "Calaos Installer", tr("Calaos Installer: Error, image is NULL !"));

        ui->label_cam->setPixmap(QPixmap::fromImage(img));

        DownloadPicture();
    });

    QNetworkRequest request(QUrl(u.c_str()));
    netmanager->get(request);
}
Ejemplo n.º 11
0
bool ConvertDepthCvMat8uToYellowQImage(const cv::Mat & srcDepthMat, QImage & destImg)
{
	if (srcDepthMat.empty() || destImg.isNull()) {
		return false;
	}

	assert (srcDepthMat.size().height == destImg.height() && srcDepthMat.size().width == destImg.width());
	assert (srcDepthMat.type() == CV_8UC1);

	const int nXRes = srcDepthMat.size().width;
	const int nYRes = srcDepthMat.size().height;
	const int srcRowStep = srcDepthMat.step;

	const uchar * srcRowPtr = NULL;
	const uchar * srcDataPtr = NULL;

	float depthHist[256];
	memset(depthHist, 0, 256 * sizeof(float));

	unsigned int pointsNumber = 0;
	srcRowPtr = srcDepthMat.data;

	for (int y = 0; y < nYRes; ++y, srcRowPtr += srcRowStep) 
	{
		srcDataPtr = srcRowPtr;
	
		for (int x = 0; x < nXRes; ++x, ++srcDataPtr) 
		{
			uchar tmp = *srcDataPtr;
			if ( tmp ) {
				++depthHist[tmp];
				++pointsNumber;
			}
		}
	}
	for (int i = 1; i < 256; ++i) {
		depthHist[i] += depthHist[i-1];
	}
	if (pointsNumber > 0)
	{
		for (int i = 1; i < 256; ++i) {
			depthHist[i] = 256.0f * (1.0f - depthHist[i] / (float)(pointsNumber));
		}
	}
	
	srcRowPtr = srcDepthMat.data;
	
	for (int y = 0; y < nYRes; ++y, srcRowPtr += srcRowStep) 
	{
		srcDataPtr = srcRowPtr;
		uchar * imageptr = destImg.scanLine(y);
	
		for (int x = 0; x < nXRes; ++x, ++srcDataPtr, imageptr += 4) 
		{
			uchar tmp = *srcDataPtr;
			if ( tmp )
			{
				imageptr[0] = 0;
				imageptr[1] = depthHist[tmp];
				imageptr[2] = depthHist[tmp];
				imageptr[3] = 0xff;
			}
			else 
			{
				imageptr[3] = imageptr[2] = imageptr[1] = imageptr[0] = 0;
			}
		}
	}

	return true;
}
Ejemplo n.º 12
0
void Session::Request::fetchImage(const QString &url) {
    QImage image = _cache->getImage(url);
    if (!image.isNull()) {
        onImageResult(url, image);
    }
}
Ejemplo n.º 13
0
void ExportAsImageDialog::accept()
{
    const QString fileName = mUi->fileNameEdit->text();
    if (fileName.isEmpty())
        return;

    if (QFile::exists(fileName)) {
        const QMessageBox::StandardButton button =
                QMessageBox::warning(this,
                                     tr("Export as Image"),
                                     tr("%1 already exists.\n"
                                        "Do you want to replace it?")
                                     .arg(QFileInfo(fileName).fileName()),
                                     QMessageBox::Yes | QMessageBox::No,
                                     QMessageBox::No);

        if (button != QMessageBox::Yes)
            return;
    }

    const bool visibleLayersOnly = mUi->visibleLayersOnly->isChecked();
    const bool useCurrentScale = mUi->currentZoomLevel->isChecked();
    const bool drawTileGrid = mUi->drawTileGrid->isChecked();
    const bool includeBackgroundColor = mUi->includeBackgroundColor->isChecked();

    MapRenderer *renderer = mMapDocument->renderer();

    // Remember the current render flags
    const Tiled::RenderFlags renderFlags = renderer->flags();

    renderer->setFlag(ShowTileObjectOutlines, false);

    QSize mapSize = renderer->mapSize();

    QMargins margins = mMapDocument->map()->computeLayerOffsetMargins();
    mapSize.setWidth(mapSize.width() + margins.left() + margins.right());
    mapSize.setHeight(mapSize.height() + margins.top() + margins.bottom());

    if (useCurrentScale)
        mapSize *= mCurrentScale;

    QImage image;

    try {
        image = QImage(mapSize, QImage::Format_ARGB32_Premultiplied);

        if (includeBackgroundColor) {
            if (mMapDocument->map()->backgroundColor().isValid())
                image.fill(mMapDocument->map()->backgroundColor());
            else
                image.fill(Qt::gray);
        } else {
            image.fill(Qt::transparent);
        }
    } catch (const std::bad_alloc &) {
        QMessageBox::critical(this,
                              tr("Out of Memory"),
                              tr("Could not allocate sufficient memory for the image. "
                                 "Try reducing the zoom level or using a 64-bit version of Tiled."));
        return;
    }

    if (image.isNull()) {
        const size_t gigabyte = 1073741824;
        const size_t memory = size_t(mapSize.width()) * size_t(mapSize.height()) * 4;
        const double gigabytes = (double) memory / gigabyte;

        QMessageBox::critical(this,
                              tr("Image too Big"),
                              tr("The resulting image would be %1 x %2 pixels and take %3 GB of memory. "
                                 "Tiled is unable to create such an image. Try reducing the zoom level.")
                              .arg(mapSize.width())
                              .arg(mapSize.height())
                              .arg(gigabytes, 0, 'f', 2));
        return;
    }

    QPainter painter(&image);

    if (useCurrentScale) {
        if (smoothTransform(mCurrentScale))
            painter.setRenderHints(QPainter::SmoothPixmapTransform);

        painter.setTransform(QTransform::fromScale(mCurrentScale,
                                                   mCurrentScale));
        renderer->setPainterScale(mCurrentScale);
    } else {
        renderer->setPainterScale(1);
    }

    painter.translate(margins.left(), margins.top());

    foreach (const Layer *layer, mMapDocument->map()->layers()) {
        if (visibleLayersOnly && !layer->isVisible())
            continue;

        painter.setOpacity(layer->opacity());
        painter.translate(layer->offset());

        const TileLayer *tileLayer = dynamic_cast<const TileLayer*>(layer);
        const ObjectGroup *objGroup = dynamic_cast<const ObjectGroup*>(layer);
        const ImageLayer *imageLayer = dynamic_cast<const ImageLayer*>(layer);

        if (tileLayer) {
            renderer->drawTileLayer(&painter, tileLayer);
        } else if (objGroup) {
            QList<MapObject*> objects = objGroup->objects();

            if (objGroup->drawOrder() == ObjectGroup::TopDownOrder)
                qStableSort(objects.begin(), objects.end(), objectLessThan);

            foreach (const MapObject *object, objects) {
                if (object->isVisible()) {
                    if (object->rotation() != qreal(0)) {
                        QPointF origin = renderer->pixelToScreenCoords(object->position());
                        painter.save();
                        painter.translate(origin);
                        painter.rotate(object->rotation());
                        painter.translate(-origin);
                    }

                    const QColor color = MapObjectItem::objectColor(object);
                    renderer->drawMapObject(&painter, object, color);

                    if (object->rotation() != qreal(0))
                        painter.restore();
                }
            }
        } else if (imageLayer) {
            renderer->drawImageLayer(&painter, imageLayer);
        }

        painter.translate(-layer->offset());
    }
Ejemplo n.º 14
0
MainWindow::MainWindow() :
	m_workspace( NULL ),
	m_templatesMenu( NULL ),
	m_recentlyOpenedProjectsMenu( NULL ),
	m_toolsMenu( NULL ),
	m_autoSaveTimer( this ),
	m_viewMenu( NULL ),
	m_metronomeToggle( 0 ),
	m_session( Normal )
{
	setAttribute( Qt::WA_DeleteOnClose );

	QWidget * main_widget = new QWidget( this );
	QVBoxLayout * vbox = new QVBoxLayout( main_widget );
	vbox->setSpacing( 0 );
	vbox->setMargin( 0 );

	QWidget * w = new QWidget( main_widget );
	QHBoxLayout * hbox = new QHBoxLayout( w );
	hbox->setSpacing( 0 );
	hbox->setMargin( 0 );

	SideBar * sideBar = new SideBar( Qt::Vertical, w );

	QSplitter * splitter = new QSplitter( Qt::Horizontal, w );
	splitter->setChildrenCollapsible( false );

	ConfigManager* confMgr = ConfigManager::inst();

	emit initProgress(tr("Preparing plugin browser"));
	sideBar->appendTab( new PluginBrowser( splitter ) );
	emit initProgress(tr("Preparing file browsers"));
	sideBar->appendTab( new FileBrowser(
				confMgr->userProjectsDir() + "*" +
				confMgr->factoryProjectsDir(),
					"*.mmp *.mmpz *.xml *.mid",
							tr( "My Projects" ),
					embed::getIconPixmap( "project_file" ).transformed( QTransform().rotate( 90 ) ),
							splitter, false, true ) );
	sideBar->appendTab( new FileBrowser(
				confMgr->userSamplesDir() + "*" +
				confMgr->factorySamplesDir(),
					"*", tr( "My Samples" ),
					embed::getIconPixmap( "sample_file" ).transformed( QTransform().rotate( 90 ) ),
							splitter, false, true ) );
	sideBar->appendTab( new FileBrowser(
				confMgr->userPresetsDir() + "*" +
				confMgr->factoryPresetsDir(),
					"*.xpf *.cs.xml *.xiz",
					tr( "My Presets" ),
					embed::getIconPixmap( "preset_file" ).transformed( QTransform().rotate( 90 ) ),
							splitter , false, true  ) );
	sideBar->appendTab( new FileBrowser( QDir::homePath(), "*",
							tr( "My Home" ),
					embed::getIconPixmap( "home" ).transformed( QTransform().rotate( 90 ) ),
							splitter, false, false ) );


	QStringList root_paths;
	QString title = tr( "Root directory" );
	bool dirs_as_items = false;

#ifdef LMMS_BUILD_APPLE
	title = tr( "Volumes" );
	root_paths += "/Volumes";
#elif defined(LMMS_BUILD_WIN32)
	title = tr( "My Computer" );
	dirs_as_items = true;
#endif

#if ! defined(LMMS_BUILD_APPLE)
	QFileInfoList drives = QDir::drives();
	for( const QFileInfo & drive : drives )
	{
		root_paths += drive.absolutePath();
	}
#endif

	sideBar->appendTab( new FileBrowser( root_paths.join( "*" ), "*", title,
					embed::getIconPixmap( "computer" ).transformed( QTransform().rotate( 90 ) ),
							splitter, dirs_as_items) );

	m_workspace = new QMdiArea( splitter );

	// Load background
	emit initProgress(tr("Loading background artwork"));
	QString bgArtwork = ConfigManager::inst()->backgroundArtwork();
	QImage bgImage;
	if( !bgArtwork.isEmpty() )
	{
		bgImage = QImage( bgArtwork );
	}
	if( !bgImage.isNull() )
	{
		m_workspace->setBackground( bgImage );
	}
	else
	{
		m_workspace->setBackground( Qt::NoBrush );
	}

	m_workspace->setOption( QMdiArea::DontMaximizeSubWindowOnActivation );
	m_workspace->setHorizontalScrollBarPolicy( Qt::ScrollBarAsNeeded );
	m_workspace->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );

	hbox->addWidget( sideBar );
	hbox->addWidget( splitter );


	// create global-toolbar at the top of our window
	m_toolBar = new QWidget( main_widget );
	m_toolBar->setObjectName( "mainToolbar" );
	m_toolBar->setFixedHeight( 64 );
	m_toolBar->move( 0, 0 );

	// add layout for organizing quite complex toolbar-layouting
	m_toolBarLayout = new QGridLayout( m_toolBar/*, 2, 1*/ );
	m_toolBarLayout->setMargin( 0 );
	m_toolBarLayout->setSpacing( 0 );

	vbox->addWidget( m_toolBar );
	vbox->addWidget( w );
	setCentralWidget( main_widget );

	m_updateTimer.start( 1000 / 20, this );  // 20 fps

	if( ConfigManager::inst()->value( "ui", "enableautosave" ).toInt() )
	{
		// connect auto save
		connect(&m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSave()));
		m_autoSaveInterval = ConfigManager::inst()->value(
					"ui", "saveinterval" ).toInt() < 1 ?
						DEFAULT_AUTO_SAVE_INTERVAL :
				ConfigManager::inst()->value(
					"ui", "saveinterval" ).toInt();

		// The auto save function mustn't run until there is a project
		// to save or it will run over recover.mmp if you hesitate at the
		// recover messagebox for a minute. It is now started in main.
		// See autoSaveTimerReset() in MainWindow.h
	}

	connect( Engine::getSong(), SIGNAL( playbackStateChanged() ),
				this, SLOT( updatePlayPauseIcons() ) );
}
Ejemplo n.º 15
0
void LocalImageLoaderPrivate::prepareImages() {
	QString file, filename, mime;
    int32 filesize = 0;
	QImage img;
	QByteArray data;
	PeerId peer;
    uint64 id, jpeg_id = 0;
	ToPrepareMediaType type;
	bool ctrlShiftEnter = false;
	{
		QMutexLocker lock(loader->toPrepareMutex());
		ToPrepareMedias &list(loader->toPrepareMedias());
		if (list.isEmpty()) return;

		file = list.front().file;
		img = list.front().img;
		data = list.front().data;
		peer = list.front().peer;
		id = list.front().id;
		type = list.front().type;
		ctrlShiftEnter = list.front().ctrlShiftEnter;
	}

	if (img.isNull()) {
		if (!file.isEmpty()) {
			QFileInfo info(file);
			if (type == ToPrepareAuto) {
				QString lower(file.toLower());
				const QStringList &photoExtensions(cPhotoExtensions());
				for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) {
					if (lower.lastIndexOf(*i) == lower.size() - i->size()) {
						if (info.size() < MaxUploadPhotoSize) {
							type = ToPreparePhoto;
							break;
						}
					}
				}
				if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				}
			}
			if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) {
				img = App::readImage(file);
			}
			if (type == ToPrepareDocument) {
				mime = QMimeDatabase().mimeTypeForFile(info).name();
			}
			filename = info.fileName();
			filesize = info.size();
		} else if (!data.isEmpty()) {
			img = App::readImage(data);
			if (type == ToPrepareAuto) {
				if (!img.isNull() && data.size() < MaxUploadPhotoSize) {
					type = ToPreparePhoto;
				} else if (data.size() < MaxUploadDocumentSize) {
					type = ToPrepareDocument;
				} else {
					img = QImage();
				}
			}
			QMimeType mimeType = QMimeDatabase().mimeTypeForData(data);
			if (type == ToPrepareDocument) {
				mime = mimeType.name();
			}
			filename = qsl("Document");
			QStringList patterns = mimeType.globPatterns();
			if (!patterns.isEmpty()) {
				filename = patterns.front().replace('*', filename);
			}
			filesize = data.size();
		}
	} else {
		if (type == ToPrepareDocument) {
			filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true);
			QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png");
			mime = mimeType.name();
			data = QByteArray();
			{
				QBuffer b(&data);
				img.save(&b, "PNG");
			}
			filesize = data.size();
		} else {
			type = ToPreparePhoto; // only photo from QImage
			filename = qsl("Untitled.jpg");
			filesize = 0;
		}
	}

	if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type
		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageFailed(id);
	} else {
		PreparedPhotoThumbs photoThumbs;
		QVector<MTPPhotoSize> photoSizes;

		MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string("")));
		MTPPhoto photo(MTP_photoEmpty(MTP_long(0)));
		MTPDocument document(MTP_documentEmpty(MTP_long(0)));

		QByteArray jpeg;
		if (type == ToPreparePhoto) {
			int32 w = img.width(), h = img.height();

			QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('s', thumb);
			photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0)));

			QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('m', medium);
			photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0)));

			QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(img.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);
			photoThumbs.insert('y', full);
			photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)));

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 77);
			}
			if (!filesize) filesize = jpeg.size();
		
			photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes));

			jpeg_id = id;
		} else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) {
			int32 w = img.width(), h = img.height();

			QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img);

			{
				QBuffer jpegBuffer(&jpeg);
				full.save(&jpegBuffer, "JPG", 87);
			}

			photoThumbs.insert('0', full);
			thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0));

			jpeg_id = MTP::nonce<uint64>();
		}

		if (type == ToPrepareDocument) {
			document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()));
		}

		{
			QMutexLocker lock(loader->readyMutex());
			loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg, ctrlShiftEnter));
		}

		{
			QMutexLocker lock(loader->toPrepareMutex());
			ToPrepareMedias &list(loader->toPrepareMedias());
			list.pop_front();
		}

		QTimer::singleShot(1, this, SLOT(prepareImages()));

		emit imageReady();
	}
}
Ejemplo n.º 16
0
void ThumbGenerator::run()
{
    RunProlog();

    m_cancel = false;
    while (moreWork() && !m_cancel)
    {
        QString file, dir;
        bool    isGallery;

        m_mutex.lock();
        dir       = m_directory;
        isGallery = m_isGallery;
        file = m_fileList.first();
        if (!m_fileList.isEmpty())
            m_fileList.pop_front();
        m_mutex.unlock();
        if (file.isEmpty())
            continue;

        QString   filePath = dir + QString("/") + file;
        QFileInfo fileInfo(filePath);
        if (!fileInfo.exists())
            continue;

        if (isGallery)
        {
            if (fileInfo.isDir())
                isGallery = checkGalleryDir(fileInfo);
            else
                isGallery = checkGalleryFile(fileInfo);
        }

        if (!isGallery)
        {
            QString cachePath = QString("%1%2.jpg").arg(getThumbcacheDir(dir))
                                                   .arg(file);
            QFileInfo cacheInfo(cachePath);

            if (cacheInfo.exists() &&
                cacheInfo.lastModified() >= fileInfo.lastModified())
            {
                continue;
            }
            else
            {
                // cached thumbnail not there or out of date
                QImage image;

                // Remove the old one if it exists
                if (cacheInfo.exists())
                    QFile::remove(cachePath);

                if (fileInfo.isDir())
                    loadDir(image, fileInfo);
                else
                    loadFile(image, fileInfo);

                if (image.isNull())
                    continue; // give up;

                // if the file is a movie save the image to use as a screenshot
                if (GalleryUtil::IsMovie(fileInfo.filePath()))
                {
                    QString screenshotPath = QString("%1%2-screenshot.jpg")
                            .arg(getThumbcacheDir(dir))
                            .arg(file);
                    image.save(screenshotPath, "JPEG", 95);
                }

                image = image.scaled(m_width,m_height,
                                Qt::KeepAspectRatio, Qt::SmoothTransformation);
                image.save(cachePath, "JPEG", 95);

                // deep copies all over
                ThumbData *td = new ThumbData;
                td->directory = dir;
                td->fileName  = file;
                td->thumb     = image.copy();

                // inform parent we have thumbnail ready for it
                QApplication::postEvent(m_parent, new ThumbGenEvent(td));

            }
        }
    }

    RunEpilog();
}
Ejemplo n.º 17
0
void UserViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    UserViewItemBase *base = dynamic_cast<UserViewItemBase*>(m_uv->itemFromIndex(index));
    if( NULL == base )
        return;

    painter->save();
    painter->translate(option.rect.x(), option.rect.y());

    QPainter *p = painter;
    QPalette cg = option.palette;
    int width = option.rect.width();
    int height = option.rect.height();
    QSize itemsize = option.rect.size();
    int margin = 1;

    switch( base->type() )
    {
    case GRP_ITEM:
        {
            GroupItem *item = static_cast<GroupItem*>(base);
            QString text = index.data( Qt::DisplayRole ).toString();
            QImage img = Image( ( option.state & QStyle::State_Open ) ? "expanded" : "collapsed");
            if (!img.isNull())
                p->drawImage(2 + margin, (height - img.height()) / 2, img);
            int x = 24 + margin;
            if (!( option.state & QStyle::State_Open ) && item->m_unread)
            {
                CommandDef *lcmdDefUnreadMessages = CorePlugin::instance()->messageTypes.find(item->m_unread);
                if (lcmdDefUnreadMessages)
                {
                    img = Image(lcmdDefUnreadMessages->icon);
                    if (!img.isNull())
                    {
                        if (m_uv->m_bUnreadBlink)
                            p->drawImage(x, (height - img.height()) / 2, img);
                        x += img.width() + 2;
                    }
                }
            }
            if (!CorePlugin::instance()->value("UseSysColors").toBool())
                p->setPen(CorePlugin::instance()->value("ColorGroup").toUInt());
            QFont f(option.font);
            if (CorePlugin::instance()->value("SmallGroupFont").toBool())
            {
                int size = f.pixelSize();
                if (size > 0)
                    f.setPixelSize(size * 3 / 4);
                else
                {
                    size = f.pointSize();
                    f.setPointSize(size * 3 / 4);
                }
            }
            f.setBold(true);
            p->setFont(f);
            x = drawText(p, x, itemsize, text);
            if (CorePlugin::instance()->value("GroupSeparator").toBool())
                drawSeparator(p, x, itemsize, m_uv->style());
            break;
        }
    case USR_ITEM:
        {
            ContactItem *item = static_cast<ContactItem*>(base);
            QFont f(option.font);
            if (item->style() & CONTACT_ITALIC)
            {
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("VisibleStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            if (item->style() & CONTACT_UNDERLINE)
            {
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("AuthStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            if (item->style() & CONTACT_STRIKEOUT)
            {
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_ITALIC)
                    f.setItalic(true);
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_UNDER)
                    f.setUnderline(true);
                if (CorePlugin::instance()->value("InvisibleStyle").toUInt()  & STYLE_STRIKE)
                    f.setStrikeOut(true);
            }
            int x = margin;
            QIcon mainIcon = index.data( Qt::DecorationRole ).value<QIcon>();
            if (!mainIcon.isNull())
            {
                QPixmap img = mainIcon.pixmap( 16 );
                x += 2;
                p->drawPixmap(x, ( height - img.height() ) / 2, img);
                x += img.width() + 2;
            }
            if (x < 24)
                x = 24;
            if (!item->isSelected() || !m_uv->hasFocus() || !CorePlugin::instance()->value("UseDblClick").toBool())
            {
                if (!CorePlugin::instance()->value("UseSysColors").toBool())
                {
                    switch (item->status())
                    {
                    case STATUS_ONLINE:
                        p->setPen(CorePlugin::instance()->value("ColorOnline").toUInt());
                        break;
                    case STATUS_FFC:
                        p->setPen(CorePlugin::instance()->value("ColorOnline").toUInt());
                        break;
                    case STATUS_AWAY:
                        p->setPen(CorePlugin::instance()->value("ColorAway").toUInt());
                        break;
                    case STATUS_NA:
                        p->setPen(CorePlugin::instance()->value("ColorNA").toUInt());
                        break;
                    case STATUS_DND:
                        p->setPen(CorePlugin::instance()->value("ColorDND").toUInt());
                        break;
                    default:
                        p->setPen(CorePlugin::instance()->value("ColorOffline").toUInt());
                        break;
                    }
                }
                if (item->status() != STATUS_ONLINE && item->status() != STATUS_FFC)
                    p->setPen(m_uv->palette().color(QPalette::Disabled,QPalette::Text));
            }
            if (item->m_bBlink)
                f.setBold(true);
            else
                f.setBold(false);

            p->setFont(f);
            QString highlight;
            QString text = index.data( Qt::DisplayRole ).toString();
            int pos=0;
            if(!m_uv->m_search.isEmpty())
            {
                pos=text.toUpper().indexOf(m_uv->m_search.toUpper());
                //Search for substring in contact name
                if (pos > -1)
                    highlight=text.mid(pos,m_uv->m_search.length());
            }
            int save_x = x;
            //p->setPen(QColor(0, 0, 0));
            x = drawText(p, x, itemsize, text);
            if (pos > 0)
                save_x = drawText(p, save_x, itemsize, text.left(pos)) - 4;
            x += 2;
            if (!highlight.isEmpty())
            {
                QPen oldPen = p->pen();
                QColor oldBg = p->background().color();
                p->setBackgroundMode(Qt::OpaqueMode);
                if (item == m_uv->m_searchItem)
                    if (item == m_uv->currentItem() && CorePlugin::instance()->value("UseDblClick").toBool())
                    {
                        p->setBackground(cg.color(QPalette::HighlightedText));
                        p->setPen(cg.color(QPalette::Highlight));
                    }
                    else
                    {
                        p->setBackground(cg.color(QPalette::Highlight));
                        p->setPen(cg.color(QPalette::HighlightedText));
                    }
                else
                {
                    p->setBackground(oldPen.color());
                    p->setPen(oldBg);
                }
                drawText(p, save_x, itemsize, highlight);
                p->setPen(oldPen);
                p->setBackground(oldBg);
                p->setBackgroundMode(Qt::TransparentMode);
            }
            unsigned xIcon = width;
            QString icons = index.data( SIM::ExtraIconsRole ).toString();
            while( !icons.isEmpty() ) 
            {
                QString icon = getToken(icons, ',');
                QImage img = Image(icon);
                if (!img.isNull())
                {
                    xIcon -= img.width() + 2;
                    if (xIcon < (unsigned)x)
                        break;
                    p->drawImage(xIcon, (height - img.height()) / 2, img);
                }
            }
            break;
        }
    case DIV_ITEM:
        {
            QString text = index.data( Qt::DisplayRole ).toString();
            QFont f(option.font);
            int size = f.pixelSize();
            if (size <= 0)
            {
                size = f.pointSize();
                f.setPointSize(size * 3 / 4);
            }
            else
                f.setPixelSize(size * 3 / 4);
            p->setFont(f);
            int x = drawText(p, 24 + margin, itemsize, text);
            drawSeparator(p, x, itemsize, m_uv->style());
            break;
        }
    }

    painter->restore();
}
Ejemplo n.º 18
0
bool ccPlane::setAsTexture(QImage image)
{
	if (image.isNull())
	{
		ccLog::Warning("[ccPlane::setAsTexture] Invalid texture image!");
		return false;
	}

	//texture coordinates
	TextureCoordsContainer* texCoords = getTexCoordinatesTable();
	if (!texCoords)
	{
		texCoords = new TextureCoordsContainer();
		if (!texCoords->reserve(4))
		{
			//not enough memory
			ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
			delete texCoords;
			return false;
		}

		//create default texture coordinates
		float TA[2] = { 0.0f, 0.0f };
		float TB[2] = { 0.0f, 1.0f };
		float TC[2] = { 1.0f, 1.0f };
		float TD[2] = { 1.0f, 0.0f };
		texCoords->addElement(TA);
		texCoords->addElement(TB);
		texCoords->addElement(TC);
		texCoords->addElement(TD);

		setTexCoordinatesTable(texCoords);
	}

	if (!hasPerTriangleTexCoordIndexes())
	{
		if (!reservePerTriangleTexCoordIndexes())
		{
			//not enough memory
			ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
			setTexCoordinatesTable(0);
			removePerTriangleMtlIndexes();
			return false;
		}
		
		//set default texture indexes
		addTriangleTexCoordIndexes(0,2,1);
		addTriangleTexCoordIndexes(0,3,2);
	}
	
	if (!hasPerTriangleMtlIndexes())
	{
		if (!reservePerTriangleMtlIndexes())
		{
			//not enough memory
			ccLog::Warning("[ccPlane::setAsTexture] Not enough memory!");
			setTexCoordinatesTable(0);
			removePerTriangleTexCoordIndexes();
			return false;
		}

		//set default material indexes
		addTriangleMtlIndex(0);
		addTriangleMtlIndex(0);
	}

	//set material
	if (!getMaterialSet())
		setMaterialSet(new ccMaterialSet());
	ccMaterialSet* materialSet = const_cast<ccMaterialSet*>(getMaterialSet());
	assert(materialSet);
	//remove old material (if any)
	materialSet->clear();
	//add new material
	{
		ccMaterial::Shared material(new ccMaterial("texture"));
		material->setTexture(image,QString(),false);
		materialSet->addMaterial(material);
	}

	showMaterials(true);

	return true;
}
Ejemplo n.º 19
0
void BrokenLinksWidget::tryFixLink(const BrokenLink &link)
{
    Document *document = mBrokenLinksModel->document();
    Preferences *prefs = Preferences::instance();

    if (link.type == TilesetImageSource || link.type == TilesetTileImageSource) {
        auto tilesetDocument = qobject_cast<TilesetDocument*>(document);
        if (!tilesetDocument) {
            // We need to open the tileset document in order to be able to make changes to it...
            const SharedTileset tileset = link.tileset()->sharedPointer();
            DocumentManager::instance()->openTileset(tileset);
            return;
        }

        QString startLocation = QFileInfo(prefs->lastPath(Preferences::ImageFile)).absolutePath();
        startLocation += QLatin1Char('/');
        startLocation += QFileInfo(link.filePath()).fileName();

        QString newFileName = QFileDialog::getOpenFileName(window(),
                                                           tr("Locate File"),
                                                           startLocation,
                                                           Utils::readableImageFormatsFilter());

        if (newFileName.isEmpty())
            return;

        QImageReader reader(newFileName);
        QImage image = reader.read();

        if (image.isNull()) {
            QMessageBox::critical(this, tr("Error Loading Image"), reader.errorString());
            return;
        }

        if (link.type == TilesetImageSource) {
            TilesetParameters parameters(*link._tileset);
            parameters.imageSource = newFileName;

            auto command = new ChangeTilesetParameters(tilesetDocument,
                                                       parameters);

            tilesetDocument->undoStack()->push(command);
        } else {
            auto command = new ChangeTileImageSource(tilesetDocument,
                                                     link._tile,
                                                     newFileName);

            tilesetDocument->undoStack()->push(command);
        }

        prefs->setLastPath(Preferences::ImageFile, newFileName);

    } else if (link.type == MapTilesetReference) {
        const QString allFilesFilter = tr("All Files (*)");

        QString selectedFilter = allFilesFilter;
        QString filter = allFilesFilter;
        FormatHelper<TilesetFormat> helper(FileFormat::Read, filter);

        QString start = prefs->lastPath(Preferences::ExternalTileset);
        const QString fileName =
                QFileDialog::getOpenFileName(this, tr("Locate External Tileset"),
                                             start,
                                             helper.filter(),
                                             &selectedFilter);

        if (fileName.isEmpty())
            return;

        QString error;

        // It could be, that we have already loaded this tileset.
        SharedTileset newTileset = TilesetManager::instance()->findTileset(fileName);
        if (!newTileset || !newTileset->loaded()) {
            newTileset = Tiled::readTileset(fileName, &error);

            if (!newTileset) {
                QMessageBox::critical(window(), tr("Error Reading Tileset"), error);
                return;
            }
        }

        MapDocument *mapDocument = static_cast<MapDocument*>(document);
        int index = mapDocument->map()->tilesets().indexOf(link._tileset->sharedPointer());
        if (index != -1)
            document->undoStack()->push(new ReplaceTileset(mapDocument, index, newTileset));

        prefs->setLastPath(Preferences::ExternalTileset,
                           QFileInfo(fileName).path());
    }
}
Ejemplo n.º 20
0
void qAnimationDlg::render()
{
	if (!m_view3d)
	{
		assert(false);
		return;
	}
	QString outputFilename = outputFileLineEdit->text();

	//save to persistent settings
	{
		QSettings settings;
		settings.beginGroup("qAnimation");
		settings.setValue("filename", outputFilename);
		settings.endGroup();
	}

	setEnabled(false);

	//count the total number of frames
	int frameCount = countFrames(0);
	int fps = fpsSpinBox->value();
	int superRes = superResolutionSpinBox->value();

	//show progress dialog
	QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this);
	progressDialog.setWindowTitle("Render");
	progressDialog.show();
	QApplication::processEvents();

#ifdef QFFMPEG_SUPPORT
	//get original viewport size
	QSize originalViewSize = m_view3d->size();

	//hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit...
	{
		//find the nearest multiples of 8
		QSize customSize = originalViewSize;
		if (originalViewSize.width() % 8 || originalViewSize.height() % 8)
		{
			if (originalViewSize.width() % 8)
				customSize.setWidth((originalViewSize.width() / 8 + 1) * 8);
			if (originalViewSize.height() % 8)
				customSize.setHeight((originalViewSize.height() / 8 + 1) * 8);
			m_view3d->resize(customSize);
			QApplication::processEvents();
		}
	}

	int bitrate = bitrateSpinBox->value() * 1024;
	int gop = fps;
	QVideoEncoder encoder(outputFilename, m_view3d->width(), m_view3d->height(), bitrate, gop, static_cast<unsigned>(fpsSpinBox->value()));
	QString errorString;
	if (!encoder.open(&errorString))
	{
		QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString));
		setEnabled(true);
		return;
	}
#endif

	bool lodWasEnabled = m_view3d->isLODEnabled();
	m_view3d->setLODEnabled(false);

	int frameIndex = 0;
	bool success = true;
	size_t vp1 = 0, vp2 = 0;
	while (getNextSegment(vp1, vp2))
	{
		Step& step1 = m_videoSteps[vp1];
		Step& step2 = m_videoSteps[vp2];

		ViewInterpolate interpolator(step1.viewport, step2.viewport);
		int frameCount = static_cast<int>( fps * step1.duration_sec );
		interpolator.setMaxStep(frameCount);

		cc2DViewportObject current_params;
		while ( interpolator.nextView( current_params ) )
		{
			applyViewport ( &current_params );

			//render to image
			QImage image = m_view3d->renderToImage(superRes, false, false, true );

			if (image.isNull())
			{
				QMessageBox::critical(this, "Error", "Failed to grab the screen!");
				success = false;
				break;
			}

			if (superRes > 1)
			{
				image = image.scaled(image.width()/superRes, image.height()/superRes, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
			}

#ifdef QFFMPEG_SUPPORT
			if (!encoder.encodeImage(image, frameIndex, &errorString))
			{
				QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex+1).arg(errorString));
				success = false;
				break;
			}
#else
			QString filename = QString("frame_%1.png").arg(frameIndex, 6, 10, QChar('0'));
			QString fullPath = QDir(outputFilename).filePath(filename);
			if (!image.save(fullPath))
			{
				QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex+1));
				success = false;
				break;
			}
#endif
			++frameIndex;
			progressDialog.setValue(frameIndex);
			QApplication::processEvents();
			if (progressDialog.wasCanceled())
			{
				QMessageBox::warning(this, "Warning", QString("Process has been cancelled"));
				success = false;
				break;
			}
		}

		if (!success)
		{
			break;
		}

		if (vp2 == 0)
		{
			//stop loop here!
			break;
		}
		vp1 = vp2;
	}

	m_view3d->setLODEnabled(lodWasEnabled);

#ifdef QFFMPEG_SUPPORT
	encoder.close();

	//hack: restore original size
	m_view3d->resize(originalViewSize);
	QApplication::processEvents();
#endif
	
	progressDialog.hide();
	QApplication::processEvents();

	if (success)
	{
		QMessageBox::information(this, "Job done", "The animation has been saved successfully");
	}

	setEnabled(true);
}
Ejemplo n.º 21
0
void PictureShape::paint(QPainter &painter, const KViewConverter &converter)
{
    QRectF pixelsF = converter.documentToView(QRectF(QPointF(0,0), size()));
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        painter.fillRect(pixelsF, QColor(Qt::gray));
        return;
    }
    const QRect pixels = pixelsF.toRect();
    QSize pixmapSize = pixels.size();

    QString key(generate_key(imageData->key(), pixmapSize));
    QPixmap pixmap;
#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) { // first check cache.
#else
    if (!QPixmapCache::find(key, pixmap)) { // first check cache.
#endif
        // no? Does the imageData have it then?
        if (!(imageData->hasCachedPixmap() && imageData->pixmap().size() == pixmapSize)) {
            // ok, not what we want.
            // before asking to render it, make sure the image doesn't get too big
            QSize imageSize = imageData->image().size();
            if (imageSize.width() < pixmapSize.width() || imageSize.height() < pixmapSize.height()) {
                // kDebug() << "clipping size to orig image size" << imageSize;
                pixmapSize.setWidth(imageSize.width());
                pixmapSize.setHeight(imageSize.height());
            }

            if (m_printQualityImage.isNull()) {
                const int MaxSize = 1000; // TODO set the number as a KImageCollection size
                // make sure our pixmap doesn't get too slow.
                // In future we may want to make this action cause a multi-threaded rescale of the pixmap.
                if (pixmapSize.width() > MaxSize) { // resize to max size.
                    pixmapSize.setHeight(qRound(pixelsF.height() / pixelsF.width() * MaxSize));
                    pixmapSize.setWidth(MaxSize);
                }
                if (pixmapSize.height() > MaxSize) {
                    pixmapSize.setWidth(qRound(pixelsF.width() / pixelsF.height() * MaxSize));
                    pixmapSize.setHeight(MaxSize);
                }
            }
            key = generate_key(imageData->key(), pixmapSize);
        }
    }

    if (!m_printQualityImage.isNull() && pixmapSize == m_printQualityImage.size()) { // painting the image as prepared in waitUntilReady()
        painter.drawImage(pixels, m_printQualityImage, QRect(0, 0, pixmapSize.width(), pixmapSize.height()));
        m_printQualityImage = QImage(); // free memory
        return;
    }

#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) {
#else
    if (!QPixmapCache::find(key, pixmap)) {
#endif
        m_renderQueue->addSize(pixmapSize);
        QTimer::singleShot(0, m_renderQueue, SLOT(renderImage()));
        if (!imageData->hasCachedPixmap()
            || imageData->pixmap().size().width() > pixmapSize.width()) { // don't scale down
            QTimer::singleShot(0, m_renderQueue, SLOT(updateShape()));
            return;
        }
        pixmap = imageData->pixmap();
    }
    painter.drawPixmap(pixels, pixmap, QRect(0, 0, pixmap.width(), pixmap.height()));
}

void PictureShape::waitUntilReady(const KViewConverter &converter, bool asynchronous) const
{
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    if (asynchronous) {
        // get pixmap and schedule it if not
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QImage image = imageData->image();
        if (image.isNull()) {
            return;
        }
        if (image.size().width() < pixels.width()) { // don't scale up.
            pixels = image.size();
        }
        m_printQualityImage = image.scaled(pixels, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    }
    else {
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QString key(generate_key(imageData->key(), pixels));
        if (QPixmapCache::find(key) == 0) {
            QPixmap pixmap = imageData->pixmap(pixels);
            QPixmapCache::insert(key, pixmap);
        }
    }
}

void PictureShape::saveOdf(KShapeSavingContext &context) const
{
    // make sure we have a valid image data pointer before saving
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    KXmlWriter &writer = context.xmlWriter();

    writer.startElement("draw:frame");
    saveOdfAttributes(context, OdfAllAttributes);
    writer.startElement("draw:image");
    // In the spec, only the xlink:href attribute is marked as mandatory, cool :)
    QString name = context.imageHref(imageData);
    writer.addAttribute("xlink:type", "simple");
    writer.addAttribute("xlink:show", "embed");
    writer.addAttribute("xlink:actuate", "onLoad");
    writer.addAttribute("xlink:href", name);
    if (parent()) {
        parent()->saveOdfChildElements(context);
    }
    writer.endElement(); // draw:image
    saveOdfCommonChildElements(context);
    writer.endElement(); // draw:frame

    context.addDataCenter(m_imageCollection);
}
Ejemplo n.º 22
0
xcb_cursor_t QXcbCursor::createNonStandardCursor(int cshape)
{
    xcb_cursor_t cursor = 0;
    xcb_connection_t *conn = xcb_connection();

    if (cshape == Qt::BlankCursor) {
        xcb_pixmap_t cp = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(), cur_blank_bits, 16, 16,
                                                             1, 0, 0, 0);
        xcb_pixmap_t mp = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(), cur_blank_bits, 16, 16,
                                                             1, 0, 0, 0);
        cursor = xcb_generate_id(conn);
        xcb_create_cursor(conn, cursor, cp, mp, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 8, 8);
    } else if (cshape >= Qt::SizeVerCursor && cshape < Qt::SizeAllCursor) {
        int i = (cshape - Qt::SizeVerCursor) * 2;
        xcb_pixmap_t pm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                             const_cast<uint8_t*>(cursor_bits16[i]),
                                                             16, 16, 1, 0, 0, 0);
        xcb_pixmap_t pmm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                              const_cast<uint8_t*>(cursor_bits16[i + 1]),
                                                              16, 16, 1, 0, 0, 0);
        cursor = xcb_generate_id(conn);
        xcb_create_cursor(conn, cursor, pm, pmm, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 8, 8);
    } else if ((cshape >= Qt::SplitVCursor && cshape <= Qt::SplitHCursor)
               || cshape == Qt::WhatsThisCursor || cshape == Qt::BusyCursor) {
        int i = (cshape - Qt::SplitVCursor) * 2;
        xcb_pixmap_t pm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                             const_cast<uint8_t*>(cursor_bits32[i]),
                                                             32, 32, 1, 0, 0, 0);
        xcb_pixmap_t pmm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                              const_cast<uint8_t*>(cursor_bits32[i + 1]),
                                                              32, 32, 1, 0, 0, 0);
        int hs = (cshape == Qt::PointingHandCursor || cshape == Qt::WhatsThisCursor
                  || cshape == Qt::BusyCursor) ? 0 : 16;
        cursor = xcb_generate_id(conn);
        xcb_create_cursor(conn, cursor, pm, pmm, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, hs, hs);
    } else if (cshape == Qt::ForbiddenCursor) {
        int i = (cshape - Qt::ForbiddenCursor) * 2;
        xcb_pixmap_t pm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                             const_cast<uint8_t*>(cursor_bits20[i]),
                                                             20, 20, 1, 0, 0, 0);
        xcb_pixmap_t pmm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                              const_cast<uint8_t*>(cursor_bits20[i + 1]),
                                                              20, 20, 1, 0, 0, 0);
        cursor = xcb_generate_id(conn);
        xcb_create_cursor(conn, cursor, pm, pmm, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 10, 10);
    } else if (cshape == Qt::OpenHandCursor || cshape == Qt::ClosedHandCursor) {
        bool open = cshape == Qt::OpenHandCursor;
        xcb_pixmap_t pm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                             const_cast<uint8_t*>(open ? openhand_bits : closedhand_bits),
                                                             16, 16, 1, 0, 0, 0);
        xcb_pixmap_t pmm = xcb_create_pixmap_from_bitmap_data(conn, m_screen->root(),
                                                             const_cast<uint8_t*>(open ? openhandm_bits : closedhandm_bits),
                                                             16, 16, 1, 0, 0, 0);
        cursor = xcb_generate_id(conn);
        xcb_create_cursor(conn, cursor, pm, pmm, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 8, 8);
    } else if (cshape == Qt::DragCopyCursor || cshape == Qt::DragMoveCursor
               || cshape == Qt::DragLinkCursor) {
        QImage image = QGuiApplicationPrivate::instance()->getPixmapCursor(static_cast<Qt::CursorShape>(cshape)).toImage();
        if (!image.isNull()) {
            xcb_pixmap_t pm = qt_xcb_XPixmapFromBitmap(m_screen, image);
            xcb_pixmap_t pmm = qt_xcb_XPixmapFromBitmap(m_screen, image.createAlphaMask());
            cursor = xcb_generate_id(conn);
            xcb_create_cursor(conn, cursor, pm, pmm, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 8, 8);
            xcb_free_pixmap(conn, pm);
            xcb_free_pixmap(conn, pmm);
        }
    }

    return cursor;
}
Ejemplo n.º 23
0
bool readPixmapNode( const QDomElement& element, QPixmap& pixmap )
{
    bool ok = true;
    int tempLengthi;
    QString tempData;
    QDomNode node = element.firstChild();
    while( !node.isNull() ) {
        QDomElement element = node.toElement();
        if( !element.isNull() ) { // was really an element
            QString tagName = element.tagName();
            if( tagName == "Format" ) {
                QString formatName;
                ok = ok & readStringNode( element, formatName );
#ifndef NDEBUG
                if( formatName != "XPM.GZ" )
                    qDebug( "Unsupported pixmap format in XML file" );
#endif
            } else if( tagName == "Length" ) {
                ok = ok & readIntNode( element, tempLengthi );
            } else if( tagName == "Data" ) {
                ok = ok & readStringNode( element, tempData );
            } else {
                qDebug( "Unknown tag in Pixmap" );
            }
        }
        node = node.nextSibling();
    }

    if( ok ) {
	if( 0 < tempLengthi ) {
            // Decode the image file format in the same way Qt Designer does.
            char *ba = new char[ tempData.length() / 2 ];
            for ( int i = 0; i < (int)tempData.length() / 2; ++i ) {
                char h = tempData[ 2 * i ].latin1();
                char l = tempData[ 2 * i  + 1 ].latin1();
                uchar r = 0;
                if ( h <= '9' )
                    r += h - '0';
                else
                    r += h - 'a' + 10;
                r = r << 4;
                if ( l <= '9' )
                    r += l - '0';
                else
                    r += l - 'a' + 10;
                ba[ i ] = r;
            }

            if( tempLengthi < (int)tempData.length() * 5 )
                tempLengthi = tempData.length() * 5;
            unsigned long tempLength = tempLengthi;
            QByteArray baunzip( tempLength );
            ::uncompress( (uchar*) baunzip.data(), &tempLength,
                          (uchar*) ba, tempData.length()/2 );
            QImage image;
            image.loadFromData( (const uchar*)baunzip.data(), tempLength, "XPM" );

            if( image.isNull() )
                pixmap.resize( 0, 0 ); // This is _not_ an error, we just read a NULL pixmap!
            else
                ok = ok & pixmap.convertFromImage( image, 0 );
        } else
            pixmap.resize( 0, 0 ); // This is _not_ an error, we just read a empty pixmap!
    }

    return ok;
}
Ejemplo n.º 24
0
void FilmstripTile::render(QPainter& painter, const Widgets::TileInfo& tileInfo, const QVariant& data)
{
    int w = painter.window().width();
    int h = painter.window().height();

    //   painter.drawLine(0,0,w-1,h-1);
    //   painter.drawLine(0,h,w-1,0);

    // TODO: Load fonts in advance??
    painter.setFont(QFont("helvetica", 18));

    if (!data.isNull())
    {
        if ((tileInfo.tileState & Widgets::TileInfo::TileStateSelected) ==
            Widgets::TileInfo::TileStateSelected)
            painter.setBrush(QBrush(QColor(Qt::darkGray).lighter(180),
                Qt::SolidPattern));
        else
            painter.setBrush(QBrush(QColor(Qt::darkGray),
                Qt::SolidPattern));
        // draw the tile
        painter.setPen(QColor(Qt::darkGray));
        painter.drawRect(0, 0, w - 2, h - 2);
        painter.setBrush(Qt::NoBrush);

        // draw the bevel
        painter.setPen(QColor(Qt::gray));
        // draw clock wise
        painter.drawLine(0, h - 1, 0, 0);     //left side
        painter.drawLine(0, 0, w - 1, 0);     // top side
        painter.setPen(QColor(Qt::black));
        painter.drawLine(w - 1, 0, w - 1, h - 1);    // right side
        painter.drawLine(w - 1, h - 1, 0, h - 1);     // bottom side

        Photo info = data.value<Photo>();

        // draw the id text
        painter.save();
        painter.setPen(QColor(Qt::darkGray).lighter(110));
        painter.setFont(QFont(QString("Verdana"), 24, QFont::Bold));
        int fontHeight = painter.fontMetrics().height();
        painter.drawText(5, fontHeight - 5, QString::number(info.id()));

        painter.restore();

        // draw the image.
        QImage image = info.libraryPreviewsRGB();
        QRect  photoFinalDimension;

        if (!image.isNull())
        {
            float ratio = 0.90f;
            int   wf    = (int)(w * ratio);     // width frame
            int   hf    = (int)(h * ratio);     // height frame

            photoFinalDimension = fitFrame(image.size(), QSize(wf, hf));

            // move the frame to the center
            photoFinalDimension.translate((w - wf) / 2, (h - hf) / 2);
            painter.drawImage(photoFinalDimension, image);

            // draw border around image
            painter.setPen(QColor(Qt::black));
            painter.drawRect(photoFinalDimension);
        }
        else
        {
            // TODO: draw missing image indicator
            painter.setPen(QColor(Qt::red));
            painter.drawLine(w / 2 - 15, h / 2 - 15, w / 2 + 15,
                h / 2 + 15);
            painter.drawLine(w / 2 - 15, h / 2 + 15, w / 2 + 15,
                h / 2 - 15);
        }
    }
    else
    {
        // TODO: draw missing picture instead of blue cross
        painter.setPen(QColor(Qt::blue));
        painter.drawLine(0, 0, w - 1, h - 1);
        painter.drawLine(0, h - 1, w - 1, 0);
    }
}
Ejemplo n.º 25
0
/*
loadImagesThreadInstance::loadImagesThreadInstance()
{
}
*/
void loadImagesThread::processLoadImageJob ( int row, QString path, int size, int tpId )
{
	ScImageCacheManager &icm = ScImageCacheManager::instance();
	bool cacheEnabled = icm.enabled();
	icm.setEnabled(false);
	//check if list of files has changed and this job is obsolete
	if ( pModel->pId != tpId )
	{
		return;
	}

	if ( qAbs ( row - pictureBrowser->currentRow ) > 2* ( pictureBrowser->previewIconsVisible ) )
	{
		emit imageLoadError ( row, tpId, 0 );
		return;
	}

	QFileInfo fi = QFileInfo(path);
	QString ext = fi.suffix().toLower();
	QStringList allFormatsV = LoadSavePlugin::getExtensionsForPreview(FORMATID_ODGIMPORT);
	if (allFormatsV.contains(ext.toUtf8()))
	{
		FileLoader *fileLoader = new FileLoader(path);
		int testResult = fileLoader->TestFile();
		delete fileLoader;
		if ((testResult != -1) && (testResult >= FORMATID_ODGIMPORT))
		{
			const FileFormat * fmt = LoadSavePlugin::getFormatById(testResult);
			if( fmt )
			{
				QImage im = fmt->readThumbnail(path);
				if (!im.isNull())
				{
					ImageInformation *imgInfo = new ImageInformation;
					( *imgInfo ).width = im.text("XSize").toDouble();
					( *imgInfo ).height = im.text("YSize").toDouble();
					( *imgInfo ).type = 6;
					( *imgInfo ).colorspace = 0;
					( *imgInfo ).xdpi = 72;
					( *imgInfo ).ydpi = 72;
					( *imgInfo ).layers = 0;
					( *imgInfo ).embedded = false;
					( *imgInfo ).profileName = "";
					( *imgInfo ).valid = true;

					if ( ( im.width() > ( size-2 ) ) || ( im.height() > ( size-2 ) ) )
					{
						emit imageLoaded ( row, im.scaled ( ( size-2 ), ( size-2 ), Qt::KeepAspectRatio, Qt::SmoothTransformation ), imgInfo, tpId );
					}
					//image is <= our icon -> put it in as it is
					else
					{
						emit imageLoaded ( row, im.copy(), imgInfo, tpId );
					}
				}
			}
		}
		icm.setEnabled(cacheEnabled);
		return;
	}

	ScImage image;
//no realCMYK
	bool mode=false;
//no document needs to be assigned to this
	CMSettings cms ( 0, "", Intent_Perceptual);
	cms.allowColorManagement(false);
	cms.setUseEmbeddedProfile(true);

	ImageInformation *imgInfo = new ImageInformation;

	//load previewimage
	if ( image.loadPicture ( path, 1, cms, ScImage::Thumbnail, 72, &mode ) )
	{
		int ix,iy;
		if ( ( image.imgInfo.exifDataValid ) && ( !image.imgInfo.exifInfo.thumbnail.isNull() ) )
		{
			ix = image.imgInfo.exifInfo.width;
			iy = image.imgInfo.exifInfo.height;
		}
		else
		{
			ix = image.width();
			iy = image.height();
		}
		( *imgInfo ).width = ix;
		( *imgInfo ).height = iy;
		( *imgInfo ).type = image.imgInfo.type;
		( *imgInfo ).colorspace = image.imgInfo.colorspace;
		( *imgInfo ).xdpi = qRound ( image.imgInfo.xres );
		( *imgInfo ).ydpi = qRound ( image.imgInfo.yres );
		( *imgInfo ).layers = image.imgInfo.layerInfo.size();
		( *imgInfo ).embedded = image.imgInfo.isEmbedded;
		( *imgInfo ).profileName = image.imgInfo.profileName;
		( *imgInfo ).valid = true;

		//image is bigger than our icon -> resize
		if ( ( image.width() > ( size-2 ) ) || ( image.height() > ( size-2 ) ) )
		{
			emit imageLoaded ( row, image.scaled ( ( size-2 ), ( size-2 ), Qt::KeepAspectRatio, Qt::SmoothTransformation ), imgInfo, tpId );
		}
		//image is <= our icon -> put it in as it is
		else
		{
			emit imageLoaded ( row, image.qImage().copy(), imgInfo, tpId );
		}
	}
	else
	{
		//emit some errorsignal here
		( *imgInfo ).valid = false;
		emit imageLoaded ( row, QImage(), imgInfo, tpId );
	}
	icm.setEnabled(cacheEnabled);
}
Ejemplo n.º 26
0
// This function loads a texture and returns
// its opengl texture ID after binding.
const Texture& TextureManager::loadTexture(const QString& filename)
{
    Texture newTex;
    QImage tex;
    QString filepath;

    filepath = FileManager::getPathOfResource("textures", filename);

    newTex.name   = filename;
    newTex.width  = 0;
    newTex.height = 0;
    newTex.loaded = false;

    glGenTextures(1, &newTex.id);

    glBindTexture(GL_TEXTURE_2D, newTex.id);
    tex = QImage(filepath).mirrored();

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    // some generic default texture parameters
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_MIRRORED_REPEAT
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
#endif

    tex = QGLWidget::convertToGLFormat(QImage(filepath));
    if(!tex.isNull())
    {
        //glEnable(GL_TEXTURE_2D);
        /*newTex.id = GAME->getGLWidget()->bindTexture(
            tex, GL_TEXTURE_2D, GL_RGBA,
            QGLContext::LinearFilteringBindOption |
            QGLContext::MipmapBindOption);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef GL_MIRRORED_REPEAT
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
#endif*/

        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, tex.width(), tex.height(), 0,
            GL_RGBA, GL_UNSIGNED_BYTE, tex.bits() );

        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, tex.width(), tex.height(),
            GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());

        qDebug() << "Loaded texture: " << filepath << "with id" << newTex.id;
        newTex.loaded = true;
    }
    else
    {   
        qCritical() << "Can't load image file: " << filepath;
    }

    textures.insert(textures.begin(), newTex);

    return getTexture(filename);
}
Ejemplo n.º 27
0
QImage QwtPlotRasterItem::compose(
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &imageArea, const QRectF &paintRect,
    const QSize &imageSize, bool doCache) const
{
    QImage image;
    if ( imageArea.isEmpty() || paintRect.isEmpty() || imageSize.isEmpty() )
        return image;

    if ( doCache )
    {
        if ( !d_data->cache.image.isNull()
            && d_data->cache.area == imageArea
            && d_data->cache.size == paintRect.size() )
        {
            image = d_data->cache.image;
        }
    }

    if ( image.isNull() )
    {
        double dx = 0.0;
        if ( paintRect.toRect().width() > imageSize.width() )
            dx = imageArea.width() / imageSize.width();

        const QwtScaleMap xxMap =
            imageMap(Qt::Horizontal, xMap, imageArea, imageSize, dx);

        double dy = 0.0;
        if ( paintRect.toRect().height() > imageSize.height() )
            dy = imageArea.height() / imageSize.height();

        const QwtScaleMap yyMap =
            imageMap(Qt::Vertical, yMap, imageArea, imageSize, dy);

        image = renderImage( xxMap, yyMap, imageArea, imageSize );

        if ( doCache )
        {
            d_data->cache.area = imageArea;
            d_data->cache.size = paintRect.size();
            d_data->cache.image = image;
        }
    }

    if ( d_data->alpha >= 0 && d_data->alpha < 255 )
    {
        QImage alphaImage( image.size(), QImage::Format_ARGB32 );

#if !defined(QT_NO_QFUTURE)
        uint numThreads = renderThreadCount();

        if ( numThreads <= 0 )
            numThreads = QThread::idealThreadCount();

        if ( numThreads <= 0 )
            numThreads = 1;

        const int numRows = image.height() / numThreads;

        QVector< QFuture<void> > futures;
        futures.reserve( numThreads - 1 );

        for ( uint i = 0; i < numThreads; i++ )
        {
            QRect tile( 0, i * numRows, image.width(), numRows );
            if ( i == numThreads - 1 )
            {
                tile.setHeight( image.height() - i * numRows );
                qwtToRgba( &image, &alphaImage, tile, d_data->alpha );
            }
            else
            {
                futures += QtConcurrent::run(
                    &qwtToRgba, &image, &alphaImage, tile, d_data->alpha );
            }
        }
        for ( int i = 0; i < futures.size(); i++ )
            futures[i].waitForFinished();
#else
        const QRect tile( 0, 0, image.width(), image.height() );
        qwtToRgba( &image, &alphaImage, tile, d_data->alpha );
#endif
        image = alphaImage;
    }

    return image;
}
Ejemplo n.º 28
0
static
void setup_qt(QImage& image, png_structp png_ptr, png_infop info_ptr, float screen_gamma=0.0)
{
    if (screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
        double file_gamma;
        png_get_gAMA(png_ptr, info_ptr, &file_gamma);
        png_set_gamma(png_ptr, screen_gamma, file_gamma);
    }

    png_uint_32 width;
    png_uint_32 height;
    int bit_depth;
    int color_type;
    png_bytep trans_alpha = 0;
    png_color_16p trans_color_p = 0;
    int num_trans;
    png_colorp palette = 0;
    int num_palette;
    png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
    png_set_interlace_handling(png_ptr);

    if (color_type == PNG_COLOR_TYPE_GRAY) {
        // Black & White or 8-bit grayscale
        if (bit_depth == 1 && png_get_channels(png_ptr, info_ptr) == 1) {
            png_set_invert_mono(png_ptr);
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Mono) {
                image = QImage(width, height, QImage::Format_Mono);
                if (image.isNull())
                    return;
            }
            image.setColorCount(2);
            image.setColor(1, qRgb(0,0,0));
            image.setColor(0, qRgb(255,255,255));
        } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_expand(png_ptr);
            png_set_strip_16(png_ptr);
            png_set_gray_to_rgb(png_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_ARGB32) {
                image = QImage(width, height, QImage::Format_ARGB32);
                if (image.isNull())
                    return;
            }
            if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
                png_set_swap_alpha(png_ptr);

            png_read_update_info(png_ptr, info_ptr);
        } else {
            if (bit_depth == 16)
                png_set_strip_16(png_ptr);
            else if (bit_depth < 8)
                png_set_packing(png_ptr);
            int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
            png_read_update_info(png_ptr, info_ptr);
            if (image.size() != QSize(width, height) || image.format() != QImage::Format_Indexed8) {
                image = QImage(width, height, QImage::Format_Indexed8);
                if (image.isNull())
                    return;
            }
            image.setColorCount(ncols);
            for (int i=0; i<ncols; i++) {
                int c = i*255/(ncols-1);
                image.setColor(i, qRgba(c,c,c,0xff));
            }
            if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_color_p) {
                const int g = trans_color_p->gray;
                if (g < ncols) {
                    image.setColor(g, 0);
                }
            }
        }
    } else if (color_type == PNG_COLOR_TYPE_PALETTE
               && png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette)
               && num_palette <= 256)
    {
        // 1-bit and 8-bit color
        if (bit_depth != 1)
            png_set_packing(png_ptr);
        png_read_update_info(png_ptr, info_ptr);
        png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0);
        QImage::Format format = bit_depth == 1 ? QImage::Format_Mono : QImage::Format_Indexed8;
        if (image.size() != QSize(width, height) || image.format() != format) {
            image = QImage(width, height, format);
            if (image.isNull())
                return;
        }
        png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
        image.setColorCount(num_palette);
        int i = 0;
        if (png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color_p) && trans_alpha) {
            while (i < num_trans) {
                image.setColor(i, qRgba(
                    palette[i].red,
                    palette[i].green,
                    palette[i].blue,
                    trans_alpha[i]
                   )
               );
                i++;
            }
        }
        while (i < num_palette) {
            image.setColor(i, qRgba(
                palette[i].red,
                palette[i].green,
                palette[i].blue,
                0xff
               )
           );
            i++;
        }
    } else {
        // 32-bit
        if (bit_depth == 16)
            png_set_strip_16(png_ptr);

        png_set_expand(png_ptr);

        if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
            png_set_gray_to_rgb(png_ptr);

        QImage::Format format = QImage::Format_ARGB32;
        // Only add filler if no alpha, or we can get 5 channel data.
        if (!(color_type & PNG_COLOR_MASK_ALPHA)
            && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
            png_set_filler(png_ptr, 0xff, QSysInfo::ByteOrder == QSysInfo::BigEndian ?
                           PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
            // We want 4 bytes, but it isn't an alpha channel
            format = QImage::Format_RGB32;
        }
        if (image.size() != QSize(width, height) || image.format() != format) {
            image = QImage(width, height, format);
            if (image.isNull())
                return;
        }

        if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
            png_set_swap_alpha(png_ptr);

        png_read_update_info(png_ptr, info_ptr);
    }

    // Qt==ARGB==Big(ARGB)==Little(BGRA)
    if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) {
        png_set_bgr(png_ptr);
    }
}
Ejemplo n.º 29
0
int HtmlDocument::insertimage() {

    bool c*k;
    bool bok;
    console(QString("Begin image handle..."));
    int found = 0;
    QRegExp expression("src=[\"\'](.*)[\"\']", Qt::CaseInsensitive);
    expression.setMinimal(true);
    int iPosition = 0;
    while ((iPosition = expression.indexIn(FULLHTMLBODY, iPosition)) != -1) {
        int greppoint = iPosition;
        const QString imagesrcx = expression.cap(1); /// this must replaced
        int loengh = imagesrcx.length();
        int backsearch = 26;
        if (imagesrcx.startsWith("Pictures/")) {
            /// grab on zip imagesrcx
            QByteArray xdata = docitem(imagesrcx);
            QImage ipic; /// i.value() /// i.key(); 
            ipic.loadFromData(xdata);
            if (xdata.size() > 0 && !ipic.isNull()) {
                int imgWI = ipic.width();
                int imgHI = ipic.height();
                int picWI = 0;
                int picHI = 0;
                bool resize = false;
                //// ok valid image & search width height if is to resize to save kb.
                QString whifind = FULLHTMLBODY.mid(greppoint - backsearch, backsearch); // back 15from src
                /// height is last..
                QStringList piece = whifind.split("|", QString::SkipEmptyParts);
                QStringList numbers = piece.filter(".");

                if (numbers.size() == 2) {
                    picWI = numbers.at(0).toFloat(&c*k);
                    picHI = numbers.at(1).toFloat(&bok);
                    if (c*k && bok && picWI > 0 && picHI > 0) {
                        // console(QString("Largo (%1) ").arg(picWI));
                        //console(QString("alto (%1) ").arg(picHI));
                        if (imgWI != picWI && RESIZEIMAGETODEFINEDWIHIGHTHTML == 1) {
                            resize = true; /// stay quality hight or down?
                        }
                    }
                }
                found++;
                QFileInfo pic(imagesrcx);
                //// tif image not work on browser!!!
                QString blob;
                const QString ext = pic.completeSuffix().toLower();
                if (ext == "tif" || ext == "tiff" || resize) {
                    if (resize) {
                        console(QString("Image resize (%1x%2) ").arg(picWI).arg(picHI));
                        xdata = this->convertPNG(ipic, picWI, picHI);
                    } else {
                        xdata = this->convertPNG(ipic);
                    }
                    blob = "data:image/png;base64,";
                } else {
                    blob = "data:image/" + pic.completeSuffix().toLower() + ";base64,";
                }
                QString imagembed(xdata.toBase64().constData());
                blob.append(imagembed); /// format_string76(blob) 
                const QString imagehtml = blob; //// Tools::f_string76(blob); /// image scroll...
                FULLHTMLBODY.replace(imagesrcx, imagehtml);
            } else {
                /// found a null image insert a 1x1 pixel.  __ONEPIXELGIF__
                FULLHTMLBODY.replace(imagesrcx, __ONEPIXELGIF__);
                QString errorimage = QString("Invalid Image Format! %1 insert a 1x1 transparent pixel..").arg(imagesrcx);
                setError(errorimage);

            }
        }

        iPosition += expression.matchedLength();
    }

    console(QString("End image handle..."));
    /////QStringList	split ( const QChar & sep, SplitBehavior behavior = KeepEmptyParts, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
    QString htmltmp;
    QStringList lines = FULLHTMLBODY.split(QRegExp("(\\r\\n)|(\\n\\r)|\\n"), QString::SkipEmptyParts);
    for (int i = 0; i < lines.size(); ++i) {
        QString line = lines.at(i);
        QString lc = line.simplified();
        if (!lc.isEmpty()) {
            htmltmp.append(line);
            htmltmp.append("\n");
        }
    }
    FULLHTMLBODY = OASIUNIT::cleanhtml(htmltmp);
    //// QString::fromUtf8(stream()); 
    return found;
}
QImage HarbourQrCodeImageProvider::requestImage(const QString& aId, QSize* aSize, const QSize&)
{
    // Default background and foreground
    QColor background(Qt::transparent), color(Qt::black);

    // Parse parameters
    QString base32;
    const int sep = aId.indexOf('?');
    if (sep < 0) {
        base32 = aId;
    } else {
        base32 = aId.left(sep);
        const QStringList params(aId.mid(sep + 1).split('&', QString::SkipEmptyParts));
        const int n = params.count();
        for (int i = 0; i < n; i++) {
            const QString param(params.at(i));
            const int eq = param.indexOf('=');
            if (eq > 0) {
                static const QString BACKGROUND("background");
                static const QString COLOR("color");
                const QString name(param.left(eq).trimmed());
                const QString value(param.mid(eq + 1).trimmed());
                if (name == COLOR) {
                    const QColor colorValue(value);
                    if (colorValue.isValid()) {
                        color = colorValue;
                    } else {
                        HDEBUG("Invalid" << qPrintable(name) << value);
                    }
                } else if (name == BACKGROUND) {
                    const QColor colorValue(value);
                    if (colorValue.isValid()) {
                        background = colorValue;
                    } else {
                        HDEBUG("Invalid" << qPrintable(name) << value);
                    }
                } else {
                    HDEBUG("Invalid parameter name" << name);
                }
            } else {
                HDEBUG("Invalid parameter" << param);
            }
        }
    }

    // Decode BASE32
    const QByteArray bits(HarbourBase32::fromBase32(base32.toLocal8Bit()));
    QImage img;
    HDEBUG(base32 << "=>" << bits.size() << "bytes");
    if (bits.size() > 0) {
        // Bits are packed, rows are rounded at byte boundary
        int rows, rowSize;
        for (rows = 2; ((rowSize = (rows + 7)/8) * rows) < bits.size(); rows++);
        if ((rows * rowSize) == bits.size()) {
            HDEBUG(rows << "x" << rows);
            img = QImage(rows, rows, QImage::Format_Mono);
            QVector<QRgb> colors;
            colors.append(background.rgba());
            colors.append(color.rgba());
            img.setColorTable(colors);
            for (int y = 0; y < rows; y++) {
                memcpy(img.scanLine(y), bits.constData() + y * rowSize, rowSize);
            }
        }
    }

    if (!img.isNull() && aSize) {
        *aSize = img.size();
    }

    return img;
}