Пример #1
0
void ut_load::testIODevice()
{
    QuillImageFilter *filter =
        QuillImageFilterFactory::createImageFilter("org.maemo.load");
    QFile *fileIO = new QFile("/usr/share/quillimagefilter-tests/images/16_color_palette.png");
    QVERIFY(fileIO->open(QIODevice::ReadOnly));
    QCOMPARE(fileIO->isOpen(),true);
    QCOMPARE(fileIO->isReadable(),true);
    QVERIFY(fileIO);
    filter->setIODevice(fileIO);
    QCOMPARE(fileIO, filter->iODevice());
    QImage image("/usr/share/quillimagefilter-tests/images/16_color_palette.png");
    QImage loadedImage1 = filter->apply(image);
    QVERIFY(Unittests::compareImage(loadedImage1, image));
    delete fileIO;
    delete filter;
}
Пример #2
0
bool ccObject::toFile(QFile& out) const
{
    assert(out.isOpen() && (out.openMode() & QIODevice::WriteOnly));

    //class ID (dataVersion>=20)
    //DGM: on 64 bits since version 34
    uint64_t classID = static_cast<uint64_t>(getClassID());
    if (out.write((const char*)&classID,8) < 0)
        return WriteError();

    //unique ID (dataVersion>=20)
    //DGM: this ID will be usefull to recreate dynamic links between entities!
    uint32_t uniqueID = (uint32_t)m_uniqueID;
    if (out.write((const char*)&uniqueID,4) < 0)
        return WriteError();

    //name (dataVersion>=22)
    {
        QDataStream outStream(&out);
        outStream << m_name;
    }

    //flags (dataVersion>=20)
    uint32_t objFlags = (uint32_t)m_flags;
    if (out.write((const char*)&objFlags,4) < 0)
        return WriteError();

    //meta data (dataVersion>=30)
    {
        //count
        uint32_t metaDataCount = (uint32_t)m_metaData.size();
        if (out.write((const char*)&metaDataCount,4) < 0)
            return WriteError();

        //"key + value" pairs
        QDataStream outStream(&out);
        for (QVariantMap::const_iterator it = m_metaData.begin(); it != m_metaData.end(); ++it)
        {
            outStream << it.key();
            outStream << it.value();
        }
    }

    return true;
}
Пример #3
0
bool ccHObject::toFile_MeOnly(QFile& out) const
{
	assert(out.isOpen() && (out.openMode() & QIODevice::WriteOnly));

	/*** ccHObject takes in charge the ccDrawableObject properties (which is not a ccSerializableObject) ***/

	//'visible' state (dataVersion>=20)
	if (out.write((const char*)&m_visible,sizeof(bool)) < 0)
		return WriteError();
	//'lockedVisibility' state (dataVersion>=20)
	if (out.write((const char*)&m_lockedVisibility,sizeof(bool)) < 0)
		return WriteError();
	//'colorsDisplayed' state (dataVersion>=20)
	if (out.write((const char*)&m_colorsDisplayed,sizeof(bool)) < 0)
		return WriteError();
	//'normalsDisplayed' state (dataVersion>=20)
	if (out.write((const char*)&m_normalsDisplayed,sizeof(bool)) < 0)
		return WriteError();
	//'sfDisplayed' state (dataVersion>=20)
	if (out.write((const char*)&m_sfDisplayed,sizeof(bool)) < 0)
		return WriteError();
	//'colorIsOverriden' state (dataVersion>=20)
	if (out.write((const char*)&m_colorIsOverriden,sizeof(bool)) < 0)
		return WriteError();
	if (m_colorIsOverriden)
	{
		//'tempColor' (dataVersion>=20)
		if (out.write((const char*)m_tempColor.rgb,sizeof(ColorCompType)*3) < 0)
			return WriteError();
	}
	//'glTransEnabled' state (dataVersion>=20)
	if (out.write((const char*)&m_glTransEnabled,sizeof(bool)) < 0)
		return WriteError();
	if (m_glTransEnabled)
		if (!m_glTrans.toFile(out))
			return false;

	//'showNameIn3D' state (dataVersion>=24)
	if (out.write((const char*)&m_showNameIn3D,sizeof(bool)) < 0)
		return WriteError();

	return true;
}
Пример #4
0
bool ccObject::fromFile(QFile& in, short dataVersion)
{
	assert(in.isOpen() && (in.openMode() & QIODevice::ReadOnly));

	if (dataVersion<20)
		return CorruptError();

	//DGM: if we are here, we assume the class ID has already been read!
	//Call ccObject::readClassIDFromFile if necessary
	////class ID (dataVersion>=20)
	//uint32_t classID = 0;
	//if (in.read((char*)&classID,4)<0)
	//	return ReadError();

	//unique ID (dataVersion>=20)
	//DGM: this ID will be usefull to recreate dynamic links between entities!
	uint32_t uniqueID = 0;
	if (in.read((char*)&uniqueID,4)<0)
		return ReadError();
	m_uniqueID = (unsigned)uniqueID;

	//name
	if (dataVersion < 22) //old style
	{
		char name[256];
		if (in.read(name,256)<0)
			return ReadError();
		setName(name);
	}
	else //(dataVersion>=22)
	{
		QDataStream inStream(&in);
		inStream >> m_name;
	}

	//flags (dataVersion>=20)
	uint32_t flags = 0;
	if (in.read((char*)&flags,4)<0)
		return ReadError();
	m_flags = (unsigned)flags;

	return true;
}
Пример #5
0
void    installMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
#ifdef  CONSOLE
    static QFile        file(QDir::tempPath().append('/').append(APP_NAME).append("_svc.log"));
#else
    static QFile        file(QDir::tempPath().append('/').append(APP_NAME).append("_app.log"));
#endif
    static QTextStream  out(&file);

    if (!file.isOpen() && !file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        abort();
    }

    out << QDateTime::currentDateTime().toString(QStringLiteral("[yy-MM-dd HH:mm:ss] "));
    switch (type) {
        case QtDebugMsg:
            out << "Debug: " << msg;
            break;
        case QtInfoMsg:
            out << "Info: " << msg;
            break;
        case QtWarningMsg:
            out << "Warning: " << msg;
            break;
        case QtCriticalMsg:
            out << "Critical: " << msg;
            break;
        case QtFatalMsg:
            out << "Fatal: " << msg;
            break;
    }

#ifdef  QT_DEBUG
    out << ' (' << context.file << ':' << context.line << ", " << context.function << ')';
#else
    Q_UNUSED(context);
