コード例 #1
0
bool AnalyzeTask::checkFile_CDDA(QFile &file)
{
	file.reset();
	QByteArray data = file.read(128);
	
	int i = data.indexOf("RIFF");
	int j = data.indexOf("CDDA");
	int k = data.indexOf("fmt ");

	return ((i >= 0) && (j >= 0) && (k >= 0) && (k > j) && (j > i));
}
コード例 #2
0
ファイル: qmime_mac.cpp プロジェクト: FilipBE/qtextended
static void qt_mac_loadMimeRegistry(QFile &file, QMap<QString, int> &registry, int &max)
{
    file.reset();
    QTextStream stream(&file);
    while(!stream.atEnd()) {
	QString mime = stream.readLine();
	int mactype = stream.readLine().toInt();
	if(mactype > max)
	    max = mactype;
	registry.insert(mime, mactype);
    }
}
コード例 #3
0
ファイル: zgui.cpp プロジェクト: OpenMagx/open-magx-src
void ZGui::saveAs ( const QString fileName, bool save )
{ 
	if ( (access(fileName.utf8(),0) == 0) && !save )
	{
		QString sBody = lng->getString("REWRITE").arg ( getFileName(fileName) );
		
		ZMessageDlg * pConfirmation = new ZMessageDlg ( lng->getString("SAVING"), sBody, ( ZMessageDlg::MessageDlgType )1, 0, this, "2", true, 0 );
		if ( pConfirmation->exec() )
		{
			ZMessageDlg * pMessage = new ZMessageDlg ( lng->getString("SAVING"), lng->getString("CHANGED"), ( ZMessageDlg::MessageDlgType )1, 0, this, "saveas", true, 0 );
			pMessage->show();
			delete pMessage;
		}
		
		delete pConfirmation;
	}
	
	if ( !(access(getFilePath(fileName).utf8(),02) == 0) ) // Check save to ReadOnly FS
	{   
		ZMessageDlg * pWarning = new ZMessageDlg ( lng->getString("ERROR"), "Do not save to ReadOnly FS!", ( ZMessageDlg::MessageDlgType )2, 0, this, "saveas", true, 0 );
		pWarning->exec();
		delete pWarning;
		return;
	}
	
	if ( access(fileName.utf8(),0) == 0 ) //remove file for rewrite
		remove(fileName.utf8());
	
	QFile file ( fileName );
	
	if ( !file.open ( IO_WriteOnly | IO_Truncate ) )
	{   
		ZMessageDlg * pWarning = new ZMessageDlg ( lng->getString("ERROR"), lng->getString("FILE_SAVING_FAILED"), ( ZMessageDlg::MessageDlgType )2, 0, this, "saveas", true, 0 );
		pWarning->exec();
		delete pWarning;
		return;
	}
	
	QTextCodec* codec = codecByLocalId(textCode);	
	file.reset();
	QCString str = codec->fromUnicode( edit->text() );
	file.writeBlock( str, str.length() );
	char endFile[]={0};
	file.writeBlock( endFile, sizeof(endFile) );
	
	file.flush();
	file.close();
	
	ZMessageDlg * pMessage = new ZMessageDlg ( lng->getString("SAVING"), lng->getString("FILE_SAVING_SUCCESS"), ( ZMessageDlg::MessageDlgType ) 2, 0, this, "saveas", true, 0 );
	pMessage->exec();
	delete pMessage;
}
コード例 #4
0
ファイル: zgui.cpp プロジェクト: OpenMagx/open-magx-src
void ZGui::load ( const QString fileName, bool AutoCodec )
{
	toLog("load ("+fileName+")");
	QFile file ( fileName );
	if (  file.open ( IO_ReadWrite ) )//IO_ReadOnly ) )
	{
		//Block update
	    edit->blockSignals(true);
		edit->setAutoUpdate(false);	
			
		//Set def editor
		edit->clear();
		edit->setText("");
	
		//Detect codec
		if ( AutoCodec )
		{
			//Reset all checked
			for (int i=0; i<CODEC_COUNT;i++)
				CodeMenu->setItemChecked(i,false);
			//Read data for detect
			char data[10000];
			int size = file.readBlock(data, sizeof(data));
			file.reset();
			textCode = detectCodec(data, size);
			//Check codec
			CodeMenu->setItemChecked(textCode, true);
		}
		
		toLog("\tload text");
		//Load file
		char data[ file.size() ];
		file.readBlock(data, sizeof(data));
		QTextCodec* codec = codecByLocalId(textCode);
		toLog("\tset text");
		edit->setText( codec->toUnicode( data ) );
		toLog("\tclose file");
		file.close();
		
		//Unblock update
	    edit->blockSignals(false);
		edit->setAutoUpdate(true);
		
		#ifdef MDI
		setMainWidgetTitle(sFileName);
		buildDlgMenu();
		#endif
		
		toLog("end load");
	}
}
コード例 #5
0
ファイル: addbrass.cpp プロジェクト: algra4/BeerTemple
AddBrass::AddBrass(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddBrass)
{
    db_ = nullptr;
    selectImage_ = nullptr;
    ui->setupUi(this);
    connexion();
    remplirPays();
    ui->lbImageBrasserie->setMaximumSize(250,250);

    QFile f (":/btn/resources/css/btn_ajouter.css");
    if(f.open((QIODevice::ReadOnly))){
        ui->ajouterBrasserie->setStyleSheet(f.readAll());
        f.reset();
    }

    f.setFileName(":/btn/resources/css/btn_addImage.css");
    if(f.open(QIODevice::ReadOnly)){
        ui->btAjoutImageBrasserie->setStyleSheet(f.readAll());
        f.reset();
    }
}
コード例 #6
0
void MetaInfoParser::errorHandling(QXmlStreamReader &reader, QFile &file)
{
    if (!reader.hasError())
        return;

    qDebug() << QString("Error at %1, %2:%3: %4")
            .arg(file.fileName())
            .arg(reader.lineNumber())
            .arg(reader.columnNumber())
            .arg(reader.errorString());

    file.reset();

    QString fileString = file.readAll();
    QString snippetString;
    int lineCount = 0;
    int position = reader.characterOffset();
    while (position >= 0)
    {
        if (fileString[position] == '\n') {
            if (lineCount > 3)
                break;
            lineCount++;
        }

        snippetString.prepend(fileString[position]);
        position--;
    }

    lineCount = 0;
    position = reader.characterOffset();
    while (position >= 0)
    {
        position++;
        if (fileString[position] == '\n') {
            if (lineCount > 1)
                break;
            lineCount++;
        }

        snippetString.append(fileString[position]);
    }

    qDebug() << snippetString;

}
コード例 #7
0
bool UtilsCode::detectFileCodec()
{
	QFile file ( mFile );
	if (  file.open ( IO_ReadWrite ) )
	{	
		//cout<<"===== file open ok ====="<<endl;
		
		char data[10000];
		int size = file.readBlock(data, sizeof(data));
		file.reset();
		int id = detectCodec(data, size);
		
		//cout<<"########## code id is "<<id<<" ########"<<endl;
		
		mTextCodec = codecByLocalId(id);
		file.close();
		return true;
	}
	return false;
}
コード例 #8
0
ファイル: LockedFile.cpp プロジェクト: arestarh/LameXP
static QByteArray fileHash(QFile &file)
{
	QByteArray hash = QByteArray::fromHex(g_seed);
	QByteArray salt = QByteArray::fromHex(g_salt);
	
	if(file.isOpen() && file.reset())
	{
		QByteArray data = file.readAll();
		QCryptographicHash sha(QCryptographicHash::Sha1);
		QCryptographicHash md5(QCryptographicHash::Md5);

		for(int r = 0; r < 8; r++)
		{
			sha.reset(); md5.reset();
			sha.addData(hash); md5.addData(hash);
			sha.addData(data); md5.addData(data);
			sha.addData(salt); md5.addData(salt);
			hash = sha.result() + md5.result();
		}
	}

	return hash;
}
コード例 #9
0
bool PlaylistImporter::parsePlaylist_pls(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
{
	QRegExp plsEntry("File(\\d+)=(.+)", Qt::CaseInsensitive);
	const QTextCodec *codec = QTextCodec::codecForName("System");
	bool foundAtLeastOneFile = false;

	data.reset();

	while(!data.atEnd())
	{
		QString filePath[3];
		QByteArray line = data.readLine();

		filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
		filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
		filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
		
		for(size_t i = 0; i < 3; i++)
		{
			if(!filePath[i].contains(QChar(QChar::ReplacementCharacter)))
			{
				if(plsEntry.indexIn(filePath[i]) >= 0)
				{
					QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
					filename.setCaching(false);
					fixFilePath(filename, baseDir, rootDir);

					if(filename.exists() && filename.isFile())
					{
						if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
						{
							fileList << filename.canonicalFilePath();
						}
						foundAtLeastOneFile = true;
						break;
					}
				}
			}
		}
	}

	//If we did not find any files yet, try UTF-16 now
	if(!foundAtLeastOneFile)
	{
		const char* codecs[2] = {"UTF-16LE", "UTF-16BE"};

		for(size_t i = 0; i < 2; i++)
		{
			QTextStream stream(&data);
			stream.setAutoDetectUnicode(false);
			stream.setCodec(codecs[i]);
			stream.seek(0i64);

			while(!stream.atEnd())
			{
				QString filePath = stream.readLine().trimmed();

				if(!filePath.contains(QChar(QChar::ReplacementCharacter)))
				{
					if(plsEntry.indexIn(filePath) >= 0)
					{
						QFileInfo filename(QDir::fromNativeSeparators(plsEntry.cap(2)).trimmed());
						filename.setCaching(false);
						fixFilePath(filename, baseDir, rootDir);

						if(filename.exists() && filename.isFile())
						{
							if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
							{
								fileList << filename.canonicalFilePath();
							}
							foundAtLeastOneFile = true;
						}
					}
				}
			}

			if(foundAtLeastOneFile) break;
		}
	}

	return foundAtLeastOneFile;
}
コード例 #10
0
ファイル: PlaylistImporter.cpp プロジェクト: arestarh/LameXP
bool PlaylistImporter::parsePlaylist_m3u(QFile &data, QStringList &fileList, const QDir &baseDir, const QDir &rootDir)
{
	const QTextCodec *codec = QTextCodec::codecForName("System");
	const bool preferUTF8 = data.fileName().endsWith(".m3u8", Qt::CaseInsensitive);
	bool foundAtLeastOneFile = false;
	
	data.reset();

	while(!data.atEnd())
	{
		QString filePath[3];
		QByteArray line = data.readLine();

		if(preferUTF8)
		{
			filePath[0] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
			filePath[1] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
			filePath[2] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
		}
		else
		{
			filePath[0] = QString(QDir::fromNativeSeparators(codec->toUnicode(line.constData(), line.size()).trimmed()));
			filePath[1] = QString(QDir::fromNativeSeparators(QString::fromLatin1(line.constData(), line.size()).trimmed()));
			filePath[2] = QString(QDir::fromNativeSeparators(QString::fromUtf8(line.constData(), line.size()).trimmed()));
		}

		for(size_t i = 0; i < 3; i++)
		{
			if(!(filePath[i].isEmpty() || filePath[i].startsWith("#") || filePath[i].contains(QChar(QChar::ReplacementCharacter))))
			{
				QFileInfo filename(filePath[i]);
				filename.setCaching(false);
				fixFilePath(filename, baseDir, rootDir);

				if(filename.exists() && filename.isFile())
				{
					qDebug("Found: \"%s\"", filePath[i].toUtf8().constData());
					if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
					{
						fileList << filename.canonicalFilePath();
					}
					foundAtLeastOneFile = true;
					break;
				}
			}
		}
	}

	//If we did not find any files yet, try UTF-16 now
	if(!foundAtLeastOneFile)
	{
		const char* codecs[2] = {"UTF-16LE", "UTF-16BE"};

		for(size_t i = 0; i < 2; i++)
		{
			QTextStream stream(&data);
			stream.setAutoDetectUnicode(false);
			stream.setCodec(codecs[i]);
			stream.seek(0i64);

			while(!stream.atEnd())
			{
				QString filePath = stream.readLine().trimmed();

				if(!(filePath.isEmpty() || filePath.startsWith("#") || filePath.contains(QChar(QChar::ReplacementCharacter))))
				{
					QFileInfo filename(filePath);
					filename.setCaching(false);
					fixFilePath(filename, baseDir, rootDir);

					if(filename.exists() && filename.isFile())
					{
						if(isPlaylist(filename.canonicalFilePath()) == notPlaylist)
						{
							fileList << filename.canonicalFilePath();
						}
						foundAtLeastOneFile = true;
					}
				}
			}

			if(foundAtLeastOneFile) break;
		}
	}

	return true;
}
コード例 #11
0
ファイル: allyourbase.cpp プロジェクト: fluxer/kde-workspace
//returns true if the item has been dropped successfully
void KWalletEntryList::itemDropped(QDropEvent *e, QTreeWidgetItem *item) {
	bool ok = true;
	bool isEntry;
	QFile file;
	QDataStream *ds;

	KWalletEntryList *el = 0L;
	QTreeWidgetItem *sel = 0L;

	//detect if we are dragging from kwallet itself
	kDebug() << e->source() << e->source()->metaObject()->className();
	if (e->source() && !strcmp(e->source()->metaObject()->className(), "KWalletEntryList")) {

		el = dynamic_cast<KWalletEntryList*>(e->source());
		if (!el) {
			KMessageBox::error(this, i18n("An unexpected error occurred trying to drop the item"));
		} else
			sel = el->currentItem();
	}

	const QMimeData *em = e->mimeData();
	if (em->hasFormat(QLatin1String("application/x-kwallet-entry"))) {
		//do nothing if we are in the same folder
		if (sel && sel->parent()->parent() ==
				KWalletEntryList::getItemFolder(item)) {
			e->ignore();
			return;
		}
		isEntry = true;
		QByteArray data = em->data(QLatin1String("application/x-kwallet-entry"));
		if (data.isEmpty()) {
			e->ignore();
			return;
		}
		ds = new QDataStream(&data, QIODevice::ReadOnly);
	} else if (em->hasFormat(QLatin1String("application/x-kwallet-folder"))) {
		//do nothing if we are in the same wallet
		if (this == el) {
			e->ignore();
			return;
		}
		isEntry = false;
		QByteArray data = em->data(QLatin1String("application/x-kwallet-folder"));
		if (data.isEmpty()) {
			e->ignore();
			return;
		}
		ds = new QDataStream(&data, QIODevice::ReadOnly);
	} else if (em->hasFormat(QLatin1String("text/uri-list"))) {
		const QList<QUrl> urls = e->mimeData()->urls();
		if (urls.isEmpty()) {
			e->ignore();
			return;
		}
		KUrl u(urls.first());
		if (u.fileName().isEmpty()) {
			e->ignore();
			return;
		}
		QString tmpFile;
		if (KIO::NetAccess::download(u, tmpFile, 0L)) {
			file.setFileName(tmpFile);
			file.open(QIODevice::ReadOnly);
			ds = new QDataStream(&file);
			//check magic to discover mime type
			quint32 magic;
			(*ds) >> magic;
			delete ds;
			if (magic == KWALLETENTRYMAGIC) {
				isEntry = true;
			} else if (magic == KWALLETFOLDERMAGIC) {
				isEntry = false;
			} else {
				kDebug() << "bad magic" ;
				e->ignore();
				return;
			}
			//set the file back to the beginning
			file.reset();
			ds = new QDataStream(&file);
			KIO::NetAccess::removeTempFile(tmpFile);
		} else {
コード例 #12
0
ファイル: header.cpp プロジェクト: elmirador/Watcher
bool filePick()
{
    //Read XSD
    file.setFileName("FACTORY.XSD");
    if (!readFile(file.fileName())) return false;

    QXmlSchema schema;
    schema.load(&file);
    if (!schema.isValid())
    {
        QMessageBox::information(NULL, QWidget::tr("XSDRead")
                                 ,QWidget::tr("This is not a valid XSD File!"));
        return false;
    }

    file.close();

    file.setFileName("FACTORY.XML");
    if (!readFile(file.fileName())) return false;

    //DOM Read-In
    QString errorStr;
    int errorLine, errorColumn;
    if (!doc.setContent(&file, true, &errorStr, &errorLine,
                                &errorColumn)) {
        QMessageBox::information(NULL, QWidget::tr("XSDRead"),
                                 QWidget::tr("Parse error at line %1, column %2:\n%3")
                                 .arg(errorLine)
                                 .arg(errorColumn)
                                 .arg(errorStr));
        return false;
    }

    //Reset the file pointer
    file.reset();

    //XSD Validator
    QXmlSchemaValidator validator(schema);
    if (!validator.validate(&file))
    {
        QMessageBox::information(NULL,QWidget::tr("XSDRead"),
                                 QWidget::tr("This is not a valid XML File!"));
        return false;
    }

    //building Treeroot
    QDomElement node = doc.documentElement();
    nodeData* temp = NULL;
    Treeroot = new nodeData;
    Treeroot->name = node.tagName();
    QDomElement child = node.firstChildElement();

    //parsing child elements (if there is)
    while (!child.isNull())
    {
        temp = new nodeData;
        Treeroot->child.append(temp);
        parseElement(temp,child);
        temp->parent = Treeroot;
        child = child.nextSiblingElement();
    }

    return true;
}
コード例 #13
0
ファイル: Model_CueSheet.cpp プロジェクト: arestarh/LameXP
int CueSheetModel::parseCueFile(QFile &cueFile, const QDir &baseDir, QCoreApplication *application, const QTextCodec *codec)
{
	cueFile.reset();
	qDebug("\n[Cue Sheet Import]");
	bool bForceLatin1 = false;

	//Reject very large files, as parsing might take until forever
	if(cueFile.size() >= 10485760i64)
	{
		qWarning("File is very big. Probably not a Cue Sheet. Rejecting...");
		return 2;
	}

	//Test selected Codepage for decoding errors
	qDebug("Character encoding is: %s.", codec->name().constData());
	const QString replacementSymbol = QString(QChar(QChar::ReplacementCharacter));
	QByteArray testData = cueFile.peek(1048576);
	if((!testData.isEmpty()) && codec->toUnicode(testData.constData(), testData.size()).contains(replacementSymbol))
	{
		qWarning("Decoding error using selected codepage (%s). Enforcing Latin-1.", codec->name().constData());
		bForceLatin1 = true;
	}
	testData.clear();

	//Init text stream
	QTextStream cueStream(&cueFile);
	cueStream.setAutoDetectUnicode(false);
	cueStream.setCodec(bForceLatin1 ? "latin1" : codec->name());
	cueStream.seek(0i64);

	//Create regular expressions
	QRegExp rxFile("^FILE\\s+(\"[^\"]+\"|\\S+)\\s+(\\w+)$", Qt::CaseInsensitive);
	QRegExp rxTrack("^TRACK\\s+(\\d+)\\s(\\w+)$", Qt::CaseInsensitive);
	QRegExp rxIndex("^INDEX\\s+(\\d+)\\s+([0-9:]+)$", Qt::CaseInsensitive);
	QRegExp rxTitle("^TITLE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxPerformer("^PERFORMER\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxGenre("^REM\\s+GENRE\\s+(\"[^\"]+\"|\\S+)$", Qt::CaseInsensitive);
	QRegExp rxYear("^REM\\s+DATE\\s+(\\d+)$", Qt::CaseInsensitive);
	
	bool bPreamble = true;
	bool bUnsupportedTrack = false;

	CueSheetFile *currentFile = NULL;
	CueSheetTrack *currentTrack = NULL;

	m_albumTitle.clear();
	m_albumPerformer.clear();
	m_albumGenre.clear();
	m_albumYear = 0;

	//Loop over the Cue Sheet until all lines were processed
	for(int lines = 0; lines < INT_MAX; lines++)
	{
		if(application)
		{
			application->processEvents();
			if(lines < 128) Sleep(10);
		}
		
		if(cueStream.atEnd())
		{
			qDebug("End of Cue Sheet file.");
			break;
		}

		QString line = cueStream.readLine().trimmed();
		
		/* --- FILE --- */
		if(rxFile.indexIn(line) >= 0)
		{
			qDebug("%03d File: <%s> <%s>", lines, rxFile.cap(1).toUtf8().constData(), rxFile.cap(2).toUtf8().constData());
			if(currentFile)
			{
				if(currentTrack)
				{
					if(currentTrack->isValid())
					{
						currentFile->addTrack(currentTrack);
						currentTrack = NULL;
					}
					else
					{
						LAMEXP_DELETE(currentTrack);
					}
				}
				if(currentFile->isValid())
				{
					m_files.append(currentFile);
					currentFile = NULL;
				}
				else
				{
					LAMEXP_DELETE(currentFile);
				}
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
			if(!rxFile.cap(2).compare("WAVE", Qt::CaseInsensitive) || !rxFile.cap(2).compare("MP3", Qt::CaseInsensitive) || !rxFile.cap(2).compare("AIFF", Qt::CaseInsensitive))
			{
				currentFile = new CueSheetFile(baseDir.absoluteFilePath(UNQUOTE(rxFile.cap(1))));
				qDebug("%03d File path: <%s>", lines, currentFile->fileName().toUtf8().constData());
			}
			else
			{
				bUnsupportedTrack = true;
				qWarning("%03d Skipping unsupported file of type '%s'.", lines, rxFile.cap(2).toUtf8().constData());
				currentFile = NULL;
			}
			bPreamble = false;
			currentTrack = NULL;
			continue;
		}
		
		/* --- TRACK --- */
		if(rxTrack.indexIn(line) >= 0)
		{
			if(currentFile)
			{
				qDebug("%03d   Track: <%s> <%s>", lines, rxTrack.cap(1).toUtf8().constData(), rxTrack.cap(2).toUtf8().constData());
				if(currentTrack)
				{
					if(currentTrack->isValid())
					{
						currentFile->addTrack(currentTrack);
						currentTrack = NULL;
					}
					else
					{
						LAMEXP_DELETE(currentTrack);
					}
				}
				if(!rxTrack.cap(2).compare("AUDIO", Qt::CaseInsensitive))
				{
					currentTrack = new CueSheetTrack(currentFile, rxTrack.cap(1).toInt());
				}
				else
				{
					bUnsupportedTrack = true;
					qWarning("%03d   Skipping unsupported track of type '%s'.", lines, rxTrack.cap(2).toUtf8().constData());
					currentTrack = NULL;
				}
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
			bPreamble = false;
			continue;
		}
		
		/* --- INDEX --- */
		if(rxIndex.indexIn(line) >= 0)
		{
			if(currentFile && currentTrack)
			{
				qDebug("%03d     Index: <%s> <%s>", lines, rxIndex.cap(1).toUtf8().constData(), rxIndex.cap(2).toUtf8().constData());
				if(rxIndex.cap(1).toInt() == 1)
				{
					currentTrack->setStartIndex(parseTimeIndex(rxIndex.cap(2)));
				}
			}
			continue;
		}

		/* --- TITLE --- */
		if(rxTitle.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				m_albumTitle = UNQUOTE(rxTitle.cap(1)).simplified();
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Title: <%s>", lines, rxTitle.cap(1).toUtf8().constData());
				currentTrack->setTitle(UNQUOTE(rxTitle.cap(1)).simplified());
			}
			continue;
		}

		/* --- PERFORMER --- */
		if(rxPerformer.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				m_albumPerformer = UNQUOTE(rxPerformer.cap(1)).simplified();
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Title: <%s>", lines, rxPerformer.cap(1).toUtf8().constData());
				currentTrack->setPerformer(UNQUOTE(rxPerformer.cap(1)).simplified());
			}
			continue;
		}

		/* --- GENRE --- */
		if(rxGenre.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				QString temp = UNQUOTE(rxGenre.cap(1)).simplified();
				for(int i = 0; g_lamexp_generes[i]; i++)
				{
					if(temp.compare(g_lamexp_generes[i], Qt::CaseInsensitive) == 0)
					{
						m_albumGenre = QString(g_lamexp_generes[i]);
						break;
					}
				}
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Genre: <%s>", lines, rxGenre.cap(1).toUtf8().constData());
				QString temp = UNQUOTE(rxGenre.cap(1).simplified());
				for(int i = 0; g_lamexp_generes[i]; i++)
				{
					if(temp.compare(g_lamexp_generes[i], Qt::CaseInsensitive) == 0)
					{
						currentTrack->setGenre(QString(g_lamexp_generes[i]));
						break;
					}
				}
			}
			continue;
		}

		/* --- YEAR --- */
		if(rxYear.indexIn(line) >= 0)
		{
			if(bPreamble)
			{
				bool ok = false;
				unsigned int temp = rxYear.cap(1).toUInt(&ok);
				if(ok) m_albumYear =  temp;
			}
			else if(currentFile && currentTrack)
			{
				qDebug("%03d     Year: <%s>", lines, rxPerformer.cap(1).toUtf8().constData());
				bool ok = false;
				unsigned int temp = rxYear.cap(1).toUInt(&ok);
				if(ok) currentTrack->setYear(temp);
			}
			continue;
		}
	}

	//Append the very last track/file that is still pending
	if(currentFile)
	{
		if(currentTrack)
		{
			if(currentTrack->isValid())
			{
				currentFile->addTrack(currentTrack);
				currentTrack = NULL;
			}
			else
			{
				LAMEXP_DELETE(currentTrack);
			}
		}
		if(currentFile->isValid())
		{
			m_files.append(currentFile);
			currentFile = NULL;
		}
		else
		{
			LAMEXP_DELETE(currentFile);
		}
	}

	//Finally calculate duration of each track
	int nFiles = m_files.count();
	for(int i = 0; i < nFiles; i++)
	{
		if(application)
		{
			application->processEvents();
			Sleep(10);
		}

		CueSheetFile *currentFile = m_files.at(i);
		int nTracks = currentFile->trackCount();
		if(nTracks > 1)
		{
			for(int j = 1; j < nTracks; j++)
			{
				CueSheetTrack *currentTrack = currentFile->track(j);
				CueSheetTrack *previousTrack = currentFile->track(j-1);
				double duration = currentTrack->startIndex() - previousTrack->startIndex();
				previousTrack->setDuration(qMax(0.0, duration));
			}
		}
	}
	
	//Sanity check of track numbers
	if(nFiles > 0)
	{
		bool hasTracks = false;
		int previousTrackNo = -1;
		bool trackNo[100];
		for(int i = 0; i < 100; i++)
		{
			trackNo[i] = false;
		}

		for(int i = 0; i < nFiles; i++)
		{
			if(application)
			{
				application->processEvents();
				Sleep(10);
			}
			CueSheetFile *currentFile = m_files.at(i);
			int nTracks = currentFile->trackCount();
			if(nTracks > 1)
			{
				for(int j = 0; j < nTracks; j++)
				{
					int currentTrackNo = currentFile->track(j)->trackNo();
					if(currentTrackNo > 99)
					{
						qWarning("Track #%02d is invalid (maximum is 99), Cue Sheet is inconsistent!", currentTrackNo);
						return ErrorInconsistent;
					}
					if(currentTrackNo <= previousTrackNo)
					{
						qWarning("Non-increasing track numbers (%02d -> %02d), Cue Sheet is inconsistent!", previousTrackNo, currentTrackNo);
						return ErrorInconsistent;
					}
					if(trackNo[currentTrackNo])
					{
						qWarning("Track #%02d exists multiple times, Cue Sheet is inconsistent!", currentTrackNo);
						return ErrorInconsistent;
					}
					trackNo[currentTrackNo] = true;
					previousTrackNo = currentTrackNo;
					hasTracks = true;
				}
			}
		}
		
		if(!hasTracks)
		{
			qWarning("Could not find at least one valid track in the Cue Sheet!");
			return ErrorInconsistent;
		}

		return ErrorSuccess;
	}
	else
	{
		qWarning("Could not find at least one valid input file in the Cue Sheet!");
		return bUnsupportedTrack ? ErrorUnsupported : ErrorBadFile;
	}
}
コード例 #14
0
ファイル: allyourbase.cpp プロジェクト: serghei/kde3-kdeutils
//returns true if the item has been dropped successfully
void KWalletEntryList::itemDropped(QDropEvent *e, QListViewItem *item) {
	bool ok = true;
	bool isEntry;
	QFile file;
	QDataStream *ds;

	KWalletEntryList *el = 0L;
	QListViewItem *sel = 0L;

	//detect if we are dragging from kwallet itself
	if (e->source() && e->source()->parent() &&
		!strcmp(e->source()->parent()->className(), "KWalletEntryList")) {

		el = dynamic_cast<KWalletEntryList*>(e->source()->parent());
		if (!el) {
			KMessageBox::error(this, i18n("An unexpected error occurred trying to drop the item"));
		} else
			sel = el->selectedItem();
	}

	if (e->provides("application/x-kwallet-entry")) {
		//do nothing if we are in the same folder
		if (sel && sel->parent()->parent() == 
				KWalletEntryList::getItemFolder(item)) {
			e->ignore();
			return;
		}
		isEntry = true;
		QByteArray data = e->encodedData("application/x-kwallet-entry");
		if (data.isEmpty()) {
			e->ignore();
			return;
		}
		ds = new QDataStream(data, IO_ReadOnly);
	} else if (e->provides("application/x-kwallet-folder")) {
		//do nothing if we are in the same wallet
		if (this == el) {
			e->ignore();
			return;
		}
		isEntry = false;
		QByteArray data = e->encodedData("application/x-kwallet-folder");
		if (data.isEmpty()) {
			e->ignore();
			return;
		}
		ds = new QDataStream(data, IO_ReadOnly);
	} else if (e->provides("text/uri-list")) {
		QStrList urls;
		QUriDrag::decode(e, urls);
		if (urls.isEmpty()) {
			e->ignore();
			return;
		}
		KURL u(urls.first());
		if (u.fileName().isEmpty()) {
			e->ignore();
			return;
		}
		QString tmpFile;
		if (KIO::NetAccess::download(u, tmpFile, 0L)) {
			file.setName(tmpFile);
			file.open(IO_ReadOnly);
			ds = new QDataStream(&file);
			//check magic to discover mime type
			Q_UINT32 magic;
			(*ds) >> magic;
			if (magic == KWALLETENTRYMAGIC) {
				isEntry = true;
			} else if (magic == KWALLETFOLDERMAGIC) {
				isEntry = false;
			} else {
				kdDebug() << "bad magic" << endl;
				e->ignore();
				return;
			}
			delete ds;
			//set the file back to the beginning
			file.reset();
			ds = new QDataStream(&file);
			KIO::NetAccess::removeTempFile(tmpFile);
		} else {