bool MetaEngine::Private::saveOperations(const QFileInfo& finfo, Exiv2::Image::AutoPtr image) const { try { Exiv2::AccessMode mode; bool wroteComment = false, wroteEXIF = false, wroteIPTC = false, wroteXMP = false; // We need to load target file metadata to merge with new one. It's mandatory with TIFF format: // like all tiff file structure is based on Exif. image->readMetadata(); // Image Comments --------------------------------- mode = image->checkMode(Exiv2::mdComment); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { image->setComment(imageComments()); wroteComment = true; } qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteComment: " << wroteComment; // Exif metadata ---------------------------------- mode = image->checkMode(Exiv2::mdExif); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { if (image->mimeType() == "image/tiff") { Exiv2::ExifData orgExif = image->exifData(); Exiv2::ExifData newExif; QStringList untouchedTags; // With tiff image we cannot overwrite whole Exif data as well, because // image data are stored in Exif container. We need to take a care about // to not lost image data. untouchedTags << QString::fromLatin1("Exif.Image.ImageWidth"); untouchedTags << QString::fromLatin1("Exif.Image.ImageLength"); untouchedTags << QString::fromLatin1("Exif.Image.BitsPerSample"); untouchedTags << QString::fromLatin1("Exif.Image.Compression"); untouchedTags << QString::fromLatin1("Exif.Image.PhotometricInterpretation"); untouchedTags << QString::fromLatin1("Exif.Image.FillOrder"); untouchedTags << QString::fromLatin1("Exif.Image.SamplesPerPixel"); untouchedTags << QString::fromLatin1("Exif.Image.StripOffsets"); untouchedTags << QString::fromLatin1("Exif.Image.RowsPerStrip"); untouchedTags << QString::fromLatin1("Exif.Image.StripByteCounts"); untouchedTags << QString::fromLatin1("Exif.Image.XResolution"); untouchedTags << QString::fromLatin1("Exif.Image.YResolution"); untouchedTags << QString::fromLatin1("Exif.Image.PlanarConfiguration"); untouchedTags << QString::fromLatin1("Exif.Image.ResolutionUnit"); for (Exiv2::ExifData::iterator it = orgExif.begin(); it != orgExif.end(); ++it) { if (untouchedTags.contains(QString::fromLatin1(it->key().c_str()))) { newExif[it->key().c_str()] = orgExif[it->key().c_str()]; } } Exiv2::ExifData readedExif = exifMetadata(); for (Exiv2::ExifData::iterator it = readedExif.begin(); it != readedExif.end(); ++it) { if (!untouchedTags.contains(QString::fromLatin1(it->key().c_str()))) { newExif[it->key().c_str()] = readedExif[it->key().c_str()]; } } image->setExifData(newExif); } else { image->setExifData(exifMetadata()); } wroteEXIF = true; } qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteEXIF: " << wroteEXIF; // Iptc metadata ---------------------------------- mode = image->checkMode(Exiv2::mdIptc); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { image->setIptcData(iptcMetadata()); wroteIPTC = true; } qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteIPTC: " << wroteIPTC; // Xmp metadata ----------------------------------- mode = image->checkMode(Exiv2::mdXmp); if ((mode == Exiv2::amWrite) || (mode == Exiv2::amReadWrite)) { #ifdef _XMP_SUPPORT_ image->setXmpData(xmpMetadata()); wroteXMP = true; #endif } qCDebug(DIGIKAM_METAENGINE_LOG) << "wroteXMP: " << wroteXMP; if (!wroteComment && !wroteEXIF && !wroteIPTC && !wroteXMP) { qCDebug(DIGIKAM_METAENGINE_LOG) << "Writing metadata is not supported for file" << finfo.fileName(); return false; } else if (!wroteEXIF || !wroteIPTC || !wroteXMP) { qCDebug(DIGIKAM_METAENGINE_LOG) << "Support for writing metadata is limited for file" << finfo.fileName(); } if (!updateFileTimeStamp) { // Don't touch access and modification timestamp of file. struct stat st; struct utimbuf ut; int ret = ::stat(QFile::encodeName(filePath).constData(), &st); if (ret == 0) { ut.modtime = st.st_mtime; ut.actime = st.st_atime; } image->writeMetadata(); if (ret == 0) { ::utime(QFile::encodeName(filePath).constData(), &ut); } qCDebug(DIGIKAM_METAENGINE_LOG) << "File time stamp restored"; } else { image->writeMetadata(); } return true; } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return false; }
AnimNode::Pointer loadInverseKinematicsNode(const QJsonObject& jsonObj, const QString& id, const QUrl& jsonUrl) { auto node = std::make_shared<AnimInverseKinematics>(id); auto targetsValue = jsonObj.value("targets"); if (!targetsValue.isArray()) { qCCritical(animation) << "AnimNodeLoader, bad array \"targets\" in inverseKinematics node, id =" << id; return nullptr; } auto targetsArray = targetsValue.toArray(); for (const auto& targetValue : targetsArray) { if (!targetValue.isObject()) { qCCritical(animation) << "AnimNodeLoader, bad state object in \"targets\", id =" << id; return nullptr; } auto targetObj = targetValue.toObject(); READ_STRING(jointName, targetObj, id, jsonUrl, nullptr); READ_STRING(positionVar, targetObj, id, jsonUrl, nullptr); READ_STRING(rotationVar, targetObj, id, jsonUrl, nullptr); READ_OPTIONAL_STRING(typeVar, targetObj); READ_OPTIONAL_STRING(weightVar, targetObj); READ_OPTIONAL_FLOAT(weight, targetObj, 1.0f); READ_OPTIONAL_STRING(poleVectorEnabledVar, targetObj); READ_OPTIONAL_STRING(poleReferenceVectorVar, targetObj); READ_OPTIONAL_STRING(poleVectorVar, targetObj); auto flexCoefficientsValue = targetObj.value("flexCoefficients"); if (!flexCoefficientsValue.isArray()) { qCCritical(animation) << "AnimNodeLoader, bad or missing flexCoefficients array in \"targets\", id =" << id; return nullptr; } auto flexCoefficientsArray = flexCoefficientsValue.toArray(); std::vector<float> flexCoefficients; for (const auto& value : flexCoefficientsArray) { flexCoefficients.push_back((float)value.toDouble()); } node->setTargetVars(jointName, positionVar, rotationVar, typeVar, weightVar, weight, flexCoefficients, poleVectorEnabledVar, poleReferenceVectorVar, poleVectorVar); }; READ_OPTIONAL_STRING(solutionSource, jsonObj); if (!solutionSource.isEmpty()) { AnimInverseKinematics::SolutionSource solutionSourceType = stringToSolutionSourceEnum(solutionSource); if (solutionSourceType != AnimInverseKinematics::SolutionSource::NumSolutionSources) { node->setSolutionSource(solutionSourceType); } } else { qCWarning(animation) << "AnimNodeLoader, bad solutionSourceType in \"solutionSource\", id = " << id; } READ_OPTIONAL_STRING(solutionSourceVar, jsonObj); if (!solutionSourceVar.isEmpty()) { node->setSolutionSourceVar(solutionSourceVar); } return node; }
int MemoryFrame::distributeVariablesIntoMemoryRows(int initialDelay) { // The duration of this animation int duration = 0; // We iterate for all variables assigned to this frame, distributing them to its memory rows MemoryAllocations::iterator variableIterator = memoryAllocations.begin(); int currentRow = 0; // Traverse all the variables while ( variableIterator != memoryAllocations.end() ) { // For convenience MemoryAllocation* variable = *variableIterator; // We must allocate a variable, if all rows were filled if ( currentRow >= memoryRows.count() ) { // We do not need to grow the frame for free memory if ( variable->isFreeFragment() ) { // Skip to next variable ++variableIterator; continue; } // All the memory rows are filled, but if the memory frame can grow, create more rows // ToDo: Only a piece of the variable may be needed to allocate, not the entire variable int requiredRows = (qMax(variable->size, 1ll) + (rowSize - 1)) / rowSize; qCCritical(logTemporary(), "Growing %d rows for %s of %lld bytes", requiredRows, qPrintable(variable->name), variable->size); // If it is unable to grow more, we have a segment overflow int growDuration = grow(requiredRows, initialDelay); if ( growDuration < 0 ) return growDuration; // Add this duration to the proccess and the remaining animations duration += growDuration; initialDelay += growDuration; // Be sure there is a memory row to continue Q_ASSERT( currentRow < memoryRows.count() ); } // Try to allocate this variable in the current row int entirelyAllocated = false; int rowAllocation = memoryRows[currentRow]->allocate(variable, entirelyAllocated, initialDelay); // Update the durations of animation duration += rowAllocation; initialDelay += rowAllocation; // If the variable was partially allocated or not allocated at all if ( entirelyAllocated <= 0 ) { // Try to allocate the variable in the next row ++currentRow; continue; } // The row accepted the variable, and it is completely allocated, move to the next variable ++variableIterator; } // All variables were distributed in the available rows return duration; }
S3DScene* Scenery3d::loadSceneBackground(const SceneInfo& scene) const { //the scoped pointer ensures this scene is deleted when errors occur QScopedPointer<S3DScene> newScene(new S3DScene(scene)); if(loadCancel) return Q_NULLPTR; updateProgress(q_("Loading model..."),1,0,6); //load model StelOBJ modelOBJ; QString modelFile = StelFileMgr::findFile( scene.fullPath+ "/" + scene.modelScenery); qCDebug(scenery3d)<<"Loading scene from "<<modelFile; if(!modelOBJ.load(modelFile, scene.vertexOrderEnum)) { qCCritical(scenery3d)<<"Failed to load OBJ file"<<modelFile; return Q_NULLPTR; } if(loadCancel) return Q_NULLPTR; updateProgress(q_("Transforming model..."),2,0,6); newScene->setModel(modelOBJ); if(loadCancel) return Q_NULLPTR; if(scene.modelGround.isEmpty()) { updateProgress(q_("Calculating collision map..."),5,0,6); newScene->setGround(modelOBJ); } else if (scene.modelGround != "NULL") { updateProgress(q_("Loading ground..."),3,0,6); StelOBJ groundOBJ; modelFile = StelFileMgr::findFile(scene.fullPath + "/" + scene.modelGround); qCDebug(scenery3d)<<"Loading ground from"<<modelFile; if(!groundOBJ.load(modelFile, scene.vertexOrderEnum)) { qCCritical(scenery3d)<<"Failed to load ground model"<<modelFile; return Q_NULLPTR; } updateProgress(q_("Transforming ground..."),4,0,6); if(loadCancel) return Q_NULLPTR; updateProgress(q_("Calculating collision map..."),5,0,6); newScene->setGround(groundOBJ); } if(loadCancel) return Q_NULLPTR; updateProgress(q_("Finalizing load..."),6,0,6); return newScene.take(); }
bool KExiv2::load(const QString& filePath) const { if (filePath.isEmpty()) { return false; } d->filePath = filePath; bool hasLoaded = false; try { Exiv2::Image::AutoPtr image; image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(filePath)).constData()); image->readMetadata(); // Size and mimetype --------------------------------- d->pixelSize = QSize(image->pixelWidth(), image->pixelHeight()); d->mimeType = QString::fromLatin1(image->mimeType().c_str()); // Image comments --------------------------------- d->imageComments() = image->comment(); // Exif metadata ---------------------------------- d->exifMetadata() = image->exifData(); // Iptc metadata ---------------------------------- d->iptcMetadata() = image->iptcData(); #ifdef _XMP_SUPPORT_ // Xmp metadata ----------------------------------- d->xmpMetadata() = image->xmpData(); #endif // _XMP_SUPPORT_ hasLoaded = true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot load metadata from file "), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #ifdef _XMP_SUPPORT_ try { if (d->useXMPSidecar4Reading) { QString xmpSidecarPath = sidecarFilePathForFile(filePath); QFileInfo xmpSidecarFileInfo(xmpSidecarPath); Exiv2::Image::AutoPtr xmpsidecar; if (xmpSidecarFileInfo.exists() && xmpSidecarFileInfo.isReadable()) { // Read sidecar data xmpsidecar = Exiv2::ImageFactory::open(QFile::encodeName(xmpSidecarPath).constData()); xmpsidecar->readMetadata(); // Merge d->loadSidecarData(xmpsidecar); hasLoaded = true; } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot load XMP sidecar"), e); } catch(...) { qCCritical(LIBKEXIV2_LOG) << "Default exception from Exiv2"; } #endif // _XMP_SUPPORT_ return hasLoaded; }
void Animation::animationParseError(int error, QString str) { qCCritical(animation) << "Animation parse error, code =" << error << str; emit failed(QNetworkReply::UnknownContentError); finishedLoading(false); }
bool ShaderMgr::preprocessShader(const QString &fileName, const uint flags, QByteArray &processedSource) { if(fileName.isEmpty()) { //no shader of this type return true; } QDir dir("data/shaders/"); QString filePath = StelFileMgr::findFile(dir.filePath(fileName),StelFileMgr::File); //open and load file QFile file(filePath); #ifndef NDEBUG //qCDebug(shaderMgr)<<"File path:"<<filePath; #endif if(!file.open(QFile::ReadOnly)) { qCCritical(shaderMgr)<<"Could not open file"<<filePath; return false; } processedSource.clear(); processedSource.reserve(file.size()); //use a text stream for "parsing" QTextStream in(&file),lineStream; QString line,word; while(!in.atEnd()) { line = in.readLine(); lineStream.setString(&line,QIODevice::ReadOnly); QString write = line; //read first word lineStream>>word; if(word == "#define") { //read second word lineStream>>word; //try to find it in our flags list auto it = featureFlagsStrings.find(word); if(it!=featureFlagsStrings.end()) { bool val = it.value() & flags; write = "#define " + word + (val?" 1":" 0"); #ifdef NDEBUG } #else //output matches for debugging //qCDebug(shaderMgr)<<"preprocess match: "<<line <<" --> "<<write; } else { //qCDebug(shaderMgr)<<"unknown define, ignoring: "<<line; } #endif }
QDateTime MetaEngine::getImageDateTime() const { try { // In first, trying to get Date & time from Exif tags. if (!d->exifMetadata().empty()) { Exiv2::ExifData exifData(d->exifMetadata()); { Exiv2::ExifKey key("Exif.Photo.DateTimeOriginal"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Exif.Photo.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::ExifKey key("Exif.Photo.DateTimeDigitized"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Exif.Photo.DateTimeDigitized => " << dateTime; return dateTime; } } } { Exiv2::ExifKey key("Exif.Image.DateTime"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Exif.Image.DateTime => " << dateTime; return dateTime; } } } } // In second, trying to get Date & time from Xmp tags. #ifdef _XMP_SUPPORT_ if (!d->xmpMetadata().empty()) { Exiv2::XmpData xmpData(d->xmpMetadata()); { Exiv2::XmpKey key("Xmp.exif.DateTimeOriginal"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.exif.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.exif.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.exif.DateTimeDigitized => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.photoshop.DateCreated"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.photoshop.DateCreated => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.CreateDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.xmp.CreateDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.tiff.DateTime"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.tiff.DateTime => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.ModifyDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.xmp.ModifyDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.xmp.MetadataDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.xmp.MetadataDate => " << dateTime; return dateTime; } } } // Video files support { Exiv2::XmpKey key("Xmp.video.DateTimeOriginal"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.video.DateTimeOriginal => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateUTC"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.video.DateUTC => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.ModificationDate"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.video.ModificationDate => " << dateTime; return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Xmp.video.DateTimeDigitized => " << dateTime; return dateTime; } } } } #endif // _XMP_SUPPORT_ // In third, trying to get Date & time from Iptc tags. if (!d->iptcMetadata().empty()) { Exiv2::IptcData iptcData(d->iptcMetadata()); // Try creation Iptc date & time entries. Exiv2::IptcKey keyDateCreated("Iptc.Application2.DateCreated"); Exiv2::IptcData::iterator it = iptcData.findKey(keyDateCreated); if (it != iptcData.end()) { QString IptcDateCreated(QString::fromLatin1(it->toString().c_str())); Exiv2::IptcKey keyTimeCreated("Iptc.Application2.TimeCreated"); Exiv2::IptcData::iterator it2 = iptcData.findKey(keyTimeCreated); if (it2 != iptcData.end()) { QString IptcTimeCreated(QString::fromLatin1(it2->toString().c_str())); QDate date = QDate::fromString(IptcDateCreated, Qt::ISODate); QTime time = QTime::fromString(IptcTimeCreated, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Iptc.Application2.DateCreated => " << dateTime; return dateTime; } } } // Try digitization Iptc date & time entries. Exiv2::IptcKey keyDigitizationDate("Iptc.Application2.DigitizationDate"); Exiv2::IptcData::iterator it3 = iptcData.findKey(keyDigitizationDate); if (it3 != iptcData.end()) { QString IptcDateDigitization(QString::fromLatin1(it3->toString().c_str())); Exiv2::IptcKey keyDigitizationTime("Iptc.Application2.DigitizationTime"); Exiv2::IptcData::iterator it4 = iptcData.findKey(keyDigitizationTime); if (it4 != iptcData.end()) { QString IptcTimeDigitization(QString::fromLatin1(it4->toString().c_str())); QDate date = QDate::fromString(IptcDateDigitization, Qt::ISODate); QTime time = QTime::fromString(IptcTimeDigitization, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime => Iptc.Application2.DigitizationDate => " << dateTime; return dateTime; } } } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif date & time tag using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return QDateTime(); }
bool MetaEngine::setImageDateTime(const QDateTime& dateTime, bool setDateTimeDigitized, bool setProgramName) const { if(!dateTime.isValid()) return false; if (!setProgramId(setProgramName)) return false; try { // In first we write date & time into Exif. // DateTimeDigitized is set by slide scanners etc. when a picture is digitized. // DateTimeOriginal specifies the date/time when the picture was taken. // For digital cameras, these dates should be both set, and identical. // Reference: http://www.exif.org/Exif2-2.PDF, chapter 4.6.5, table 4, section F. const std::string &exifdatetime(dateTime.toString(QString::fromLatin1("yyyy:MM:dd hh:mm:ss")).toLatin1().constData()); d->exifMetadata()["Exif.Image.DateTime"] = exifdatetime; d->exifMetadata()["Exif.Photo.DateTimeOriginal"] = exifdatetime; if(setDateTimeDigitized) d->exifMetadata()["Exif.Photo.DateTimeDigitized"] = exifdatetime; #ifdef _XMP_SUPPORT_ // In second we write date & time into Xmp. const std::string &xmpdatetime(dateTime.toString(Qt::ISODate).toLatin1().constData()); Exiv2::Value::AutoPtr xmpTxtVal = Exiv2::Value::create(Exiv2::xmpText); xmpTxtVal->read(xmpdatetime); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.exif.DateTimeOriginal"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.photoshop.DateCreated"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.tiff.DateTime"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.CreateDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.MetadataDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.xmp.ModifyDate"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateTimeOriginal"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateUTC"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.ModificationDate"), xmpTxtVal.get()); if(setDateTimeDigitized) { d->xmpMetadata().add(Exiv2::XmpKey("Xmp.exif.DateTimeDigitized"), xmpTxtVal.get()); d->xmpMetadata().add(Exiv2::XmpKey("Xmp.video.DateTimeDigitized"), xmpTxtVal.get()); } // Tag not updated: // "Xmp.dc.DateTime" is a sequence of date relevant of dublin core change. // This is not the picture date as well #endif // _XMP_SUPPORT_ // In third we write date & time into Iptc. const std::string &iptcdate(dateTime.date().toString(Qt::ISODate).toLatin1().constData()); const std::string &iptctime(dateTime.time().toString(Qt::ISODate).toLatin1().constData()); d->iptcMetadata()["Iptc.Application2.DateCreated"] = iptcdate; d->iptcMetadata()["Iptc.Application2.TimeCreated"] = iptctime; if(setDateTimeDigitized) { d->iptcMetadata()["Iptc.Application2.DigitizationDate"] = iptcdate; d->iptcMetadata()["Iptc.Application2.DigitizationTime"] = iptctime; } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Date & Time into image using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return false; }
MetaEngine::ImageOrientation MetaEngine::getImageOrientation() const { try { Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifData::iterator it; long orientation; ImageOrientation imageOrient = ORIENTATION_NORMAL; // -- Standard Xmp tag -------------------------------- #ifdef _XMP_SUPPORT_ bool ok = false; QString str = getXmpTagString("Xmp.tiff.Orientation"); if (!str.isEmpty()) { orientation = str.toLong(&ok); if (ok) { qCDebug(DIGIKAM_METAENGINE_LOG) << "Orientation => Xmp.tiff.Orientation => " << (int)orientation; return (ImageOrientation)orientation; } } #endif // _XMP_SUPPORT_ // Because some camera set a wrong standard exif orientation tag, // We need to check makernote tags in first! // -- Minolta Cameras ---------------------------------- Exiv2::ExifKey minoltaKey1("Exif.MinoltaCs7D.Rotation"); it = exifData.findKey(minoltaKey1); if (it != exifData.end() && it->count()) { orientation = it->toLong(); qCDebug(DIGIKAM_METAENGINE_LOG) << "Orientation => Exif.MinoltaCs7D.Rotation => " << (int)orientation; switch(orientation) { case 76: imageOrient = ORIENTATION_ROT_90; break; case 82: imageOrient = ORIENTATION_ROT_270; break; } return imageOrient; } Exiv2::ExifKey minoltaKey2("Exif.MinoltaCs5D.Rotation"); it = exifData.findKey(minoltaKey2); if (it != exifData.end() && it->count()) { orientation = it->toLong(); qCDebug(DIGIKAM_METAENGINE_LOG) << "Orientation => Exif.MinoltaCs5D.Rotation => " << (int)orientation; switch(orientation) { case 76: imageOrient = ORIENTATION_ROT_90; break; case 82: imageOrient = ORIENTATION_ROT_270; break; } return imageOrient; } // -- Standard Exif tag -------------------------------- Exiv2::ExifKey keyStd("Exif.Image.Orientation"); it = exifData.findKey(keyStd); if (it != exifData.end() && it->count()) { orientation = it->toLong(); qCDebug(DIGIKAM_METAENGINE_LOG) << "Orientation => Exif.Image.Orientation => " << (int)orientation; return (ImageOrientation)orientation; } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif Orientation tag using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return ORIENTATION_UNSPECIFIED; }
bool MetaEngine::setImageOrientation(ImageOrientation orientation, bool setProgramName) const { if (!setProgramId(setProgramName)) return false; try { if (orientation < ORIENTATION_UNSPECIFIED || orientation > ORIENTATION_ROT_270) { qCDebug(DIGIKAM_METAENGINE_LOG) << "Image orientation value is not correct!"; return false; } // Set Exif values. d->exifMetadata()["Exif.Image.Orientation"] = static_cast<uint16_t>(orientation); qCDebug(DIGIKAM_METAENGINE_LOG) << "Exif.Image.Orientation tag set to: " << (int)orientation; // Set Xmp values. #ifdef _XMP_SUPPORT_ setXmpTagString("Xmp.tiff.Orientation", QString::number((int)orientation), false); #endif // _XMP_SUPPORT_ // -- Minolta/Sony Cameras ---------------------------------- // Minolta and Sony camera store image rotation in Makernote. // We remove these information to prevent duplicate values. Exiv2::ExifData::iterator it; Exiv2::ExifKey minoltaKey1("Exif.MinoltaCs7D.Rotation"); it = d->exifMetadata().findKey(minoltaKey1); if (it != d->exifMetadata().end()) { d->exifMetadata().erase(it); qCDebug(DIGIKAM_METAENGINE_LOG) << "Removing Exif.MinoltaCs7D.Rotation tag"; } Exiv2::ExifKey minoltaKey2("Exif.MinoltaCs5D.Rotation"); it = d->exifMetadata().findKey(minoltaKey2); if (it != d->exifMetadata().end()) { d->exifMetadata().erase(it); qCDebug(DIGIKAM_METAENGINE_LOG) << "Removing Exif.MinoltaCs5D.Rotation tag"; } // -- Exif embedded thumbnail ---------------------------------- Exiv2::ExifKey thumbKey("Exif.Thumbnail.Orientation"); it = d->exifMetadata().findKey(thumbKey); if (it != d->exifMetadata().end() && it->count()) { MetaEngineRotation operation((MetaEngine::ImageOrientation)it->toLong()); operation *= orientation; (*it) = static_cast<uint16_t>(operation.exifOrientation()); } return true; } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot set Exif Orientation tag using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return false; }
QSize MetaEngine::getImageDimensions() const { try { long width=-1, height=-1; // Try to get Exif.Photo tags Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Photo.PixelXDimension"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end() && it->count()) width = it->toLong(); Exiv2::ExifKey key2("Exif.Photo.PixelYDimension"); Exiv2::ExifData::iterator it2 = exifData.findKey(key2); if (it2 != exifData.end() && it2->count()) height = it2->toLong(); if (width != -1 && height != -1) return QSize(width, height); // Try to get Exif.Image tags width = -1; height = -1; Exiv2::ExifKey key3("Exif.Image.ImageWidth"); Exiv2::ExifData::iterator it3 = exifData.findKey(key3); if (it3 != exifData.end() && it3->count()) width = it3->toLong(); Exiv2::ExifKey key4("Exif.Image.ImageLength"); Exiv2::ExifData::iterator it4 = exifData.findKey(key4); if (it4 != exifData.end() && it4->count()) height = it4->toLong(); if (width != -1 && height != -1) return QSize(width, height); #ifdef _XMP_SUPPORT_ // Try to get Xmp.tiff tags width = -1; height = -1; bool wOk = false; bool hOk = false; QString str = getXmpTagString("Xmp.tiff.ImageWidth"); if (!str.isEmpty()) width = str.toInt(&wOk); str = getXmpTagString("Xmp.tiff.ImageLength"); if (!str.isEmpty()) height = str.toInt(&hOk); if (wOk && hOk) return QSize(width, height); // Try to get Xmp.exif tags width = -1; height = -1; wOk = false; hOk = false; str = getXmpTagString("Xmp.exif.PixelXDimension"); if (!str.isEmpty()) width = str.toInt(&wOk); str = getXmpTagString("Xmp.exif.PixelYDimension"); if (!str.isEmpty()) height = str.toInt(&hOk); if (wOk && hOk) return QSize(width, height); #endif // _XMP_SUPPORT_ } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse image dimensions tag using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } return QSize(); }
void TwitterMicroBlog::createPostWithAttachment(Choqok::Account *theAccount, Choqok::Post *post, const QString &mediumToAttach) { if (mediumToAttach.isEmpty()) { TwitterApiMicroBlog::createPost(theAccount, post); } else { const QUrl picUrl = QUrl::fromUserInput(mediumToAttach); KIO::StoredTransferJob *picJob = KIO::storedGet(picUrl, KIO::Reload, KIO::HideProgressInfo); picJob->exec(); if (picJob->error()) { qCCritical(CHOQOK) << "Job error:" << picJob->errorString(); KMessageBox::detailedError(Choqok::UI::Global::mainWindow(), i18n("Uploading medium failed: cannot read the medium file."), picJob->errorString()); return; } const QByteArray picData = picJob->data(); if (picData.count() == 0) { qCCritical(CHOQOK) << "Cannot read the media file, please check if it exists."; KMessageBox::error(Choqok::UI::Global::mainWindow(), i18n("Uploading medium failed: cannot read the medium file.")); return; } TwitterAccount *account = qobject_cast<TwitterAccount *>(theAccount); QUrl url = account->uploadUrl(); url.setPath(url.path() + QStringLiteral("/statuses/update_with_media.%1").arg(format)); const QMimeDatabase db; QByteArray fileContentType = db.mimeTypeForUrl(picUrl).name().toUtf8(); QMap<QString, QByteArray> formdata; formdata[QLatin1String("status")] = post->content.toUtf8(); if (!post->replyToPostId.isEmpty()) { formdata[QLatin1String("in_reply_to_status_id")] = post->replyToPostId.toLatin1(); } formdata[QLatin1String("source")] = QCoreApplication::applicationName().toLatin1(); QMap<QString, QByteArray> mediafile; mediafile[QLatin1String("name")] = "media[]"; mediafile[QLatin1String("filename")] = picUrl.fileName().toUtf8(); mediafile[QLatin1String("mediumType")] = fileContentType; mediafile[QLatin1String("medium")] = picData; QList< QMap<QString, QByteArray> > listMediafiles; listMediafiles.append(mediafile); QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles); KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ; if (!job) { qCCritical(CHOQOK) << "Cannot create a http POST request!"; return; } job->addMetaData(QStringLiteral("content-type"), QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x")); job->addMetaData(QStringLiteral("customHTTPHeader"), QStringLiteral("Authorization: ") + QLatin1String(authorizationHeader(account, url, QOAuth::POST))); mCreatePostMap[ job ] = post; mJobsAccount[job] = theAccount; connect(job, SIGNAL(result(KJob*)), SLOT(slotCreatePost(KJob*))); job->start(); } }
void MetaEngine::Private::printExiv2ExceptionError(const QString& msg, Exiv2::Error& e) { std::string s(e.what()); qCCritical(DIGIKAM_METAENGINE_LOG) << msg.toLatin1().constData() << " (Error #" << e.code() << ": " << s.c_str(); }
bool GlxBackend::initFbConfig() { const int attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_ALPHA_SIZE, 0, GLX_DEPTH_SIZE, 0, GLX_STENCIL_SIZE, 0, GLX_CONFIG_CAVEAT, GLX_NONE, GLX_DOUBLEBUFFER, true, 0 }; // Try to find a double buffered configuration int count = 0; GLXFBConfig *configs = glXChooseFBConfig(display(), DefaultScreen(display()), attribs, &count); struct FBConfig { GLXFBConfig config; int depth; int stencil; }; std::deque<FBConfig> candidates; for (int i = 0; i < count; i++) { int depth, stencil; glXGetFBConfigAttrib(display(), configs[i], GLX_DEPTH_SIZE, &depth); glXGetFBConfigAttrib(display(), configs[i], GLX_STENCIL_SIZE, &stencil); candidates.emplace_back(FBConfig{configs[i], depth, stencil}); } if (count > 0) XFree(configs); std::stable_sort(candidates.begin(), candidates.end(), [](const FBConfig &left, const FBConfig &right) { if (left.depth < right.depth) return true; if (left.stencil < right.stencil) return true; return false; }); if (candidates.size() > 0) { fbconfig = candidates.front().config; int fbconfig_id, visual_id, red, green, blue, alpha, depth, stencil; glXGetFBConfigAttrib(display(), fbconfig, GLX_FBCONFIG_ID, &fbconfig_id); glXGetFBConfigAttrib(display(), fbconfig, GLX_VISUAL_ID, &visual_id); glXGetFBConfigAttrib(display(), fbconfig, GLX_RED_SIZE, &red); glXGetFBConfigAttrib(display(), fbconfig, GLX_GREEN_SIZE, &green); glXGetFBConfigAttrib(display(), fbconfig, GLX_BLUE_SIZE, &blue); glXGetFBConfigAttrib(display(), fbconfig, GLX_ALPHA_SIZE, &alpha); glXGetFBConfigAttrib(display(), fbconfig, GLX_DEPTH_SIZE, &depth); glXGetFBConfigAttrib(display(), fbconfig, GLX_STENCIL_SIZE, &stencil); qCDebug(KWIN_CORE, "Choosing GLXFBConfig %#x X visual %#x depth %d RGBA %d:%d:%d:%d ZS %d:%d", fbconfig_id, visual_id, visualDepth(visual_id), red, green, blue, alpha, depth, stencil); } if (fbconfig == nullptr) { qCCritical(KWIN_CORE) << "Failed to find a usable framebuffer configuration"; return false; } return true; }
QDateTime MetaEngine::getDigitizationDateTime(bool fallbackToCreationTime) const { try { // In first, trying to get Date & time from Exif tags. if (!d->exifMetadata().empty()) { // Try Exif date time digitized. Exiv2::ExifData exifData(d->exifMetadata()); Exiv2::ExifKey key("Exif.Photo.DateTimeDigitized"); Exiv2::ExifData::iterator it = exifData.findKey(key); if (it != exifData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime (Exif digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } // In second, we trying XMP #ifdef _XMP_SUPPORT_ if (!d->xmpMetadata().empty()) { Exiv2::XmpData xmpData(d->xmpMetadata()); { Exiv2::XmpKey key("Xmp.exif.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime (XMP-Exif digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } { Exiv2::XmpKey key("Xmp.video.DateTimeDigitized"); Exiv2::XmpData::iterator it = xmpData.findKey(key); if (it != xmpData.end()) { QDateTime dateTime = QDateTime::fromString(QString::fromLatin1(it->toString().c_str()), Qt::ISODate); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "DateTime (XMP-Video digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } } #endif // _XMP_SUPPORT_ // In third, trying to get Date & time from Iptc tags. if (!d->iptcMetadata().empty()) { // Try digitization Iptc date time entries. Exiv2::IptcData iptcData(d->iptcMetadata()); Exiv2::IptcKey keyDigitizationDate("Iptc.Application2.DigitizationDate"); Exiv2::IptcData::iterator it = iptcData.findKey(keyDigitizationDate); if (it != iptcData.end()) { QString IptcDateDigitization(QString::fromLatin1(it->toString().c_str())); Exiv2::IptcKey keyDigitizationTime("Iptc.Application2.DigitizationTime"); Exiv2::IptcData::iterator it2 = iptcData.findKey(keyDigitizationTime); if (it2 != iptcData.end()) { QString IptcTimeDigitization(QString::fromLatin1(it2->toString().c_str())); QDate date = QDate::fromString(IptcDateDigitization, Qt::ISODate); QTime time = QTime::fromString(IptcTimeDigitization, Qt::ISODate); QDateTime dateTime = QDateTime(date, time); if (dateTime.isValid()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "Date (IPTC digitalized): " << dateTime.toString().toLatin1().constData(); return dateTime; } } } } } catch( Exiv2::Error& e ) { d->printExiv2ExceptionError(QString::fromLatin1("Cannot parse Exif digitization date & time tag using Exiv2 "), e); } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; } if (fallbackToCreationTime) return getImageDateTime(); else return QDateTime(); }
FBConfigInfo *GlxBackend::infoForVisual(xcb_visualid_t visual) { FBConfigInfo *&info = m_fbconfigHash[visual]; if (info) return info; info = new FBConfigInfo; info->fbconfig = nullptr; info->bind_texture_format = 0; info->texture_targets = 0; info->y_inverted = 0; info->mipmap = 0; const xcb_render_pictformat_t format = XRenderUtils::findPictFormat(visual); const xcb_render_directformat_t *direct = XRenderUtils::findPictFormatInfo(format); if (!direct) { qCCritical(KWIN_CORE).nospace() << "Could not find a picture format for visual 0x" << hex << visual; return info; } const int red_bits = bitCount(direct->red_mask); const int green_bits = bitCount(direct->green_mask); const int blue_bits = bitCount(direct->blue_mask); const int alpha_bits = bitCount(direct->alpha_mask); const int depth = visualDepth(visual); const auto rgb_sizes = std::tie(red_bits, green_bits, blue_bits); const int attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_PIXMAP_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_X_RENDERABLE, True, GLX_CONFIG_CAVEAT, int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst GLX_BUFFER_SIZE, red_bits + green_bits + blue_bits + alpha_bits, GLX_RED_SIZE, red_bits, GLX_GREEN_SIZE, green_bits, GLX_BLUE_SIZE, blue_bits, GLX_ALPHA_SIZE, alpha_bits, GLX_STENCIL_SIZE, 0, GLX_DEPTH_SIZE, 0, 0 }; int count = 0; GLXFBConfig *configs = glXChooseFBConfig(display(), DefaultScreen(display()), attribs, &count); if (count < 1) { qCCritical(KWIN_CORE).nospace() << "Could not find a framebuffer configuration for visual 0x" << hex << visual; return info; } struct FBConfig { GLXFBConfig config; int depth; int stencil; int format; }; std::deque<FBConfig> candidates; for (int i = 0; i < count; i++) { int red, green, blue; glXGetFBConfigAttrib(display(), configs[i], GLX_RED_SIZE, &red); glXGetFBConfigAttrib(display(), configs[i], GLX_GREEN_SIZE, &green); glXGetFBConfigAttrib(display(), configs[i], GLX_BLUE_SIZE, &blue); if (std::tie(red, green, blue) != rgb_sizes) continue; xcb_visualid_t visual; glXGetFBConfigAttrib(display(), configs[i], GLX_VISUAL_ID, (int *) &visual); if (visualDepth(visual) != depth) continue; int bind_rgb, bind_rgba; glXGetFBConfigAttrib(display(), configs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba); glXGetFBConfigAttrib(display(), configs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &bind_rgb); if (!bind_rgb && !bind_rgba) continue; int depth, stencil; glXGetFBConfigAttrib(display(), configs[i], GLX_DEPTH_SIZE, &depth); glXGetFBConfigAttrib(display(), configs[i], GLX_STENCIL_SIZE, &stencil); int texture_format; if (alpha_bits) texture_format = bind_rgba ? GLX_TEXTURE_FORMAT_RGBA_EXT : GLX_TEXTURE_FORMAT_RGB_EXT; else texture_format = bind_rgb ? GLX_TEXTURE_FORMAT_RGB_EXT : GLX_TEXTURE_FORMAT_RGBA_EXT; candidates.emplace_back(FBConfig{configs[i], depth, stencil, texture_format}); } if (count > 0) XFree(configs); std::stable_sort(candidates.begin(), candidates.end(), [](const FBConfig &left, const FBConfig &right) { if (left.depth < right.depth) return true; if (left.stencil < right.stencil) return true; return false; }); if (candidates.size() > 0) { const FBConfig &candidate = candidates.front(); int y_inverted, texture_targets; glXGetFBConfigAttrib(display(), candidate.config, GLX_BIND_TO_TEXTURE_TARGETS_EXT, &texture_targets); glXGetFBConfigAttrib(display(), candidate.config, GLX_Y_INVERTED_EXT, &y_inverted); info->fbconfig = candidate.config; info->bind_texture_format = candidate.format; info->texture_targets = texture_targets; info->y_inverted = y_inverted; info->mipmap = 0; } if (info->fbconfig) { int fbc_id = 0; int visual_id = 0; glXGetFBConfigAttrib(display(), info->fbconfig, GLX_FBCONFIG_ID, &fbc_id); glXGetFBConfigAttrib(display(), info->fbconfig, GLX_VISUAL_ID, &visual_id); qCDebug(KWIN_CORE).nospace() << "Using FBConfig 0x" << hex << fbc_id << " for visual 0x" << hex << visual_id; } return info; }
void TeXFontDefinition::read_VF_index() { #ifdef DEBUG_FONTS qCDebug(OkularDviDebug) << "font::read_VF_index()"; #endif FILE *VF_file = file; unsigned char cmnd; // available space for macros unsigned char *avail, *availend; flags |= FONT_VIRTUAL; set_char_p = &dviRenderer::set_vf_char; #ifdef DEBUG_FONTS qCDebug(OkularDviDebug) << "TeXFontDefinition::read_VF_index: reading VF pixel file " << filename; #endif // Read preamble. fseek(VF_file, (long) one(VF_file), 1); /* skip comment */ quint32 const file_checksum = four(VF_file); if (file_checksum && checksum && file_checksum != checksum) qCCritical(OkularDviDebug) << "Checksum mismatch dvi = " << checksum << "u, vf = " << file_checksum << "u) in font file" << filename << endl; (void) four(VF_file); /* skip design size */ // Read the fonts. first_font = NULL; while ((cmnd = one(VF_file)) >= FNTDEF1 && cmnd <= FNTDEF4) { int TeXnumber = num(VF_file, (int) cmnd - FNTDEF1 + 1); quint32 checksum = four(VF_file); quint32 scale = four(VF_file); quint32 design = four(VF_file); Q_UNUSED(design); quint16 len = one(VF_file) + one(VF_file); /* sequence point in the middle */ char *fontname = new char[len + 1]; fread(fontname, sizeof(char), len, VF_file); fontname[len] = '\0'; #ifdef DEBUG_FONTS qCDebug(OkularDviDebug) << "Virtual font defines subfont \"" << fontname << "\" scale=" << scale << " design=" << design; #endif // According to Knuth's documentation found in the web source code // of the "vftovp" program (which seems to be the standard // definition of virtual fonts), the "scale" is a fixed point // number which describes extra enlargement that the virtual font // imposes. One obtains the enlargement by dividing 2^20. double enlargement_factor = double(scale)/(1<<20) * enlargement; // TeXFontDefinition *newfontp = font_pool->appendx(fontname, checksum, (quint32)(scaled_size_in_DVI_units*enlargement_factor), enlargement_factor); TeXFontDefinition *newfontp = font_pool->appendx(QString::fromLocal8Bit(fontname), checksum, (quint32)((double(scale)/(1<<20))*scaled_size_in_DVI_units), enlargement_factor); // Insert font in dictionary and make sure the dictionary is big // enough. if (vf_table.capacity()-2 <= vf_table.count()) // Not quite optimal. The size of the dictionary should be a // prime. I don't care. vf_table.reserve(vf_table.capacity()*2); vf_table.insert(TeXnumber, newfontp); if (first_font == NULL) first_font = newfontp; } // Prepare macro array. macrotable = new macro[max_num_of_chars_in_font]; if (macrotable == 0) { qCCritical(OkularDviDebug) << "Could not allocate memory for a macro table."; exit(0); } // Read macros. avail = availend = NULL; for (; cmnd <= LONG_CHAR; cmnd = one(VF_file)) { macro *m; int len; unsigned long cc; long width; if (cmnd == LONG_CHAR) { /* long form packet */ len = four(VF_file); cc = four(VF_file); width = four(VF_file); if (cc >= 256) { qCCritical(OkularDviDebug) << "Virtual character" << cc << "in font" << fontname << "ignored."; fseek(VF_file, (long) len, 1); continue; } } else { /* short form packet */ len = cmnd; cc = one(VF_file); width = num(VF_file, 3); } m = ¯otable[cc]; m->dvi_advance_in_units_of_design_size_by_2e20 = width; if (len > 0) { if (len <= availend - avail) { m->pos = avail; avail += len; } else { m->free_me = true; if (len <= VF_PARM_1) { m->pos = avail = new unsigned char [VF_PARM_2]; availend = avail + VF_PARM_2; avail += len; } else m->pos = new unsigned char[len]; } fread((char *) m->pos, 1, len, VF_file); m->end = m->pos + len; } } if (cmnd != POST) oops(i18n("Wrong command byte found in VF macro list: %1", cmnd)); fclose (VF_file); file = NULL; }
QOpenGLShaderProgram* ShaderMgr::findOrLoadShader(uint flags) { auto it = m_shaderCache.find(flags); // This may also return Q_NULLPTR if the load failed. //We wait until user explictly forces shader reload until we try again to avoid spamming errors. if(it!=m_shaderCache.end()) return *it; //get shader file names QString vShaderFile = getVShaderName(flags); QString gShaderFile = getGShaderName(flags); QString fShaderFile = getFShaderName(flags); qCDebug(shaderMgr)<<"Loading Scenery3d shader: flags:"<<flags<<", vs:"<<vShaderFile<<", gs:"<<gShaderFile<<", fs:"<<fShaderFile<<""; //load shader files & preprocess QByteArray vShader,gShader,fShader; QOpenGLShaderProgram *prog = Q_NULLPTR; if(preprocessShader(vShaderFile,flags,vShader) && preprocessShader(gShaderFile,flags,gShader) && preprocessShader(fShaderFile,flags,fShader) ) { //check if this content-hash was already created for optimization //(so that shaders with different flags, but identical implementation use the same program) QCryptographicHash hash(QCryptographicHash::Sha256); hash.addData(vShader); hash.addData(gShader); hash.addData(fShader); QByteArray contentHash = hash.result(); if(m_shaderContentCache.contains(contentHash)) { #ifndef NDEBUG //qCDebug(shaderMgr)<<"Using existing shader with content-hash"<<contentHash.toHex(); #endif prog = m_shaderContentCache[contentHash]; } else { //we have to compile the shader prog = new QOpenGLShaderProgram(); if(!loadShader(*prog,vShader,gShader,fShader)) { delete prog; prog = Q_NULLPTR; qCCritical(shaderMgr)<<"ERROR: Shader '"<<flags<<"' could not be compiled. Fix errors and reload shaders or restart program."; } #ifndef NDEBUG else { //qCDebug(shaderMgr)<<"Shader '"<<flags<<"' created, content-hash"<<contentHash.toHex(); } #endif m_shaderContentCache[contentHash] = prog; } } else { qCCritical(shaderMgr)<<"ERROR: Shader '"<<flags<<"' could not be loaded/preprocessed."; } //may put null in cache on fail! m_shaderCache[flags] = prog; return prog; }
QT_USE_NAMESPACE int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription(QLatin1String("winrtrunner installs, runs, and collects test " "results for packages made with Qt.")); parser.addPositionalArgument(QStringLiteral("package [arguments]"), QLatin1String("The executable or package manifest to act upon. " "Arguments after the package name will be passed " "to the application when it starts.")); QCommandLineOption testOption(QStringLiteral("test"), QLatin1String("Install, start, collect output, stop (if needed), " "and uninstall the package. This is the " "default action of winrtrunner.")); parser.addOption(testOption); QCommandLineOption startOption(QStringLiteral("start"), QLatin1String("Start the package. The package is installed if " "it is not already installed. Pass --install to " "force reinstallation.")); parser.addOption(startOption); QCommandLineOption debugOption(QStringLiteral("debug"), QLatin1String("Start the package with the debugger attached. " "The package is installed if it is not already " "installed. Pass --install to force " "reinstallation."), QLatin1Literal("debugger")); parser.addOption(debugOption); QCommandLineOption debuggerArgumentsOption(QStringLiteral("debugger-arguments"), QLatin1String("Arguments that are passed to the " "debugger when --debug is used. If no " "debugger was provided this option is " "ignored."), QLatin1String("arguments")); parser.addOption(debuggerArgumentsOption); QCommandLineOption suspendOption(QStringLiteral("suspend"), QLatin1String("Suspend a running package. When combined " "with --stop or --test, the app will be " "suspended before being terminated.")); parser.addOption(suspendOption); QCommandLineOption stopOption(QStringLiteral("stop"), QLatin1String("Terminate a running package. Can be be " "combined with --start and --suspend.")); parser.addOption(stopOption); QCommandLineOption waitOption(QStringLiteral("wait"), QLatin1String("If the package is running, waits the given " "number of seconds before continuing to the next " "task. Passing 0 causes the runner to wait " "indefinitely."), QStringLiteral("seconds")); parser.addOption(waitOption); QCommandLineOption installOption(QStringLiteral("install"), QStringLiteral("(Re)installs the package.")); parser.addOption(installOption); QCommandLineOption removeOption(QStringLiteral("remove"), QStringLiteral("Uninstalls the package.")); parser.addOption(removeOption); QCommandLineOption deviceOption(QStringLiteral("device"), QLatin1String("Specifies the device to target as a device name " " or index. Use --list-devices to find available " "devices. The default device is the first device " "found for the active run profile."), QStringLiteral("name|index")); parser.addOption(deviceOption); QCommandLineOption profileOption(QStringLiteral("profile"), QStringLiteral("Force a particular run profile."), QStringLiteral("name")); parser.addOption(profileOption); QCommandLineOption listDevicesOption(QStringLiteral("list-devices"), QLatin1String("List the available devices " "(for use with --device).")); parser.addOption(listDevicesOption); QCommandLineOption verbosityOption(QStringLiteral("verbose"), QLatin1String("The verbosity level of the message output " "(0 - silent, 1 - info, 2 - debug). Defaults to 1."), QStringLiteral("level"), QStringLiteral("1")); parser.addOption(verbosityOption); QCommandLineOption ignoreErrorsOption(QStringLiteral("ignore-errors"), QStringLiteral("Always exit with code 0, regardless of the error state.")); parser.addOption(ignoreErrorsOption); parser.addHelpOption(); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); QStringList arguments = QCoreApplication::arguments(); parser.parse(arguments); QStringList filterRules = QStringList() // Default logging rules << QStringLiteral("qt.winrtrunner.warning=true") << QStringLiteral("qt.winrtrunner.critical=true") << QStringLiteral("qt.winrtrunner.app=true"); if (parser.isSet(verbosityOption)) { bool ok; uint verbosity = parser.value(verbosityOption).toUInt(&ok); if (!ok || verbosity > 2) { qCCritical(lcWinRtRunner) << "Incorrect value specified for verbosity."; parser.showHelp(1); } switch (verbosity) { case 2: // Enable debug print filterRules.append(QStringLiteral("qt.winrtrunner.debug=true")); break; case 1: // Remove warnings filterRules.removeFirst(); // fall through case 0: // Silent filterRules.removeFirst(); // fall through default: // Impossible break; } } QLoggingCategory::setFilterRules(filterRules.join(QLatin1Char('\n'))); if (parser.isSet(listDevicesOption)) { std::wcout << "Available devices:\n"; const QMap<QString, QStringList> deviceNames = Runner::deviceNames(); foreach (const QString &profile, deviceNames.keys()) { std::wcout << reinterpret_cast<const wchar_t *>(profile.utf16()) << ":\n"; int index = 0; foreach (const QString &device, deviceNames.value(profile)) { std::wcout << " " << index++ << ' ' << reinterpret_cast<const wchar_t *>(device.utf16()) << '\n'; } } std::wcout << std::endl; return 0; }
void LibretroRunner::commandIn( Command command, QVariant data, qint64 timeStamp ) { // Command is not relayed to children automatically switch( command ) { case Command::Play: { // Make sure we're only connecting LibretroCore to this node if it's a command that only shows up when // emulation is active (in other words, never during loading) if( !connectedToCore ) { connectedToCore = true; qDebug() << "LibretroRunner will now emit signals from LibretroCore"; connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); } qCDebug( phxCore ) << command; libretroCore.state = State::Playing; emit commandOut( Command::Play, QVariant(), nodeCurrentTime() ); break; } case Command::Pause: { if( !connectedToCore ) { connectedToCore = true; qDebug() << "LibretroRunner will now emit signals from LibretroCore"; connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); } qCDebug( phxCore ) << command; libretroCore.state = State::Paused; emit commandOut( Command::Pause, QVariant(), nodeCurrentTime() ); break; } case Command::Stop: { if( !connectedToCore ) { connectedToCore = true; qDebug() << "LibretroRunner will now emit signals from LibretroCore"; connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); } qCDebug( phxCore ) << command; libretroCore.state = State::Unloading; emit commandOut( Command::Unload, QVariant(), nodeCurrentTime() ); // Write SRAM qCInfo( phxCore ) << "=======Saving game...======="; LibretroCoreStoreSaveData(); qCInfo( phxCore ) << "============================"; // Unload core { // symbols.retro_api_version is reasonably expected to be defined if the core is loaded if( libretroCore.symbols.retro_api_version ) { libretroCore.symbols.retro_unload_game(); libretroCore.symbols.retro_deinit(); libretroCore.symbols.clear(); libretroCore.coreFile.unload(); qCDebug( phxCore ) << "Unloaded core successfully"; } else { qCCritical( phxCore ) << "stop() called on an unloaded core!"; } } // Unload game (if we've read its contents into a buffer) { libretroCore.gameData.clear(); } // Disconnect LibretroCore from the rest of the pipeline disconnect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); disconnect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); connectedToCore = false; // Delete the FBO { if( libretroCore.fbo ) { delete libretroCore.fbo; } libretroCore.fbo = nullptr; } // Reset video mode to 2D (will be set to 3D if the next core asks for it) libretroCore.videoFormat.videoMode = SOFTWARERENDER; libretroCore.state = State::Stopped; emit commandOut( Command::Stop, QVariant(), nodeCurrentTime() ); break; } case Command::Heartbeat: { // Drop any heartbeats from too far in the past if( nodeCurrentTime() - timeStamp > 50 ) { return; } emit commandOut( command, data, timeStamp ); if( libretroCore.state == State::Playing ) { // If in 3D mode, lock the mutex before emulating then activate our context and FBO // This is because we're not sure exactly when the core will render to the texture. So, we'll just lock the // mutex for the *entire* frame to be safe and not just from the start of the frame until the video callback // In 2D mode it's simpler: We know that the data will come in a buffer which we can quickly copy within // the video callback. if( libretroCore.videoFormat.videoMode == HARDWARERENDER ) { libretroCore.videoMutex.lock(); //qDebug() << "LibretroRunner lock"; libretroCore.context->makeCurrent( libretroCore.surface ); libretroCore.fbo->bind(); } // Invoke libretro core libretroCore.symbols.retro_run(); // Update rumble state // TODO: Apply per-controller for( GamepadState &gamepad : libretroCore.gamepads ) { if( gamepad.instanceID == -1 || !gamepad.haptic ) { //qDebug() << gamepad.instanceID << ( !gamepad.haptic ) << ( gamepad.hapticID < 0 ); continue; } else if( libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ] != gamepad.fallbackRumbleRequestedStrength ) { //qDebug() << "from" << core.fallbackRumbleCurrentStrength[ gamepad.instanceID ] << "to" << gamepad.fallbackRumbleRequestedStrength; libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ] = gamepad.fallbackRumbleRequestedStrength; SDL_HapticRumbleStop( gamepad.haptic ); if( SDL_HapticRumblePlay( gamepad.haptic, libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ], SDL_HAPTIC_INFINITY ) != 0 ) { qWarning() << gamepad.friendlyName << SDL_GetError(); qWarning().nospace() << gamepad.friendlyName << ": SDL_HapticRumblePlay( " << gamepad.haptic << ", " << libretroCore.fallbackRumbleCurrentStrength << ", SDL_HAPTIC_INFINITY ) != 0, rumble not available"; qWarning() << "SDL:" << SDL_GetError(); } // Reset the requested strength // Implicitly reset by incoming Gamepads overwriting the value set by us with the default of 0.0 // gamepad.fallbackRumbleRequestedStrength = 0.0; } } if( libretroCore.videoFormat.videoMode == HARDWARERENDER ) { libretroCore.context->makeCurrent( libretroCore.surface ); libretroCore.context->functions()->glFlush(); libretroCore.context->doneCurrent(); //qDebug() << "LibretroRunner unlock"; libretroCore.videoMutex.unlock(); } // Flush stderr, some cores may still write to it despite having RETRO_LOG fflush( stderr ); } break; } case Command::SetWindowGeometry: { emit commandOut( command, data, timeStamp ); libretroCore.windowGeometry = data.toRect(); emit commandOut( command, data, timeStamp ); break; } case Command::SetAspectRatioMode: { libretroCore.aspectMode = data.toInt(); emit commandOut( command, data, timeStamp ); break; } case Command::SetLibretroVariable: { LibretroVariable var = data.value<LibretroVariable>(); libretroCore.variables.insert( var.key(), var ); libretroCore.variablesAreDirty = true; emit commandOut( command, data, timeStamp ); break; } case Command::AddController: { if( !connectedToCore ) { connectedToCore = true; qDebug() << "LibretroRunner will now emit signals from LibretroCore"; connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); } GamepadState gamepad = data.value<GamepadState>(); int instanceID = gamepad.instanceID; libretroCore.fallbackRumbleCurrentStrength[ instanceID ] = 0.0; emit commandOut( command, data, timeStamp ); break; } case Command::RemoveController: { if( !connectedToCore ) { connectedToCore = true; qDebug() << "LibretroRunner will now emit signals from LibretroCore"; connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut ); connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut ); } GamepadState gamepad = data.value<GamepadState>(); int instanceID = gamepad.instanceID; libretroCore.gamepads.remove( instanceID ); emit commandOut( command, data, timeStamp ); break; } default: { emit commandOut( command, data, timeStamp ); break; } } }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); app.setApplicationName("Icecream Server"); app.setApplicationVersion(ICECREAM_SERVER_VERSION); app.setOrganizationName("Jan Dalheimer"); QLoggingCategory::installFilter(&loggingFilter); qInstallMessageHandler(&messageHandler); qAddPostRoutine(&cleanup); QCommandLineParser parser; parser.setApplicationDescription(QObject::tr("The default server implementation for the Icecream voxel game")); parser.addHelpOption(); parser.addVersionOption(); parser.addOption(QCommandLineOption("pluginspath", "Path to the plugins folder", "PATH", "plugins/")); parser.addOption(QCommandLineOption("configspath", "Path to the configs folder", "PATH", "configs/")); parser.addOption(QCommandLineOption("save", "Path to the save to load", "PATH")); parser.addOption(QCommandLineOption("singleplayer", "Only the specified user may join", "USER")); parser.addOption(QCommandLineOption("port", "Set an explicit port", "PORT", "0")); parser.process(app); if (!parser.isSet("save")) { qCCritical(LOG_GENERAL) << "You need to specify a save"; parser.showHelp(-1); } if (parser.isSet("port")) { bool ok = true; parser.value("port").toLongLong(&ok); if (!ok) { qCCritical(LOG_GENERAL) << "The specified port is not parsable as an integer"; parser.showHelp(-1); } } QObject *root = new QObject; AI::AIManager::instance = new AI::AIManager(root); Cache::CacheManager::instance = new Cache::CacheManager(root); Entities::EntityManager::instance = new Entities::EntityManager(root); Network::NetworkManager::instance = new Network::NetworkManager(root, parser.value("port").toLongLong(), parser.value("singleplayer")); Permissions::PermissionManager::instance = new Permissions::PermissionManager(root); Physics::PhysicsManager::instance = new Physics::PhysicsManager(root); Plugins::PluginManager::instance = new Plugins::PluginManager(root, QDir(parser.value("pluginspath"))); Saves::SaveManager::instance = new Saves::SaveManager(root, QDir(parser.value("save"))); qCDebug(LOG_GENERAL) << "All managers ready"; InputHandler *inputHandler = new InputHandler; QObject::connect(inputHandler, &InputHandler::command, [](const QString &cmd) { Permissions::PermissionManager::instance->command(QString(), cmd); }); inputHandler->start(); Plugins::PluginManager::instance->discoverPlugins(); Network::NetworkManager::instance->startServer(); qCDebug(LOG_GENERAL) << "Init done. Running server"; int ret = app.exec(); qCDebug(LOG_GENERAL) << "Shutting down"; return ret; }
void Baker::handleError(const QString& error) { qCCritical(model_baking).noquote() << error; _errorList.append(error); setIsFinished(true); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //![2] QLoggingCategory::setFilterRules(QStringLiteral("qt.driver.usb.debug=true")); //![2] //![22] // ... oldCategoryFilter = QLoggingCategory::installFilter(myCategoryFilter); //![22] //![3] qSetMessagePattern("%{category} %{message}"); //![3] //![4] // usbEntries() will only be called if QT_DRIVER_USB category is enabled qCDebug(QT_DRIVER_USB) << "devices: " << usbEntries(); //![4] { //![10] QLoggingCategory category("qt.driver.usb"); qCDebug(category) << "a debug message"; //![10] } { //![11] QLoggingCategory category("qt.driver.usb"); qCWarning(category) << "a warning message"; //![11] } { //![12] QLoggingCategory category("qt.driver.usb"); qCCritical(category) << "a critical message"; //![12] } { //![13] QLoggingCategory category("qt.driver.usb"); qCDebug(category, "a debug message logged into category %s", category.categoryName()); //![13] } { //![14] QLoggingCategory category("qt.driver.usb"); qCWarning(category, "a warning message logged into category %s", category.categoryName()); //![14] } { //![15] QLoggingCategory category("qt.driver.usb"); qCCritical(category, "a critical message logged into category %s", category.categoryName()); //![15] } return 0; }
static AnimNode::Pointer loadNode(const QJsonObject& jsonObj, const QUrl& jsonUrl) { auto idVal = jsonObj.value("id"); if (!idVal.isString()) { qCCritical(animation) << "AnimNodeLoader, bad string \"id\""; return nullptr; } QString id = idVal.toString(); auto typeVal = jsonObj.value("type"); if (!typeVal.isString()) { qCCritical(animation) << "AnimNodeLoader, bad object \"type\", id =" << id; return nullptr; } QString typeStr = typeVal.toString(); AnimNode::Type type = stringToAnimNodeType(typeStr); if (type == AnimNode::Type::NumTypes) { qCCritical(animation) << "AnimNodeLoader, unknown node type" << typeStr << ", id =" << id; return nullptr; } auto dataValue = jsonObj.value("data"); if (!dataValue.isObject()) { qCCritical(animation) << "AnimNodeLoader, bad string \"data\", id =" << id; return nullptr; } auto dataObj = dataValue.toObject(); std::vector<QString> outputJoints; auto outputJoints_VAL = dataObj.value("outputJoints"); if (outputJoints_VAL.isArray()) { QJsonArray outputJoints_ARRAY = outputJoints_VAL.toArray(); for (int i = 0; i < outputJoints_ARRAY.size(); i++) { outputJoints.push_back(outputJoints_ARRAY.at(i).toString()); } } assert((int)type >= 0 && type < AnimNode::Type::NumTypes); auto node = (animNodeTypeToLoaderFunc(type))(dataObj, id, jsonUrl); if (!node) { return nullptr; } auto childrenValue = jsonObj.value("children"); if (!childrenValue.isArray()) { qCCritical(animation) << "AnimNodeLoader, bad array \"children\", id =" << id; return nullptr; } auto childrenArray = childrenValue.toArray(); for (const auto& childValue : childrenArray) { if (!childValue.isObject()) { qCCritical(animation) << "AnimNodeLoader, bad object in \"children\", id =" << id; return nullptr; } AnimNode::Pointer child = loadNode(childValue.toObject(), jsonUrl); if (child) { node->addChild(child); } else { return nullptr; } } if ((animNodeTypeToProcessFunc(type))(node, dataObj, id, jsonUrl)) { for (auto&& outputJoint : outputJoints) { node->addOutputJoint(outputJoint); } return node; } else { return nullptr; } }
void Sound::soundProcessError(int error, QString str) { qCCritical(audio) << "Failed to process sound file" << _url.toDisplayString() << "code =" << error << str; emit failed(QNetworkReply::UnknownContentError); finishedLoading(false); }
bool processStateMachineNode(AnimNode::Pointer node, const QJsonObject& jsonObj, const QString& nodeId, const QUrl& jsonUrl) { auto smNode = std::static_pointer_cast<AnimStateMachine>(node); assert(smNode); READ_STRING(currentState, jsonObj, nodeId, jsonUrl, false); auto statesValue = jsonObj.value("states"); if (!statesValue.isArray()) { qCCritical(animation) << "AnimNodeLoader, bad array \"states\" in stateMachine node, id =" << nodeId; return false; } // build a map for all children by name. std::map<QString, int> childMap; buildChildMap(childMap, node); // first pass parse all the states and build up the state and transition map. using StringPair = std::pair<QString, QString>; using TransitionMap = std::multimap<AnimStateMachine::State::Pointer, StringPair>; TransitionMap transitionMap; using StateMap = std::map<QString, AnimStateMachine::State::Pointer>; StateMap stateMap; auto statesArray = statesValue.toArray(); for (const auto& stateValue : statesArray) { if (!stateValue.isObject()) { qCCritical(animation) << "AnimNodeLoader, bad state object in \"states\", id =" << nodeId; return false; } auto stateObj = stateValue.toObject(); READ_STRING(id, stateObj, nodeId, jsonUrl, false); READ_FLOAT(interpTarget, stateObj, nodeId, jsonUrl, false); READ_FLOAT(interpDuration, stateObj, nodeId, jsonUrl, false); READ_OPTIONAL_STRING(interpType, stateObj); READ_OPTIONAL_STRING(interpTargetVar, stateObj); READ_OPTIONAL_STRING(interpDurationVar, stateObj); READ_OPTIONAL_STRING(interpTypeVar, stateObj); auto iter = childMap.find(id); if (iter == childMap.end()) { qCCritical(animation) << "AnimNodeLoader, could not find stateMachine child (state) with nodeId =" << nodeId << "stateId =" << id; return false; } AnimStateMachine::InterpType interpTypeEnum = AnimStateMachine::InterpType::SnapshotPrev; // default value if (!interpType.isEmpty()) { interpTypeEnum = stringToInterpType(interpType); if (interpTypeEnum == AnimStateMachine::InterpType::NumTypes) { qCCritical(animation) << "AnimNodeLoader, bad interpType on stateMachine state, nodeId = " << nodeId << "stateId =" << id; return false; } } auto statePtr = std::make_shared<AnimStateMachine::State>(id, iter->second, interpTarget, interpDuration, interpTypeEnum); assert(statePtr); if (!interpTargetVar.isEmpty()) { statePtr->setInterpTargetVar(interpTargetVar); } if (!interpDurationVar.isEmpty()) { statePtr->setInterpDurationVar(interpDurationVar); } if (!interpTypeVar.isEmpty()) { statePtr->setInterpTypeVar(interpTypeVar); } smNode->addState(statePtr); stateMap.insert(StateMap::value_type(statePtr->getID(), statePtr)); auto transitionsValue = stateObj.value("transitions"); if (!transitionsValue.isArray()) { qCritical(animation) << "AnimNodeLoader, bad array \"transitions\" in stateMachine node, stateId =" << id << "nodeId =" << nodeId; return false; } auto transitionsArray = transitionsValue.toArray(); for (const auto& transitionValue : transitionsArray) { if (!transitionValue.isObject()) { qCritical(animation) << "AnimNodeLoader, bad transition object in \"transtions\", stateId =" << id << "nodeId =" << nodeId; return false; } auto transitionObj = transitionValue.toObject(); READ_STRING(var, transitionObj, nodeId, jsonUrl, false); READ_STRING(state, transitionObj, nodeId, jsonUrl, false); transitionMap.insert(TransitionMap::value_type(statePtr, StringPair(var, state))); } } // second pass: now iterate thru all transitions and add them to the appropriate states. for (auto& transition : transitionMap) { AnimStateMachine::State::Pointer srcState = transition.first; auto iter = stateMap.find(transition.second.second); if (iter != stateMap.end()) { srcState->addTransition(AnimStateMachine::State::Transition(transition.second.first, iter->second)); } else { qCCritical(animation) << "AnimNodeLoader, bad state machine transtion from srcState =" << srcState->_id << "dstState =" << transition.second.second << "nodeId =" << nodeId; return false; } } auto iter = stateMap.find(currentState); if (iter == stateMap.end()) { qCCritical(animation) << "AnimNodeLoader, bad currentState =" << currentState << "could not find child node" << "id =" << nodeId; } smNode->setCurrentState(iter->second); return true; }
void throw_exception(std::exception const &e) { qCCritical(GRAPHTHEORY_FILEFORMAT) << "Exception:" << e.what(); }
bool MemoryFrame::deallocate(MemoryAllocation* memoryAllocation) { // ToDo: implement deallocation qCCritical(logTemporary) << "Memory Frame: Deallocating" << memoryAllocation->name << "releasing" << memoryAllocation->size << "bytes"; return true; }
bool MetaEngine::Private::saveToFile(const QFileInfo& finfo) const { if (!finfo.isWritable()) { qCDebug(DIGIKAM_METAENGINE_LOG) << "File" << finfo.fileName() << "is read only. Metadata not written."; return false; } QStringList rawTiffBasedSupported, rawTiffBasedNotSupported; // Raw files supported by Exiv2 0.21 rawTiffBasedSupported << QString::fromLatin1("dng") << QString::fromLatin1("nef") << QString::fromLatin1("pef") << QString::fromLatin1("orf") << QString::fromLatin1("srw"); if (Exiv2::testVersion(0,23,0)) { rawTiffBasedSupported << QString::fromLatin1("cr2"); } // Raw files not supported by Exiv2 0.21 rawTiffBasedNotSupported << QString::fromLatin1("3fr") << QString::fromLatin1("arw") << QString::fromLatin1("dcr") << QString::fromLatin1("erf") << QString::fromLatin1("k25") << QString::fromLatin1("kdc") << QString::fromLatin1("mos") << QString::fromLatin1("raw") << QString::fromLatin1("sr2") << QString::fromLatin1("srf") << QString::fromLatin1("rw2"); if (!Exiv2::testVersion(0,23,0)) { rawTiffBasedNotSupported << QString::fromLatin1("cr2"); } QString ext = finfo.suffix().toLower(); if (!writeRawFiles && (rawTiffBasedSupported.contains(ext) || rawTiffBasedNotSupported.contains(ext)) ) { qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName() << "is a TIFF based RAW file, writing to such a file is disabled by current settings."; return false; } /* if (rawTiffBasedNotSupported.contains(ext)) { qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName() << "is TIFF based RAW file not yet supported. Metadata not saved."; return false; } if (rawTiffBasedSupported.contains(ext) && !writeRawFiles) { qCDebug(DIGIKAM_METAENGINE_LOG) << finfo.fileName() << "is TIFF based RAW file supported but writing mode is disabled. " << "Metadata not saved."; return false; } qCDebug(DIGIKAM_METAENGINE_LOG) << "File Extension: " << ext << " is supported for writing mode"; bool ret = false; */ try { Exiv2::Image::AutoPtr image; image = Exiv2::ImageFactory::open((const char*)(QFile::encodeName(finfo.filePath()).constData())); return saveOperations(finfo, image); } catch( Exiv2::Error& e ) { printExiv2ExceptionError(QString::fromLatin1("Cannot save metadata to image using Exiv2 "), e); return false; } catch(...) { qCCritical(DIGIKAM_METAENGINE_LOG) << "Default exception from Exiv2"; return false; } }