#endif

    endl(out);
    if (type == QtFatalMsg) {
        abort();
    }
}
Пример #6
0
void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    bool toFile = data.isOpen();

    QByteArray localMsg = msg.toLocal8Bit();
    QTextStream out;
    if (toFile)
        out.setDevice(&data);
    QString newLine = "\n";
    #ifdef Q_OS_WIN32
        newLine = "\r\n";
    #endif

    QString f = QString("%1").arg(context.function, -70, QChar(' '));

    switch (type) {
    case QtDebugMsg:
        if (toFile)
            out << "[" << f << "] " << localMsg << newLine;
        else
            fprintf(stderr, "%s %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtWarningMsg:
        if (toFile)
            out << "[" << f << "] " << "WARNING: " << localMsg << newLine;
        else
            fprintf(stderr, "%s WARNING: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtCriticalMsg:
        if (toFile)
            out << "[" << f << "] " << "CRITICAL: " << localMsg << newLine;
        else
            fprintf(stderr, "%s CRITICAL: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        break;
    case QtFatalMsg:
        if (toFile)
            out << "[" << f << "] " << "FATAL: " << localMsg << newLine;
        else
            fprintf(stderr, "%s FATAL: %s%s", qPrintable(f), qPrintable(localMsg), qPrintable(newLine));
        abort();
    }
}
Пример #7
0
/**
 * Save the informations of coordinates
 * @brief MainWindow::on_savefinButton_clicked
 */
void MainWindow::on_savefinButton_clicked()
{
    myPlayer->Stop();
    ui->playBtn->setText("Play");
    //QMessageBox pour confirmer de sauvegarder
    QMessageBox msgBox;
    QFile infoFile;
    QTextStream output;
    QString listitem;
    msgBox.setInformativeText("Voulez-vous confirmer l'enregistrement?");
    msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Save);
    int ret = msgBox.exec();
    if(ret == QMessageBox::Save){
        //myPlayer->setSaveFin(true);
        /****Créer une répertoire avec le nom de vidéo*************/
        QDir *temp = new QDir;
        QString repertoire = "C://temp/"+videoName;
        bool exist = temp->exists(repertoire);
        if(!exist)
        {
           bool ok = temp->mkdir(repertoire);
        }
        //Ouvrir la fenêtre de sauvegarder
        QString fileName = QFileDialog::getSaveFileName(this, "Sauvegarder trajectoire", repertoire,
                                                        "csv fichiers (*.csv);;All files (*.*)");
        infoFile.setFileName(fileName);
        infoFile.open(QIODevice::WriteOnly);
        /* Check it opened OK */
        if(!infoFile.isOpen()){
            qDebug() <<  "Error, unable to open" ;
        }
        output.setDevice(&infoFile);
        //Sauvegarder les textes dans QListWidget
        int c = ui->listWidget->count();
        for(int row = 0; row < c; row++){
            QListWidgetItem *item = ui->listWidget->item(row);
            listitem = item->text() + "\n";
            output<<listitem;
        }
    }
}
Пример #8
0
void Gitarre::WriteSavedRepos ()
{
	QFile saveFile (UserDataDir.absolutePath() + "/repos");
	saveFile.open (QIODevice::WriteOnly | QIODevice::Text);
	if (saveFile.isOpen())
	{
		QXmlStreamWriter writer (&saveFile);
		writer.setAutoFormatting(true);
		writer.writeStartDocument("1.0");
		writer.writeStartElement ("saves");
		for (unsigned int i = 0; i < Repos.size(); ++i)
		{
			writer.writeStartElement ("repository");
			writer.writeAttribute ("path", Repos[i]->GetDir().absolutePath());
			writer.writeEndElement ();
		}
		writer.writeEndDocument();
		saveFile.close();
	}
}
Пример #9
0
//specific methods (old style)
static int ReadEntityHeader(QFile& in, unsigned &numberOfPoints, HeaderFlags& header)
{
	assert(in.isOpen());

	//number of points
	uint32_t ptsCount;
	if (in.read((char*)&ptsCount,4) < 0)
		return -1;
	numberOfPoints = (unsigned)ptsCount;

	//flags (colors, etc.)
	uint8_t flag;
	if (in.read((char*)&flag,1) < 0)
		return -1;

	header.flags.fromByte((unsigned char)flag);
	//assert(header.bit1 == true); //should always be 0!

	return 0;
}
Пример #10
0
ExchangeFile::ExchangeFile()
{
    QFile exFile;
    exFile.setFileName("Message.txt");
    if(exFile.size() == 0){
        exFile.remove();
        return;
    }else{
        exFile.close();
    }
    QSettings settings("AO_Batrakov_Inc.", "EmployeeClient");
    QString fileName = settings.value("numprefix").toString();
    fileName += "_SRV.txt";

    qDebug()<<exFile.rename(fileName);
    exFile.close();

    qDebug()<<exFile.isOpen()<<" - "<<exFile.fileName()<<fileName;

    QString fN = exFile.fileName();

    PutFile putFile;
    putFile.putFile(fN);

    PutFile putFtp1;
    QString nullFileName = "Null.txt";
    //nullFileName += fN;
    QFile nullFile;
    nullFile.setFileName(nullFileName);
    nullFile.open(QIODevice::WriteOnly);
    QByteArray rr = "22\n10";
    nullFile.write(rr);
    nullFile.close();
    putFtp1.putFile(nullFileName);
    nullFile.remove();

    QFile file;

    file.setFileName("null.txt");
    file.remove();
}
Пример #11
0
//----------------------------------------------------------------------------------------------------------------------
void myMessageOutput(QtMsgType /*type*/, const QMessageLogContext& /*context*/, const QString& msg)
{
#ifdef TEST_ONLY
    static QFile logFile("TokenTest_Log.txt");
#else
    static QFile logFile("TokenGraver_Log.txt");
#endif

    if (!logFile.isOpen()) {
        logFile.open(QIODevice::Append);
        QString newStartString("\r\n\r\n==========================================\r\n   Новый запуск   ");
        newStartString += curDateTime() + "\r\n==========================================\r\n\r\n";
        logFile.write(newStartString.toLocal8Bit());
    }

    if(!msg.isEmpty()) {
        QString logMsg = curTime() + "   " + msg + "\r\n";
        logFile.write(logMsg.toLocal8Bit());
        logFile.flush();
    }
}
Пример #12
0
void MainWindow::on_pbSaveLog_clicked()
{
    use_settings;

    settings.beginGroup("FileDialogs");
    QString path = settings.value("BinDialogPath","").toString();
    settings.endGroup();


    QString s = QFileDialog::getSaveFileName(this, tr("Save log"),path,tr("Log (*.log);;All files (*.*)"));
    if(s.isEmpty())return;
    QFile f (s);
    f.open(QFile::WriteOnly);
    if(!f.isOpen())
    {
        QMessageBox::warning(this,tr("File save error"),tr("Can't save file"));
        return;
    }
    f.write(ui->consoleView->toPlainText().toUtf8());
    f.close();
}
Пример #13
0
static __forceinline void doValidateHash(HANDLE &fileHandle, const int &fileDescriptor, const QByteArray &expectedHash, const QString &filePath)
{
	QFile checkFile;

	//Now re-open the file for reading
	if(g_useFileDescrForQFile)
	{
		checkFile.open(fileDescriptor, QIODevice::ReadOnly);
	}
	else
	{
		checkFile.setFileName(filePath);
		for(int i = 0; i < 64; i++)
		{
			if(checkFile.open(QIODevice::ReadOnly)) break;
			if(!i) qWarning("Failed to re-open file on first attemp, retrying...");
			Sleep(100);
		}
	}

	//Opened successfully
	if((!checkFile.isOpen()) || checkFile.peek(1).isEmpty())
	{
		QFile::remove(filePath);
		MUTILS_THROW_FMT("File '%s' could not be read!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
	}

	//Verify file contents
	const QByteArray hash = FileHash::computeHash(checkFile);
	checkFile.close();

	//Compare hashes
	if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
	{
		qWarning("\nFile checksum error:\n A = %s\n B = %s\n", expectedHash.constData(), hash.constData());
		CLOSE_HANDLE(fileHandle);
		QFile::remove(filePath);
		MUTILS_THROW_FMT("File '%s' is corruputed, take care!", MUTILS_UTF8(QFileInfo(filePath).fileName()));
	}
}
Пример #14
0
void CrashHandler::generateReport(void)
{
    Messagebox msgbox;
    QByteArray buf, comp_buf;
    QFile output;

    //Configures the path to the .crash file generated
    QString crash_file=QFileInfo((GlobalAttributes::TEMPORARY_DIR +
                                  GlobalAttributes::DIR_SEPARATOR +
                                  GlobalAttributes::CRASH_REPORT_FILE).arg(QDateTime::currentDateTime().toString("_yyyyMMdd_hhmm"))).absoluteFilePath();

    //Opens the file for writting
    output.setFileName(crash_file);
    output.open(QFile::WriteOnly);

    if(!output.isOpen())
        msgbox.show(trUtf8("Error"), Exception::getErrorMessage(ERR_FILE_NOT_WRITTEN).arg(crash_file), Messagebox::ERROR_ICON);
    else
    {
        buf.append(actions_txt->toPlainText().toUtf8());
        buf.append(CHR_DELIMITER);

        if(attach_mod_chk->isChecked())
            buf.append(model_txt->toPlainText().toUtf8());
        buf.append(CHR_DELIMITER);

        buf.append(stack_txt->toPlainText().toUtf8());
        buf.append(CHR_DELIMITER);

        //Compress the buffer (using zlib) in a compression rate at 8
        comp_buf=qCompress(buf, 8);

        //Saves the buffer
        output.write(comp_buf.data(), comp_buf.size());
        output.close();

        msgbox.show(trUtf8("Information"), trUtf8("Crash report successfuly generated! Please send the file <strong>%1</strong> to <em>%2</em> in order be debugged. Thank you for the collaboration!").arg(crash_file).arg("*****@*****.**"), Messagebox::INFO_ICON);
        this->close();
    }
}
Пример #15
0
bool ccHObject::fromFile_MeOnly(QFile& in, short dataVersion)
{
	assert(in.isOpen() && (in.openMode() & QIODevice::ReadOnly));

	/*** ccHObject takes in charge the ccDrawableObject properties (which is not a ccSerializableObject) ***/

	//'visible' state (dataVersion>=20)
	if (in.read((char*)&visible,sizeof(bool))<0)
		return ReadError();
	//'lockedVisibility' state (dataVersion>=20)
	if (in.read((char*)&lockedVisibility,sizeof(bool))<0)
		return ReadError();
	//'colorsDisplayed' state (dataVersion>=20)
	if (in.read((char*)&colorsDisplayed,sizeof(bool))<0)
		return ReadError();
	//'normalsDisplayed' state (dataVersion>=20)
	if (in.read((char*)&normalsDisplayed,sizeof(bool))<0)
		return ReadError();
	//'sfDisplayed' state (dataVersion>=20)
	if (in.read((char*)&sfDisplayed,sizeof(bool))<0)
		return ReadError();
	//'colorIsOverriden' state (dataVersion>=20)
	if (in.read((char*)&colorIsOverriden,sizeof(bool))<0)
		return ReadError();
	if (colorIsOverriden)
	{
		//'tempColor' (dataVersion>=20)
		if (in.read((char*)tempColor,sizeof(colorType)*3)<0)
			return ReadError();
	}
	//'glTransEnabled' state (dataVersion>=20)
	if (in.read((char*)&glTransEnabled,sizeof(bool))<0)
		return ReadError();
	if (glTransEnabled)
		if (!glTrans.fromFile(in,dataVersion))
			return false;

	return true;
}
Пример #16
0
void MapsPrivate::loadDiffs( const QString& basepath, unsigned int id )
{
	// Try to read the index
	QFile mapdiflist( basepath + QString( "mapdifl%1.mul" ).arg( id ) );
	mapdifdata.setName( basepath + QString( "mapdif%1.mul" ).arg( id ) );
	mapdifdata.open( IO_ReadOnly );

	// Try to read a list of ids
	if ( mapdifdata.isOpen() && mapdiflist.open( IO_ReadOnly ) )
	{
		QDataStream listinput( &mapdiflist );
		listinput.setByteOrder( QDataStream::LittleEndian );
		unsigned int offset = 0;
		while ( !listinput.atEnd() )
		{
			unsigned int id;
			listinput >> id;
			mappatches.insert( id, offset );
			offset += sizeof( mapblock );
		}
		mapdiflist.close();
	}
Пример #17
0
QByteArray QCOMM::md5(QFile &file)
{
    unsigned char *buf;
    bool isopen;
    if(!file.exists())
        return QByteArray();
    if(file.size()==0)
        return QByteArray();
    if(file.isOpen())
        isopen = TRUE;
    if(isopen&&(!file.open(QIODevice::ReadOnly)))
        return QByteArray();
    buf = file.map(0,file.size());
    if(isopen)
        file.close();
    if(0==buf)
        return QByteArray();
    QByteArray data = QByteArray::fromRawData((char*)buf,file.size());
    QByteArray md5 =  QCryptographicHash::hash (data, QCryptographicHash::Md5);
    file.unmap(buf);
    return md5;
}
Пример #18
0
bool ccHObject::toFile(QFile& out) const
{
	assert(out.isOpen() && (out.openMode() & QIODevice::WriteOnly));

	//write 'ccObject' header
	if (!ccObject::toFile(out))
		return false;

	//write own data
	if (!toFile_MeOnly(out))
		return false;

	//(serializable) child count (dataVersion >= 20)
	uint32_t serializableCount = 0;
	for (unsigned i = 0; i < m_children.size(); ++i)
		if (m_children[i]->isSerializable())
			++serializableCount;
	if (out.write((const char*)&serializableCount, sizeof(uint32_t)) < 0)
		return WriteError();

	//write serializable children (if any)
	for (unsigned i = 0; i < m_children.size(); ++i)
	{
		if (m_children[i]->isSerializable())
		{
			if (!m_children[i]->toFile(out))
				return false;
		}
	}

	//write current selection behavior (dataVersion >= 23)
	if (out.write((const char*)&m_selectionBehavior, sizeof(SelectionBehavior)) < 0)
		return WriteError();

	//write transformation history (dataVersion >= 45)
	m_glTransHistory.toFile(out);

	return true;
}
Пример #19
0
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;
}
Пример #20
0
void tst_QWaveDecoder::readPerByte()
{
    QFile stream;
    stream.setFileName(testFilePath("isawav_2_8_44100.wav"));
    stream.open(QIODevice::ReadOnly);

    QVERIFY(stream.isOpen());

    QWaveDecoder waveDecoder(&stream);
    QSignalSpy validFormatSpy(&waveDecoder, SIGNAL(formatKnown()));

    QTRY_COMPARE(validFormatSpy.count(), 1);
    QVERIFY(waveDecoder.size() > 0);

    qint64 readSize = 0;
    char buf;
    for (int ii = 0; ii < waveDecoder.size(); ++ii)
        readSize += waveDecoder.read(&buf, 1);
    QVERIFY(readSize == waveDecoder.size());
    QVERIFY(waveDecoder.read(&buf,1) == 0);

    stream.close();
}
Пример #21
0
bool FormattedTouchstone::Write(FormattedNetworkData &network, QString filename) {
    QFile file;
    CreateFile(file, filename, network);
    if (file.isWritable() == false) {
        if (file.isOpen()) file.close();
        return(false);
    }
    //else
    QTextStream snpFile(&file);
    WriteComments(network, snpFile);
    WriteOptions(network, snpFile);
    if (network.numberOfPorts() != 2)
        WriteData(network, snpFile);
    else {
        FormattedNetworkData copyNetwork = network;
        Flip2Ports(copyNetwork);
        WriteData(copyNetwork, snpFile);

    }
    snpFile.flush();
    file.close();
    return(true);
}
Пример #22
0
CC_CLASS_ENUM ccObject::ReadClassIDFromFile(QFile& in, short dataVersion)
{
    assert(in.isOpen() && (in.openMode() & QIODevice::ReadOnly));

    //class ID (on 32 bits between version 2.0 and 3.3, then 64 bits from version 3.4)
    CC_CLASS_ENUM classID = CC_TYPES::OBJECT;
    if (dataVersion < 34)
    {
        uint32_t _classID = 0;
        if (in.read((char*)&_classID,4) < 0)
            return ReadError();
        classID = static_cast<CC_CLASS_ENUM>(_classID);
    }
    else
    {
        uint64_t _classID = 0;
        if (in.read((char*)&_classID,8) < 0)
            return ReadError();
        classID = static_cast<CC_CLASS_ENUM>(_classID);
    }

    return classID;
}
Пример #23
0
// Write stack frames as task file for displaying it in the build issues pane.
void saveTaskFile(QWidget *parent, const StackHandler *sh)
{
    QFile file;
    QFileDialog fileDialog(parent);
    fileDialog.setAcceptMode(QFileDialog::AcceptSave);
    fileDialog.selectFile(QDir::currentPath() + QLatin1String("/stack.tasks"));
    while (!file.isOpen()) {
        if (fileDialog.exec() != QDialog::Accepted)
            return;
        const QString fileName = fileDialog.selectedFiles().front();
        file.setFileName(fileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            Core::AsynchronousMessageBox::warning(StackTreeView::tr("Cannot Open Task File"),
                                 StackTreeView::tr("Cannot open \"%1\": %2").arg(QDir::toNativeSeparators(fileName), file.errorString()));
        }
    }

    QTextStream str(&file);
    foreach (const StackFrame &frame, sh->frames()) {
        if (frame.isUsable())
            str << frame.file << '\t' << frame.line << "\tstack\tFrame #" << frame.level << '\n';
    }
}
Пример #24
0
bool QMacPasteboardMimeQt3Any::loadMimeRegistry()
{
    if(!library_file.isOpen()) {
        if(!qt_mac_openMimeRegistry(true, QIODevice::ReadWrite, library_file)) {
            QFile global;
            if(qt_mac_openMimeRegistry(true, QIODevice::ReadOnly, global)) {
                qt_mac_loadMimeRegistry(global, mime_registry, current_max);
                global.close();
            }
            if(!qt_mac_openMimeRegistry(false, QIODevice::ReadWrite, library_file)) {
                qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open mime resources %s -- %s", library_file.fileName().toLatin1().constData(),
                         library_file.errorString().toLatin1().constData());
                return false;
            }
        }
    }

    QFileInfo fi(library_file);
    if(!mime_registry_loaded.isNull() && mime_registry_loaded == fi.lastModified())
        return true;
    mime_registry_loaded = fi.lastModified();
    qt_mac_loadMimeRegistry(library_file, mime_registry, current_max);
    return true;
}
Пример #25
0
// Write stack frames as task file for displaying it in the build issues pane.
void StackHandler::saveTaskFile()
{
    QFile file;
    QFileDialog fileDialog(Core::ICore::dialogParent());
    fileDialog.setAcceptMode(QFileDialog::AcceptSave);
    fileDialog.selectFile(QDir::currentPath() + "/stack.tasks");
    while (!file.isOpen()) {
        if (fileDialog.exec() != QDialog::Accepted)
            return;
        const QString fileName = fileDialog.selectedFiles().constFirst();
        file.setFileName(fileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QString msg = tr("Cannot open \"%1\": %2")
                    .arg(QDir::toNativeSeparators(fileName), file.errorString());
            Core::AsynchronousMessageBox::warning(tr("Cannot Open Task File"), msg);
        }
    }

    QTextStream str(&file);
    for (const StackFrame &frame : frames()) {
        if (frame.isUsable())
            str << frame.file << '\t' << frame.line << "\tstack\tFrame #" << frame.level << '\n';
    }
}
Пример #26
0
PgnGame PgnGameIterator::next(bool* ok, int depth)
{
	Q_ASSERT(hasNext());

	int newDbIndex = m_dlg->databaseIndexFromGame(m_gameIndex);
	Q_ASSERT(newDbIndex != -1);

	if (newDbIndex != m_dbIndex)
	{
		m_dbIndex = newDbIndex;
		m_file.close();

		const PgnDatabase* db = m_dlg->m_dbManager->databases().at(m_dbIndex);
		if (db->status() == PgnDatabase::Ok)
		{
			m_file.setFileName(db->fileName());
			if (m_file.open(QIODevice::ReadOnly | QIODevice::Text))
				m_in.setDevice(&m_file);
			else
				m_in.setDevice(nullptr);
		}
	}

	PgnGame game;
	if (!m_file.isOpen())
	{
		*ok = false;
		m_gameIndex++;
		return game;
	}

	const PgnGameEntry* entry = m_dlg->m_pgnGameEntryModel->entryAt(m_gameIndex++);
	*ok = m_in.seek(entry->pos(), entry->lineNumber()) && game.read(m_in, depth);

	return game;
}
Пример #27
0
bool ccScalarField::fromFile(QFile& in, short dataVersion, int flags)
{
	assert(in.isOpen() && (in.openMode() & QIODevice::ReadOnly));

	if (dataVersion < 20)
		return CorruptError();

	//name (dataVersion>=20)
	if (in.read(m_name,256) < 0)
		return ReadError();

	//'strictly positive' state (20 <= dataVersion < 26)
	bool onlyPositiveValues = false;
	if (dataVersion < 26)
	{
		if (in.read((char*)&onlyPositiveValues,sizeof(bool)) < 0)
			return ReadError();
	}

	//data (dataVersion>=20)
	bool result = false;
	{
		bool fileScalarIsFloat = (flags & ccSerializableObject::DF_SCALAR_VAL_32_BITS);
		if (fileScalarIsFloat && sizeof(ScalarType) == 8) //file is 'float' and current type is 'double'
		{
			result = ccSerializationHelper::GenericArrayFromTypedFile<1,ScalarType,float>(*this,in,dataVersion);
		}
		else if (!fileScalarIsFloat && sizeof(ScalarType) == 4) //file is 'double' and current type is 'float'
		{
			result = ccSerializationHelper::GenericArrayFromTypedFile<1,ScalarType,double>(*this,in,dataVersion);
		}
		else
		{
			result = ccSerializationHelper::GenericArrayFromFile(*this,in,dataVersion);
		}
	}
	if (!result)
		return false;

	//convert former 'hidden/NaN' values for non strictly positive SFs (dataVersion < 26)
	if (dataVersion < 26)
	{
		const ScalarType FORMER_BIG_VALUE = static_cast<ScalarType>(sqrt(3.4e38f)-1.0f);

		for (unsigned i=0; i<m_maxCount; ++i)
		{
			ScalarType val = getValue(i);
			//convert former 'HIDDEN_VALUE' and 'BIG_VALUE' to 'NAN_VALUE'
			if ((onlyPositiveValues && val < 0) || (!onlyPositiveValues && val >= FORMER_BIG_VALUE))
				val = NAN_VALUE;
		}
	}

	//displayed values & saturation boundaries (dataVersion>=20)
	double minDisplayed = 0;
	if (in.read((char*)&minDisplayed,sizeof(double)) < 0)
		return ReadError();
	double maxDisplayed = 0;
	if (in.read((char*)&maxDisplayed,sizeof(double)) < 0)
		return ReadError();
	double minSaturation = 0;
	if (in.read((char*)&minSaturation,sizeof(double)) < 0)
		return ReadError();
	double maxSaturation = 0;
	if (in.read((char*)&maxSaturation,sizeof(double)) < 0)
		return ReadError();
	double minLogSaturation = 0;
	if (in.read((char*)&minLogSaturation,sizeof(double)) < 0)
		return ReadError();
	double maxLogSaturation = 0;
	if (in.read((char*)&maxLogSaturation,sizeof(double)) < 0)
		return ReadError();

	if (dataVersion < 27)
	{
		//'absolute saturation' state (27>dataVersion>=20)
		bool absSaturation = false;
		if (in.read((char*)&absSaturation,sizeof(bool)) < 0)
			return ReadError();
		//quite equivalent to 'symmetrical mode' now...
		m_symmetricalScale = absSaturation;
	}

	//'logarithmic scale' state (dataVersion>=20)
	if (in.read((char*)&m_logScale,sizeof(bool)) < 0)
		return ReadError();

	if (dataVersion < 27)
	{
		bool autoBoundaries = false;
		//'automatic boundaries update' state (dataVersion>=20)
		if (in.read((char*)&autoBoundaries,sizeof(bool)) < 0)
			return ReadError();
		//warn the user that this option is deprecated
		if (!autoBoundaries)
		{
			ccLog::Warning("[ccScalarField] Former 'released' boundaries are deprecated!");
			ccLog::Warning("[ccScalarField] You'll have to create the corresponding 'absolute' color scale (see the Color Scale Manager) and replace the file.");
		}
	}

	//new attributes
	if (dataVersion >= 27)
	{
		//'symmetrical scale' state (27<=dataVersion)
		if (in.read((char*)&m_symmetricalScale,sizeof(bool)) < 0)
			return ReadError();

		//'NaN values in grey' state (dataVersion>=27)
		if (in.read((char*)&m_showNaNValuesInGrey,sizeof(bool)) < 0)
			return ReadError();

		//'always show 0' state (27<=dataVersion)
		if (in.read((char*)&m_alwaysShowZero,sizeof(bool)) < 0)
			return ReadError();
	}

	//color scale
	{
		ccColorScalesManager* colorScalesManager = ccColorScalesManager::GetUniqueInstance();
		if (!colorScalesManager)
		{
			ccLog::Warning("[ccScalarField::fromFile] Failed to access color scales manager?!");
			assert(false);
		}

		//old versions
		if (dataVersion<27)
		{
			uint32_t activeColorScale = 0;
			if (in.read((char*)&activeColorScale,4) < 0)
				return ReadError();

			//Retrieve equivalent default scale
			ccColorScalesManager::DEFAULT_SCALES activeColorScaleType = ccColorScalesManager::BGYR;
			switch(activeColorScale)
			{
			case ccColorScalesManager::BGYR:
				activeColorScaleType = ccColorScalesManager::BGYR;
				break;
			case ccColorScalesManager::GREY:
				activeColorScaleType = ccColorScalesManager::GREY;
				break;
			case ccColorScalesManager::BWR:
				activeColorScaleType = ccColorScalesManager::BWR;
				break;
			case ccColorScalesManager::RY:
				activeColorScaleType = ccColorScalesManager::RY;
				break;
			case ccColorScalesManager::RW:
				activeColorScaleType = ccColorScalesManager::RW;
				break;
			default:
				ccLog::Warning("[ccScalarField::fromFile] Color scale is no more supported!");
				break;
			}
			m_colorScale = ccColorScalesManager::GetDefaultScale(activeColorScaleType);
		}
		else //(dataVersion>=27)
		{
			bool hasColorScale = false;
			if (in.read((char*)&hasColorScale,sizeof(bool)) < 0)
				return ReadError();

			if (hasColorScale)
			{
				ccColorScale::Shared colorScale = ccColorScale::Create("temp");
				if (!colorScale->fromFile(in, dataVersion, flags))
					return ReadError();
				m_colorScale = colorScale;

				if (colorScalesManager)
				{
					ccColorScale::Shared existingColorScale = colorScalesManager->getScale(colorScale->getUuid());
					if (!existingColorScale)
					{
						colorScalesManager->addScale(colorScale);
					}
					else //same UUID?
					{
						//FIXME: we should look if the color scale is exactly the same!
						m_colorScale = existingColorScale;
					}
				}
			}
		}

		//A scalar fiels must have a color scale!
		if (!m_colorScale)
			m_colorScale = ccColorScalesManager::GetDefaultScale();

		//color ramp steps (dataVersion>=20)
		uint32_t colorRampSteps = 0;
		if (in.read((char*)&colorRampSteps,4) < 0)
			return ReadError();
		setColorRampSteps((unsigned)colorRampSteps);
	}

	//update values
	computeMinAndMax();
	m_displayRange.setStart((ScalarType)minDisplayed);
	m_displayRange.setStop((ScalarType)maxDisplayed);
	m_saturationRange.setStart((ScalarType)minSaturation);
	m_saturationRange.setStop((ScalarType)maxSaturation);
	m_logSaturationRange.setStart((ScalarType)minLogSaturation);
	m_logSaturationRange.setStop((ScalarType)maxLogSaturation);

	m_modified = true;

	return true;
}
Пример #28
0
CC_FILE_ERROR BinFilter::LoadFileV2(QFile& in, ccHObject& container, int flags)
{
	assert(in.isOpen());

	uint32_t binVersion = 20;
	if (in.read((char*)&binVersion,4) < 0)
		return CC_FERR_READING;

	if (binVersion < 20) //should be superior to 2.0!
		return CC_FERR_MALFORMED_FILE;

	QString coordsFormat = ( (flags & ccSerializableObject::DF_POINT_COORDS_64_BITS) ? "double" : "float");
	QString scalarFormat = ( (flags & ccSerializableObject::DF_SCALAR_VAL_32_BITS)   ? "float" : "double");
	ccLog::Print(QString("[BIN] Version %1.%2 (coords: %3 / scalar: %4)").arg(binVersion/10).arg(binVersion%10).arg(coordsFormat).arg(scalarFormat));

	//we keep track of the last unique ID before load
	unsigned lastUniqueIDBeforeLoad = ccObject::GetLastUniqueID();

	//we read first entity type
	CC_CLASS_ENUM classID = ccObject::ReadClassIDFromFile(in, static_cast<short>(binVersion));
	if (classID == CC_TYPES::OBJECT)
		return CC_FERR_CONSOLE_ERROR;

	ccHObject* root = ccHObject::New(classID);

	if (!root)
		return CC_FERR_MALFORMED_FILE;

	if (classID == CC_TYPES::CUSTOM_H_OBJECT)
	{
		// store seeking position
		size_t original_pos = in.pos();
		// we need to load it as plain ccCustomHobject
		root->fromFileNoChildren(in, static_cast<short>(binVersion), flags); // this will load it
		in.seek(original_pos); // reseek back the file

		QString classId = root->getMetaData("class_name").toString();
		QString pluginId = root->getMetaData("plugin_name").toString();

		// try to get a new object from external factories
		ccHObject* new_child = ccHObject::New(pluginId, classId);
		if (new_child) // found a plugin that can deserialize it
			root = new_child;
		else
			return CC_FERR_FILE_WAS_WRITTEN_BY_UNKNOWN_PLUGIN;
	}

	if (!root->fromFile(in,static_cast<short>(binVersion),flags))
	{
		//DGM: can't delete it, too dangerous (bad pointers ;)
		//delete root;
		return CC_FERR_CONSOLE_ERROR;
	}

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//re-link objects (and check errors)
	bool checkErrors = true;
	ccHObject* orphans = new ccHObject("Orphans (CORRUPTED FILE)");;
	ccHObject::Container toCheck;
	toCheck.push_back(root);
	while (!toCheck.empty())
	{
		ccHObject* currentObject = toCheck.back();
		toCheck.pop_back();

		assert(currentObject);

		//we check objects that have links to other entities (meshes, polylines, etc.)
		if (currentObject->isKindOf(CC_TYPES::MESH))
		{
			//specific case: mesh groups are deprecated!
			if (currentObject->isA(CC_TYPES::MESH_GROUP))
			{
				//TODO
				ccLog::Warning(QString("[BIN] Mesh groups are deprecated! Entity %1 should be ignored...").arg(currentObject->getName()));
			}
			else if (currentObject->isA(CC_TYPES::SUB_MESH))
			{
				ccSubMesh* subMesh = ccHObjectCaster::ToSubMesh(currentObject);

				//normally, the associated mesh should be the sub-mesh's parent!
				//however we have its ID so we will look for it just to be sure
				intptr_t meshID = (intptr_t)subMesh->getAssociatedMesh();
				if (meshID > 0)
				{
					ccHObject* mesh = FindRobust(root,subMesh,static_cast<unsigned>(meshID),CC_TYPES::MESH);
					if (mesh)
					{
						subMesh->setAssociatedMesh(ccHObjectCaster::ToMesh(mesh),false); //'false' because previous mesh is not null (= real mesh ID)!!!
					}
					else
					{
						//we have a problem here ;)
						//normally, the associated mesh should be the sub-mesh's parent!
						if (subMesh->getParent() && subMesh->getParent()->isA(CC_TYPES::MESH))
						{
							subMesh->setAssociatedMesh(ccHObjectCaster::ToMesh(subMesh->getParent()),false); //'false' because previous mesh is not null (= real mesh ID)!!!
						}
						else
						{
							subMesh->setAssociatedMesh(0,false); //'false' because previous mesh is not null (= real mesh ID)!!!
							//DGM: can't delete it, too dangerous (bad pointers ;)
							//delete subMesh;
							ccLog::Warning(QString("[BIN] Couldn't find associated mesh (ID=%1) for sub-mesh '%2' in the file!").arg(meshID).arg(subMesh->getName()));
							return CC_FERR_MALFORMED_FILE;
						}
					}
				}
			}
			else if (currentObject->isA(CC_TYPES::MESH) || currentObject->isKindOf(CC_TYPES::PRIMITIVE)) //CC_TYPES::MESH or CC_TYPES::PRIMITIVE!
			{
				ccMesh* mesh = ccHObjectCaster::ToMesh(currentObject);
				assert(mesh);

				//vertices
				intptr_t cloudID = (intptr_t)mesh->getAssociatedCloud();
				if (cloudID > 0)
				{
					ccHObject* cloud = FindRobust(root,mesh,static_cast<unsigned>(cloudID),CC_TYPES::POINT_CLOUD);
					if (cloud)
					{
						mesh->setAssociatedCloud(ccHObjectCaster::ToGenericPointCloud(cloud));
					}
					else
					{
						//we have a problem here ;)
						mesh->setAssociatedCloud(0);
						if (mesh->getMaterialSet())
							mesh->setMaterialSet(0,false);
						//DGM: can't delete it, too dangerous (bad pointers ;)
						//delete mesh;
						if (mesh->getParent())
						{
							mesh->getParent()->removeDependencyWith(mesh);
							mesh->getParent()->removeChild(mesh);
						}
						ccLog::Warning(QString("[BIN] Couldn't find vertices (ID=%1) for mesh '%2' in the file!").arg(cloudID).arg(mesh->getName()));
						mesh = 0;
						//return CC_FERR_MALFORMED_FILE;
					}
				}

				if (mesh)
				{
					//materials
					ccHObject* materials = 0;
					intptr_t matSetID = (intptr_t)mesh->getMaterialSet();
					if (matSetID > 0)
					{
						materials = FindRobust(root,mesh,static_cast<unsigned>(matSetID),CC_TYPES::MATERIAL_SET);
						if (materials)
						{
							mesh->setMaterialSet(static_cast<ccMaterialSet*>(materials),false);
						}
						else
						{
							//we have a (less severe) problem here ;)
							mesh->setMaterialSet(0,false);
							mesh->showMaterials(false);
							ccLog::Warning(QString("[BIN] Couldn't find shared materials set (ID=%1) for mesh '%2' in the file!").arg(matSetID).arg(mesh->getName()));
							result = CC_FERR_BROKEN_DEPENDENCY_ERROR;

							//add it to the 'orphans' set
							if (materials)
								orphans->addChild(materials);
							materials = 0;
						}
					}
					//per-triangle normals
					ccHObject* triNormsTable = 0;
					intptr_t triNormsTableID = (intptr_t)mesh->getTriNormsTable();
					if (triNormsTableID > 0)
					{
						triNormsTable = FindRobust(root,mesh,static_cast<unsigned>(triNormsTableID),CC_TYPES::NORMAL_INDEXES_ARRAY);
						if (triNormsTable)
						{
							mesh->setTriNormsTable(static_cast<NormsIndexesTableType*>(triNormsTable),false);
						}
						else
						{
							//we have a (less severe) problem here ;)
							mesh->setTriNormsTable(0,false);
							mesh->showTriNorms(false);
							ccLog::Warning(QString("[BIN] Couldn't find shared normals (ID=%1) for mesh '%2' in the file!").arg(triNormsTableID).arg(mesh->getName()));
							result = CC_FERR_BROKEN_DEPENDENCY_ERROR;

							//add it to the 'orphans' set
							if (triNormsTable)
								orphans->addChild(triNormsTable);
							triNormsTable = 0;
						}
					}
					//per-triangle texture coordinates
					ccHObject* texCoordsTable = 0;
					intptr_t texCoordArrayID = (intptr_t)mesh->getTexCoordinatesTable();
					if (texCoordArrayID > 0)
					{
						texCoordsTable = FindRobust(root,mesh,static_cast<unsigned>(texCoordArrayID),CC_TYPES::TEX_COORDS_ARRAY);
						if (texCoordsTable)
						{
							mesh->setTexCoordinatesTable(static_cast<TextureCoordsContainer*>(texCoordsTable),false);
						}
						else
						{
							//we have a (less severe) problem here ;)
							mesh->setTexCoordinatesTable(0,false);
							ccLog::Warning(QString("[BIN] Couldn't find shared texture coordinates (ID=%1) for mesh '%2' in the file!").arg(texCoordArrayID).arg(mesh->getName()));
							result = CC_FERR_BROKEN_DEPENDENCY_ERROR;

							//add it to the 'orphans' set
							if (texCoordsTable)
								orphans->addChild(texCoordsTable);
							texCoordsTable = 0;
						}
					}

					if (checkErrors)
					{
						ccGenericPointCloud* pc = mesh->getAssociatedCloud();
						unsigned faceCount = mesh->size();
						unsigned vertCount = pc->size();
						for (unsigned i=0; i<faceCount; ++i)
						{
							const CCLib::VerticesIndexes* tri = mesh->getTriangleVertIndexes(i);
							if (	tri->i1 >= vertCount
								||	tri->i2 >= vertCount
								||	tri->i3 >= vertCount )
							{
								ccLog::Warning(QString("[BIN] File is corrupted: missing vertices for mesh '%1'!").arg(mesh->getName()));

								//add cloud to the 'orphans' set
								pc->setName(mesh->getName() + QString(".") + pc->getName());
								orphans->addChild(pc);
								if (texCoordsTable)
								{
									texCoordsTable->setName(mesh->getName() + QString(".") + texCoordsTable->getName());
									orphans->addChild(texCoordsTable);
								}
								if (triNormsTable)
								{
									triNormsTable->setName(mesh->getName() + QString(".") + triNormsTable->getName());
									orphans->addChild(triNormsTable);
								}
								if (materials)
								{
									materials->setName(mesh->getName() + QString(".") + materials->getName());
									orphans->addChild(materials);
								}

								//delete corrupted mesh
								mesh->setMaterialSet(0,false);
								mesh->setTriNormsTable(0,false);
								mesh->setTexCoordinatesTable(0,false);
								if (mesh->getParent())
									mesh->getParent()->removeChild(mesh);
								mesh = 0;

								break;
							}
						}
					}
				}
			}
		}
		else if (currentObject->isKindOf(CC_TYPES::POLY_LINE))
		{
			ccPolyline* poly = ccHObjectCaster::ToPolyline(currentObject);
			intptr_t cloudID = (intptr_t)poly->getAssociatedCloud();
			ccHObject* cloud = FindRobust(root,poly,static_cast<unsigned>(cloudID),CC_TYPES::POINT_CLOUD);
			if (cloud)
			{
				poly->setAssociatedCloud(ccHObjectCaster::ToGenericPointCloud(cloud));
			}
			else
			{
				//we have a problem here ;)
				poly->setAssociatedCloud(0);
				//DGM: can't delete it, too dangerous (bad pointers ;)
				//delete root;
				ccLog::Warning(QString("[BIN] Couldn't find vertices (ID=%1) for polyline '%2' in the file!").arg(cloudID).arg(poly->getName()));
				return CC_FERR_MALFORMED_FILE;
			}
		}
		else if (currentObject->isKindOf(CC_TYPES::SENSOR))
		{
			ccSensor* sensor = ccHObjectCaster::ToSensor(currentObject);
			intptr_t bufferID = (intptr_t)sensor->getPositions();
			if (bufferID > 0)
			{
				ccHObject* buffer = FindRobust(root,sensor,static_cast<unsigned>(bufferID),CC_TYPES::TRANS_BUFFER);
				if (buffer)
				{
					sensor->setPositions(ccHObjectCaster::ToTransBuffer(buffer));
				}
				else
				{
					//we have a problem here ;)
					sensor->setPositions(0);

					//DGM: can't delete it, too dangerous (bad pointers ;)
					//delete root;

					ccLog::Warning(QString("[BIN] Couldn't find trans. buffer (ID=%1) for sensor '%2' in the file!").arg(bufferID).arg(sensor->getName()));

					//positions are optional, so we can simply set them to NULL and go ahead, we do not need to return.
					//return CC_FERR_MALFORMED_FILE;
				}
			}
		}
		else if (currentObject->isA(CC_TYPES::LABEL_2D))
		{
			cc2DLabel* label = ccHObjectCaster::To2DLabel(currentObject);
			std::vector<cc2DLabel::PickedPoint> correctedPickedPoints;
			//we must check all label 'points'!
			for (unsigned i=0; i<label->size(); ++i)
			{
				const cc2DLabel::PickedPoint& pp = label->getPoint(i);
				intptr_t cloudID = (intptr_t)pp.cloud;
				ccHObject* cloud = FindRobust(root,label,static_cast<unsigned>(cloudID),CC_TYPES::POINT_CLOUD);
				if (cloud)
				{
					ccGenericPointCloud* genCloud = ccHObjectCaster::ToGenericPointCloud(cloud);
					assert(genCloud->size()>pp.index);
					correctedPickedPoints.push_back(cc2DLabel::PickedPoint(genCloud,pp.index));
				}
				else
				{
					//we have a problem here ;)
					ccLog::Warning(QString("[BIN] Couldn't find cloud (ID=%1) associated to label '%2' in the file!").arg(cloudID).arg(label->getName()));
					if (label->getParent())
						label->getParent()->removeChild(label);
					//DGM: can't delete it, too dangerous (bad pointers ;)
					//delete label;
					label = 0;
					break;
				}
			}

			if (label) //correct label data
			{
				assert(correctedPickedPoints.size() == label->size());
				bool visible = label->isVisible();
				QString originalName(label->getRawName());
				label->clear(true);
				for (unsigned i=0; i<correctedPickedPoints.size(); ++i)
					label->addPoint(correctedPickedPoints[i].cloud,correctedPickedPoints[i].index);
				label->setVisible(visible);
				label->setName(originalName);
			}
		}
		else if (currentObject->isA(CC_TYPES::FACET))
		{
			ccFacet* facet = ccHObjectCaster::ToFacet(currentObject);

			//origin points
			{
				intptr_t cloudID = (intptr_t)facet->getOriginPoints();
				if (cloudID > 0)
				{
					ccHObject* cloud = FindRobust(root,facet,static_cast<unsigned>(cloudID),CC_TYPES::POINT_CLOUD);
					if (cloud && cloud->isA(CC_TYPES::POINT_CLOUD))
					{
						facet->setOriginPoints(ccHObjectCaster::ToPointCloud(cloud));
					}
					else
					{
						//we have a problem here ;)
						facet->setOriginPoints(0);
						ccLog::Warning(QString("[BIN] Couldn't find origin points (ID=%1) for facet '%2' in the file!").arg(cloudID).arg(facet->getName()));
					}
				}
			}
			//contour points
			{
				intptr_t cloudID = (intptr_t)facet->getContourVertices();
				if (cloudID > 0)
				{
					ccHObject* cloud = FindRobust(root,facet,static_cast<unsigned>(cloudID),CC_TYPES::POINT_CLOUD);
					if (cloud)
					{
						facet->setContourVertices(ccHObjectCaster::ToPointCloud(cloud));
					}
					else
					{
						//we have a problem here ;)
						facet->setContourVertices(0);
						ccLog::Warning(QString("[BIN] Couldn't find contour points (ID=%1) for facet '%2' in the file!").arg(cloudID).arg(facet->getName()));
					}
				}
			}
			//contour polyline
			{
				intptr_t polyID = (intptr_t)facet->getContour();
				if (polyID > 0)
				{
					ccHObject* poly = FindRobust(root,facet,static_cast<unsigned>(polyID),CC_TYPES::POLY_LINE);
					if (poly)
					{
						facet->setContour(ccHObjectCaster::ToPolyline(poly));
					}
					else
					{
						//we have a problem here ;)
						facet->setContourVertices(0);
						ccLog::Warning(QString("[BIN] Couldn't find contour polyline (ID=%1) for facet '%2' in the file!").arg(polyID).arg(facet->getName()));
					}
				}
			}
			//polygon mesh
			{
				intptr_t polyID = (intptr_t)facet->getPolygon();
				if (polyID > 0)
				{
					ccHObject* poly = FindRobust(root,facet,static_cast<unsigned>(polyID),CC_TYPES::MESH);
					if (poly)
					{
						facet->setPolygon(ccHObjectCaster::ToMesh(poly));
					}
					else
					{
						//we have a problem here ;)
						facet->setPolygon(0);
						ccLog::Warning(QString("[BIN] Couldn't find polygon mesh (ID=%1) for facet '%2' in the file!").arg(polyID).arg(facet->getName()));
					}
				}
			}
		}
		else if (currentObject->isKindOf(CC_TYPES::IMAGE))
		{
			ccImage* image = ccHObjectCaster::ToImage(currentObject);
			
			intptr_t sensorID = (intptr_t)image->getAssociatedSensor();
			if (sensorID > 0)
			{
				ccHObject* sensor = FindRobust(root,image,static_cast<unsigned>(sensorID),CC_TYPES::CAMERA_SENSOR);
				if (sensor)
				{
					image->setAssociatedSensor(ccHObjectCaster::ToCameraSensor(sensor));
				}
				else
				{
					//we have a problem here ;)
					image->setAssociatedSensor(0);

					//DGM: can't delete it, too dangerous (bad pointers ;)
					//delete root;

					ccLog::Warning(QString("[BIN] Couldn't find camera sensor (ID=%1) for image '%2' in the file!").arg(sensorID).arg(image->getName()));
					//return CC_FERR_MALFORMED_FILE;
				}
			}
		}

		if (currentObject)
			for (unsigned i=0; i<currentObject->getChildrenNumber() ;++i)
				toCheck.push_back(currentObject->getChild(i));
	}

	//check for unique IDs duplicate (yes it happens :-( )
	{
		std::unordered_set<unsigned> uniqueIDs;
		unsigned maxUniqueID = root->findMaxUniqueID_recursive();
		assert(toCheck.empty());
		toCheck.push_back(root);
		while (!toCheck.empty())
		{
			ccHObject* currentObject = toCheck.back();
			toCheck.pop_back();

			assert(currentObject);

			//check that the ID is not already used (strangely it happens!)
			unsigned uniqueID = currentObject->getUniqueID();
			if (uniqueIDs.find(uniqueID) != uniqueIDs.end())
			{
				ccLog::Warning(QString("[BIN] Duplicate 'unique ID' found! (ID = %1)").arg(uniqueID));
				currentObject->setUniqueID(++maxUniqueID);
			}
			else
			{
				uniqueIDs.insert(uniqueID);
			}

			for (unsigned i=0; i<currentObject->getChildrenNumber() ;++i)
			{
				toCheck.push_back(currentObject->getChild(i));
			}
		}
	}

	//update 'unique IDs'
	toCheck.push_back(root);
	while (!toCheck.empty())
	{
		ccHObject* currentObject = toCheck.back();
		toCheck.pop_back();

		currentObject->setUniqueID(lastUniqueIDBeforeLoad+currentObject->getUniqueID());

		for (unsigned i=0; i<currentObject->getChildrenNumber(); ++i)
			toCheck.push_back(currentObject->getChild(i));
	}

	if (root->isA(CC_TYPES::HIERARCHY_OBJECT))
	{
		//transfer children to container
		root->transferChildren(container,true);
		delete root;
		root = 0;
	}
	else
	{
		container.addChild(root);
	}

	//orphans
	if (orphans)
	{
		if (orphans->getChildrenNumber() != 0)
		{
			orphans->setEnabled(false);
			container.addChild(orphans);
		}
		else
		{
			delete orphans;
			orphans = 0;
		}
	}

	return result;
}
Пример #29
0
inline bool QStorageIterator::isValid() const
{
    return file.isOpen();
}
Пример #30
0
CC_FILE_ERROR BinFilter::loadFileV2(QFile& in, ccHObject& container)
{
	assert(in.isOpen());

	uint32_t binVersion = 20;
	if (in.read((char*)&binVersion,4)<0)
		return CC_FERR_READING;

	if (binVersion<20) //should be superior to 2.0!
		return CC_FERR_MALFORMED_FILE;

	ccLog::Print(QString("[BIN] Version %1.%2").arg(binVersion/10).arg(binVersion%10));

	ccProgressDialog pdlg(true);
	pdlg.setMethodTitle(qPrintable(QString("Open Bin file (V%1.%2)").arg(binVersion/10).arg(binVersion%10)));

	//we keep track of the last unique ID before load
	unsigned lastUniqueIDBeforeLoad = ccObject::GetLastUniqueID();

	//we read first entity type
	unsigned classID=0;
	if (!ccObject::ReadClassIDFromFile(classID, in, binVersion))
		return CC_FERR_CONSOLE_ERROR;

	ccHObject* root = ccHObject::New(classID);
	if (!root)
		return CC_FERR_MALFORMED_FILE;

	if (!root->fromFile(in,binVersion))
	{
		//DGM: can't delete it, too dangerous (bad pointers ;)
		//delete root;
		return CC_FERR_CONSOLE_ERROR;
	}

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//re-link objects
	ccHObject::Container toCheck;
	toCheck.push_back(root);
	while (!toCheck.empty())
	{
		ccHObject* currentObject = toCheck.back();
		toCheck.pop_back();

		assert(currentObject);
		//we check objects that have links to other entities (meshes, polylines, etc.)
		if (currentObject->isKindOf(CC_MESH))
		{
			ccGenericMesh* mesh = static_cast<ccGenericMesh*>(currentObject);
			//vertices
			//special case: if the parent is a mesh group, then the job has already be done once and for all!
			if (!mesh->getParent() || !mesh->getParent()->isA(CC_MESH_GROUP))
			{
				intptr_t cloudID = (intptr_t)mesh->getAssociatedCloud();
				if (cloudID>0)
				{
					ccHObject* cloud = root->find(cloudID);
					if (cloud && cloud->isKindOf(CC_POINT_CLOUD))
						mesh->setAssociatedCloud(static_cast<ccGenericPointCloud*>(cloud));
					else
					{
						//we have a problem here ;)
						mesh->setAssociatedCloud(0);
						if (mesh->getMaterialSet())
							mesh->setMaterialSet(0,false);
						//DGM: can't delete it, too dangerous (bad pointers ;)
						//delete root;
						ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find vertices (ID=%1) for mesh '%2' in the file!").arg(cloudID).arg(mesh->getName()));
						return CC_FERR_MALFORMED_FILE;
					}
				}
			}
			//materials
			intptr_t matSetID = (intptr_t)mesh->getMaterialSet();
			if (matSetID>0)
			{
				ccHObject* materials = root->find(matSetID);
				if (materials && materials->isA(CC_MATERIAL_SET))
					mesh->setMaterialSet(static_cast<ccMaterialSet*>(materials),false);
				else
				{
					//we have a (less severe) problem here ;)
					mesh->setMaterialSet(0,false);
					mesh->showMaterials(false);
					ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find shared materials set (ID=%1) for mesh '%2' in the file!").arg(matSetID).arg(mesh->getName()));
					result = CC_FERR_BROKEN_DEPENDENCY_ERROR;
				}
			}
			//per-triangle normals
			intptr_t triNormsTableID = (intptr_t)mesh->getTriNormsTable();
			if (triNormsTableID>0)
			{
				ccHObject* triNormsTable = root->find(triNormsTableID);
				if (triNormsTable && triNormsTable->isA(CC_NORMAL_INDEXES_ARRAY))
					mesh->setTriNormsTable(static_cast<NormsIndexesTableType*>(triNormsTable),false);
				else
				{
					//we have a (less severe) problem here ;)
					mesh->setTriNormsTable(0,false);
					mesh->showTriNorms(false);
					ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find shared normals (ID=%1) for mesh '%2' in the file!").arg(matSetID).arg(mesh->getName()));
					result = CC_FERR_BROKEN_DEPENDENCY_ERROR;
				}
			}
			//per-triangle texture coordinates
			intptr_t texCoordArrayID = (intptr_t)mesh->getTexCoordinatesTable();
			if (texCoordArrayID>0)
			{
				ccHObject* texCoordsTable = root->find(texCoordArrayID);
				if (texCoordsTable && texCoordsTable->isA(CC_TEX_COORDS_ARRAY))
					mesh->setTexCoordinatesTable(static_cast<TextureCoordsContainer*>(texCoordsTable),false);
				else
				{
					//we have a (less severe) problem here ;)
					mesh->setTexCoordinatesTable(0,false);
					ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find shared texture coordinates (ID=%1) for mesh '%2' in the file!").arg(matSetID).arg(mesh->getName()));
					result = CC_FERR_BROKEN_DEPENDENCY_ERROR;
				}
			}
		}
		else if (currentObject->isKindOf(CC_POLY_LINE))
		{
			ccPolyline* poly = static_cast<ccPolyline*>(currentObject);
			intptr_t cloudID = (intptr_t)poly->getAssociatedCloud();
			ccHObject* cloud = root->find(cloudID);
			if (cloud && cloud->isKindOf(CC_POINT_CLOUD))
				poly->setAssociatedCloud(static_cast<ccGenericPointCloud*>(cloud));
			else
			{
				//we have a problem here ;)
				poly->setAssociatedCloud(0);
				//DGM: can't delete it, too dangerous (bad pointers ;)
				//delete root;
				ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find vertices (ID=%1) for polyline '%2' in the file!").arg(cloudID).arg(poly->getName()));
				return CC_FERR_MALFORMED_FILE;
			}
		}
		else if (currentObject->isA(CC_2D_LABEL))
		{
			cc2DLabel* label = static_cast<cc2DLabel*>(currentObject);
			std::vector<cc2DLabel::PickedPoint> correctedPickedPoints;
			//we must check all label 'points'!
			for (unsigned i=0;i<label->size();++i)
			{
				const cc2DLabel::PickedPoint& pp = label->getPoint(i);
				intptr_t cloudID = (intptr_t)pp.cloud;
				ccHObject* cloud = root->find(cloudID);
				if (cloud && cloud->isKindOf(CC_POINT_CLOUD))
				{
					ccGenericPointCloud* genCloud = static_cast<ccGenericPointCloud*>(cloud);
					assert(genCloud->size()>pp.index);
					correctedPickedPoints.push_back(cc2DLabel::PickedPoint(genCloud,pp.index));
				}
				else
				{
					//we have a problem here ;)
					ccLog::Warning(QString("[BinFilter::loadFileV2] Couldn't find cloud (ID=%1) associated to label '%2' in the file!").arg(cloudID).arg(label->getName()));
					if (label->getParent())
						label->getParent()->removeChild(label);
					if (!label->getFlagState(CC_FATHER_DEPENDANT))
					{
						//DGM: can't delete it, too dangerous (bad pointers ;)
						//delete label;
					}
					label=0;
					break;
				}
			}

			if (label) //correct label data
			{
				assert(correctedPickedPoints.size() == label->size());
				bool visible = label->isVisible();
				QString originalName(label->getRawName());
				label->clear();
				for (unsigned i=0;i<correctedPickedPoints.size();++i)
					label->addPoint(correctedPickedPoints[i].cloud,correctedPickedPoints[i].index);
				label->setVisible(visible);
				label->setName(originalName);
			}
		}

		for (unsigned i=0;i<currentObject->getChildrenNumber();++i)
			toCheck.push_back(currentObject->getChild(i));
	}

	//update 'unique IDs'
	toCheck.push_back(root);
	while (!toCheck.empty())
	{
		ccHObject* currentObject = toCheck.back();
		toCheck.pop_back();

		currentObject->setUniqueID(lastUniqueIDBeforeLoad+currentObject->getUniqueID());

		for (unsigned i=0;i<currentObject->getChildrenNumber();++i)
			toCheck.push_back(currentObject->getChild(i));
	}

	if (root->isA(CC_HIERARCHY_OBJECT))
	{
		//transfer children to container
		root->transferChildren(container,true);
	}
	else
	{
		container.addChild(root);
	}

	return result;
}