void MainWindow::updateWindowTitle() { // setWindowTitle() requires "[*]" (see docs) const TabData& gameData(m_tabs.at(m_tabBar->currentIndex())); setWindowTitle(genericTitle(gameData) + QLatin1String("[*]")); }
void QDeclarativeTester::save() { QString filename = m_script + QLatin1String(".qml"); QFileInfo filenameInfo(filename); QDir saveDir = filenameInfo.absoluteDir(); saveDir.mkpath(QLatin1String(".")); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream ts(&file); ts << "import Qt.VisualTest 4.7\n\n"; ts << "VisualTest {\n"; int imgCount = 0; QList<KeyEvent> keyevents = m_savedKeyEvents; QList<MouseEvent> mouseevents = m_savedMouseEvents; for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) { const FrameEvent &fe = m_savedFrameEvents.at(ii); ts << " Frame {\n"; ts << " msec: " << fe.msec << "\n"; if (!fe.hash.isEmpty()) { ts << " hash: \"" << fe.hash.toHex() << "\"\n"; } else if (!fe.image.isNull()) { QString filename = filenameInfo.baseName() + QLatin1String(".") + QString::number(imgCount) + QLatin1String(".png"); fe.image.save(m_script + QLatin1String(".") + QString::number(imgCount) + QLatin1String(".png")); imgCount++; ts << " image: \"" << filename << "\"\n"; } ts << " }\n"; while (!mouseevents.isEmpty() && mouseevents.first().msec == fe.msec) { MouseEvent me = mouseevents.takeFirst(); ts << " Mouse {\n"; ts << " type: " << me.type << "\n"; ts << " button: " << me.button << "\n"; ts << " buttons: " << me.buttons << "\n"; ts << " x: " << me.pos.x() << "; y: " << me.pos.y() << "\n"; ts << " modifiers: " << me.modifiers << "\n"; if (me.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } while (!keyevents.isEmpty() && keyevents.first().msec == fe.msec) { KeyEvent ke = keyevents.takeFirst(); ts << " Key {\n"; ts << " type: " << ke.type << "\n"; ts << " key: " << ke.key << "\n"; ts << " modifiers: " << ke.modifiers << "\n"; ts << " text: \"" << ke.text.toUtf8().toHex() << "\"\n"; ts << " autorep: " << (ke.autorep?"true":"false") << "\n"; ts << " count: " << ke.count << "\n"; if (ke.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } } ts << "}\n"; file.close(); }
/*! * Parses a APIGateway GetDocumentationVersions response element from \a xml. */ void GetDocumentationVersionsResponsePrivate::parseGetDocumentationVersionsResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("GetDocumentationVersionsResponse")); Q_UNUSED(xml) ///< @todo }
// Default Implementation bool WindowManager::openDisplayImpl(QString *errorMessage) { *errorMessage = QLatin1String("Not implemented."); return false; }
bool WindowManager::sendCloseEventImpl(const QString &, Q_PID, QString *errorMessage) { *errorMessage = QLatin1String("Not implemented."); return false; }
/*! \fn Ebackup::generar_config() Genera un una copia de los valores de configuracion del programa y los prepara para la compresion. */ bool Ebackup::generar_config() { preferencias *p = preferencias::getInstancia(); // Obtengo todas las claves QStringList claves = p->allKeys(); PBProgreso->setRange( 0, ( claves.size() * 2 ) + 2 ); PBProgreso->setValue( 0 ); // Genero los datos concatenando las variables // Inicio de preferencias // Cabecera de los datos datos->append("|->preferencias->"); // bucle que recorre cada valor QStringList::const_iterator iterador; for( iterador = claves.constBegin(); iterador != claves.constEnd(); ++iterador ) { if( !_continuar ) { return false; } datos->append( (*iterador).toLocal8Bit().constData() ); PBProgreso->setValue( PBProgreso->value() + 1 ); datos->append( "=" ); // Separador de valores QVariant v = p->value( (*iterador), QVariant() ); QString result; switch( v.type() ) { /////////////////////////////////////////////////////////////////////////// // Copiado desde la clase qsettings de qt case QVariant::Invalid: { result = QLatin1String("@Invalid()"); break; } case QVariant::ByteArray: { QByteArray a = v.toByteArray(); result = QLatin1String("@ByteArray("); result += QString::fromLatin1(a.constData(), a.size()); result += QLatin1Char(')'); break; } case QVariant::String: case QVariant::LongLong: case QVariant::ULongLong: case QVariant::Int: case QVariant::UInt: case QVariant::Bool: case QVariant::Double: case QVariant::KeySequence: { result = v.toString(); if (result.startsWith(QLatin1Char('@'))) result.prepend(QLatin1Char('@')); break; } case QVariant::Rect: { QRect r = qvariant_cast<QRect>(v); result += QLatin1String("@Rect("); result += QString::number(r.x()); result += QLatin1Char(' '); result += QString::number(r.y()); result += QLatin1Char(' '); result += QString::number(r.width()); result += QLatin1Char(' '); result += QString::number(r.height()); result += QLatin1Char(')'); break; } case QVariant::Size: { QSize s = qvariant_cast<QSize>(v); result += QLatin1String("@Size("); result += QString::number(s.width()); result += QLatin1Char(' '); result += QString::number(s.height()); result += QLatin1Char(')'); break; } case QVariant::Point: { QPoint p = qvariant_cast<QPoint>(v); result += QLatin1String("@Point("); result += QString::number(p.x()); result += QLatin1Char(' '); result += QString::number(p.y()); result += QLatin1Char(')'); break; } default: { QByteArray a; { QDataStream s(&a, QIODevice::WriteOnly); s.setVersion(QDataStream::Qt_4_0); s << v; } result = QLatin1String("@Variant("); result += QString::fromLatin1(a.constData(), a.size()); result += QLatin1Char(')'); break; } ////////////////////////////////////////////////////////////////////////////// } datos->append( result ); PBProgreso->setValue( PBProgreso->value() + 1 ); // Separador de preferencia datos->append( "\n" ); } // fin de los datos datos->append("<-preferencias<-|"); // Comprimo los datos y los envio al buffer de comprimidos LDebug->setText( LDebug->text() + "... Comprimiendo.... " ); comprimir(); PBProgreso->setValue( PBProgreso->value() + 1 ); // Limpio el buffer asi se libera la memoria LDebug->setText( LDebug->text() + "... Limpiando.... " ); datos->clear(); PBProgreso->setValue( PBProgreso->value() + 1 ); LDebug->setText( "Listo backup de configuracion" ); return true; }
/*! * Parses a AppSync DeleteType response element from \a xml. */ void DeleteTypeResponsePrivate::parseDeleteTypeResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("DeleteTypeResponse")); Q_UNUSED(xml) ///< @todo }
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); int res = 0; QString appIni; QHash<QString, QString> args = convertArgs(QCoreApplication::arguments()); if (!args.value("-f").isEmpty()) { appIni = args.value("-f"); devIni = QFileInfo(appIni).dir().path() + QDir::separator() + "development.ini"; } else { QString dir = QLatin1String("..") + QDir::separator() + QLatin1String("..") + QDir::separator() + "config" + QDir::separator(); appIni = dir + "application.ini"; devIni = dir + "development.ini"; } if (!QFile::exists(appIni)) { usage(); return 1; } QSettings appSetting(appIni, QSettings::IniFormat); QSettings devSetting(devIni, QSettings::IniFormat); // Default codec QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QString codecName = appSetting.value("InternalEncoding").toString(); if (!codecName.isEmpty()) { QTextCodec *c = QTextCodec::codecForName(codecName.toLatin1().constData()); if (c) { codec = c; } } QTextCodec::setCodecForLocale(codec); defaultTrimMode = devSetting.value("Erb.DefaultTrimMode", "1").toInt(); printf("Erb.DefaultTrimMode: %d\n", defaultTrimMode); QDir viewDir("."); if (!args.value("-v").isEmpty()) { viewDir.setPath(args.value("-v")); } if (!viewDir.exists()) { usage(); return 1; } QDir outputDir(DEFAULT_OUTPUT_DIR); if (!args.value("-d").isEmpty()) { outputDir.setPath(args.value("-d")); } if (outputDir.exists()) { if (outputDir.path() != ".") { printf(" exists %s\n", qPrintable(outputDir.path())); } } else { if (outputDir.mkpath(".")) { printf(" created %s\n", qPrintable(outputDir.path())); } else { usage(); return 1; } } bool createProFile = (args.contains("-p") || !args.contains("-P")); ViewConverter conv(viewDir, outputDir, createProFile); QString templateSystem = devSetting.value("TemplateSystem").toString(); if (templateSystem.isEmpty()) { templateSystem = appSetting.value("TemplateSystem", "Erb").toString(); } res = conv.convertView(templateSystem); return res; }
/** * Saves the widget to the "boxwidget" XMI element. * Note: For loading from XMI, the inherited parent method is used. */ void BoxWidget::saveToXMI(QDomDocument& qDoc, QDomElement& qElement) { QDomElement boxElement = qDoc.createElement(QLatin1String("boxwidget")); UMLWidget::saveToXMI(qDoc, boxElement); qElement.appendChild(boxElement); }
bool SyncJournalDb::updateMetadataTableStructure() { QStringList columns = tableColumns("metadata"); bool re = true; // check if the file_id column is there and create it if not if( !checkConnect() ) { return false; } if( columns.indexOf(QLatin1String("fileid")) == -1 ) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN fileid VARCHAR(128);"); if( !query.exec() ) { sqlFail("updateMetadataTableStructure: Add column fileid", query); re = false; } query.prepare("CREATE INDEX metadata_file_id ON metadata(fileid);"); if( ! query.exec() ) { sqlFail("updateMetadataTableStructure: create index fileid", query); re = false; } commitInternal("update database structure: add fileid col"); } if( columns.indexOf(QLatin1String("remotePerm")) == -1 ) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN remotePerm VARCHAR(128);"); if( !query.exec()) { sqlFail("updateMetadataTableStructure: add column remotePerm", query); re = false; } commitInternal("update database structure (remotePerm)"); } if( columns.indexOf(QLatin1String("filesize")) == -1 ) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN filesize BIGINT;"); if( !query.exec()) { sqlFail("updateDatabaseStructure: add column filesize", query); re = false; } commitInternal("update database structure: add filesize col"); } if( 1 ) { SqlQuery query(_db); query.prepare("CREATE INDEX IF NOT EXISTS metadata_inode ON metadata(inode);"); if( !query.exec()) { sqlFail("updateMetadataTableStructure: create index inode", query); re = false; } commitInternal("update database structure: add inode index"); } if( 1 ) { SqlQuery query(_db); query.prepare("CREATE INDEX IF NOT EXISTS metadata_path ON metadata(path);"); if( !query.exec()) { sqlFail("updateMetadataTableStructure: create index path", query); re = false; } commitInternal("update database structure: add path index"); } if( columns.indexOf(QLatin1String("ignoredChildrenRemote")) == -1 ) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN ignoredChildrenRemote INT;"); if( !query.exec()) { sqlFail("updateMetadataTableStructure: add ignoredChildrenRemote column", query); re = false; } commitInternal("update database structure: add ignoredChildrenRemote col"); } return re; }
QStringList QM3uPlaylistPlugin::keys() const { return QStringList() << QLatin1String("m3u"); }
bool SyncJournalDb::checkConnect() { if( _db.isOpen() ) { return true; } if( _dbFile.isEmpty()) { qDebug() << "Database filename" + _dbFile + " is empty"; return false; } bool isNewDb = !QFile::exists(_dbFile); // The database file is created by this call (SQLITE_OPEN_CREATE) if( !_db.openOrCreateReadWrite(_dbFile) ) { QString error = _db.error(); qDebug() << "Error opening the db: " << error; return false; } if( !QFile::exists(_dbFile) ) { qDebug() << "Database file" + _dbFile + " does not exist"; return false; } SqlQuery pragma1(_db); pragma1.prepare("SELECT sqlite_version();"); if (!pragma1.exec()) { return sqlFail("SELECT sqlite_version()", pragma1); } else { pragma1.next(); qDebug() << "sqlite3 version" << pragma1.stringValue(0); } // Allow forcing the journal mode for debugging static QString env_journal_mode = QString::fromLocal8Bit(qgetenv("OWNCLOUD_SQLITE_JOURNAL_MODE")); QString journal_mode = env_journal_mode; if (journal_mode.isEmpty()) { journal_mode = defaultJournalMode(_dbFile); } pragma1.prepare(QString("PRAGMA journal_mode=%1;").arg(journal_mode)); if (!pragma1.exec()) { return sqlFail("Set PRAGMA journal_mode", pragma1); } else { pragma1.next(); qDebug() << "sqlite3 journal_mode=" << pragma1.stringValue(0); } // For debugging purposes, allow temp_store to be set static QString env_temp_store = QString::fromLocal8Bit(qgetenv("OWNCLOUD_SQLITE_TEMP_STORE")); if (!env_temp_store.isEmpty()) { pragma1.prepare(QString("PRAGMA temp_store = %1;").arg(env_temp_store)); if (!pragma1.exec()) { return sqlFail("Set PRAGMA temp_store", pragma1); } qDebug() << "sqlite3 with temp_store =" << env_temp_store; } pragma1.prepare("PRAGMA synchronous = 1;"); if (!pragma1.exec()) { return sqlFail("Set PRAGMA synchronous", pragma1); } pragma1.prepare("PRAGMA case_sensitive_like = ON;"); if (!pragma1.exec()) { return sqlFail("Set PRAGMA case_sensitivity", pragma1); } /* Because insert is so slow, we do everything in a transaction, and only need one call to commit */ startTransaction(); SqlQuery createQuery(_db); createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata(" "phash INTEGER(8)," "pathlen INTEGER," "path VARCHAR(4096)," "inode INTEGER," "uid INTEGER," "gid INTEGER," "mode INTEGER," "modtime INTEGER(8)," "type INTEGER," "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */ // updateDatabaseStructure() will add a fileid column // updateDatabaseStructure() will add a remotePerm column "PRIMARY KEY(phash)" ");"); if (!createQuery.exec()) { return sqlFail("Create table metadata", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo(" "path VARCHAR(4096)," "tmpfile VARCHAR(4096)," "etag VARCHAR(32)," "errorcount INTEGER," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table downloadinfo", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo(" "path VARCHAR(4096)," "chunk INTEGER," "transferid INTEGER," "errorcount INTEGER," "size INTEGER(8)," "modtime INTEGER(8)," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table uploadinfo", createQuery); } // create the blacklist table. createQuery.prepare("CREATE TABLE IF NOT EXISTS blacklist (" "path VARCHAR(4096)," "lastTryEtag VARCHAR[32]," "lastTryModtime INTEGER[8]," "retrycount INTEGER," "errorstring VARCHAR[4096]," "PRIMARY KEY(path)" ");"); if (!createQuery.exec()) { return sqlFail("Create table blacklist", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS poll(" "path VARCHAR(4096)," "modtime INTEGER(8)," "pollpath VARCHAR(4096));"); if (!createQuery.exec()) { return sqlFail("Create table poll", createQuery); } // create the selectivesync table. createQuery.prepare("CREATE TABLE IF NOT EXISTS selectivesync (" "path VARCHAR(4096)," "type INTEGER" ");"); if (!createQuery.exec()) { return sqlFail("Create table selectivesync", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS version(" "major INTEGER(8)," "minor INTEGER(8)," "patch INTEGER(8)," "custom VARCHAR(256)" ");"); if (!createQuery.exec()) { return sqlFail("Create table version", createQuery); } bool forceRemoteDiscovery = false; SqlQuery versionQuery("SELECT major, minor, patch FROM version;", _db); if (!versionQuery.next()) { // If there was no entry in the table, it means we are likely upgrading from 1.5 if (!isNewDb) { qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_5 detected!"; forceRemoteDiscovery = true; } createQuery.prepare("INSERT INTO version VALUES (?1, ?2, ?3, ?4);"); createQuery.bindValue(1, MIRALL_VERSION_MAJOR); createQuery.bindValue(2, MIRALL_VERSION_MINOR); createQuery.bindValue(3, MIRALL_VERSION_PATCH); createQuery.bindValue(4, MIRALL_VERSION_BUILD); createQuery.exec(); } else { int major = versionQuery.intValue(0); int minor = versionQuery.intValue(1); int patch = versionQuery.intValue(2); if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) { qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_8_0_or_1 detected!"; forceRemoteDiscovery = true; } // Not comparing the BUILD id here, correct? if( !(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH) ) { createQuery.prepare("UPDATE version SET major=?1, minor=?2, patch =?3, custom=?4 " "WHERE major=?5 AND minor=?6 AND patch=?7;"); createQuery.bindValue(1, MIRALL_VERSION_MAJOR); createQuery.bindValue(2, MIRALL_VERSION_MINOR); createQuery.bindValue(3, MIRALL_VERSION_PATCH); createQuery.bindValue(4, MIRALL_VERSION_BUILD); createQuery.bindValue(5, major); createQuery.bindValue(6, minor); createQuery.bindValue(7, patch); if (!createQuery.exec()) { return sqlFail("Update version", createQuery); } } } commitInternal("checkConnect"); bool rc = updateDatabaseStructure(); if( !rc ) { qDebug() << "WARN: Failed to update the database structure!"; } /* * If we are upgrading from a client version older than 1.5, * we cannot read from the database because we need to fetch the files id and etags. * * If 1.8.0 caused missing data in the local tree, so we also don't read from DB * to get back the files that were gone. * In 1.8.1 we had a fix to re-get the data, but this one here is better */ if (forceRemoteDiscovery) { forceRemoteDiscoveryNextSyncLocked(); } _getFileRecordQuery.reset(new SqlQuery(_db)); _getFileRecordQuery->prepare("SELECT path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote FROM " "metadata WHERE phash=?1" ); _setFileRecordQuery.reset(new SqlQuery(_db) ); _setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata " "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote) " "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7, ?8 , ?9 , ?10, ?11, ?12, ?13, ?14);" ); _getDownloadInfoQuery.reset(new SqlQuery(_db) ); _getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM " "downloadinfo WHERE path=?1" ); _setDownloadInfoQuery.reset(new SqlQuery(_db) ); _setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo " "(path, tmpfile, etag, errorcount) " "VALUES ( ?1 , ?2, ?3, ?4 )" ); _deleteDownloadInfoQuery.reset(new SqlQuery(_db) ); _deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?1" ); _getUploadInfoQuery.reset(new SqlQuery(_db)); _getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM " "uploadinfo WHERE path=?1" ); _setUploadInfoQuery.reset(new SqlQuery(_db)); _setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo " "(path, chunk, transferid, errorcount, size, modtime) " "VALUES ( ?1 , ?2, ?3 , ?4 , ?5, ?6 )"); _deleteUploadInfoQuery.reset(new SqlQuery(_db)); _deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1" ); _deleteFileRecordPhash.reset(new SqlQuery(_db)); _deleteFileRecordPhash->prepare("DELETE FROM metadata WHERE phash=?1"); _deleteFileRecordRecursively.reset(new SqlQuery(_db)); _deleteFileRecordRecursively->prepare("DELETE FROM metadata WHERE path LIKE(?||'/%')"); QString sql( "SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration " "FROM blacklist WHERE path=?1"); if( Utility::fsCasePreserving() ) { // if the file system is case preserving we have to check the blacklist // case insensitively sql += QLatin1String(" COLLATE NOCASE"); } _getErrorBlacklistQuery.reset(new SqlQuery(_db)); _getErrorBlacklistQuery->prepare(sql); _setErrorBlacklistQuery.reset(new SqlQuery(_db)); _setErrorBlacklistQuery->prepare("INSERT OR REPLACE INTO blacklist " "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration) " "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7)"); _getSelectiveSyncListQuery.reset(new SqlQuery(_db)); _getSelectiveSyncListQuery->prepare("SELECT path FROM selectivesync WHERE type=?1"); // don't start a new transaction now commitInternal(QString("checkConnect End"), false); // Hide 'em all! FileSystem::setFileHidden(databaseFilePath(), true); FileSystem::setFileHidden(databaseFilePath() + "-wal", true); FileSystem::setFileHidden(databaseFilePath() + "-shm", true); FileSystem::setFileHidden(databaseFilePath() + "-journal", true); return rc; }
bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) { Q_D(QFSFileEngine); Q_ASSERT(!isReallyOpen()); openMode |= QIODevice::ReadWrite; if (!filePathIsTemplate) return QFSFileEngine::open(openMode); QString qfilename = d->fileEntry.filePath(); // Ensure there is a placeholder mask uint phPos = qfilename.length(); uint phLength = 0; while (phPos != 0) { --phPos; if (qfilename[phPos] == QLatin1Char('X')) { ++phLength; continue; } if (phLength >= 6 || qfilename[phPos] == QLatin1Char('/')) { ++phPos; break; } // start over phLength = 0; } if (phLength < 6) qfilename.append(QLatin1String(".XXXXXX")); // "Nativify" :-) QFileSystemEntry::NativePath filename = QFileSystemEngine::absoluteName( QFileSystemEntry(qfilename, QFileSystemEntry::FromInternalPath())) .nativeFilePath(); // Find mask in native path phPos = filename.length(); phLength = 0; while (phPos != 0) { --phPos; if (filename[phPos] == Latin1Char('X')) { ++phLength; continue; } if (phLength >= 6) { ++phPos; break; } // start over phLength = 0; } Q_ASSERT(phLength >= 6); QSystemError error; #if defined(Q_OS_WIN) NativeFileHandle &file = d->fileHandle; #elif defined(Q_OS_SYMBIAN) NativeFileHandle &file = d->symbianFile; #else // POSIX NativeFileHandle &file = d->fd; #endif if (!createFileFromTemplate(file, filename, phPos, phLength, error)) { setError(QFile::OpenError, error.toString()); return false; } d->fileEntry = QFileSystemEntry(filename, QFileSystemEntry::FromNativePath()); #if !defined(Q_OS_WIN) d->closeFileHandle = true; #endif filePathIsTemplate = false; d->openMode = openMode; d->lastFlushFailed = false; d->tried_stat = 0; return true; }
FlexStyle::FlexStyle(QStyle* style) : QProxyStyle(style), impl(new FlexStyleImpl) { setObjectName(QLatin1String("FlexStyle")); }
QString Control::version() { return QLatin1String(ABOUT_VERSION); }
void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) { QStringList messages; // assume the layer is invalid until proven otherwise mLayerValid = false; mValid = false; mRescanRequired = false; clearInvalidLines(); // Initiallize indexes resetIndexes(); bool buildSpatialIndex = buildIndexes && nullptr != mSpatialIndex; // No point building a subset index if there is no geometry, as all // records will be included. bool buildSubsetIndex = buildIndexes && mBuildSubsetIndex && mGeomRep != GeomNone; if ( ! mFile->isValid() ) { // uri is invalid so the layer must be too... messages.append( tr( "File cannot be opened or delimiter parameters are not valid" ) ); reportErrors( messages ); QgsDebugMsg( "Delimited text source invalid - filename or delimiter parameters" ); return; } // Open the file and get number of rows, etc. We assume that the // file has a header row and process accordingly. Caller should make // sure that the delimited file is properly formed. if ( mGeomRep == GeomAsWkt ) { mWktFieldIndex = mFile->fieldIndex( mWktFieldName ); if ( mWktFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Wkt" ), mWktFieldName ) ); } } else if ( mGeomRep == GeomAsXy ) { mXFieldIndex = mFile->fieldIndex( mXFieldName ); mYFieldIndex = mFile->fieldIndex( mYFieldName ); if ( mXFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "X" ), mWktFieldName ) ); } if ( mYFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Y" ), mWktFieldName ) ); } } if ( !messages.isEmpty() ) { reportErrors( messages ); QgsDebugMsg( "Delimited text source invalid - missing geometry fields" ); return; } // Scan the entire file to determine // 1) the number of fields (this is handled by QgsDelimitedTextFile mFile // 2) the number of valid features. Note that the selection of valid features // should match the code in QgsDelimitedTextFeatureIterator // 3) the geometric extents of the layer // 4) the type of each field // // Also build subset and spatial indexes. QStringList parts; long nEmptyRecords = 0; long nBadFormatRecords = 0; long nIncompatibleGeometry = 0; long nInvalidGeometry = 0; long nEmptyGeometry = 0; mNumberFeatures = 0; mExtent = QgsRectangle(); QList<bool> isEmpty; QList<bool> couldBeInt; QList<bool> couldBeLongLong; QList<bool> couldBeDouble; bool foundFirstGeometry = false; while ( true ) { QgsDelimitedTextFile::Status status = mFile->nextRecord( parts ); if ( status == QgsDelimitedTextFile::RecordEOF ) break; if ( status != QgsDelimitedTextFile::RecordOk ) { nBadFormatRecords++; recordInvalidLine( tr( "Invalid record format at line %1" ) ); continue; } // Skip over empty records if ( recordIsEmpty( parts ) ) { nEmptyRecords++; continue; } // Check geometries are valid bool geomValid = true; if ( mGeomRep == GeomAsWkt ) { if ( mWktFieldIndex >= parts.size() || parts[mWktFieldIndex].isEmpty() ) { nEmptyGeometry++; mNumberFeatures++; } else { // Get the wkt - confirm it is valid, get the type, and // if compatible with the rest of file, add to the extents QString sWkt = parts[mWktFieldIndex]; QgsGeometry geom; if ( !mWktHasPrefix && sWkt.indexOf( sWktPrefixRegexp ) >= 0 ) mWktHasPrefix = true; geom = geomFromWkt( sWkt, mWktHasPrefix ); if ( !geom.isNull() ) { QgsWkbTypes::Type type = geom.wkbType(); if ( type != QgsWkbTypes::NoGeometry ) { if ( mGeometryType == QgsWkbTypes::UnknownGeometry || geom.type() == mGeometryType ) { mGeometryType = geom.type(); if ( !foundFirstGeometry ) { mNumberFeatures++; mWkbType = type; mExtent = geom.boundingBox(); foundFirstGeometry = true; } else { mNumberFeatures++; if ( geom.isMultipart() ) mWkbType = type; QgsRectangle bbox( geom.boundingBox() ); mExtent.combineExtentWith( bbox ); } if ( buildSpatialIndex ) { QgsFeature f; f.setId( mFile->recordId() ); f.setGeometry( geom ); mSpatialIndex->insertFeature( f ); } } else { nIncompatibleGeometry++; geomValid = false; } } } else { geomValid = false; nInvalidGeometry++; recordInvalidLine( tr( "Invalid WKT at line %1" ) ); } } } else if ( mGeomRep == GeomAsXy ) { // Get the x and y values, first checking to make sure they // aren't null. QString sX = mXFieldIndex < parts.size() ? parts[mXFieldIndex] : QString(); QString sY = mYFieldIndex < parts.size() ? parts[mYFieldIndex] : QString(); if ( sX.isEmpty() && sY.isEmpty() ) { nEmptyGeometry++; mNumberFeatures++; } else { QgsPointXY pt; bool ok = pointFromXY( sX, sY, pt, mDecimalPoint, mXyDms ); if ( ok ) { if ( foundFirstGeometry ) { mExtent.combineExtentWith( pt.x(), pt.y() ); } else { // Extent for the first point is just the first point mExtent.set( pt.x(), pt.y(), pt.x(), pt.y() ); mWkbType = QgsWkbTypes::Point; mGeometryType = QgsWkbTypes::PointGeometry; foundFirstGeometry = true; } mNumberFeatures++; if ( buildSpatialIndex && std::isfinite( pt.x() ) && std::isfinite( pt.y() ) ) { QgsFeature f; f.setId( mFile->recordId() ); f.setGeometry( QgsGeometry::fromPointXY( pt ) ); mSpatialIndex->insertFeature( f ); } } else { geomValid = false; nInvalidGeometry++; recordInvalidLine( tr( "Invalid X or Y fields at line %1" ) ); } } } else { mWkbType = QgsWkbTypes::NoGeometry; mNumberFeatures++; } if ( !geomValid ) continue; if ( buildSubsetIndex ) mSubsetIndex.append( mFile->recordId() ); // If we are going to use this record, then assess the potential types of each column for ( int i = 0; i < parts.size(); i++ ) { QString &value = parts[i]; // Ignore empty fields - spreadsheet generated CSV files often // have random empty fields at the end of a row if ( value.isEmpty() ) continue; // Expand the columns to include this non empty field if necessary while ( couldBeInt.size() <= i ) { isEmpty.append( true ); couldBeInt.append( false ); couldBeLongLong.append( false ); couldBeDouble.append( false ); } // If this column has been empty so far then initiallize it // for possible types if ( isEmpty[i] ) { isEmpty[i] = false; couldBeInt[i] = true; couldBeLongLong[i] = true; couldBeDouble[i] = true; } if ( ! mDetectTypes ) { continue; } // Now test for still valid possible types for the field // Types are possible until first record which cannot be parsed if ( couldBeInt[i] ) { value.toInt( &couldBeInt[i] ); } if ( couldBeLongLong[i] && ! couldBeInt[i] ) { value.toLongLong( &couldBeLongLong[i] ); } if ( couldBeDouble[i] && ! couldBeLongLong[i] ) { if ( ! mDecimalPoint.isEmpty() ) { value.replace( mDecimalPoint, QLatin1String( "." ) ); } value.toDouble( &couldBeDouble[i] ); } } } // Now create the attribute fields. Field types are integer by preference, // failing that double, failing that text. QStringList fieldNames = mFile->fieldNames(); mFieldCount = fieldNames.size(); attributeColumns.clear(); attributeFields.clear(); QString csvtMessage; QStringList csvtTypes = readCsvtFieldTypes( mFile->fileName(), &csvtMessage ); for ( int i = 0; i < fieldNames.size(); i++ ) { // Skip over WKT field ... don't want to display in attribute table if ( i == mWktFieldIndex ) continue; // Add the field index lookup for the column attributeColumns.append( i ); QVariant::Type fieldType = QVariant::String; QString typeName = QStringLiteral( "text" ); if ( i < csvtTypes.size() ) { typeName = csvtTypes[i]; } else if ( mDetectTypes && i < couldBeInt.size() ) { if ( couldBeInt[i] ) { typeName = QStringLiteral( "integer" ); } else if ( couldBeLongLong[i] ) { typeName = QStringLiteral( "longlong" ); } else if ( couldBeDouble[i] ) { typeName = QStringLiteral( "double" ); } } if ( typeName == QStringLiteral( "integer" ) ) { fieldType = QVariant::Int; } else if ( typeName == QStringLiteral( "longlong" ) ) { fieldType = QVariant::LongLong; } else if ( typeName == QStringLiteral( "real" ) || typeName == QStringLiteral( "double" ) ) { typeName = QStringLiteral( "double" ); fieldType = QVariant::Double; } else { typeName = QStringLiteral( "text" ); } attributeFields.append( QgsField( fieldNames[i], fieldType, typeName ) ); } QgsDebugMsg( "Field count for the delimited text file is " + QString::number( attributeFields.size() ) ); QgsDebugMsg( "geometry type is: " + QString::number( mWkbType ) ); QgsDebugMsg( "feature count is: " + QString::number( mNumberFeatures ) ); QStringList warnings; if ( ! csvtMessage.isEmpty() ) warnings.append( csvtMessage ); if ( nBadFormatRecords > 0 ) warnings.append( tr( "%1 records discarded due to invalid format" ).arg( nBadFormatRecords ) ); if ( nEmptyGeometry > 0 ) warnings.append( tr( "%1 records have missing geometry definitions" ).arg( nEmptyGeometry ) ); if ( nInvalidGeometry > 0 ) warnings.append( tr( "%1 records discarded due to invalid geometry definitions" ).arg( nInvalidGeometry ) ); if ( nIncompatibleGeometry > 0 ) warnings.append( tr( "%1 records discarded due to incompatible geometry types" ).arg( nIncompatibleGeometry ) ); reportErrors( warnings ); // Decide whether to use subset ids to index records rather than simple iteration through all // If more than 10% of records are being skipped, then use index. (Not based on any experimentation, // could do with some analysis?) if ( buildSubsetIndex ) { long recordCount = mFile->recordCount(); recordCount -= recordCount / SUBSET_ID_THRESHOLD_FACTOR; mUseSubsetIndex = mSubsetIndex.size() < recordCount; if ( ! mUseSubsetIndex ) mSubsetIndex = QList<quintptr>(); } mUseSpatialIndex = buildSpatialIndex; mValid = mGeometryType != QgsWkbTypes::UnknownGeometry; mLayerValid = mValid; // If it is valid, then watch for changes to the file connect( mFile.get(), &QgsDelimitedTextFile::fileUpdated, this, &QgsDelimitedTextProvider::onFileUpdated ); }
Control::~Control() { dbus->unregisterObject(QLatin1String(LIRI_DBUS_OBJECT_RECEIVERS)); delete snInt; delete snTerm; }
QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString &uri, const ProviderOptions &options ) : QgsVectorDataProvider( uri, options ) { // Add supported types to enable creating expression fields in field calculator setNativeTypes( QList< NativeType >() << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 ) << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64 bit)" ), QStringLiteral( "int8" ), QVariant::LongLong ) << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 ) << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 ) ); QgsDebugMsg( "Delimited text file uri is " + uri ); QUrl url = QUrl::fromEncoded( uri.toLatin1() ); mFile = qgis::make_unique< QgsDelimitedTextFile >(); mFile->setFromUrl( url ); QString subset; if ( url.hasQueryItem( QStringLiteral( "geomType" ) ) ) { QString gtype = url.queryItemValue( QStringLiteral( "geomType" ) ).toLower(); if ( gtype == QLatin1String( "point" ) ) mGeometryType = QgsWkbTypes::PointGeometry; else if ( gtype == QLatin1String( "line" ) ) mGeometryType = QgsWkbTypes::LineGeometry; else if ( gtype == QLatin1String( "polygon" ) ) mGeometryType = QgsWkbTypes::PolygonGeometry; else if ( gtype == QLatin1String( "none " ) ) mGeometryType = QgsWkbTypes::NullGeometry; } if ( mGeometryType != QgsWkbTypes::NullGeometry ) { if ( url.hasQueryItem( QStringLiteral( "wktField" ) ) ) { mWktFieldName = url.queryItemValue( QStringLiteral( "wktField" ) ); mGeomRep = GeomAsWkt; QgsDebugMsg( "wktField is: " + mWktFieldName ); } else if ( url.hasQueryItem( QStringLiteral( "xField" ) ) && url.hasQueryItem( QStringLiteral( "yField" ) ) ) { mGeomRep = GeomAsXy; mGeometryType = QgsWkbTypes::PointGeometry; mXFieldName = url.queryItemValue( QStringLiteral( "xField" ) ); mYFieldName = url.queryItemValue( QStringLiteral( "yField" ) ); QgsDebugMsg( "xField is: " + mXFieldName ); QgsDebugMsg( "yField is: " + mYFieldName ); if ( url.hasQueryItem( QStringLiteral( "xyDms" ) ) ) { mXyDms = ! url.queryItemValue( QStringLiteral( "xyDms" ) ).toLower().startsWith( 'n' ); } } else { mGeometryType = QgsWkbTypes::NullGeometry; } } mDetectTypes = true; if ( url.hasQueryItem( QStringLiteral( "detectTypes" ) ) ) mDetectTypes = ! url.queryItemValue( QStringLiteral( "detectTypes" ) ).toLower().startsWith( 'n' ); if ( url.hasQueryItem( QStringLiteral( "decimalPoint" ) ) ) mDecimalPoint = url.queryItemValue( QStringLiteral( "decimalPoint" ) ); if ( url.hasQueryItem( QStringLiteral( "crs" ) ) ) mCrs.createFromString( url.queryItemValue( QStringLiteral( "crs" ) ) ); if ( url.hasQueryItem( QStringLiteral( "subsetIndex" ) ) ) { mBuildSubsetIndex = ! url.queryItemValue( QStringLiteral( "subsetIndex" ) ).toLower().startsWith( 'n' ); } if ( url.hasQueryItem( QStringLiteral( "spatialIndex" ) ) ) { mBuildSpatialIndex = ! url.queryItemValue( QStringLiteral( "spatialIndex" ) ).toLower().startsWith( 'n' ); } if ( url.hasQueryItem( QStringLiteral( "subset" ) ) ) { // We need to specify FullyDecoded so that %25 is decoded as % subset = QUrlQuery( url ).queryItemValue( QStringLiteral( "subset" ), QUrl::FullyDecoded ); QgsDebugMsg( "subset is: " + subset ); } if ( url.hasQueryItem( QStringLiteral( "quiet" ) ) ) mShowInvalidLines = false; // Do an initial scan of the file to determine field names, types, // geometry type (for Wkt), extents, etc. Parameter value subset.isEmpty() // avoid redundant building indexes if we will be building a subset string, // in which case indexes will be rebuilt. scanFile( subset.isEmpty() ); if ( ! subset.isEmpty() ) { setSubsetString( subset ); } }
void MainWindow::setSaveSettings(bool saveSettings) { m_saveSettings = saveSettings; QSettings settings; settings.setValue(m_settingsName+QLatin1String("/saveSettings"), saveSettings); }
void QmlOutputParser::processOutput(const QString &output) { m_buffer.append(output); while (true) { const int nlIndex = m_buffer.indexOf(QLatin1Char('\n')); if (nlIndex < 0) // no further complete lines break; const QString msg = m_buffer.left(nlIndex); m_buffer = m_buffer.right(m_buffer.size() - nlIndex - 1); // used in Qt4 static const QString qddserver4 = QLatin1String("QDeclarativeDebugServer: "); // used in Qt5 static const QString qddserver5 = QLatin1String("QML Debugger: "); QString status; int index = msg.indexOf(qddserver4); if (index != -1) { status = msg; status.remove(0, index + qddserver4.length()); // chop of 'QDeclarativeDebugServer: ' } else { index = msg.indexOf(qddserver5); if (index != -1) { status = msg; status.remove(0, index + qddserver5.length()); // chop of 'QML Debugger: ' } } if (!status.isEmpty()) { static QString waitingForConnection = QLatin1String(Constants::STR_WAITING_FOR_CONNECTION); static QString unableToListen = QLatin1String(Constants::STR_UNABLE_TO_LISTEN); static QString debuggingNotEnabled = QLatin1String(Constants::STR_IGNORING_DEBUGGER); static QString debuggingNotEnabled2 = QLatin1String(Constants::STR_IGNORING_DEBUGGER2); static QString connectionEstablished = QLatin1String(Constants::STR_CONNECTION_ESTABLISHED); if (status.startsWith(waitingForConnection)) { status.remove(0, waitingForConnection.size()); // chop of 'Waiting for connection ' static QRegExp waitingTcp( QString::fromLatin1(Constants::STR_ON_PORT_PATTERN)); if (waitingTcp.indexIn(status) > -1) { bool canConvert; quint16 port = waitingTcp.cap(1).toUShort(&canConvert); if (canConvert) emit waitingForConnectionOnPort(port); continue; } static QString waitingOst = QLatin1String(Constants::STR_VIA_OST); if (status.startsWith(waitingOst)) emit waitingForConnectionViaOst(); } else if (status.startsWith(unableToListen)) { //: Error message shown after 'Could not connect ... debugger:" emit errorMessage(tr("The port seems to be in use.")); } else if (status.startsWith(debuggingNotEnabled) || status.startsWith(debuggingNotEnabled2)) { //: Error message shown after 'Could not connect ... debugger:" emit errorMessage(tr("The application is not set up for QML/JS debugging.")); } else if (status.startsWith(connectionEstablished)) { emit connectionEstablishedMessage(); } else { emit unknownMessage(status); } } else if (msg.contains(m_noOutputText)) { emit noOutputMessage(); } } }
static inline QString msgNoDisplayOpen() { return QLatin1String("No display opened."); }
void QgsGeometryCheckerSetupTab::runChecks() { // Get selected layer QList<QgsVectorLayer *> layers = getSelectedLayers(); if ( layers.isEmpty() ) return; if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : layers ) { if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) ) { QMessageBox::critical( this, tr( "Invalid Output Directory" ), tr( "The chosen output directory contains one or more input layers." ) ); return; } } } QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr; QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr; if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) ) { QMessageBox::critical( this, tr( "Error" ), tr( "The test layer set contains a layer selected for a topology check." ) ); return; } for ( QgsVectorLayer *layer : layers ) { if ( layer->isEditable() ) { QMessageBox::critical( this, tr( "Editable Input Layer" ), tr( "Input layer '%1' is not allowed to be in editing mode." ).arg( layer->name() ) ); return; } } bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked(); // Set window busy setCursor( Qt::WaitCursor ); mRunButton->setEnabled( false ); ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) ); ui.labelStatus->show(); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QList<QgsVectorLayer *> processLayers; if ( ui.radioButtonOutputNew->isChecked() ) { // Get output directory and file extension QDir outputDir = QDir( ui.lineEditOutputDirectory->text() ); QString outputDriverName = ui.comboBoxOutputFormat->currentData().toString(); QgsVectorFileWriter::MetaData metadata; if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) ) { QMessageBox::critical( this, tr( "Unknown Output Format" ), tr( "The specified output format cannot be recognized." ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } QString outputExtension = metadata.ext; // List over input layers, check which existing project layers need to be removed and create output layers QString filenamePrefix = ui.lineEditFilenamePrefix->text(); QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix ); QStringList toRemove; QStringList createErrors; for ( QgsVectorLayer *layer : layers ) { QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension ); // Remove existing layer with same uri from project for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() ) { if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) ) { toRemove.append( projectLayer->id() ); } } // Create output layer QString errMsg; QgsVectorFileWriter::WriterError err = QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg ); if ( err != QgsVectorFileWriter::NoError ) { createErrors.append( errMsg ); continue; } QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) ); if ( selectedOnly ) { QgsFeature feature; // Get features to select (only selected features were written up to this point) QgsFeatureIds selectedFeatures = newlayer->allFeatureIds(); // Write non-selected feature ids QgsFeatureList features; QgsFeatureIterator it = layer->getFeatures(); while ( it.nextFeature( feature ) ) { if ( !layer->selectedFeatureIds().contains( feature.id() ) ) { features.append( feature ); } } newlayer->dataProvider()->addFeatures( features ); // Set selected features newlayer->selectByIds( selectedFeatures ); } processLayers.append( newlayer ); } // Remove layers from project if ( !toRemove.isEmpty() ) { QgsProject::instance()->removeMapLayers( toRemove ); } // Error if an output layer could not be created if ( !createErrors.isEmpty() ) { QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create one or more output layers:\n%1" ).arg( createErrors.join( "\n" ) ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } } else { processLayers = layers; } // Check if output layers are editable QList<QgsVectorLayer *> nonEditableLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 ) { nonEditableLayers.append( layer ); } } if ( !nonEditableLayers.isEmpty() ) { QStringList nonEditableLayerNames; for ( QgsVectorLayer *layer : nonEditableLayers ) { nonEditableLayerNames.append( layer->name() ); } if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Non-editable Output Layers" ), tr( "The following output layers are in a format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) ) { if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { QString layerPath = layer->dataProvider()->dataSourceUri(); delete layer; if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) ) { QgsVectorFileWriter::deleteShapeFile( layerPath ); } else { QFile( layerPath ).remove(); } } mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); } return; } } // Setup checker ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) ); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QMap<QString, QgsFeaturePool *> featurePools; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer ); QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() ); featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) ); } // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) ) { QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ); Q_ASSERT( layer ); double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer ); QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() ); featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) ); } QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), QgsProject::instance()->crs(), featurePools ); QList<QgsGeometryCheck *> checks; for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() ) { QgsGeometryCheck *check = factory->createInstance( context, ui ); if ( check ) { checks.append( check ); } } QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context ); emit checkerStarted( checker ); if ( ui.radioButtonOutputNew->isChecked() ) { QList<QgsMapLayer *> addLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { addLayers.append( layer ); } QgsProject::instance()->addMapLayers( addLayers ); } // Run ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole ); mRunButton->hide(); ui.progressBar->setRange( 0, 0 ); ui.labelStatus->hide(); ui.progressBar->show(); ui.widgetInputs->setEnabled( false ); QEventLoop evLoop; QFutureWatcher<void> futureWatcher; connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue ); connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit ); connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel ); connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback ); int maxSteps = 0; futureWatcher.setFuture( checker->execute( &maxSteps ) ); ui.progressBar->setRange( 0, maxSteps ); evLoop.exec(); // Restore window unsetCursor(); mAbortButton->setEnabled( true ); ui.buttonBox->removeButton( mAbortButton ); mRunButton->setEnabled( true ); mRunButton->show(); ui.progressBar->hide(); ui.labelStatus->hide(); ui.widgetInputs->setEnabled( true ); // Show result emit checkerFinished( !futureWatcher.isCanceled() ); }
QString WindowManager::waitForTopLevelWindowImpl(unsigned, Q_PID, int, QString *errorMessage) { *errorMessage = QLatin1String("Not implemented."); return QString(); }
void load() { // for old config data migration QString dir_old = qApp->applicationDirPath() + QString::fromLatin1("/data"); if (!QDir(dir_old).exists()) { dir_old = QDir::homePath() + QString::fromLatin1("/.QtAV"); } if (QDir(dir_old).exists()) { if (!QFile(file).exists()) { QString old = dir_old + QString::fromLatin1("/") + qApp->applicationName() + QString::fromLatin1(".ini"); if (QFile(old).exists()) { QFile::copy(old, file); QFile::remove(old); } old = dir_old + QString::fromLatin1("/playlist.qds"); if (QFile(old).exists()) { if (!QFile::copy(old, appDataDir() + QString::fromLatin1("/playlist.qds"))) qWarning("error to move old playlist data"); QFile::remove(old); } old = dir_old + QString::fromLatin1("/history.qds"); if (QFile(old).exists()) { if (!QFile::copy(old, appDataDir() + QString::fromLatin1("/history.qds"))) qWarning("error to move old history data"); QFile::remove(old); } } } QSettings settings(file, QSettings::IniFormat); log = settings.value(QString::fromLatin1("log"), QString()).toString(); last_file = settings.value(QString::fromLatin1("last_file"), QString()).toString(); timeout = settings.value(QString::fromLatin1("timeout"), 30.0).toReal(); abort_timeout = settings.value(QString::fromLatin1("abort_timeout"), true).toBool(); force_fps = settings.value(QString::fromLatin1("force_fps"), 0.0).toReal(); settings.beginGroup(QString::fromLatin1("decoder")); settings.beginGroup(QString::fromLatin1("video")); QString decs_default(QString::fromLatin1("FFmpeg")); //decs_default.append(QString::fromLatin1(" CUDA ")).append(QString::fromLatin1(" DXVA ")).append(QString::fromLatin1(" VAAPI ")).append(QString::fromLatin1(" VDA ")); #if 0 QString all_names_string = settings.value("all", QString()).toString(); if (!all_names_string.isEmpty()) { all_names = all_names_string.split(" ", QString::SkipEmptyParts); } #endif video_decoders = settings.value(QString::fromLatin1("priority"), decs_default).toString().split(QString::fromLatin1(" "), QString::SkipEmptyParts); settings.endGroup(); //video settings.endGroup(); //decoder settings.beginGroup(QString::fromLatin1("capture")); capture_dir = settings.value(QString::fromLatin1("dir"), QString()).toString(); if (capture_dir.isEmpty()) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) capture_dir = QDesktopServices::storageLocation(QDesktopServices::PicturesLocation); #else capture_dir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); #endif } capture_fmt = settings.value(QString::fromLatin1("format"), QString::fromLatin1("png")).toString(); capture_quality = settings.value(QString::fromLatin1("quality"), 100).toInt(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("subtitle")); subtitle_autoload = settings.value(QString::fromLatin1("autoLoad"), true).toBool(); subtitle_enabled = settings.value(QString::fromLatin1("enabled"), true).toBool(); subtitle_engines = settings.value(QString::fromLatin1("engines"), QStringList() << QString::fromLatin1("FFmpeg") << QString::fromLatin1("LibASS")).toStringList(); subtitle_delay = settings.value(QString::fromLatin1("delay"), 0.0).toInt(); QFont f; f.setPointSize(20); f.setBold(true); subtitle_font = settings.value(QString::fromLatin1("font"), f).value<QFont>(); subtitle_color = settings.value(QString::fromLatin1("color"), QColor("white")).value<QColor>(); subtitle_outline_color = settings.value(QString::fromLatin1("outline_color"), QColor("blue")).value<QColor>(); subtitle_outline = settings.value(QString::fromLatin1("outline"), true).toBool(); subtilte_bottom_margin = settings.value(QString::fromLatin1("bottom margin"), 8).toInt(); settings.beginGroup(QString::fromLatin1("ass")); ass_font_file = settings.value(QString::fromLatin1("font_file"), QString()).toString(); ass_force_font_file = settings.value(QString::fromLatin1("force_font_file"), false).toBool(); ass_fonts_dir = settings.value(QString::fromLatin1("fonts_dir"), QString()).toString(); settings.endGroup(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("preview")); preview_enabled = settings.value(QString::fromLatin1("enabled"), true).toBool(); preview_w = settings.value(QString::fromLatin1("width"), 160).toInt(); preview_h = settings.value(QString::fromLatin1("height"), 90).toInt(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("avformat")); avformat_on = settings.value(QString::fromLatin1("enable"), false).toBool(); direct = settings.value(QString::fromLatin1("avioflags"), 0).toString() == QLatin1String("direct"); probe_size = settings.value(QString::fromLatin1("probesize"), 5000000).toUInt(); analyze_duration = settings.value(QString::fromLatin1("analyzeduration"), 5000000).toInt(); avformat_extra = settings.value(QString::fromLatin1("extra"), QString()).toString(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("avfilterVideo")); avfilterVideo_on = settings.value(QString::fromLatin1("enable"), true).toBool(); avfilterVideo = settings.value(QString::fromLatin1("options"), QString()).toString(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("avfilterAudio")); avfilterAudio_on = settings.value(QString::fromLatin1("enable"), true).toBool(); avfilterAudio = settings.value(QString::fromLatin1("options"), QString()).toString(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("opengl")); egl = settings.value(QString::fromLatin1("egl"), false).toBool(); const QString glname = settings.value(QString::fromLatin1("type"), QString::fromLatin1("OpenGLES")).toString(); opengl = (Config::OpenGLType)Config::staticMetaObject.enumerator(Config::staticMetaObject.indexOfEnumerator("OpenGLType")).keysToValue(glname.toLatin1().constData()); // d3d11 bad performance (gltexsubimage2d) angle_dx = settings.value(QString::fromLatin1("angle_platform"), QString::fromLatin1("d3d9")).toString(); settings.endGroup(); settings.beginGroup(QString::fromLatin1("buffer")); buffer_value = settings.value(QString::fromLatin1("value"), -1).toInt(); settings.endGroup(); }
void MessageHighlighter::highlightBlock(const QString &text) { static const QLatin1Char tab = QLatin1Char('\t'); static const QLatin1Char space = QLatin1Char(' '); static const QLatin1Char amp = QLatin1Char('&'); static const QLatin1Char endTag = QLatin1Char('>'); static const QLatin1Char quot = QLatin1Char('"'); static const QLatin1Char apos = QLatin1Char('\''); static const QLatin1Char semicolon = QLatin1Char(';'); static const QLatin1Char equals = QLatin1Char('='); static const QLatin1Char percent = QLatin1Char('%'); static const QLatin1String startComment = QLatin1String("<!--"); static const QLatin1String endComment = QLatin1String("-->"); static const QLatin1String endElement = QLatin1String("/>"); int state = previousBlockState(); int len = text.length(); int start = 0; int pos = 0; while (pos < len) { switch (state) { case NormalState: default: while (pos < len) { QChar ch = text.at(pos); if (ch == QLatin1Char('<')) { if (text.mid(pos, 4) == startComment) { state = InComment; } else { state = InTag; start = pos; while (pos < len && text.at(pos) != space && text.at(pos) != endTag && text.at(pos) != tab && text.mid(pos, 2) != endElement) ++pos; if (text.mid(pos, 2) == endElement) ++pos; setFormat(start, pos - start, m_formats[Tag]); break; } break; } else if (ch == amp && pos + 1 < len) { // Default is Accelerator if (text.at(pos + 1).isLetterOrNumber()) setFormat(pos + 1, 1, m_formats[Accelerator]); // When a semicolon follows assume an Entity start = pos; ch = text.at(++pos); while (pos + 1 < len && ch != semicolon && ch.isLetterOrNumber()) ch = text.at(++pos); if (ch == semicolon) setFormat(start, pos - start + 1, m_formats[Entity]); } else if (ch == percent) { start = pos; // %[1-9]* for (++pos; pos < len && text.at(pos).isDigit(); ++pos) {} // %n if (pos < len && pos == start + 1 && text.at(pos) == QLatin1Char('n')) ++pos; setFormat(start, pos - start, m_formats[Variable]); } else { // No tag, comment or entity started, continue... ++pos; } } break; case InComment: start = pos; while (pos < len) { if (text.mid(pos, 3) == endComment) { pos += 3; state = NormalState; break; } else { ++pos; } } setFormat(start, pos - start, m_formats[Comment]); break; case InTag: QChar quote = QChar::Null; while (pos < len) { QChar ch = text.at(pos); if (quote.isNull()) { start = pos; if (ch == apos || ch == quot) { quote = ch; } else if (ch == endTag) { ++pos; setFormat(start, pos - start, m_formats[Tag]); state = NormalState; break; } else if (text.mid(pos, 2) == endElement) { pos += 2; setFormat(start, pos - start, m_formats[Tag]); state = NormalState; break; } else if (ch != space && text.at(pos) != tab) { // Tag not ending, not a quote and no whitespace, so // we must be dealing with an attribute. ++pos; while (pos < len && text.at(pos) != space && text.at(pos) != tab && text.at(pos) != equals) ++pos; setFormat(start, pos - start, m_formats[Attribute]); start = pos; } } else if (ch == quote) { quote = QChar::Null; // Anything quoted is a value setFormat(start, pos - start, m_formats[Value]); } ++pos; } break; } } setCurrentBlockState(state); }
// Compile a map of hard-coded string property types static const PropertyNameTypeMap &stringPropertyTypes() { static PropertyNameTypeMap propertyNameTypeMap; if (propertyNameTypeMap.empty()) { const StringPropertyParameters richtext(ValidationRichText, true); // Accessibility. Both are texts the narrator reads propertyNameTypeMap.insert(QLatin1String("accessibleDescription"), richtext); propertyNameTypeMap.insert(QLatin1String("accessibleName"), richtext); // object names const StringPropertyParameters objectName(ValidationObjectName, false); propertyNameTypeMap.insert(QLatin1String("buddy"), objectName); propertyNameTypeMap.insert(QLatin1String("currentItemName"), objectName); propertyNameTypeMap.insert(QLatin1String("currentPageName"), objectName); propertyNameTypeMap.insert(QLatin1String("currentTabName"), objectName); propertyNameTypeMap.insert(QLatin1String("layoutName"), objectName); propertyNameTypeMap.insert(QLatin1String("spacerName"), objectName); // Style sheet propertyNameTypeMap.insert(QLatin1String("styleSheet"), StringPropertyParameters(ValidationStyleSheet, false)); // Buttons/ QCommandLinkButton const StringPropertyParameters multiline(ValidationMultiLine, true); propertyNameTypeMap.insert(QLatin1String("description"), multiline); propertyNameTypeMap.insert(QLatin1String("iconText"), multiline); // Tooltips, etc. propertyNameTypeMap.insert(QLatin1String("toolTip"), richtext); propertyNameTypeMap.insert(QLatin1String("whatsThis"), richtext); propertyNameTypeMap.insert(QLatin1String("windowIconText"), richtext); propertyNameTypeMap.insert(QLatin1String("html"), richtext); // A QWizard page id propertyNameTypeMap.insert(QLatin1String("pageId"), StringPropertyParameters(ValidationSingleLine, false)); // QPlainTextEdit propertyNameTypeMap.insert(QLatin1String("plainText"), StringPropertyParameters(ValidationMultiLine, true)); } return propertyNameTypeMap; }
void QDeclarativeTester::updateCurrentTime(int msec) { QDeclarativeItemPrivate::setConsistentTime(msec); if (!testscript && msec > 16 && options & QDeclarativeViewer::Snapshot) return; QImage img(m_view->width(), m_view->height(), QImage::Format_RGB32); if (options & QDeclarativeViewer::TestImages) { img.fill(qRgb(255,255,255)); #ifdef Q_WS_MAC bool oldSmooth = qt_applefontsmoothing_enabled; qt_applefontsmoothing_enabled = false; #endif QPainter p(&img); #ifdef Q_WS_MAC qt_applefontsmoothing_enabled = oldSmooth; #endif m_view->render(&p); } bool snapshot = msec == 16 && (options & QDeclarativeViewer::Snapshot || (testscript && testscript->count() == 2)); FrameEvent fe; fe.msec = msec; if (msec == 0 || !(options & QDeclarativeViewer::TestImages)) { // Skip first frame, skip if not doing images } else if (0 == ((m_savedFrameEvents.count()-1) % 60) || snapshot) { fe.image = img; } else { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)img.bits(), img.bytesPerLine() * img.height()); fe.hash = hash.result(); } m_savedFrameEvents.append(fe); // Deliver mouse events filterEvents = false; if (!testscript) { for (int ii = 0; ii < m_mouseEvents.count(); ++ii) { MouseEvent &me = m_mouseEvents[ii]; me.msec = msec; QMouseEvent event(me.type, me.pos, me.button, me.buttons, me.modifiers); if (me.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } for (int ii = 0; ii < m_keyEvents.count(); ++ii) { KeyEvent &ke = m_keyEvents[ii]; ke.msec = msec; QKeyEvent event(ke.type, ke.key, ke.modifiers, ke.text, ke.autorep, ke.count); if (ke.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } m_savedMouseEvents.append(m_mouseEvents); m_savedKeyEvents.append(m_keyEvents); } m_mouseEvents.clear(); m_keyEvents.clear(); // Advance test script while (testscript && testscript->count() > testscriptidx) { QObject *event = testscript->eventAt(testscriptidx); if (QDeclarativeVisualTestFrame *frame = qobject_cast<QDeclarativeVisualTestFrame *>(event)) { if (frame->msec() < msec) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester(" << m_script << "): Extra frame. Seen:" << msec << "Expected:" << frame->msec(); imagefailure(); } } else if (frame->msec() == msec) { if (!frame->hash().isEmpty() && frame->hash().toUtf8() != fe.hash.toHex()) { if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record)) { qWarning() << "QDeclarativeTester(" << m_script << "): Mismatched frame hash at" << msec << ". Seen:" << fe.hash.toHex() << "Expected:" << frame->hash().toUtf8(); imagefailure(); } } } else if (frame->msec() > msec) { break; } if (options & QDeclarativeViewer::TestImages && !(options & QDeclarativeViewer::Record) && !frame->image().isEmpty()) { QImage goodImage(frame->image().toLocalFile()); if (frame->msec() == 16 && goodImage.size() != img.size()){ //Also an image mismatch, but this warning is more informative. Only checked at start though. qWarning() << "QDeclarativeTester(" << m_script << "): Size mismatch. This test must be run at " << goodImage.size(); imagefailure(); } if (goodImage != img) { QString reject(frame->image().toLocalFile() + QLatin1String(".reject.png")); qWarning() << "QDeclarativeTester(" << m_script << "): Image mismatch. Reject saved to:" << reject; img.save(reject); bool doDiff = (goodImage.size() == img.size()); if (doDiff) { QImage diffimg(m_view->width(), m_view->height(), QImage::Format_RGB32); diffimg.fill(qRgb(255,255,255)); QPainter p(&diffimg); int diffCount = 0; for (int x = 0; x < img.width(); ++x) { for (int y = 0; y < img.height(); ++y) { if (goodImage.pixel(x,y) != img.pixel(x,y)) { ++diffCount; p.drawPoint(x,y); } } } QString diff(frame->image().toLocalFile() + QLatin1String(".diff.png")); diffimg.save(diff); qWarning().nospace() << " Diff (" << diffCount << " pixels differed) saved to: " << diff; } imagefailure(); } } } else if (QDeclarativeVisualTestMouse *mouse = qobject_cast<QDeclarativeVisualTestMouse *>(event)) { QPoint pos(mouse->x(), mouse->y()); QPoint globalPos = m_view->mapToGlobal(QPoint(0, 0)) + pos; QMouseEvent event((QEvent::Type)mouse->type(), pos, globalPos, (Qt::MouseButton)mouse->button(), (Qt::MouseButtons)mouse->buttons(), (Qt::KeyboardModifiers)mouse->modifiers()); MouseEvent me(&event); me.msec = msec; if (!mouse->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); me.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); me.destination = ViewPort; } m_savedMouseEvents.append(me); } else if (QDeclarativeVisualTestKey *key = qobject_cast<QDeclarativeVisualTestKey *>(event)) { QKeyEvent event((QEvent::Type)key->type(), key->key(), (Qt::KeyboardModifiers)key->modifiers(), QString::fromUtf8(QByteArray::fromHex(key->text().toUtf8())), key->autorep(), key->count()); KeyEvent ke(&event); ke.msec = msec; if (!key->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); ke.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); ke.destination = ViewPort; } m_savedKeyEvents.append(ke); } testscriptidx++; } filterEvents = true; if (testscript && testscript->count() <= testscriptidx) { //if (msec == 16) //for a snapshot, leave it up long enough to see // (void)::sleep(1); complete(); } }
static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns) { return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath())); }
QStringList ViewGenerator::generateViews() const { QStringList files; TableSchema ts(tableName); if (ts.primaryKeyIndex() < 0) { qWarning("Primary key not found. [table name: %s]", qPrintable(ts.tableName())); return files; } FileWriter fw; QString output; QString caption = fieldNameToCaption(tableName); QString className = fieldNameToEnumName(tableName); QString varName = fieldNameToVariableName(tableName); QPair<QString, QString> pkFld = ts.getPrimaryKeyField(); // Generates index.html QString th ,td, indexOtm, showColumn, showOtm, entryColumn, editColumn, editOtm; QList<QPair<QString, QString> > fields = ts.getFieldList(); for (QListIterator<QPair<QString, QString> > i(fields); i.hasNext(); ) { const QPair<QString, QString> &p = i.next(); QString cap = fieldNameToCaption(p.first); QString var = fieldNameToVariableName(p.first); QString readonly; if (!excludedColumn()->contains(p.first)) { th += " <th>"; th += cap; th += "</th>\n"; td += " <td data-tf=\"#"; td += var; td += "\"></td>\n"; indexOtm += QString("#%1 ~= i.%1()\n\n").arg(var); entryColumn += QString(" <p>\n <label for=\"%1_%2\">%3</label><br />\n <input id=\"%1_%2\" name=\"%1[%2]\" />\n </p>\n").arg(varName, var, cap); if (p.first == pkFld.first) { readonly = QLatin1String("readonly "); } editColumn += QString(" <p>\n <label for=\"%1_%2\">%3</label><br />\n <input id=\"%1_%2\" %4data-tf=\"#%2\" />\n </p>\n").arg(varName, var, cap, readonly); editOtm += QString("#%1 |== inputTextTag(\"%2[%1]\", %2.%1());\n\n").arg(var, varName); } showColumn += QString("<p>\n <b>%1:</b>\n <span data-tf=\"#%2\">(%2)</span>\n</p>\n").arg(cap, var); showOtm += QString("#%1 := %2.%1()\n\n").arg(var, varName); } output = QString(INDEX_HTML_TEMPLATE).arg(caption, th, td); fw.setFileName(dstDir.filePath("index.html")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates index.otm QString pkVarName = fieldNameToVariableName(pkFld.first); output = QString(INDEX_OTM_TEMPLATE).arg(varName.toLower(), className, varName, indexOtm, pkVarName); fw.setFileName(dstDir.filePath("index.otm")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates show.html output = QString(SHOW_HTML_TEMPLATE).arg(showColumn); fw.setFileName(dstDir.filePath("show.html")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates show.otm output = QString(SHOW_OTM_TEMPLATE).arg(varName.toLower(), className, varName, showOtm, pkVarName); fw.setFileName(dstDir.filePath("show.otm")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates entry.html output = QString(ENTRY_HTML_TEMPLATE).arg(caption, entryColumn); fw.setFileName(dstDir.filePath("entry.html")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates entry.otm output = QString(ENTRY_OTM_TEMPLATE).arg(varName.toLower()); fw.setFileName(dstDir.filePath("entry.otm")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates edit.html output = QString(EDIT_HTML_TEMPLATE).arg(caption, editColumn); fw.setFileName(dstDir.filePath("edit.html")); if (fw.write(output, false)) { files << fw.fileName(); } // Generates edit.otm output = QString(EDIT_OTM_TEMPLATE).arg(varName.toLower(), className, varName, pkVarName, editOtm); fw.setFileName(dstDir.filePath("edit.otm")); if (fw.write(output, false)) { files << fw.fileName(); } return files; }
QVariant PlaylistsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { switch (role) { case Cantata::Role_TitleText: return title(); case Cantata::Role_SubText: return descr(); case Qt::DecorationRole: return icon(); } return QVariant(); } #ifndef ENABLE_UBUNTU if (Qt::TextAlignmentRole==role) { return alignments[index.column()]; } #endif Item *item=static_cast<Item *>(index.internalPointer()); if (item->isPlaylist()) { PlaylistItem *pl=static_cast<PlaylistItem *>(item); switch(role) { #ifdef ENABLE_UBUNTU case Cantata::Role_Image: return QString(); #endif case Cantata::Role_ListImage: return false; case Cantata::Role_IsCollection: return true; case Cantata::Role_CollectionId: return pl->key; case Cantata::Role_Key: return 0; case Cantata::Role_SongWithRating: case Cantata::Role_Song: { QVariant var; var.setValue<Song>(Song()); return var; } case Cantata::Role_AlbumDuration: return pl->totalTime(); case Cantata::Role_SongCount: if (!pl->loaded) { pl->loaded=true; emit playlistInfo(pl->name); } return pl->songs.count(); case Cantata::Role_CurrentStatus: case Cantata::Role_Status: return (int)GroupedView::State_Default; case Qt::FontRole: if (multiCol) { QFont font; font.setBold(true); return font; } return QVariant(); case Cantata::Role_TitleText: case Cantata::Role_MainText: case Qt::DisplayRole: if (multiCol) { switch (index.column()) { case COL_TITLE: return pl->visibleName(); case COL_ARTIST: case COL_ALBUM: return QVariant(); case COL_LENGTH: if (!pl->loaded) { pl->loaded=true; emit playlistInfo(pl->name); } return pl->loaded && !pl->isSmartPlaylist ? Utils::formatTime(pl->totalTime()) : QVariant(); case COL_YEAR: case COL_GENRE: return QVariant(); default: break; } } return pl->visibleName(); case Qt::ToolTipRole: if (!Settings::self()->infoTooltips()) { return QVariant(); } if (!pl->loaded) { pl->loaded=true; emit playlistInfo(pl->name); } return 0==pl->songs.count() ? pl->visibleName() : pl->visibleName()+"\n"+Plurals::tracksWithDuration(pl->songs.count(), Utils::formatTime(pl->totalTime())); #ifndef ENABLE_UBUNTU case Qt::DecorationRole: return multiCol ? QVariant() : (pl->isSmartPlaylist ? Icons::self()->dynamicRuleIcon : Icons::self()->playlistListIcon); #endif case Cantata::Role_SubText: if (!pl->loaded) { pl->loaded=true; emit playlistInfo(pl->name); } if (pl->isSmartPlaylist) { return i18n("Smart Playlist"); } return Plurals::tracksWithDuration(pl->songs.count(), Utils::formatTime(pl->totalTime())); case Cantata::Role_TitleActions: return true; default: return ActionModel::data(index, role); } } else { SongItem *s=static_cast<SongItem *>(item); switch (role) { #ifdef ENABLE_UBUNTU case Cantata::Role_Image: return QString(); #endif case Cantata::Role_ListImage: return true; case Cantata::Role_IsCollection: return false; case Cantata::Role_CollectionId: return s->parent->key; case Cantata::Role_Key: return s->key; case Cantata::Role_CoverSong: case Cantata::Role_SongWithRating: case Cantata::Role_Song: { QVariant var; var.setValue<Song>(*s); return var; } case Cantata::Role_AlbumDuration: { quint32 d=s->time; for (int i=index.row()+1; i<s->parent->songs.count(); ++i) { const SongItem *song = s->parent->songs.at(i); if (song->key!=s->key) { break; } d+=song->time; } if (index.row()>1) { for (int i=index.row()-1; i<=0; ++i) { const SongItem *song = s->parent->songs.at(i); if (song->key!=s->key) { break; } d+=song->time; } } return d; } case Cantata::Role_SongCount:{ quint32 count=1; for (int i=index.row()+1; i<s->parent->songs.count(); ++i) { const SongItem *song = s->parent->songs.at(i); if (song->key!=s->key) { break; } count++; } if (index.row()>1) { for (int i=index.row()-1; i<=0; ++i) { const SongItem *song = s->parent->songs.at(i); if (song->key!=s->key) { break; } count++; } } return count; } case Cantata::Role_CurrentStatus: case Cantata::Role_Status: return (int)GroupedView::State_Default; case Qt::DisplayRole: if (multiCol) { switch (index.column()) { case COL_TITLE: return s->trackAndTitleStr(false); case COL_ARTIST: return s->artist.isEmpty() ? Song::unknown() : s->artist; case COL_ALBUM: if (s->isStream() && s->album.isEmpty()) { QString n=s->name(); if (!n.isEmpty()) { return n; } } return s->album; case COL_LENGTH: return Utils::formatTime(s->time); case COL_YEAR: if (s->year <= 0) { return QVariant(); } return s->year; case COL_GENRE: return s->displayGenre(); case COL_COMPOSER: return s->composer(); case COL_PERFORMER: return s->performer(); default: break; } } return s->entryName(); case Qt::ToolTipRole: if (!Settings::self()->infoTooltips()) { return QVariant(); } return s->toolTip(); #ifndef ENABLE_UBUNTU case Qt::DecorationRole: return multiCol ? QVariant() : (s->title.isEmpty() ? Icons::self()->streamIcon : Icons::self()->audioListIcon); #endif case Cantata::Role_MainText: return s->title.isEmpty() ? s->file : s->title; case Cantata::Role_SubText: return s->artist+QLatin1String(" - ")+s->displayAlbum()+QLatin1String(" - ")+Utils::formatTime(s->time); default: return ActionModel::data(index, role); } } return QVariant(); }