Пример #1
0
bool PictureLoader::cardImageExistsOnDisk(QString & setName, QString & correctedCardname)
{
    QImage image;
    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);

    //The list of paths to the folders in which to search for images
    QList<QString> picsPaths = QList<QString>() << picsPath + "/CUSTOM/" + correctedCardname;

    if(!setName.isEmpty())
    {
        picsPaths   << picsPath + "/" + setName + "/" + correctedCardname
                    << picsPath + "/downloadedPics/" + setName + "/" + correctedCardname;
    }

    //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
    for (int i = 0; i < picsPaths.length(); i ++) {
        imgReader.setFileName(picsPaths.at(i));
        if (imgReader.read(&image)) {
            qDebug() << "Picture found on disk (set: " << setName << " card: " << correctedCardname << ")";
            imageLoaded(cardBeingLoaded.getCard(), image);
            return true;
        }
        imgReader.setFileName(picsPaths.at(i) + ".full");
        if (imgReader.read(&image)) {
            qDebug() << "Picture.full found on disk (set: " << setName << " card: " << correctedCardname << ")";
            imageLoaded(cardBeingLoaded.getCard(), image);
            return true;
        }
    }

    return false;
}
Пример #2
0
void PictureLoader::picDownloadFinished(QNetworkReply *reply)
{
    QString picsPath = _picsPath;
    if (reply->error()) {
        qDebug() << "Download failed:" << reply->errorString();
    }

    const QByteArray &picData = reply->peek(reply->size()); //peek is used to keep the data in the buffer for use by QImageReader
    QImage testImage;

    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);
    imgReader.setDevice(reply);
    QString extension = "." + imgReader.format(); //the format is determined prior to reading the QImageReader data into a QImage object, as that wipes the QImageReader buffer
    if (extension == ".jpeg")
        extension = ".jpg";

    if (imgReader.read(&testImage)) {
        QString setName = cardBeingDownloaded.getSetName();
        if(!setName.isEmpty())
        {
            if (!QDir().mkpath(picsPath + "/downloadedPics/" + setName)) {
                qDebug() << picsPath + "/downloadedPics/" + setName + " could not be created.";
                return;
            }

            QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + extension);
            if (!newPic.open(QIODevice::WriteOnly))
                return;
            newPic.write(picData);
            newPic.close();
        }

        emit imageLoaded(cardBeingDownloaded.getCard(), testImage);
    } else if (cardBeingDownloaded.getHq()) {
        qDebug() << "HQ: received invalid picture. URL:" << reply->request().url();
        cardBeingDownloaded.setHq(false);
        cardsToDownload.prepend(cardBeingDownloaded);
    } else {
        qDebug() << "LQ: received invalid picture. URL:" << reply->request().url();
        if (cardBeingDownloaded.nextSet()) {
            cardBeingDownloaded.setHq(true);
            mutex.lock();
            loadQueue.prepend(cardBeingDownloaded);
            mutex.unlock();
            emit startLoadQueue();
        } else
            emit imageLoaded(cardBeingDownloaded.getCard(), QImage());
    }

    reply->deleteLater();
    startNextPicDownload();
}
void AssemblyMainWindow::loadImage( const QString& imageName ) {
	QPixmap* img = new QPixmap();
	try {
		if( img->load(imageName) ) {
			// udalo sie zaladowac obrazek. Czy trasa jest juz utworzona?
			if( mpTrack != 0 ) {
				// aktualizujemy obrazek istniejacej trasy
				mpTrack->reloadImage( img, static_cast<int>( pow( 2, ui->gridSlider->value() ) ) );
			} else {
				// tworzy nowa trase
				mpTrack = new Track( img, static_cast<int>( pow( 2, ui->gridSlider->value() ) ) );
			}
			trackView->setTrack( mpTrack );
			ui->loadImageButton->setEnabled( false );
			ui->labelImageState->setText("Stan obrazka: <font color=\"green\">OK</font>");
			ui->labelResolution->setText( QString::number(mpTrack->getWidth()) + QString("x") + QString::number(mpTrack->getHeight()) );
			enableMenus();
			emit imageLoaded();
		} else {
			delete img;
		}
	} catch( std::exception& e ) {
		if( img != 0 ) delete img;
		if( mpTrack != 0 ) delete mpTrack;
		trackView->setTrack( 0 );
		ui->labelImageState->setText("Stan obrazka: <font color=\"red\">b³¹d</font>");
		ui->labelResolution->setText("Niepoprawny rozmiar.");
	}

}
void LoadImagesThread::run() {
	// Set row heights/column widths
	for(int index = 0; index < images.size() && !shouldStop; ++index) {
		QImage image(images[index]);
		emit imageLoaded(index, image);
	}
}
Пример #5
0
void GetConnection::onPictureReady()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QByteArray data;
    QUrl redir;
    if (!reply) {
        qDebug() << "Cast to qnetwork reply fail!";
        return;
    }
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Picture get fail!";
        reply->deleteLater();
        reply = 0;

        return;
    }

    redir = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    // Facebook is redirecting the picture request
    if(!redir.isEmpty()) {
        qDebug() << "Redirecting picture request to " + redir.toString();
        reply = m_qFacebook->get(redir);
        if (reply)
            connect(reply, SIGNAL(finished()), this, SLOT(onPictureReady()));
        // not finished yet!
        return;
    }

    qDebug() << "######### Parsed picture:";
    data = reply->readAll();
    qDebug() << data;
    QImage m_picture = QImage::fromData(data, "JPEG");

    emit imageLoaded(m_picture);
}
Пример #6
0
void PictureLoader::picDownloadFinished(QNetworkReply *reply)
{
    if (reply->error()) {
        qDebug() << "Download failed:" << reply->errorString();
    }

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (statusCode == 301 || statusCode == 302) {
        QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        QNetworkRequest req(redirectUrl);
        qDebug() << "following redirect:" << cardBeingDownloaded.getCard()->getName() << "Url:" << req.url();
        networkManager->get(req);
        return;
    }

    const QByteArray &picData = reply->peek(reply->size()); //peek is used to keep the data in the buffer for use by QImageReader

    if(imageIsBlackListed(picData))
    {
        qDebug() << "Picture downloaded, but blacklisted, will consider it as not found";
        picDownloadFailed();
        reply->deleteLater();
        startNextPicDownload();
        return;
    }

    QImage testImage;
    
    QImageReader imgReader;
    imgReader.setDecideFormatFromContent(true);
    imgReader.setDevice(reply);
    QString extension = "." + imgReader.format(); //the format is determined prior to reading the QImageReader data into a QImage object, as that wipes the QImageReader buffer
    if (extension == ".jpeg")
        extension = ".jpg";
    
    if (imgReader.read(&testImage)) {
        QString setName = cardBeingDownloaded.getSetName();
        if(!setName.isEmpty())
        {
            if (!QDir().mkpath(picsPath + "/downloadedPics/" + setName)) {
                qDebug() << picsPath + "/downloadedPics/" + setName + " could not be created.";
                return;
            }

            QFile newPic(picsPath + "/downloadedPics/" + setName + "/" + cardBeingDownloaded.getCard()->getCorrectedName() + extension);
            if (!newPic.open(QIODevice::WriteOnly))
                return;
            newPic.write(picData);
            newPic.close();
        }

        imageLoaded(cardBeingDownloaded.getCard(), testImage);
    } else {
        picDownloadFailed();
    } 

    reply->deleteLater();
    startNextPicDownload();
}
Пример #7
0
BackgroundInner::BackgroundInner() :
_bgCount(0), _rows(0), _over(-1), _overDown(-1) {
	connect(App::wnd(), SIGNAL(imageLoaded()), this, SLOT(update()));
	if (App::cServerBackgrounds().isEmpty()) {
		resize(BackgroundsInRow * (st::backgroundSize.width() + st::backgroundPadding) + st::backgroundPadding, 2 * (st::backgroundSize.height() + st::backgroundPadding) + st::backgroundPadding);
		MTP::send(MTPaccount_GetWallPapers(), rpcDone(&BackgroundInner::gotWallpapers));
	} else {
		updateWallpapers();
	}
	setMouseTracking(true);
}
ImageFunctor::ImageFunctor(QObject* parent)
    : QObject(parent)
{

    m_imageLoader = new ImageLoader(this);
    connect (m_imageLoader, SIGNAL(imageLoaded(QImage)),
             this, SLOT(grabImage(QImage)));
    connect (m_imageLoader, SIGNAL(finished()), this, SLOT(transformQueue()));
    m_futureWatcher = 0;
    newFutureWatcher();
}
Пример #9
0
LocalStorageBox::LocalStorageBox() : AbstractBox()
, _clear(this, lang(lng_local_storage_clear), st::defaultBoxLinkButton)
, _close(this, lang(lng_box_ok), st::defaultBoxButton) {
	connect(_clear, SIGNAL(clicked()), this, SLOT(onClear()));
	connect(_close, SIGNAL(clicked()), this, SLOT(onClose()));

	connect(App::wnd(), SIGNAL(imageLoaded()), this, SLOT(update()));
	connect(App::wnd(), SIGNAL(tempDirCleared(int)), this, SLOT(onTempDirCleared(int)));
	connect(App::wnd(), SIGNAL(tempDirClearFailed(int)), this, SLOT(onTempDirClearFailed(int)));

	checkLocalStoredCounts();
	prepare();
}
Пример #10
0
void MainWindow::on_itemList_itemDoubleClicked(QListWidgetItem *item)
{
    loadingTheInformations=true;
    quint32 selectedItem=item->data(99).toUInt();
    if(!items[selectedItem].hasAttribute("price"))
        items[selectedItem].setAttribute("price",0);
    bool ok;
    ui->price->setValue(items[selectedItem].attribute("price").toUInt(&ok));
    if(!ok)
        ui->price->setValue(0);
    if(items[selectedItem].hasAttribute("image"))
    {
        QPixmap imageLoaded(QFileInfo(ui->lineEditItemFile->text()).absolutePath()+"/"+items[selectedItem].attribute("image"));
        imageLoaded.scaled(96,96);
        ui->image->setPixmap(imageLoaded);
    }
    else
        ui->image->setPixmap(QPixmap());
    //load name
    {
        ui->nameEditLanguageList->clear();
        QDomElement name = items[selectedItem].firstChildElement("name");
        while(!name.isNull())
        {
            if(!name.hasAttribute("lang"))
                ui->nameEditLanguageList->addItem("en");
            else
                ui->nameEditLanguageList->addItem(name.attribute("lang"));
            name = name.nextSiblingElement("name");
        }
    }
    //load description
    {
        ui->descriptionEditLanguageList->clear();
        QDomElement description = items[selectedItem].firstChildElement("description");
        while(!description.isNull())
        {
            if(!description.hasAttribute("lang"))
                ui->descriptionEditLanguageList->addItem("en");
            else
                ui->descriptionEditLanguageList->addItem(description.attribute("lang"));
            description = description.nextSiblingElement("description");
        }
    }
    ui->stackedWidget->setCurrentWidget(ui->page_edit);
    ui->tabWidget->setCurrentWidget(ui->tabGeneral);
    loadingTheInformations=false;
    on_nameEditLanguageList_currentIndexChanged(ui->nameEditLanguageList->currentIndex());
    on_descriptionEditLanguageList_currentIndexChanged(ui->descriptionEditLanguageList->currentIndex());
}
Пример #11
0
void PictureLoader::picDownloadFailed()
{
    if (cardBeingDownloaded.nextSet())
    {
        qDebug() << "Picture NOT found, download failed, moving to next set (newset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getCorrectedName() << ")";
        mutex.lock();
        loadQueue.prepend(cardBeingDownloaded);
        mutex.unlock();
        emit startLoadQueue();
    } else {
        qDebug() << "Picture NOT found, download failed, no more sets to try: BAILING OUT (oldset: " << cardBeingDownloaded.getSetName() << " card: " << cardBeingDownloaded.getCard()->getCorrectedName() << ")";
        cardBeingDownloaded = 0;
        emit imageLoaded(cardBeingDownloaded.getCard(), QImage());
    }
}
Пример #12
0
Window::Window(QWidget *parent) : PsMainWindow(parent), _serviceHistoryRequest(0), title(0),
_passcode(0), intro(0), main(0), settings(0), layerBG(0), _isActive(false), _topWidget(0),
_connecting(0), _clearManager(0), dragging(false), _inactivePress(false), _shouldLockAt(0), _mediaView(0) {

	icon16 = icon256.scaledToWidth(16, Qt::SmoothTransformation);
	icon32 = icon256.scaledToWidth(32, Qt::SmoothTransformation);
	icon64 = icon256.scaledToWidth(64, Qt::SmoothTransformation);
	iconbig16 = iconbig256.scaledToWidth(16, Qt::SmoothTransformation);
	iconbig32 = iconbig256.scaledToWidth(32, Qt::SmoothTransformation);
	iconbig64 = iconbig256.scaledToWidth(64, Qt::SmoothTransformation);

	if (objectName().isEmpty()) {
		setObjectName(qsl("MainWindow"));
	}
	resize(st::wndDefWidth, st::wndDefHeight);
	setWindowOpacity(1);
	setLocale(QLocale(QLocale::English, QLocale::UnitedStates));
	centralwidget = new QWidget(this);
	centralwidget->setObjectName(qsl("centralwidget"));
	setCentralWidget(centralwidget);

	QMetaObject::connectSlotsByName(this);

	_inactiveTimer.setSingleShot(true);
	connect(&_inactiveTimer, SIGNAL(timeout()), this, SLOT(onInactiveTimer()));

	connect(&notifyWaitTimer, SIGNAL(timeout()), this, SLOT(notifyFire()));

	_isActiveTimer.setSingleShot(true);
	connect(&_isActiveTimer, SIGNAL(timeout()), this, SLOT(updateIsActive()));

	connect(&_autoLockTimer, SIGNAL(timeout()), this, SLOT(checkAutoLock()));

	connect(this, SIGNAL(imageLoaded()), this, SLOT(update()));
	connect(this, SIGNAL(imageLoaded()), this, SLOT(notifyUpdateAllPhotos()));
}
void FormMaterialIndicesManager::pasteImageFromClipboard(QImage& _image){


    int mIndex = FBOImageProporties::currentMaterialIndeks;
    if(updateMaterials(_image)){
          image    = _image;
          imageProp.init(image);
          emit materialChanged();
          FBOImageProporties::currentMaterialIndeks = mIndex;
          emit imageLoaded(image.width(),image.height());
          // repaint all materials
          if(FBOImageProporties::currentMaterialIndeks != MATERIALS_DISABLED){
              toggleMaterials(true);
          }
    }
}
Пример #14
0
void NetworkTexture::setImage(const QImage& image, bool translucent) {
    _translucent = translucent;
    
    finishedLoading(true);
    imageLoaded(image);
    glBindTexture(GL_TEXTURE_2D, getID());
    if (image.hasAlphaChannel()) {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 1,
            GL_BGRA, GL_UNSIGNED_BYTE, image.constBits());
    } else {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 1,
            GL_RGB, GL_UNSIGNED_BYTE, image.constBits());
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glBindTexture(GL_TEXTURE_2D, 0);
}
Пример #15
0
WizardController::WizardController(QObject *wizardDialog, QObject *parent)
    : QObject(parent)
{
    connect(this, SIGNAL(wizardStepChanged(int)), wizardDialog, SLOT(setWizardStep(int)));
    connect(this, SIGNAL(wizardStepDescriptionChanged(const QString&, const QString&)), wizardDialog, SLOT(setWizardStepDescription(const QString&, const QString&)));
    connect(this, SIGNAL(prevButtonEnabled(bool)), wizardDialog, SLOT(setPrevButtonEnabled(bool)));
    connect(this, SIGNAL(nextButtonEnabled(bool)), wizardDialog, SLOT(setNextButtonEnabled(bool)));
    connect(this, SIGNAL(previewStateChanged(const QString&)), wizardDialog, SLOT(setPreviewState(const QString&)));
    connect(this, SIGNAL(showManualSignal(const QString&, const QString&)), wizardDialog, SLOT(showManual(const QString&, const QString&)));
    connect(this, SIGNAL(showWizardStepHelpSignal(const QString&, const QString&)), wizardDialog, SLOT(showWizardStepHelp(const QString&, const QString&)));
    connect(wizardDialog, SIGNAL(imageLoaded()), SLOT(handleImageLoaded()));
    connect(wizardDialog, SIGNAL(prevButtonPressed()), SLOT(handlePrevButtonPressed()));
    connect(wizardDialog, SIGNAL(nextButtonPressed()), SLOT(handleNextButtonPressed()));
    connect(wizardDialog, SIGNAL(manualSignal()), SLOT(showManual()));
    connect(wizardDialog, SIGNAL(wizardStepHelpSignal()), SLOT(showHelpForCurrentStep()));

    updateDialogWizardStep();
}
Пример #16
0
void PictureLoader::processLoadQueue()
{
    if (loadQueueRunning)
        return;

    loadQueueRunning = true;
    forever {
        mutex.lock();
        if (loadQueue.isEmpty()) {
            mutex.unlock();
            loadQueueRunning = false;
            return;
        }
        cardBeingLoaded = loadQueue.takeFirst();
        mutex.unlock();

        QString setName = cardBeingLoaded.getSetName();
        QString correctedCardname = cardBeingLoaded.getCard()->getCorrectedName();
        qDebug() << "Trying to load picture (set: " << setName << " card: " << correctedCardname << ")";

        if(cardImageExistsOnDisk(setName, correctedCardname))
            continue;

        if (picDownload) {
            qDebug() << "Picture NOT found, trying to download (set: " << setName << " card: " << correctedCardname << ")";
            cardsToDownload.append(cardBeingLoaded);
            cardBeingLoaded=0;
            if (!downloadRunning)
                startNextPicDownload();
        } else {
            if (cardBeingLoaded.nextSet())
            {
                qDebug() << "Picture NOT found and download disabled, moving to next set (newset: " << setName << " card: " << correctedCardname << ")";
                mutex.lock();
                loadQueue.prepend(cardBeingLoaded);
                cardBeingLoaded=0;
                mutex.unlock();
            } else {
                qDebug() << "Picture NOT found, download disabled, no more sets to try: BAILING OUT (oldset: " << setName << " card: " << correctedCardname << ")";
                imageLoaded(cardBeingLoaded.getCard(), QImage());
            }
        }
    }
}
Пример #17
0
void Wizard::updateImageInfoFields(const QSize &inputImageSizeInPixels, const QSizeF &imageSize, double verticalDpi, double horizontalDpi, Types::ColorTypes colorType, int bitsPerPixel)
{
    Q_UNUSED(horizontalDpi)

    m_imageInformationSizeInPixelsValue->setText(QString("%1 x %2").arg(inputImageSizeInPixels.width()).arg(inputImageSizeInPixels.height()));
    m_imageInformationSizeValue->setText(QString("%1 x %2").arg(imageSize.width(), 0, 'f', 2).arg(imageSize.height(), 0, 'f', 2));
    m_imageInformationResolutionValue->setText(QString("%1 dpi").arg(verticalDpi, 0, 'f', 1));
    const QString colorTypeString = (
        colorType==Types::ColorTypeMonochrome?QCoreApplication::translate("Main window", "Monochrome"):
        colorType==Types::ColorTypeGreyscale?QCoreApplication::translate("Main window", "Gray scale"):
        colorType==Types::ColorTypePalette?QCoreApplication::translate("Main window", "Palette"):
        colorType==Types::ColorTypeRGB?QCoreApplication::translate("Main window", "RGB"):
        colorType==Types::ColorTypeRGBA?QCoreApplication::translate("Main window", "RGBA"):
        /*colorType==ColorTypeCMYK?*/ QCoreApplication::translate("Main window", "CMYK")
    ) + QString(" %1bpp").arg(bitsPerPixel);
    m_imageInformationColorTypeValue->setText(colorTypeString);
    m_imageInfoGroup->setVisible(true);
    emit imageLoaded();
}
Пример #18
0
bool FormImageProp::loadFile(const QString &fileName)
{
    QFileInfo fileInfo(fileName);
    QImage _image;

    // Targa support added
    if(fileInfo.completeSuffix().compare("tga") == 0){
        TargaImage tgaImage;
        _image = tgaImage.read(fileName);
    }else{
        QImageReader loadedImage(fileName);
        _image = loadedImage.read();
    }

    if (_image.isNull()) {
        QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
                                 tr("Cannot load %1.").arg(QDir::toNativeSeparators(fileName)));
        return false;
    }
    if(bOpenNormalMapMixer){
        qDebug() << "<FormImageProp> Open normal mixer image:" << fileName;

        imageProp.glWidget_ptr->makeCurrent();
        if(glIsTexture(imageProp.normalMixerInputTexId)) imageProp.glWidget_ptr->deleteTexture(imageProp.normalMixerInputTexId);
        imageProp.normalMixerInputTexId = imageProp.glWidget_ptr->bindTexture(_image,GL_TEXTURE_2D);
        ui->labelNormalMixerInfo->setText("Current image:"+ fileInfo.baseName());
        emit imageChanged();

    }else{
        qDebug() << "<FormImageProp> Open image:" << fileName;

        imageName = fileInfo.baseName();
        (*recentDir).setPath(fileName);
        image    = _image;
        imageProp.init(image);

        //emit imageChanged();
        emit imageLoaded(image.width(),image.height());
    }
    return true;
}
Пример #19
0
void WebImageView::setUrl(const QUrl url) {
	if(url != mUrl){
		resetImage();
		mUrl = url;
		QIODevice *temp = diskCache->data(url);
		if(temp){
			setImage(Image(temp->readAll()));
			mLoading = 1;
			emit loadingChanged();
		} else{
			mLoading = 0.01;
			emit loadingChanged();
			if(defaultImageUrl!=QUrl(""))
				setImage(Image(defaultImageUrl));
			urls.push_back(url);
			replies.push_back(mNetManager->get(QNetworkRequest(url)));
			connect(replies.back(),SIGNAL(finished()), this, SLOT(imageLoaded()));
			connect(replies.back(),SIGNAL(downloadProgress ( qint64 , qint64  )), this, SLOT(downloadProgressed(qint64,qint64)));
		}
		emit urlChanged();
	}
}
bool FormMaterialIndicesManager::loadFile(const QString &fileName)
{
    QFileInfo fileInfo(fileName);
    QImage _image;

    // Targa support added
    if(fileInfo.completeSuffix().compare("tga") == 0){
        TargaImage tgaImage;
        _image = tgaImage.read(fileName);
    }else{
        QImageReader loadedImage(fileName);
        _image = loadedImage.read();
    }

    if (_image.isNull()) {
        QMessageBox::information(this, QGuiApplication::applicationDisplayName(),
                                 tr("Cannot load material image %1.").arg(QDir::toNativeSeparators(fileName)));
        return false;
    }

    qDebug() << "<FormImageProp> Open material image:" << fileName;


    (*FormImageProp::recentDir).setPath(fileName);

    int mIndex = FBOImageProporties::currentMaterialIndeks;
    if(updateMaterials(_image)){
          image    = _image;
          imageProp.init(image);
          emit materialChanged();
          FBOImageProporties::currentMaterialIndeks = mIndex;
          emit imageLoaded(image.width(),image.height());
          // repaint all materials
          if(FBOImageProporties::currentMaterialIndeks != MATERIALS_DISABLED){
              toggleMaterials(true);
          }
    }
    return true;
}
Пример #21
0
void WebImageView::imageLoaded() {
	QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());
	if (reply->error() == QNetworkReply::NoError) {
		QVariant repliestatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
		int i=replies.indexOf(reply);
		// HANDLES REDIRECTIONS
		if (repliestatus == 301 || repliestatus == 302)
		{
			QString redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
			replies[i]=mNetManager->get(QNetworkRequest(redirectUrl));
			connect(replies[i],SIGNAL(finished()), this, SLOT(imageLoaded()));
			connect(replies[i],SIGNAL(downloadProgress ( qint64 , qint64  )), this, SLOT(downloadProgressed(qint64,qint64)));
		} else {
			if(urls.at(i)==mUrl)
				setImage(Image(reply->readAll()));
			urls.removeAt(i);
			replies.removeAt(i);
		}
	}
	mLoading = 1;
	emit loadingChanged();
	reply->deleteLater();
}
Пример #22
0
void MainWindow::on_imageBrowse_clicked()
{
    QString image=QFileDialog::getOpenFileName(this,"Item image",QFileInfo(ui->lineEditItemFile->text()).absolutePath(),tr("Images (*.png)"));
    if(image.isEmpty())
        return;
    image=QFileInfo(image).absoluteFilePath();
    QPixmap imageLoaded(image);
    if(imageLoaded.isNull())
    {
        QMessageBox::warning(this,tr("Error"),tr("The image can't be loaded, wrong format?"));
        return;
    }
    imageLoaded.scaled(96,96);
    image.remove(QFileInfo(ui->lineEditItemFile->text()).absolutePath());
    image.replace("\\","/");
    image.remove(QRegularExpression("^/"));
    ui->image->setPixmap(imageLoaded);
    QList<QListWidgetItem *> itemsUI=ui->itemList->selectedItems();
    if(itemsUI.size()!=1)
        return;
    quint32 selectedItem=itemsUI.first()->data(99).toUInt();
    items[selectedItem].setAttribute("image",image);
}
Пример #23
0
void DkImageContainerT::fetchImage() {

	if (mFetchingBuffer)
		mBufferWatcher.waitForFinished();

	if (mFetchingImage) {
		mLoadState = loading;
		return;
	}

	if (getLoader()->hasImage() || /*!fileBuffer || fileBuffer->isEmpty() ||*/ mLoadState == exists_not) {
		loadingFinished();
		return;
	}
	
	qDebug() << "fetching: " << filePath();
	mFetchingImage = true;

	connect(&mImageWatcher, SIGNAL(finished()), this, SLOT(imageLoaded()), Qt::UniqueConnection);

	mImageWatcher.setFuture(QtConcurrent::run(this, 
		&nmc::DkImageContainerT::loadImageIntern, filePath(), mLoader, mFileBuffer));
}
void MainWindow::loadImage()
{
    QString file_name = QFileDialog::getOpenFileName(this, tr("Open File"), QDir::currentPath(), "Images(*.png *.jpg *.bmp)");

    if ( ! file_name.isEmpty())
    {
        sourceImage = QImage(file_name);
        if (sourceImage.isNull())
        {
            QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(file_name));
            return;
        }
        if (sourceImage.width() > 800)
        {
            QPixmap mp = QPixmap::fromImage(sourceImage);
            mp = mp.scaledToWidth(800, Qt::SmoothTransformation);
            sourceImage = mp.toImage();
        }

        displayImage(sourceImage);
        emit imageLoaded(sourceImage);
    }
}
Пример #25
0
// DkImageContainerT --------------------------------------------------------------------
DkImageContainerT::DkImageContainerT(const QFileInfo& file) : DkImageContainer(file) {

	thumb = QSharedPointer<DkThumbNailT>(new DkThumbNailT(file));
#ifdef WITH_QUAZIP	
	if(isFromZip()) thumb = QSharedPointer<DkThumbNailT>(new DkThumbNailT(zipData->getEncodedFileInfo()));
#endif	
	
	fetchingImage = false;
	fetchingBuffer = false;
	
	// our file watcher
	fileUpdateTimer.setSingleShot(false);
	fileUpdateTimer.setInterval(500);
	waitForUpdate = false;

	connect(&fileUpdateTimer, SIGNAL(timeout()), this, SLOT(checkForFileUpdates()));
	connect(&saveImageWatcher, SIGNAL(finished()), this, SLOT(savingFinished()));
	connect(&bufferWatcher, SIGNAL(finished()), this, SLOT(bufferLoaded()));
	connect(&imageWatcher, SIGNAL(finished()), this, SLOT(imageLoaded()));
	connect(loader.data(), SIGNAL(errorDialogSignal(const QString&)), this, SIGNAL(errorDialogSignal(const QString&)));
	connect(thumb.data(), SIGNAL(thumbLoadedSignal(bool)), this, SIGNAL(thumbLoadedSignal(bool)));
	//connect(&metaDataWatcher, SIGNAL(finished()), this, SLOT(metaDataLoaded()));
}
Пример #26
0
void BrowseWidget::parseBrowserData(const QString &t_id,
                                    QNetworkReply *t_reply) {
  if (t_id != m_request_id) return;

  auto title_language = User::sharedUser()->titleLanguage();
  QByteArray data = t_reply->readAll();
  QJsonArray browse_results = QJsonDocument::fromJson(data).array();

  for (int i = 0; i <= browse_results.size(); i++) {
    QJsonObject anime = browse_results.at(i).toObject();
    auto title = anime.value(title_language).toString();

    if (title.isEmpty()) {
      qDebug() << "Unknown title for: " << QJsonDocument(anime).toJson();
      continue;
    }

    AnimePtr a = User::sharedUser()->getAnimeByTitle(title);

    if (a == AnimePtr(nullptr)) {
      a = Anime::makeAnime();
      a->setId(QString::number(anime.value("id").toInt()));
      a->setTitle(title);
      a->setImageUrl(anime.value("image_url_lge").toString());
      a->setTitleRomaji(anime.value("title_romaji").toString());
      a->setTitleJapanese(anime.value("title_japanese").toString());
      a->setTitleEnglish(anime.value("title_english").toString());
      a->setType(anime.value("type").toString());
      a->setAiringStatus(anime.value("airing_status").toString());
      a->setAverageScore(anime.value("average_score").toString().toDouble());
      a->setTotalEpisodes(anime.value("total_episodes").toInt());
      a->setAdult(anime.value("adult").toBool());

      if (a->id() == "0") {
        continue;
      }

      User::sharedUser()->addKnownAnime(a);
    }

    if (a->adult() && !User::sharedUser()->adultContent()) {
      continue;
    }

    BrowseAnime *s = new BrowseAnime(this, User::sharedUser()->scoreType());

    if (!a->hasLoaded()) {
      connect(a.get(), SIGNAL(imageLoaded()), s, SLOT(repaint()));
      emit loadAnime(a);
    }

    s->setAnime(a);

    m_browse_layout->addWidget(s);
    m_browse_layout->setGeometry(m_ui->result_area->geometry());

    int width = m_browse_layout->geometry().width();
    int cwidth = m_browse_layout->contentsWidth();

    if (m_browse_layout->heightForWidth(width) > this->geometry().height()) {
      width -= qApp->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
    }

    m_browse_layout->setContentsMargins((width - cwidth) / 2, 0, 0, 0);
  }

  m_ui->browse_button->setEnabled(true);
}
Пример #27
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);
}
Пример #28
0
void FormImageProp::pasteImageFromClipboard(QImage& _image){
    imageName = "clipboard_image";
    image     = _image;
    imageProp.init(image);
    emit imageLoaded(image.width(),image.height());
}
Пример #29
0
void PictureLoader::processLoadQueue()
{
    if (loadQueueRunning)
        return;

    loadQueueRunning = true;
    forever {
        mutex.lock();
        if (loadQueue.isEmpty()) {
            mutex.unlock();
            loadQueueRunning = false;
            return;
        }
        cardBeingLoaded = loadQueue.takeFirst();
        mutex.unlock();

        QString setName = cardBeingLoaded.getSetName();
        QString correctedCardname = cardBeingLoaded.getCard()->getCorrectedName();
        qDebug() << "Trying to load picture (set: " << setName << " card: " << correctedCardname << ")";

        //The list of paths to the folders in which to search for images
        QList<QString> picsPaths = QList<QString>() << _picsPath + "/CUSTOM/" + correctedCardname;

        if(!setName.isEmpty())
        {
            picsPaths   << _picsPath + "/" + setName + "/" + correctedCardname
                        << _picsPath + "/downloadedPics/" + setName + "/" + correctedCardname;
        }

        QImage image;
        QImageReader imgReader;
        imgReader.setDecideFormatFromContent(true);
        bool found = false;

        //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
        for (int i = 0; i < picsPaths.length() && !found; i ++) {
            imgReader.setFileName(picsPaths.at(i));
            if (imgReader.read(&image)) {
                qDebug() << "Picture found on disk (set: " << setName << " card: " << correctedCardname << ")";
                emit imageLoaded(cardBeingLoaded.getCard(), image);
                found = true;
                break;
            }
            imgReader.setFileName(picsPaths.at(i) + ".full");
            if (imgReader.read(&image)) {
                qDebug() << "Picture.full found on disk (set: " << setName << " card: " << correctedCardname << ")";
                emit imageLoaded(cardBeingLoaded.getCard(), image);
                found = true;
            }
        }

        if (!found) {
            if (picDownload) {
                qDebug() << "Picture NOT found, trying to download (set: " << setName << " card: " << correctedCardname << ")";
                cardsToDownload.append(cardBeingLoaded);
                cardBeingLoaded=0;
                if (!downloadRunning)
                    startNextPicDownload();
            } else {
                if (cardBeingLoaded.nextSet())
                {
                    qDebug() << "Picture NOT found and download disabled, moving to next set (newset: " << setName << " card: " << correctedCardname << ")";
                    mutex.lock();
                    loadQueue.prepend(cardBeingLoaded);
                    cardBeingLoaded=0;
                    mutex.unlock();
                } else {
                    qDebug() << "Picture NOT found, download disabled, no more sets to try: BAILING OUT (oldset: " << setName << " card: " << correctedCardname << ")";
                    emit imageLoaded(cardBeingLoaded.getCard(), QImage());
                }
            }
        }
    }
}
Пример #30
0
void ImageLoader::run()
{
    QString fn = m_url.toLocalFile();
    int pos = fn.lastIndexOf('.');
    QString ext;
    if (pos != -1)
        ext = fn.mid(pos).toUpper();
    if (ext.isEmpty() ||
            !QImageReader::supportedImageFormats().contains(ext.toLocal8Bit()))
        ext = QString();
    QFile f(fn);
    if (!f.open(QIODevice::ReadOnly))
    {
        qWarning("Could not read: %s", qPrintable(m_url.path()));
        return;
    }
    QByteArray bytes;
    while (!f.atEnd())
    {
        QThread::yieldCurrentThread();
        bytes.append(f.read(1024));
    }
    QThread::yieldCurrentThread();
    QImage im = ext.isEmpty() ? QImage::fromData(bytes)
                : QImage::fromData(bytes, qPrintable(ext));
    if (im.isNull())
        return;
    QString p = m_url.path();
    p = p.section("/", -1);
    int max = qMax(im.width(), im.height());
    QImage frm;
    if (max <= 64)
        frm = QImage(QSize(64, 64), QImage::Format_ARGB32);
    else if (max <= 128)
        frm = QImage(QSize(128, 128), QImage::Format_ARGB32);
    else if (max <= 256)
        frm = QImage(QSize(256, 256), QImage::Format_ARGB32);
    else if (max <= 512)
        frm = QImage(QSize(512, 512), QImage::Format_ARGB32);
    else
        frm = QImage(QSize(1024, 1024), QImage::Format_ARGB32);
    frm.fill(qRgba(0, 0, 0, 0));
    QPainter ptr;
    ptr.begin(&frm);
    ptr.setBackgroundMode(Qt::TransparentMode);
    QRect r;
    if (max > 1024)
    {
        if (max == im.width())
        {
            float h = float(1024) * float(im.height()) / float(im.width());
            r.setSize(QSize(1024, h));
        }
        else
        {
            float w = float(1024) * float(im.width()) / float(im.height());
            r.setSize(QSize(w, 1024));
        }
    }
    else
    {
        r.setSize(im.size());
    }
    int left = (frm.width() - r.width()) / 2;
    int top = (frm.height() - r.height()) / 2;
    r.moveTopLeft(QPoint(left, top));
    QThread::yieldCurrentThread();
    ptr.drawImage(r, im);
    ptr.end();
    emit imageLoaded(frm);
}