예제 #1
0
파일: main.cpp 프로젝트: UpWind/devel
int main(int argc, char *argv[]) {

    const int splashTime = 1000;

    QApplication app(argc, argv);
    ControllerWindow w;

    QDir imageDir(qApp->applicationDirPath());
    imageDir.cd("plugins");

    QPixmap pixmap(imageDir.absoluteFilePath("logoupwind.png"));
    QSplashScreen *splash = new QSplashScreen(pixmap);

    splash->setAttribute(Qt::WA_DeleteOnClose);

    fadePlugin(splash, splashTime, false);
    splash->show();

    QTimer::singleShot(splashTime, &w, SLOT(show()));
    QTimer::singleShot(splashTime, splash, SLOT(close()));

    //w.show();

    return app.exec();

}
예제 #2
0
//! SLOTS
//!
//!
void ImageView::openDir()
{
  folderName = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "./", QFileDialog::ShowDirsOnly);

  if (folderName == "") {
      return;
    }

  QDir imageDir(folderName);
  QStringList imageFilters;
  imageFilters << "*.bmp" << "*.png" << "*.jpg" << "*.jpeg" << "*.gif";

  imageDir.setNameFilters(imageFilters);
  imageDir.setFilter(QDir::Files);
  imageDir.setSorting(QDir::Name);

  fileList.clear();
  fileList = imageDir.entryInfoList();

  imageNumber = 0;
  totalImages = fileList.size();

  updateGUI();
  if(!ui->actionSave->isEnabled())
    ui->actionSave->setEnabled(true);
}
예제 #3
0
void KImGalleryPlugin::deleteCancelledGallery(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat)
{
    if (m_recurseSubDirectories && (recursionLevel >= 0)) {
        QStringList subDirList;
        QDir toplevel_dir = QDir( sourceDirName );
        toplevel_dir.setFilter( QDir::Dirs );
        subDirList = toplevel_dir.entryList();

        for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end(); it++) {
            if (*it == "." || *it == ".." || *it == "thumbs" || (m_copyFiles && *it == "images")) {
                continue; //disregard the "." and ".." directories
            }
            deleteCancelledGallery( KURL( url.directory() + "/" + *it + "/" + url.fileName() ),
                                    sourceDirName + "/" + *it,
                                    recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat);
        }
    }

    const QString imgGalleryDir = url.directory();
    QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/"));
    QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/"));
    QDir imageDir( sourceDirName, "*.png *.PNG *.gif *.GIF *.jpg *.JPG *.jpeg *.JPEG *.bmp *.BMP",
                   QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable);
    QFile file( url.path() );

    // Remove the image file ..
    file.remove();
    // ..all the thumbnails ..
    for (uint i=0; i < imageDir.count(); i++) {
        const QString imgName = imageDir[i];
        const QString imgNameFormat = imgName + extension(imageFormat);
        bool isRemoved = thumb_dir.remove(imgNameFormat);
        kdDebug(90170) << "removing: " << thumb_dir.path() << "/" << imgNameFormat << "; "<< isRemoved << endl;
    }
    // ..and the thumb directory
    thumb_dir.rmdir(thumb_dir.path());

    // ..and the images directory if images were to be copied
    if (m_copyFiles) {
        for (uint i=0; i < imageDir.count(); i++) {
            const QString imgName = imageDir[i];
            bool isRemoved = images_dir.remove(imgName);
            kdDebug(90170) << "removing: " << images_dir.path() << "/" << imgName << "; "<< isRemoved << endl;
        }
        images_dir.rmdir(images_dir.path());
    }
}
ImageProvider::ImageProvider (ros::NodeHandle& nodeHandle, const ImageProviderConfiguration::ConstPtr& configuration)
        : nodeHandle(nodeHandle), imgTransport(nodeHandle), configuration(configuration), numberOfImages(0), imagePos(configuration->startPos) {
    // setup the file pattern to be used for all files
    boost::regex re(configuration->filePattern);
    // iterate the configurations and retrieve matching files
    runtimeData.reserve(configuration->cameraConfigs.size());
    if (configuration->cameraConfigs.size() > 0) {
        for (CameraConfigEntry::ConstPtrList::const_iterator it = configuration->cameraConfigs.begin(); it != configuration->cameraConfigs.end(); ++it) {
            bfs::path imageDir ((*it)->directoryName);
            if (!imageDir.is_absolute()) { imageDir = bfs::path(configuration->sourceDir) / imageDir; }
            if (!bfs::exists(imageDir)) {
                throw ImageProviderException(std::string("Image directory '") + imageDir.string() + std::string("' does not exist"));
            }
            if (!bfs::is_directory(imageDir)) {
                throw ImageProviderException(std::string("Image directory '") + imageDir.string() + std::string("' is not a directory"));
            }
            FileListPtr fileList = boost::make_shared<FileListPtr::element_type>();
            for (bfs::directory_iterator dirIterator (imageDir); dirIterator != bfs::directory_iterator(); ++dirIterator) {
                bfs::path fileName = dirIterator->path().filename();
                if (boost::regex_match(fileName.string(), re)) {
                    fileList->push_back(fileName);
                }
            }
            std::sort(fileList->begin(), fileList->end());
            ImageProviderRuntimeData rtData;
            rtData.cameraConfiguration = *it;
            rtData.directory = imageDir;
            rtData.fileList = fileList;
            runtimeData.push_back(rtData);
        }
        // validate the file lists
        FlagErrorReturnValue retVal = validateFileLists(runtimeData);
        if (boost::get<0>(retVal)) {
            for (ImageProviderRuntimeData::List::iterator it = runtimeData.begin(); it != runtimeData.end(); ++it) {
                it->pubImage = boost::make_shared<image_transport::Publisher>();
                *it->pubImage = imgTransport.advertise(configuration->topicPrefix + "/" + it->cameraConfiguration->cameraName, it->cameraConfiguration->bufferSize);
            }
            numberOfImages = runtimeData[0].fileList->size();
        }
        else {
            throw ImageProviderException("Validation of file lists: " + boost::get<1>(retVal));
        }
    }
    else {
        throw ImageProviderException("No camera configuration available");
    }
}
예제 #5
0
void KNMusicLibraryImageManager::recoverFromFolder()
{
    //Check is the path exist or it's a file.
    QFileInfo pathChecker(m_imageFolderPath);
    QDir imageDir(m_imageFolderPath);
    //Check it's existance and it's file or not.
    if(pathChecker.exists() && pathChecker.isFile())
    {
        //Delete the file.
        QFile fileRemover(pathChecker.absoluteFilePath());
        fileRemover.remove();
    }
    //Check if it's not exist, simply generate the folder.
    if(!pathChecker.exists())
    {
        //Generate the folder.
        imageDir.mkpath(imageDir.absolutePath());
        //Do nothing, return.
        return;
    }
    //Load the image in the dir.
    QFileInfoList contentInfos=imageDir.entryInfoList();
    //Check each file.
    for(QFileInfoList::iterator i=contentInfos.begin();
        i!=contentInfos.end();
        ++i)
    {
        //Load all the png image to hash list.
        if((*i).isFile() && (*i).suffix().toLower()=="png")
        {
            //Load the image.
            QImage currentImage=QImage((*i).absoluteFilePath(), "png");
            //If there's image data, insert to pixmap list.
            if(!currentImage.isNull())
            {
                m_pixmapList->setImage((*i).completeBaseName(), currentImage);
            }
        }
    }
    //Emit recover complete signal.
    emit recoverComplete();
}
예제 #6
0
int mythplugin_run (void)
{
    MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();

    try
    {
        QDir imageDir(GetConfDir() + "/mythsvtplay/images/");
        imageDir.mkpath(imageDir.path());

        MainWindow* mainWindow = new MainWindow(mainStack);
        mainStack->AddScreen(mainWindow);

        mainWindow->beginProgramDownload();
    }
    catch (...)
    {
        return -1;
    }

    return 0;
}
예제 #7
0
void MythUIImage::FindRandomImage(void)
{
    QDir imageDir(m_imageDirectory);

    if (!imageDir.exists())
    {
        QString themeDir = GetMythUI()->GetThemeDir() + '/';
        imageDir = themeDir + m_imageDirectory;
    }

    QStringList imageTypes;

    QList< QByteArray > exts = QImageReader::supportedImageFormats();
    QList< QByteArray >::Iterator it = exts.begin();

    for (; it != exts.end(); ++it)
    {
        imageTypes.append(QString("*.").append(*it));
    }

    imageDir.setNameFilters(imageTypes);

    QStringList imageList = imageDir.entryList();
    QString randFile;

    if (imageList.size())
    {
        // try to find a different image
        do
        {
            randFile = QString("%1%2").arg(m_imageDirectory)
                                      .arg(imageList.takeAt(random() % imageList.size()));

        } while (imageList.size() > 1 && randFile == m_OrigFilename);
    }

    m_OrigFilename = m_imageProperties.filename = randFile;
}
void BrowserUtils::generateIconFromFile(const QString inFile, const QString outFile, const QSize imageSize)
{
	QImage inImage(inFile);
	if (inImage.isNull()) {
		qWarning() << "generateIconFromFile - failed to open source file";
		Q_EMIT iconGenerated(false, outFile);
		return;
	}
	const int nMargin = 4;// Must agree with pixel data in image files
	const int nIconSize = 64;// Width & height of output image
	const int nIconWidth = nIconSize-2*nMargin;// Width of icon image within file
	const int nIconHeight = nIconSize-2*nMargin;
	QImage outImage(nIconSize, nIconSize, QImage::Format_ARGB32_Premultiplied);
	outImage.fill(0);
	QPainter painter(&outImage);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	QRectF source(0.0, 0.0, imageSize.width(), imageSize.height());
	QRectF target(nMargin, nMargin, nIconWidth, nIconHeight);
	QRectF size(0.0, 0.0, nIconSize, nIconSize);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	painter.drawImage(target, inImage, source);
	painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
	QImage maskImage(kIconMaskFile);
	painter.drawImage(target, maskImage, target);
	painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
	QImage overlayImage(kIconOverlayFile);
	painter.drawImage(size, overlayImage, size);

	QFileInfo imageInfo(outFile);
	QDir imageDir(imageInfo.path());
	if (!imageDir.exists()) {
		imageDir.mkpath(".");
	}

	bool saved = outImage.save(outFile);
	Q_EMIT iconGenerated(saved, outFile);
}
예제 #9
0
void ClientThread::getSignalFromClient()
{
    if (client.bytesAvailable() < 1)
        return;
    QByteArray data = client.read(5);
    qint64 size;
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    char *d = data.data();
    if (d[0] == 'f' || d[0] == 'd'){  //client is asking for all the entry names in image folder
        isCanceled = false;
        QDir imageDir(filePath);
        fileNames = imageDir.entryList(fileFilters, QDir::Files);
        folderNames = imageDir.entryList(folderFilters, QDir::Dirs);
        folderNames.removeAt(folderNames.indexOf("."));
        folderNames.removeAt(folderNames.indexOf(".."));
        for (int i = 0; i < folderNames.length(); i ++){
            block.clear();
            out.device()->seek(0);
            out << qint16(0x0000) << folderNames.at(i).toUtf8();
            size = block.size();
            client.write((char*)&size, sizeof(qint64));
            client.write(block.data(), size);
            if(!client.waitForBytesWritten(-1)){
                emit error(3);
                return;
            }
        }
        for (int i = 0; i < fileNames.length(); i ++){
            block.clear();
            out.device()->seek(0);
            out << qint16(0x0000) << fileNames.at(i).toUtf8();
            size = block.size();
            client.write((char*)&size, sizeof(qint64));
            client.write(block.data(), size);
            if(!client.waitForBytesWritten(-1)){
                emit error(3);
                return;
            }
        }
        //send file name
        block.clear();
        out.device()->seek(0);
        if (d[0] == 'f')
            out << qint16(0x000A);
        else if (d[0] == 'd')
            out << qint16(0x000B);
        size = block.size();
        client.write((char*)&size, sizeof(qint64));
        client.write(block.data(), size);
        if(!client.waitForBytesWritten(-1)){
            emit error(3);
            return;
        }
    }
    else if (d[0] == 't' || d[0] == 'r'){  //client has selected an entry in image folder and asks server to transmit that entry
        numberOfBytesToBeTransmit = 0;
        numberOfFilesSent = 0;
        indexOfEntry = d[1] + (d[2] << 8) + (d[3] << 16) + (d[4] << 24);

        if (d[0] == 't'){
            if (indexOfEntry < folderNames.length()){ //entry selected is a folder
                imageFolderPath = folderNames.at(indexOfEntry);
                imageFolderPath.prepend(filePath);
                imageFolderPath.append("/");
                QDir dir(imageFolderPath);
                QStringList nameFilters;
                nameFilters << "*.tif" << "*.ppf";
                QStringList filesInFolder = dir.entryList(nameFilters, QDir::Files);
                //send file quantity
                block.clear();
                out.device()->seek(0);
                QString fileQuantity;
                fileQuantity.setNum(filesInFolder.length());
                out << qint16(0x0001) << fileQuantity.toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);
                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }
                numberOfFilesToBeTransmit = filesInFolder.length();
                isFileSelected = false;
                isFolderSelected = true;
                for (int i = 0; i < filesInFolder.length(); i ++){
                    QString fp = filesInFolder.at(i);
                    fp.prepend(imageFolderPath);
                    QFile f(fp);
                    numberOfBytesToBeTransmit += f.size();
                }
                emit progressRange(numberOfBytesToBeTransmit);
            }
            else if (indexOfEntry < (folderNames.length() + fileNames.length())){       //entry selected is a single file
                imageFilePath = fileNames.at(indexOfEntry - folderNames.length());
                imageFilePath.prepend(filePath);

                //send file quantity
                block.clear();
                out.device()->seek(0);
                QString fileQuantity;
                fileQuantity.setNum(1);
                out << qint16(0x0001) << fileQuantity.toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);
                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }
                numberOfFilesToBeTransmit = 1;
                isFileSelected = true;
                isFolderSelected = false;

                QString fp = imageFilePath;
                QFile f(fp);
                numberOfBytesToBeTransmit = f.size();
                emit progressRange(numberOfBytesToBeTransmit);
            }
        }
        else if (d[0] == 'r'){
            if (indexOfEntry < folderNames.length() && (indexOfEntry >= 0)){
                QString pathOfTheFolderToDelete = filePath + folderNames.at(indexOfEntry);
                pathOfTheFolderToDelete = pathOfTheFolderToDelete.replace('/', '\\');
                char str[100];
                QByteArray tempString1 = pathOfTheFolderToDelete.toAscii();
                const char *tempString2 = tempString1.data();
                sprintf(str, "rd/s/q %s", tempString2);
                system(str);
            }
            else if (indexOfEntry < (folderNames.length() + fileNames.length()) && (indexOfEntry >= 0)){
                QString pathOfTheFileToDelete = filePath + fileNames.at(indexOfEntry - folderNames.length());
                QFile fileToDelete(pathOfTheFileToDelete);
                fileToDelete.remove();
            }
            else{   //DELETE ALL FILES!!!
                qDebug() << "DELETING ALL FILES!!!" << d[1] << d[2] << d[3] << d[4];
                for (int i = 0; i < (folderNames.length() + fileNames.length()); i ++){
                    if (i < folderNames.length()){          //delete all the folders
                        QString pathOfTheFolderToDelete = filePath + folderNames.at(i);
                        pathOfTheFolderToDelete = pathOfTheFolderToDelete.replace('/', '\\');
                        char str[100];
                        QByteArray tempString1 = pathOfTheFolderToDelete.toAscii();
                        const char *tempString2 = tempString1.data();
                        sprintf(str, "rd/s/q %s", tempString2);
                        system(str);
                    }
                    else{                                   //delete all the files
                        QString pathOfTheFileToDelete = filePath + fileNames.at(i - folderNames.length());
                        QFile fileToDelete(pathOfTheFileToDelete);
                        fileToDelete.remove();
                    }
                }
            }
        }
    }
    else if (d[0] == 'e'){  //errors,could be more than 6 color files or file size too big
        emit bytesSent(0);
        emit progressRange(10000);
        return;
    }
    else if (d[0] == 'n'){  //send file name and size
        if (isFolderSelected){  //sending folder
            QDir dir(imageFolderPath);
            QStringList nameFilters;
            nameFilters << "*.tif" << "*.ppf";
            QStringList filesInFolder = dir.entryList(nameFilters, QDir::Files);
            if (numberOfFilesSent < numberOfFilesToBeTransmit){
                QString fileName, fileSize;

                //send file name
                block.clear();
                out.device()->seek(0);
                out << qint16(0x0002) << filesInFolder.at(numberOfFilesSent).toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);

                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }

                //send file size
                block.clear();
                out.device()->seek(0);
                fileName = imageFolderPath;
                fileName.append(filesInFolder.at(numberOfFilesSent));
                QFile imageFile(fileName);
                fileSize = fileSize.setNum(imageFile.size());
                out << qint16(0x0003) << fileSize.toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);

                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }
            }
        }
        else{       //sending single file
            if (numberOfFilesSent < numberOfFilesToBeTransmit){
                QString fileName, fileSize;
                QFile imageFile(imageFilePath);
                fileName = imageFilePath.right(imageFilePath.length() - imageFilePath.lastIndexOf("/") - 1);
                //send file name
                block.clear();
                out.device()->seek(0);
                out << qint16(0x0002) << fileName.toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);

                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }

                //send file size
                block.clear();
                out.device()->seek(0);
                fileSize = fileSize.setNum(imageFile.size());
                out << qint16(0x0003) << fileSize.toUtf8();
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);

                if(!client.waitForBytesWritten(-1)){
                    emit error(3);
                    return;
                }
            }
        }
    }
    else if (d[0] == 'g'){
        if (isFolderSelected){  //sending folder
            QDir dir(imageFolderPath);
            QStringList nameFilters;
            nameFilters << "*.tif" << "*.ppf";
            QStringList filesInFolder = dir.entryList(nameFilters, QDir::Files);
            if (numberOfFilesSent < numberOfFilesToBeTransmit){
                QString fileName = imageFolderPath;
                fileName.append(filesInFolder.at(numberOfFilesSent));
                QFile imageFile(fileName);

                imageFile.open(QIODevice::ReadWrite);
                //send file content
                do{
                    qApp->processEvents();
                    if (!isCanceled){
                        block.clear();
                        out.device()->seek(0);
                        out << qint16(0x0004) << imageFile.read(0xFFF0);
                        size = block.size();

                        client.write((char*)&size, sizeof(qint64));
                        client.write(block.data(), size);
                        if(!client.waitForBytesWritten(-1)){
                            emit error(3);
                        }
                    }
                    else{
                        block.clear();
                        out.device()->seek(0);
                        out << qint16(0x0006);
                        size = block.size();

                        client.write((char*)&size, sizeof(qint64));
                        client.write(block.data(), size);
                        if(!client.waitForBytesWritten(-1)){
                            emit error(3);
                        }
                        emit status(6);
                        return;
                    }
                } while(!imageFile.atEnd() && (!isCanceled));
                //send file EOF
                block.clear();
                out.device()->seek(0);
                out << qint16(0x0005);
                size = block.size();
                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);
                if(!client.waitForBytesWritten(-1))
                    emit error(3);
                emit status(3);
                imageFile.close();

                numberOfFilesSent ++;
            }
        }
        else{
            if (numberOfFilesSent < numberOfFilesToBeTransmit){
                QString fileName;
                QFile imageFile(imageFilePath);
                fileName = imageFilePath.right(imageFilePath.length() - imageFilePath.lastIndexOf("/") - 1);

                imageFile.open(QIODevice::ReadWrite);
                //send file content
                do{
                    if (!isCanceled){
                        block.clear();
                        out.device()->seek(0);
                        out << qint16(0x0004) << imageFile.read(0xFFF0);
                        size = block.size();

                        client.write((char*)&size, sizeof(qint64));
                        client.write(block.data(), size);
                        if(!client.waitForBytesWritten(-1)){
                            emit error(3);
                        }
                    }
                    else{
                        block.clear();
                        out.device()->seek(0);
                        out << qint16(0x0006);
                        size = block.size();

                        client.write((char*)&size, sizeof(qint64));
                        client.write(block.data(), size);
                        if(!client.waitForBytesWritten(-1))
                            emit error(3);
                        emit status(6);
                        return;
                    }
                } while(!imageFile.atEnd() && (!isCanceled));
                //send file EOF
                block.clear();
                out.device()->seek(0);
                out << qint16(0x0005);
                size = block.size();

                client.write((char*)&size, sizeof(qint64));
                client.write(block.data(), size);
                if(!client.waitForBytesWritten(-1))
                    emit error(3);
                emit status(3);
                imageFile.close();
                numberOfFilesSent ++;
            }
        }
    }
}
예제 #10
0
bool KImGalleryPlugin::createHtml(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat)
{
    if(m_cancelled) return false;


    if( !parent() || !parent()->inherits("KonqDirPart"))
        return false;
    KonqDirPart * part = static_cast<KonqDirPart *>(parent());

    QStringList subDirList;
    if (m_recurseSubDirectories && (recursionLevel >= 0)) { //recursionLevel == 0 means endless
        QDir toplevel_dir = QDir( sourceDirName );
        toplevel_dir.setFilter( QDir::Dirs | QDir::Readable | QDir::Writable );
        subDirList = toplevel_dir.entryList();

        for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end() && !m_cancelled; it++) {
            const QString currentDir = *it;
            if (currentDir == "." || currentDir == "..") { continue;} //disregard the "." and ".." directories
            QDir subDir = QDir( url.directory() + "/" + currentDir );
            if (!subDir.exists()) {
                subDir.setPath( url.directory() );
                if (!(subDir.mkdir(currentDir, false))) {
                    KMessageBox::sorry(part->widget(), i18n("Couldn't create folder: %1").arg(subDir.path()));
                    continue;
                } else {
                    subDir.setPath( url.directory() + "/" + currentDir );
                }
            }
            if(!createHtml( KURL( subDir.path() + "/" + url.fileName() ), sourceDirName + "/" + currentDir,
                            recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat)) { return false; }
        }
    }

    if (m_useCommentFile) {
        loadCommentFile();
    }

    kdDebug(90170) << "sourceDirName: " << sourceDirName << endl;
    //We're interested in only the patterns, so look for the first |
    //#### perhaps an accessor should be added to KImageIO instead?
    QString filter = KImageIO::pattern(KImageIO::Reading).section('|', 0, 0);

    QDir imageDir( sourceDirName, filter.latin1(),
                   QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable);

    const QString imgGalleryDir = url.directory();
    kdDebug(90170) << "imgGalleryDir: " << imgGalleryDir << endl;

    // Create the "thumbs" subdirectory if necessary
    QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/"));
    if (createDirectory(thumb_dir, imgGalleryDir, "thumbs") == false)
        return false;

    // Create the "images" subdirectory if necessary
    QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/"));
    if (m_copyFiles) {
        if (createDirectory(images_dir, imgGalleryDir, "images") == false)
            return false;
    }

    QFile file( url.path() );
    kdDebug(90170) << "url.path(): " << url.path() << ", thumb_dir: "<< thumb_dir.path()
              << ", imageDir: "<< imageDir.path() << endl;

    if ( imageDir.exists() && file.open(IO_WriteOnly) ) {
        QTextStream stream(&file);
        stream.setEncoding(QTextStream::Locale);

        createHead(stream);
        createBody(stream, sourceDirName, subDirList, imageDir, url, imageFormat); //ugly

        file.close();

        return !m_cancelled;

    } else {
        KMessageBox::sorry(m_part->widget(),i18n("Couldn't open file: %1").arg(url.path(+1)));
        return false;
    }
}
예제 #11
0
void DocumentTest::testImageLocalDirectory() {
  Tellico::Config::setImageLocation(Tellico::Config::ImagesInLocalDir);
  // the default collection will use a temporary directory as a local image dir
  QVERIFY(!Tellico::ImageFactory::localDir().isEmpty());

  QString tempDirName;

  QTemporaryDir tempDir;
  QVERIFY(tempDir.isValid());
  tempDir.setAutoRemove(true);
  tempDirName = tempDir.path();
  QString fileName = tempDirName + "/with-image.tc";
  QString imageDirName = tempDirName + "/with-image_files/";

  // copy a collection file that includes an image into the temporary directory
  QVERIFY(QFile::copy(QFINDTESTDATA("data/with-image.tc"), fileName));

  Tellico::Data::Document* doc = Tellico::Data::Document::self();
  QVERIFY(doc->openDocument(QUrl::fromLocalFile(fileName)));
  QCOMPARE(Tellico::ImageFactory::localDir(), imageDirName);

  Tellico::Data::CollPtr coll = doc->collection();
  QVERIFY(coll);
  QCOMPARE(coll->type(), Tellico::Data::Collection::Book);
  QCOMPARE(coll->title(), QLatin1String("My Books"));
  QCOMPARE(coll->entries().size(), 1);

  Tellico::Data::EntryPtr e = coll->entries().at(0);
  QVERIFY(e);
  QCOMPARE(e->field(QLatin1String("cover")), QLatin1String("17b54b2a742c6d342a75f122d615a793.jpeg"));

  // save the document, so the images get copied out of the .tc file into the local image directory
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName)));
  // verify that backup file gets created
  QVERIFY(QFile::exists(fileName + '~'));

  // check that the local image directory is created with the image file inside
  QDir imageDir(imageDirName);
  QVERIFY(imageDir.exists());
  QVERIFY(imageDir.exists(e->field(QLatin1String("cover"))));

  // clear the internal image cache
  Tellico::ImageFactory::clean(true);

  // verify that the images are copied from the old directory when saving to a new file
  QString fileName2 = tempDirName + "/with-image2.tc";
  QString imageDirName2 = tempDirName + "/with-image2_files/";
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName2)));
  QVERIFY(QFile::exists(fileName2));
  QDir imageDir2(imageDirName2);
  QVERIFY(imageDir2.exists());
  QVERIFY(imageDir2.exists(e->field(QLatin1String("cover"))));

  /*************************************************************************/
  /* now also verify image directory when file name has multiple periods */
  /* see https://bugs.kde.org/show_bug.cgi?id=348088 */
  /* also have to check backwards compatibility with prior behavior */
  /*************************************************************************/

  QString fileName3 = tempDirName + "/with-image.1.tc";
  QString imageDirName3 = tempDirName + "/with-image.1_files/";

  // copy the collection file, which no longer contains the images inside
  QVERIFY(QFile::copy(fileName, fileName3));
  QVERIFY(doc->openDocument(QUrl::fromLocalFile(fileName3)));
  QCOMPARE(Tellico::ImageFactory::localDir(), imageDirName3);
  QDir imageDir3(imageDirName3);

  // verify that the images can be loaded from the image directory that does NOT have multiple periods
  // since that was the behavior prior to the bug being fixed
  coll = doc->collection();
  e = coll->entries().at(0);
  // image should not be in the next image dir yet since we haven't saved
  QVERIFY(!imageDir3.exists(e->field(QLatin1String("cover"))));
  QVERIFY(!Tellico::ImageFactory::imageById(e->field("cover")).isNull());

  // now remove the first image from the first image directory, save the document, and verify that
  // the proper image exists and is written
  QVERIFY(imageDir.remove(e->field("cover")));
  QVERIFY(!imageDir.exists(e->field(QLatin1String("cover"))));
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName3)));
  // now the file should exist in the proper location
  QVERIFY(imageDir3.exists(e->field(QLatin1String("cover"))));
  // clear the cache
  Tellico::ImageFactory::clean(true);
  QVERIFY(!Tellico::ImageFactory::imageById(e->field("cover")).isNull());

  // sanity check, the directory should not exists after QTemporaryDir destruction
  tempDir.remove();
  QVERIFY(!QDir(tempDirName).exists());
}
QSGNode* BrowserUtils::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData* updatePaintNodeData)
{
	Q_UNUSED(updatePaintNodeData);

	if (!(m_webview && (flags() & QQuickItem::ItemHasContents))) {
		return oldNode;
	}
	setFlag(QQuickItem::ItemHasContents, false);
#if 0
	QQuickWebPage* page = m_webview->page();
	qreal xmin = qMin(page->width(), m_webview->width());
	qreal ymin = qMin(m_webview->height(), page->height());
#else
	// Here the screenshot of the page might be too large if the page is tiny
	qreal xmin = m_webview->width();
	qreal ymin = m_webview->height();
#endif
	ymin = qMin(static_cast<int>(ymin), m_imageSize.height());
	xmin = qMin(static_cast<int>(xmin), m_imageSize.width());

	QSize size(xmin, ymin);

	QSGNode* node = QQuickItemPrivate::get(m_webview)->itemNode();
	QSGNode* parent = node->QSGNode::parent();
	QSGNode* previousSibling = node->previousSibling();
	if (parent) {
		parent->removeChildNode(node);
	}
	QSGRootNode root;
	root.appendChildNode(node);

	QSGRenderer* renderer;
#if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
	renderer = QQuickItemPrivate::get(this)->sceneGraphContext()->createRenderer();
#else
	renderer = QQuickItemPrivate::get(this)->sceneGraphRenderContext()->createRenderer();
#endif
	renderer->setRootNode(static_cast<QSGRootNode*>(&root));

	QOpenGLFramebufferObject fbo(size);

	renderer->setDeviceRect(size);
	renderer->setViewportRect(size);
	renderer->setProjectionMatrixToRect(QRectF(QPointF(), size));
	renderer->setClearColor(Qt::transparent);

	renderer->renderScene(BindableFbo(&fbo));

	fbo.release();

	QImage image = fbo.toImage().scaled(m_imageSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
	QFileInfo imageInfo(m_outFile);
	QDir imageDir(imageInfo.path());
	if (!imageDir.exists()) {
		imageDir.mkpath(".");
	}

	bool saved = image.save(m_outFile);

	root.removeChildNode(node);
	renderer->setRootNode(0);
	delete renderer;

	if (parent) {
		if (previousSibling) {
			parent->insertChildNodeAfter(node, previousSibling);
		} else {
			parent->prependChildNode(node);
		}
	}

	Q_EMIT webViewSaved(saved, m_outFile);

	return oldNode;
}
예제 #13
0
void KNMusicLibraryImageManager::recoverAlbumArt(const QStringList &hashList)
{
    //Check out the image hash list has been set or not.
    if(m_hashAlbumArt==nullptr)
    {
        return;
    }
    //Get the image folder path information.
    QFileInfo pathChecker(m_imageFolderPath);
    //Check is the path exist or it's a file
    if(pathChecker.exists() && pathChecker.isFile())
    {
        //Delete the file.
        QFile::remove(pathChecker.absoluteFilePath());
    }
    //Generate the image directory.
    QDir imageDir(m_imageFolderPath);
    //Check if it's not exist, simply generate the folder.
    if(!pathChecker.exists())
    {
        //Generate the folder.
        imageDir.mkpath(imageDir.absolutePath());
        //Do nothing, return. Because the folder is just created.
        return;
    }
    //Check the existance again, if the path is still not exist, then failed.
    if(!pathChecker.isDir() || !pathChecker.exists())
    {
        return;
    }
    //Get the entry info list.
    QFileInfoList contentInfos=imageDir.entryInfoList();
    //Check each file.
    for(auto i : contentInfos)
    {
        //Check the information of all the file and the suffix.
        if(i.isFile() && i.suffix().toLower()=="png")
        {
            //Get the hash key, which is the base name.
            QString hashKey=i.completeBaseName();
            //Check whether the file is in the hash list.
            if(hashList.contains(hashKey))
            {
                //Load the image.
                QPixmap currentPixmap=QPixmap(i.absoluteFilePath(), "png");
                //If there's image data is not null.
                if(!currentPixmap.isNull())
                {
                    //Insert the image to the hash list.
                    m_hashAlbumArt->insert(i.completeBaseName(),
                                           QVariant(currentPixmap));
                    //Continue to next file.
                    continue;
                }
            }
        }
        //Remove the no use file.
        QFile::remove(i.absoluteFilePath());
    }
    //After loading the images, emit recover signal.
    emit recoverImageComplete();
}
예제 #14
0
/**
 *  \copydoc MythUIType::ParseElement()
 */
bool MythUIImage::ParseElement(
    const QString &filename, QDomElement &element, bool showWarnings)
{
    QWriteLocker updateLocker(&d->m_UpdateLock);
    if (element.tagName() == "filename")
    {
        m_OrigFilename = m_Filename = getFirstText(element);
        if (m_Filename.endsWith('/'))
        {
            QDir imageDir(m_Filename);
            if (!imageDir.exists())
            {
                QString themeDir = GetMythUI()->GetThemeDir() + '/';
                imageDir = themeDir + m_Filename;
            }
            QStringList imageTypes;

            QList< QByteArray > exts = QImageReader::supportedImageFormats();
            QList< QByteArray >::Iterator it = exts.begin();
            for (;it != exts.end();++it)
            {
                imageTypes.append( QString("*.").append(*it) );
            }

            imageDir.setNameFilters(imageTypes);

            QStringList imageList = imageDir.entryList();
            srand(time(NULL));
            QString randFile;
            if (imageList.size())
                randFile = QString("%1%2").arg(m_Filename)
                           .arg(imageList.takeAt(rand() % imageList.size()));
            m_OrigFilename = m_Filename = randFile;
        }
    }
    else if (element.tagName() == "filepattern")
    {
        m_OrigFilename = m_Filename = getFirstText(element);
        QString tmp = element.attribute("low");
        if (!tmp.isEmpty())
            m_LowNum = tmp.toInt();
        tmp = element.attribute("high");
        if (!tmp.isEmpty())
            m_HighNum = tmp.toInt();
        tmp = element.attribute("cycle", "start");
        if (tmp == "reverse")
            m_animationCycle = kCycleReverse;
    }
    else if (element.tagName() == "area")
    {
        SetArea(parseRect(element));
        m_ForceSize = m_Area.size();
    }
    else if (element.tagName() == "preserveaspect")
        m_preserveAspect = parseBool(element);
    else if (element.tagName() == "crop")
        m_cropRect = parseRect(element);
    else if (element.tagName() == "delay")
    {
        QString value = getFirstText(element);
        if (value.contains(","))
        {
            QVector<int> delays;
            QStringList tokens = value.split(",");
            QStringList::iterator it = tokens.begin();
            for (; it != tokens.end(); ++it)
            {
                if ((*it).isEmpty())
                {
                    if (delays.size())
                        delays.append(delays[delays.size()-1]);
                    else
                        delays.append(0); // Default 0ms delay before first image
                }
                else
                {
                    delays.append((*it).toInt());
                }
            }

            if (delays.size())
            {
                m_Delay = delays[0];
                SetDelays(delays);
            }
        }
        else
        {
            m_Delay = value.toInt();
        }
    }
    else if (element.tagName() == "reflection")
    {
        m_isReflected = true;
        QString tmp = element.attribute("axis");
        if (!tmp.isEmpty())
        {
            if (tmp.toLower() == "horizontal")
                m_reflectAxis = ReflectHorizontal;
            else
                m_reflectAxis = ReflectVertical;
        }
        tmp = element.attribute("shear");
        if (!tmp.isEmpty())
            m_reflectShear = tmp.toInt();
        tmp = element.attribute("scale");
        if (!tmp.isEmpty())
            m_reflectScale = tmp.toInt();
        tmp = element.attribute("length");
        if (!tmp.isEmpty())
            m_reflectLength = tmp.toInt();
        tmp = element.attribute("spacing");
        if (!tmp.isEmpty())
            m_reflectSpacing = tmp.toInt();
    }
    else if (element.tagName() == "mask")
    {
        QString maskfile = getFirstText(element);
        if (m_maskImage)
        {
            m_maskImage->DownRef();
            m_maskImage = NULL;
        }

        m_maskImage = GetPainter()->GetFormatImage();
        m_maskImage->UpRef();
        if (m_maskImage->Load(maskfile))
            m_isMasked = true;
        else
        {
            m_maskImage->DownRef();
            m_maskImage = NULL;
            m_isMasked = false;
        }
    }
    else if (element.tagName() == "grayscale" ||
             element.tagName() == "greyscale")
    {
        m_isGreyscale = parseBool(element);
    }
    else
    {
        return MythUIType::ParseElement(filename, element, showWarnings);
    }

    m_NeedLoad = true;

    if (m_Parent && m_Parent->IsDeferredLoading(true))
        m_NeedLoad = false;

    return true;
}