Beispiel #1
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
qint64 RifEclipseInputFileTools::findKeyword(const QString& keyword, QFile& file, qint64 startPos)
{
    QString line;

    file.seek(startPos);

    do 
    {
        line = file.readLine();
        line = line.trimmed();

        if (line.startsWith("--", Qt::CaseInsensitive))
        {
            continue;
        }

        if (line.startsWith(keyword, Qt::CaseInsensitive))
        {
            return file.pos();
        }

    } while (!file.atEnd());


    return -1;
}
Beispiel #2
0
//static
long SoundSourceOggVorbis::TellCallback(void* datasource) {
   QFile* pFile = static_cast<QFile*>(datasource);
   if (!pFile) {
       return 0;
   }
   return pFile->pos();
}
Beispiel #3
0
//----------------------------------------------------------------------------------
void tst_QIODevice::constructing_QFile()
{
    QFile file;
    QIODevice *device = &file;

    QVERIFY(!device->isOpen());

    file.setFileName(SRCDIR "tst_qiodevice.cpp");
    QVERIFY(file.open(QFile::ReadOnly));
    QVERIFY(device->isOpen());
    QCOMPARE((int) device->openMode(), (int) QFile::ReadOnly);

    char buf[1024];
    memset(buf, 0, sizeof(buf));
    qlonglong lineLength = device->readLine(buf, sizeof(buf));
    QVERIFY(lineLength > 0);
    QCOMPARE(file.pos(), lineLength);

    file.seek(0);
    char buf2[1024];
    memset(buf2, 0, sizeof(buf2));
    QCOMPARE(file.readLine(buf2, sizeof(buf2)), lineLength);

    char *c1 = buf;
    char *c2 = buf2;
    while (*c1 && *c2) {
        QCOMPARE(*c1, *c2);
        ++c1;
        ++c2;
    }
    QCOMPARE(*c1, *c2);
}
Beispiel #4
0
// static
uint32_t SoundSourceWV::GetPosCallback(void *id)
{
    QFile* pFile = static_cast<QFile*>(id);
    if (!pFile) {
        return 0;
    }
    return pFile->pos();
}
Beispiel #5
0
void Robotino::readFileHeader(QFile& file)
{
  unsigned buflen = 20;
  char buffer[buflen];

  recordSize = 0;
  file.seek(0);
  file.readLine(buffer, buflen);
  while(!file.atEnd() && strncmp(buffer,"end", strlen("end"))!=0)
  {
    if(strncmp(buffer,"action:", strlen("action:"))==0)
    {
      actionOffset = recordSize;
      actionSize = atoi(buffer+strlen("action:"));
      recordSize += actionSize;
    }
    else if(strncmp(buffer,"distance:", strlen("distance:"))==0)
    {
      distanceOffset = recordSize;
      distanceSize = atoi(buffer+strlen("distance:"));
      recordSize += distanceSize;
    }
    else if(strncmp(buffer,"accel:", strlen("accel:"))==0)
    {
      accelOffset = recordSize;
      accelSize = atoi(buffer+strlen("accel:"));
      recordSize += accelSize;
    }
    else if(strncmp(buffer,"current:", strlen("current:"))==0)
    {
      currentOffset = recordSize;
      currentSize = atoi(buffer+strlen("current:"));
      recordSize += currentSize;
    }
    else if(strncmp(buffer,"power:", strlen("power:"))==0)
    {
      powerOffset = recordSize;
      powerSize = atoi(buffer+strlen("power:"));
      recordSize += powerSize;
    }
    else if(strncmp(buffer,"bumper:", strlen("bumper:"))==0)
    {
      bumperOffset = recordSize;
      bumperSize = atoi(buffer+strlen("bumper:"));
      recordSize += bumperSize;
    }
    else if(strncmp(buffer,"audio:", strlen("audio:"))==0)
    {
      audioOffset = recordSize;
      audioSize = atoi(buffer+strlen("audio:"));
      recordSize += audioSize;
    }
    file.readLine(buffer, buflen);
  }
  headerSize = file.pos();
  //std::cout << "Fertig" << std::endl;
}
Beispiel #6
0
bool ReaderDataBlockHeader::find(DataBlockHeader* outHeader, QFile& fin) {
    unsigned char buffer[BUFFER_SIZE];

    unsigned int nReadBytes;

    while ((nReadBytes = fin.read(reinterpret_cast<char*>(buffer), BUFFER_SIZE)) >
            HEADER_SIZE) {
        unsigned char* findPos =
            std::search(buffer, buffer + nReadBytes + 1, JAA::ARCHIVER_ID,
                        JAA::ARCHIVER_ID + JAA::ARCHIVER_ID_SIZE);

        if (findPos == buffer + nReadBytes + 1) {
            fin.seek(-(std::streamoff)(HEADER_SIZE - 1) + fin.pos());
        } else {
            // found at findPos

            if ((BUFFER_SIZE - (findPos - buffer)) > HEADER_SIZE) {
                // enough space in buffer

                outHeader->setData(findPos);

                if (!outHeader->checkCRC()) {
                    // valid CRC
                    fin.seek(-(std::streamoff)(nReadBytes - (findPos - buffer) - HEADER_SIZE) + fin.pos());
                    return false;
                } else {
                    // not valid CRC may be not header?
                    fin.seek(-static_cast<std::streamoff>(nReadBytes - (findPos - buffer) - 2) + fin.pos());
                    // try again with offset
                }
            } else {
                // not enough space
                fin.seek(-(nReadBytes - (findPos - buffer) - 1) + fin.pos());
            }
        }
    }

    return true;
}
Beispiel #7
0
QString readNullTerminatedString(QFile &file, QTextCodec *codec, qint64 &length)
{
    if(codec == NULL)
    {
        throw std::runtime_error("Codec is NULL");
    }
    qint64 pos = file.pos();
    while (true)
    {
        quint8 nextSymbol = 0;
        if (file.read(reinterpret_cast<char *> (&nextSymbol),
                Q_INT64_C(1)) != Q_INT64_C(1))
        {
            throw std::runtime_error("Unable to read file");
        }
        if (nextSymbol == 0)
        {
            break;
        }
    }
    qint64 stringLength = file.pos() - pos;
    length = stringLength;
    seekFile(file, pos);
    QScopedArrayPointer<quint8> stringIn(new quint8[stringLength]);
    if (file.read(reinterpret_cast<char *> (stringIn.data()),
            stringLength) != stringLength)
    {
        throw std::runtime_error("Unable to read file");
    }
    QScopedPointer<QTextDecoder> decoder(codec->makeDecoder());
    if (decoder.isNull())
    {
        throw std::runtime_error("Unable to create text decoder");
    }
    return decoder->toUnicode(
        reinterpret_cast<const char *> (stringIn.data()),
        static_cast<int> (stringLength - Q_INT64_C(1)));
}
Beispiel #8
0
//static
size_t SoundSourceOggVorbis::ReadCallback(void *ptr, size_t size, size_t nmemb,
       void *datasource) {
   if (!size || !nmemb) {
       return 0;
   }
   QFile* pFile = static_cast<QFile*>(datasource);
   if (!pFile) {
       return 0;
   }

   nmemb = math_min<size_t>((pFile->size() - pFile->pos()) / size, nmemb);
   pFile->read((char*)ptr, nmemb * size);
   return nmemb;
}
Beispiel #9
0
unsigned int FileTrans::readTransPos(QFile &file)
{
    unsigned int postemp = file.pos();  //push file pos
    file.seek(file.size()-4);
    QDataStream str(&file);
    str.setByteOrder(QDataStream::LittleEndian);
    unsigned int pos ;
    str>>pos;
    file.seek(postemp);    //pop file pos
    if(pos<file.size())
        return pos;
    else
        return 0;
}
Beispiel #10
0
void FileWriter::writeHeader(QDataStream & dataStream, QFile & file, AssetInformation & info)
{
    if (info.properties().empty())
        return;

    dataStream << static_cast<quint16>(RawFile::s_signature);

    quint64 rawDataOffsetPosition = file.pos();
    dataStream << static_cast<quint64>(0);

    QMapIterator<QVariantMap::key_type, QVariantMap::mapped_type> iterator(info.properties());

    while (iterator.hasNext())
    {
        iterator.next();

        QString key = iterator.key();
        QVariant value = iterator.value();

		RawFile::PropertyType type = propertyType(value.type());

        if (type == RawFile::PropertyType::Unknown)
            continue;

        dataStream << static_cast<uint8_t>(type);
        writeString(dataStream, key);

        writeValue(dataStream, value);
    }

    quint64 rawDataOffset = file.pos();

    file.seek(rawDataOffsetPosition);
    dataStream << rawDataOffset;
    file.seek(rawDataOffset);
}
Beispiel #11
0
void Table_Control::saveTablesInfo(QFile &archivo, int sizeBlock, int HeadSize){
    for(int i=0;i<this->metaData.count();i++){
        archivo.write(reinterpret_cast<char*>(&this->metaData[i]),sizeof(MetaDataTable));
    }
    qDebug()<<"Cantidad campo to save:"<<this->campos.count();
    QMap<int,Table_Fields>::ConstIterator it;
    for(it=this->campos.constBegin();it!=this->campos.constEnd();it++){
        Table_Fields tempField=it.value();
        archivo.seek(HeadSize+this->metaData.at(it.key()).pointerToFields*sizeBlock);
        qDebug()<<archivo.pos();
        for(int i=0;i<tempField.campos.count();i++){
            qDebug()<<tempField.campos[i].name<<i<<HeadSize+this->metaData.at(it.key()).pointerToFields*sizeBlock+(i*sizeof(Field))<<it.key()<<this->metaData.at(it.key()).pointerToFields*sizeBlock;
            archivo.write(reinterpret_cast<char*>(&tempField.campos[i]),sizeof(Field));
        }
    }
    this->campos.clear();
}
Beispiel #12
0
//static
int SoundSourceOggVorbis::SeekCallback(void *datasource, ogg_int64_t offset,
       int whence) {
   QFile* pFile = static_cast<QFile*>(datasource);
   if (!pFile) {
       return 0;
   }

   switch(whence) {
   case SEEK_SET:
       return pFile->seek(offset) ? 0 : -1;
   case SEEK_CUR:
       return pFile->seek(pFile->pos() + offset) ? 0 : -1;
   case SEEK_END:
       return pFile->seek(pFile->size() + offset) ? 0 : -1;
   default:
       return -1;
   }
}
Beispiel #13
0
int qfileSeekCallback( void * _udata, ogg_int64_t _offset, int _whence )
{
	QFile * f = static_cast<QFile *>( _udata );

	if( _whence == SEEK_CUR )
	{
		f->seek( f->pos() + _offset );
	}
	else if( _whence == SEEK_END )
	{
		f->seek( f->size() + _offset );
	}
	else
	{
		f->seek( _offset );
	}
	return 0;
}
Beispiel #14
0
//static
int SoundSourceWV::SetPosRelCallback(void *id, int delta, int mode)
{
    QFile* pFile = static_cast<QFile*>(id);
    if (!pFile) {
        return 0;
    }

    switch(mode) {
    case SEEK_SET:
        return pFile->seek(delta) ? 0 : -1;
    case SEEK_CUR:
        return pFile->seek(pFile->pos() + delta) ? 0 : -1;
    case SEEK_END:
        return pFile->seek(pFile->size() + delta) ? 0 : -1;
    default:
        return -1;
    }
}
Beispiel #15
0
qint64 StateImport::loadRaw(State* state, QFile& file)
{
    auto size = file.size() - file.pos();
    if (size % 8 !=0)
    {
        state->setErrorMessage(QObject::tr("Warning: file is not multiple of 8. Characters might be incomplete"));
        qDebug() << "File size not multiple of 8 (" << size << "). Characters might be incomplete";
    }

    int toRead = std::min((int)size, State::CHAR_BUFFER_SIZE);

    // clean previous memory in case not all the chars are loaded
    state->resetCharsetBuffer();

    auto total = file.read((char*)state->getCharsetBuffer(), toRead);

    Q_ASSERT(total == toRead && "Failed to read file");

    return total;
}
Beispiel #16
0
void DecodeAudioFile::WriteWavHeadToFile(QFile &f,int outLen, int sampleRate, int sampleSize, int channel)
{
    WAVFMT wavHeader ;
    wavHeader.RIFF[0] = 'R';
    wavHeader.RIFF[1] = 'I';
    wavHeader.RIFF[2] = 'F';
    wavHeader.RIFF[3] = 'F';

    wavHeader.totalSize = 44 + outLen;

    wavHeader.WAVE[0] = 'W';
    wavHeader.WAVE[1] = 'A';
    wavHeader.WAVE[2] = 'V';
    wavHeader.WAVE[3] = 'E';

    wavHeader.FMT[0] = 'f';
    wavHeader.FMT[1] = 'm';
    wavHeader.FMT[2] = 't';
    wavHeader.FMT[3] = ' ';

    wavHeader.FILTER = 0x00000010;
    wavHeader.formatTag = 1;
    wavHeader.channels = channel;
    wavHeader.sampleRate = sampleRate;
    wavHeader.bytesPerSec = sampleRate*sampleSize*channel/8;
    wavHeader.bytesInSample = sampleSize/8;
    wavHeader.bitsDepth = sampleSize;

    wavHeader.DATA[0] = 'd';
    wavHeader.DATA[1] = 'a';
    wavHeader.DATA[2] = 't';
    wavHeader.DATA[3] = 'a';

    wavHeader.dataSize = outLen;
    int pos = f.pos();
    f.seek(0);
    f.write((char*)&wavHeader,sizeof(WAVFMT));
    f.seek(pos);
    f.flush();
}
Beispiel #17
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;
}
Beispiel #18
0
void FileServerThread::run()    //TODO: use mutexes
{
    QString filename;
    QString ID;
    QFile file;
    QTcpSocket socket;
    socket.setSocketDescriptor (m_descriptor);

    while (!m_doQuit) {
        m_status = Waiting;
        while (!socket.bytesAvailable() && !m_doQuit) {
            socket.waitForReadyRead();
        }
        if (m_doQuit)
            break;

        QString data (socket.readAll());

        if (!Kapotah::TransferManager::instance()->pathForId (data).isEmpty()) {
            setStatus(PreparingToSend);
            ID = data;
            filename = Kapotah::TransferManager::instance()->pathForId (data);

            file.setFileName (filename);

            if (!file.open (QIODevice::ReadOnly)) {
                setStatus(ErrorFileNotFound);
                break;
            }

            socket.write ("OK");
            socket.waitForBytesWritten();
            emit startedTransfer (ID);
            setStatus(Sending);

            while (!file.atEnd() && !m_doQuit) {
                if (socket.state() != QTcpSocket::ConnectedState) {
                    emit finishedTransfer (ID);
                    setStatus(Finished);
                    break;
                }

                socket.write (file.read (s_bytesPerBlock));
                socket.waitForBytesWritten();

                while (socket.bytesToWrite())
                    socket.flush();

                emit transferProgress (ID, file.pos() / file.size() *100);
            }

            file.close();

            if (m_doQuit) {
                setStatus(Canceled);
                emit canceledTransfer(ID);
                socket.disconnectFromHost();
            } else {
                setStatus(Finished);
                emit finishedTransfer (ID);
            }

            socket.waitForDisconnected ();
            break;
        } else {
            setStatus(ErrorIDNotFound);
            emit transferNotFound(ID);
            break;
        }

        deleteLater();
    }
}
Beispiel #19
0
WinHelpPhraseFile::WinHelpPhraseFile(QFile &file, qint64 off,
    QTextCodec *codec, bool compressed, bool mvbHint) :
    phrases(), phrasesRaw()
{
    PRINT_DBG("Loading WinHelp phrase file at %lld", off);
    if (codec == NULL)
    {
        throw std::runtime_error("Codec is NULL");
    }
    seekFile(file, off);
    InternalDirectoryFileHeader hdr(file, off);
    if (compressed)
    {
        if (mvbHint)
        {
            seekFile(file, off + InternalDirectoryFileHeader::size);
            quint16 eightHundr = readUnsignedWord(file);
            quint16 nPhr = readUnsignedWord(file);
            quint16 oneHundr = readUnsignedWord(file);
            if ((eightHundr == 0x0800) && (oneHundr == 0x0100) && (nPhr != 0))
            {
                PRINT_DBG(
                    "Loading compressed WinHelp phrase file, MVB alternative");
                seekFile(file, off + InternalDirectoryFileHeader::size);
                quint16 eightHundred = readUnsignedWord(file);
                PRINT_DBG("        Eight hundred: %d", eightHundred);
                quint16 numPhrases = readUnsignedWord(file);
                PRINT_DBG("        Num phrases: %d", numPhrases);
                quint16 oneHundred = readUnsignedWord(file);
                PRINT_DBG("        One hundred: %d", oneHundred);
                if (oneHundred != 0x0100)
                {
                    throw std::runtime_error("Not a WinHelp phrase file");
                }
                quint32 uncompressedSize = readUnsignedDWord(file);
                PRINT_DBG("        Uncompressed size: %d", uncompressedSize);
                for (int i = 0; i < 30; i++)
                {
                    quint8 unused = readUnsignedByte(file);
                    PRINT_DBG("        Unused: %d", unused);
                }
                QScopedArrayPointer<uint> phraseOffset(
                    new uint[static_cast<size_t> (numPhrases + 1)]);
                PRINT_DBG("Reading phrase offsets at %lld", file.pos());
                for (quint16 index = 0; index < numPhrases + 1; index++)
                {
                    phraseOffset[index] = static_cast<uint> (readUnsignedWord(
                            file));
                    PRINT_DBG("        Phrase offset: %d", phraseOffset[index]);
                }
                qint64 inputLength = off + hdr.getReservedSpace() - file.pos();
                PRINT_DBG("Reading compressed phrases at %lld", file.pos());
                QScopedArrayPointer<quint8>
                uncompressedPhrases(
                    new quint8[static_cast<size_t> (uncompressedSize)]);
                unpackLZ77(file, file.pos(), inputLength,
                    uncompressedPhrases.data(),
                    static_cast<size_t> (uncompressedSize));
                size_t pointer = static_cast<size_t> (0);
                for (quint16 index = 0; index < numPhrases; index++)
                {
                    uint size = phraseOffset[index + 1] - phraseOffset[index];
                    QString phrase = readFixedLengthStringFromBuffer(
                        uncompressedPhrases.data(),
                        static_cast<size_t> (uncompressedSize),
                        pointer, size, codec);
                    this->phrases.append(phrase);
                    QScopedArrayPointer<quint8> phraseRaw(
                        new quint8[static_cast<size_t> (size)]);
                    copyBytesFromBuffer(
                        reinterpret_cast<const void *> (uncompressedPhrases.
                            data()),
                        static_cast<size_t> (uncompressedSize),
                        pointer, static_cast<size_t> (size),
                        reinterpret_cast<void *> (phraseRaw.data()),
                        static_cast<size_t> (size));
                    this->phrasesRaw.append(QByteArray(
                            reinterpret_cast<const char *> (phraseRaw.data()),
                            static_cast<int> (size)));
                    pointer += static_cast<size_t> (size);
                    PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
                }
            }
            else
            {
                PRINT_DBG("Loading compressed WinHelp phrase file");
                seekFile(file, off + InternalDirectoryFileHeader::size);
                quint16 numPhrases = readUnsignedWord(file);
                PRINT_DBG("        Num phrases: %d", numPhrases);
                quint16 oneHundred = readUnsignedWord(file);
                PRINT_DBG("        One hundred: %d", oneHundred);
                if (oneHundred != 0x0100)
                {
                    throw std::runtime_error("Not a WinHelp phrase file");
                }
                quint32 uncompressedSize = readUnsignedDWord(file);
                PRINT_DBG("        Uncompressed size: %d", uncompressedSize);
                QScopedArrayPointer<uint> phraseOffset(
                    new uint[static_cast<size_t> (numPhrases + 1)]);
                PRINT_DBG("Reading phrase offsets at %lld", file.pos());
                for (quint16 index = 0; index < numPhrases + 1; index++)
                {
                    phraseOffset[index] = static_cast<uint> (readUnsignedWord(
                            file));
                    PRINT_DBG("        Phrase offset: %d", phraseOffset[index]);
                }
                PRINT_DBG("Reading compressed phrases at %lld", file.pos());
                qint64 inputLength = off + hdr.getReservedSpace() - file.pos();
                QScopedArrayPointer<quint8>
                uncompressedPhrases(
                    new quint8[static_cast<size_t> (uncompressedSize)]);
                unpackLZ77(file, file.pos(), inputLength,
                    uncompressedPhrases.data(),
                    static_cast<size_t> (uncompressedSize));
                size_t pointer = static_cast<size_t> (0);
                for (quint16 index = 0; index < numPhrases; index++)
                {
                    uint size = phraseOffset[index + 1] - phraseOffset[index];
                    QString phrase = readFixedLengthStringFromBuffer(
                        uncompressedPhrases.data(),
                        static_cast<size_t> (uncompressedSize),
                        pointer, size, codec);
                    this->phrases.append(phrase);
                    QScopedArrayPointer<quint8> phraseRaw(
                        new quint8[static_cast<size_t> (size)]);
                    copyBytesFromBuffer(
                        reinterpret_cast<const void *> (uncompressedPhrases.
                            data()),
                        static_cast<size_t> (uncompressedSize),
                        pointer, static_cast<size_t> (size),
                        reinterpret_cast<void *> (phraseRaw.data()),
                        static_cast<size_t> (size));
                    this->phrasesRaw.append(QByteArray(
                            reinterpret_cast<const char *> (phraseRaw.data()),
                            static_cast<int> (size)));
                    pointer += static_cast<size_t> (size);
                    PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
                }
            }
        }
        else
        {
            PRINT_DBG("Loading compressed WinHelp phrase file");
            seekFile(file, off + InternalDirectoryFileHeader::size);
            quint16 numPhrases = readUnsignedWord(file);
            PRINT_DBG("        Num phrases: %d", numPhrases);
            quint16 oneHundred = readUnsignedWord(file);
            PRINT_DBG("        One hundred: %d", oneHundred);
            if (oneHundred != 0x0100)
            {
                throw std::runtime_error("Not a WinHelp phrase file");
            }
            quint32 uncompressedSize = readUnsignedDWord(file);
            PRINT_DBG("        Uncompressed size: %d", uncompressedSize);
            QScopedArrayPointer<uint> phraseOffset(
                new uint[static_cast<size_t> (numPhrases + 1)]);
            PRINT_DBG("Reading phrase offsets at %lld", file.pos());
            for (quint16 index = 0; index < numPhrases + 1; index++)
            {
                phraseOffset[index]
                    = static_cast<uint> (readUnsignedWord(file));
                PRINT_DBG("        Phrase offset: %d", phraseOffset[index]);
            }
            PRINT_DBG("Reading compressed phrases at %lld", file.pos());
            qint64 inputLength = off + hdr.getReservedSpace() - file.pos();
            QScopedArrayPointer<quint8> uncompressedPhrases(
                new quint8[static_cast<size_t> (uncompressedSize)]);
            unpackLZ77(file, file.pos(), inputLength,
                uncompressedPhrases.data(),
                static_cast<size_t> (uncompressedSize));
            size_t pointer = static_cast<size_t> (0);
            for (quint16 index = 0; index < numPhrases; index++)
            {
                uint size = phraseOffset[index + 1] - phraseOffset[index];
                QString phrase = readFixedLengthStringFromBuffer(
                    uncompressedPhrases.data(),
                    static_cast<size_t> (uncompressedSize), pointer,
                    size, codec);
                this->phrases.append(phrase);
                QScopedArrayPointer<quint8> phraseRaw(
                    new quint8[static_cast<size_t> (size)]);
                copyBytesFromBuffer(
                    reinterpret_cast<const void *> (uncompressedPhrases.data()),
                    static_cast<size_t> (uncompressedSize), pointer,
                    static_cast<size_t> (size),
                    reinterpret_cast<void *> (phraseRaw.data()),
                    static_cast<size_t> (size));
                this->phrasesRaw.append(QByteArray(
                        reinterpret_cast<const char *> (phraseRaw.data()),
                        static_cast<int> (size)));
                pointer += static_cast<size_t> (size);
                PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
            }
        }
    }
    else
    {
        PRINT_DBG("Loading uncompressed WinHelp phrase file");
        seekFile(file, off + InternalDirectoryFileHeader::size);
        quint16 numPhrases = readUnsignedWord(file);
        PRINT_DBG("        Num phrases: %d", numPhrases);
        quint16 oneHundred = readUnsignedWord(file);
        PRINT_DBG("        One hundred: %d", oneHundred);
        if (oneHundred != 0x0100)
        {
            throw std::runtime_error("Not a WinHelp phrase file");
        }
        QScopedArrayPointer<uint> phraseOffset(
            new uint[static_cast<size_t> (numPhrases + 1)]);
        PRINT_DBG("Reading phrase offsets at %lld", file.pos());
        for (quint16 index = 0; index < numPhrases + 1; index++)
        {
            phraseOffset[index] = static_cast<uint> (readUnsignedWord(file));
            PRINT_DBG("        Phrase offset: %d", phraseOffset[index]);
        }
        PRINT_DBG("Reading phrases at %lld", file.pos());
        for (quint16 index = 0; index < numPhrases; index++)
        {
            uint size = phraseOffset[index + 1] - phraseOffset[index];
            qint64 posMem = file.pos();
            QString phrase = readFixedLengthString(file, size, codec);
            this->phrases.append(phrase);
            QScopedArrayPointer<quint8> phraseRaw(
                new quint8[static_cast<size_t> (size)]);
            seekFile(file, posMem);
            fillBuffer(file, static_cast<qint64> (size),
                reinterpret_cast<void *> (phraseRaw.data()),
                static_cast<size_t> (size));
            this->phrasesRaw.append(QByteArray(
                    reinterpret_cast<const char *> (phraseRaw.data()),
                    static_cast<int> (size)));
            PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
        }
    }
    PRINT_DBG("WinHelp phrase file loaded successfully");
}
WinHelpPhrImageFile::WinHelpPhrImageFile(QFile &file, qint64 off,
    QTextCodec *codec, const WinHelpPhrIndexFile &index) :
    phrases(), phrasesRaw()
{
    PRINT_DBG("Loading WinHelp PhrImage file at %lld", off);
    if (codec == NULL)
    {
        throw std::runtime_error("Codec is NULL");
    }
    seekFile(file, off);
    InternalDirectoryFileHeader hdr(file, off);
    seekFile(file, off + InternalDirectoryFileHeader::size);
    if (index.getPhrImageCompressedSize() < index.getPhrImageSize())
    {
        PRINT_DBG("Reading compressed phrases at %lld", file.pos());
        QScopedArrayPointer<quint8> uncompressedPhrases(
            new quint8[static_cast<size_t> (index.getPhrImageSize())]);
        unpackLZ77(file, file.pos(), index.getPhrImageCompressedSize(),
            uncompressedPhrases.data(),
            static_cast<size_t> (index.getPhrImageSize()));
        quint64 pointer = 0;
        for (quint16 i = 0; i
            < (static_cast<quint16> (index.getPhraseOffsetsCount()) - 1); i++)
        {
            uint size = index.getPhraseOffset(i + 1) - index.getPhraseOffset(i);
            QString phrase = readFixedLengthStringFromBuffer(
                uncompressedPhrases.data(),
                static_cast<size_t> (index.getPhrImageSize()),
                static_cast<size_t> (pointer), size, codec);
            this->phrases.append(phrase);
            QScopedArrayPointer<quint8> phraseRaw(
                new quint8[static_cast<size_t> (size)]);
            copyBytesFromBuffer(
                reinterpret_cast<const void *> (uncompressedPhrases.data()),
                static_cast<size_t> (index.getPhrImageSize()),
                static_cast<size_t> (pointer),
                static_cast<size_t> (size),
                reinterpret_cast<void *> (phraseRaw.data()),
                static_cast<size_t> (size));
            this->phrasesRaw.append(QByteArray(
                    reinterpret_cast<const char *> (phraseRaw.data()),
                    static_cast<int>(size)));
            pointer += static_cast<quint64> (size);
            PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
        }
    }
    else
    {
        PRINT_DBG("Reading phrases at %lld", file.pos());
        for (quint16 i = 0; i
            < (static_cast<quint16> (index.getPhraseOffsetsCount()) - 1); i++)
        {
            uint size = index.getPhraseOffset(i + 1) - index.getPhraseOffset(i);
            qint64 posMem = file.pos();
            QString phrase = readFixedLengthString(file, size, codec);
            this->phrases.append(phrase);
            QScopedArrayPointer<quint8> phraseRaw(
                new quint8[static_cast<size_t> (size)]);
            seekFile(file, posMem);
            fillBuffer(file, static_cast<qint64> (size),
                reinterpret_cast<void *> (phraseRaw.data()),
                static_cast<size_t> (size));
            this->phrasesRaw.append(QByteArray(
                    reinterpret_cast<const char *> (phraseRaw.data()),
                    static_cast<int>(size)));
            PRINT_DBG("        Phrase: %s", phrase.toLocal8Bit().data());
        }
    }
    PRINT_DBG("WinHelp PhrImage file loaded successfully");
}
bool BadgeData::setTimetable(TimeTable tt)
{
#ifdef ONLY_BADGE
    QFile data;
    TimeTable dum;
    qint64 pos = 0;

    data.setFileName(QDir::homePath() + QDir::separator() + "badge.data");
    data.open(QIODevice::ReadWrite);
    QDataStream out(&data);
    while (!data.atEnd()) {
        out >> dum;
        if (dum.day == tt.day) {
            data.seek(pos);

            out << tt;
            data.close();
            return true;
        }
         pos = data.pos();
    }
    out << tt;
    data.close();
    return true;
#else
    QSqlQuery query;
    QVariant vday(tt.day);
    QVariant venter(tt.entrance);
    QVariant vexit(tt.exit);
    QVariant vbeginFirst(tt.firstPause);
    QVariant vendFirst(tt.endFirstPause);
    QVariant vbeginSecond(tt.secondPause);
    QVariant vendSecond(tt.endSecondPause);

    //QVariant vdefinition (definition);

    query.prepare("select count(*)  from days where daywork = ?");
    query.addBindValue(vday);
    query.exec();
    query.next();

    if(query.value(0).toInt() > 0)
    {

        query.prepare("update days set enter = ? , exit = ? , beginfirst = ? , endfirst = ? , beginsecond = ? , endsecond = ? where daywork = ?");

        query.addBindValue(venter);
        query.addBindValue(vexit);
        query.addBindValue(vbeginFirst);
        query.addBindValue(vendFirst);
        query.addBindValue(vbeginSecond);
        query.addBindValue(vendSecond);
        query.addBindValue(vday);
        if(query.exec())
            qDebug() << "UPDATE OK\n";

    }
    else
    {
        query.prepare("insert into days values(?,?, ?, ?, ?, ?, ?)");
        query.addBindValue(vday);
        query.addBindValue(venter);
        query.addBindValue(vexit);
        query.addBindValue(vbeginFirst);
        query.addBindValue(vendFirst);
        query.addBindValue(vbeginSecond);
        query.addBindValue(vendSecond);

        query.exec();

    }
#endif
    return false;
}
Beispiel #22
0
void SecurityManager::loadMembers()
{
    if (isSql()) {
        loadSqlMembers();
        return;
    }
    const char *path = "serverdb/members.txt";
    const char *backup = "serverdb/members.backup.txt";
    {
        QDir d;
        d.mkdir("serverdb");
    }

    if (!QFile::exists(path) && QFile::exists(backup)) {
        QFile::rename(backup, path);
    }

    memberFile.setFileName(path);
    if (!memberFile.open(QFile::ReadWrite)) {
        throw QObject::tr("Error: cannot open the file that contains the members (%1)").arg(path);
    }

    int pos = memberFile.pos();
    while (!memberFile.atEnd()) {
        QByteArray arr = memberFile.readLine();
        QString s = QString::fromUtf8(arr.constData(), std::max(0,arr.length()-1)); //-1 to remove the \n

        QStringList ls = s.split('%');

        if (ls.size() >= 6 && isValid(ls[0])) {
            Member m (ls[0], ls[1].trimmed(), ls[2][0].toLatin1() - '0', ls[2][1] == '1', ls[3].trimmed().toLatin1(), ls[4].trimmed().toLatin1(), ls[5].trimmed());

            if (ls.size() >= 7) {
                m.ban_expire_time = ls[6].toInt();
            }

            m.filepos = pos;
            members[ls[0]] = m;

            /* Update pos for next iteration */
            pos = memberFile.pos();

            if (m.isBanned()) {
                bannedIPs.insert(m.ip, m.ban_expire_time);
                bannedMembers.insert(m.name.toLower(), std::pair<QString, int>(m.ip, m.ban_expire_time));
            }
            if (m.authority() > 0) {
                authed.insert(m.name);
            }
            playersByIp.insert(m.ip, m.name);
        }
        lastPlace = memberFile.pos();
    }

    //We also clean up the file by rewritting it with only the valid contents
    QFile temp (backup);
    if (!temp.open(QFile::WriteOnly | QFile::Truncate))
        throw QObject::tr("Impossible to change %1").arg(backup);

    pos = temp.pos();

    for(auto it = members.begin(); it != members.end(); ++it) {
        Member &m = it->second;
        m.write(&temp);
        m.filepos = pos;
        pos = temp.pos();
    }

    lastPlace = temp.pos();

    temp.flush();
    memberFile.remove();

    if (!temp.rename(path)) {
        throw QObject::tr("Error: cannot rename the file that contains the members (%1 -> %2)").arg(backup).arg(path);
    }

    temp.rename(path);

    if (!memberFile.open(QFile::ReadWrite)) {
        throw QObject::tr("Error: cannot reopen the file that contains the members (%1)").arg(path);
    }
}
Beispiel #23
0
qint64 StateImport::parseVICESnapshot(QFile& file, quint8* buffer64k)
{
    struct VICESnapshotHeader header;
    struct VICESnapshoptModule module;
    struct VICESnapshoptC64Mem c64mem;

    static const char VICE_MAGIC[] = "VICE Snapshot File\032";
    static const char VICE_C64MEM[] = "C64MEM";

    auto state = State::getInstance();

    if (!file.isOpen())
        file.open(QIODevice::ReadOnly);

    auto size = file.size();
    if (size < (qint64)sizeof(VICESnapshotHeader))
    {
        state->setErrorMessage(QObject::tr("Error: VICE file too small"));
        return -1;
    }

    file.seek(0);
    size = file.read((char*)&header, sizeof(header));
    if (size != sizeof(header))
    {
        state->setErrorMessage(QObject::tr("Error: VICE header too small"));
        return -1;
    }

    if (memcmp(header.id, VICE_MAGIC, sizeof(header.id)) != 0)
    {
        state->setErrorMessage(QObject::tr("Error: Invalid VICE header Id"));
        return -1;
    }

    int offset = file.pos();
    bool found = false;

    while (1) {
        size = file.read((char*)&module, sizeof(module));
        if (size != sizeof(module))
            break;

        /* Found?  */
        if (memcmp(module.moduleName, VICE_C64MEM, sizeof(VICE_C64MEM)) == 0 &&
                module.major == 0)
        {
            found = true;
            break;
        }
        offset += qFromLittleEndian(module.lenght);
        if (!file.seek(offset))
            break;
    }

    if (found)
    {
        size = file.read((char*)&c64mem, sizeof(c64mem));
        if (size != sizeof(c64mem))
        {
            state->setErrorMessage(QObject::tr("Error: Invalid VICE C64MEM segment"));
            return -1;
        }

        memcpy(buffer64k, c64mem.ram, sizeof(c64mem.ram));
    }
    else
    {
        state->setErrorMessage(QObject::tr("Error: VICE C64MEM segment not found"));
        return -1;
    }

    return 0;
}
Beispiel #24
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
bool RifEclipseInputFileTools::readFaultsAndParseIncludeStatementsRecursively(  QFile& file, 
                                                                                qint64 startPos, 
                                                                                const std::vector< std::pair<QString, QString> >& pathAliasDefinitions, 
                                                                                cvf::Collection<RigFault>* faults, 
                                                                                std::vector<QString>* filenamesWithFaults, 
                                                                                bool* isEditKeywordDetected,
                                                                                const QString& faultIncludeFileAbsolutePathPrefix)
{
    QString line;

    if (!file.seek(startPos))
    {
        return false;
    }

    bool continueParsing = true;

    do 
    {
        line = file.readLine();
        line = line.trimmed();

        if (line.startsWith("--", Qt::CaseInsensitive))
        {
            continue;
        }
        else if (line.startsWith(editKeyword, Qt::CaseInsensitive))
        {
            if (isEditKeywordDetected)
            {
                *isEditKeywordDetected = true;
            }

            return false;
        }

        if (line.startsWith(includeKeyword, Qt::CaseInsensitive))
        {
            line = file.readLine();
            line = line.trimmed();

            while (line.startsWith("--", Qt::CaseInsensitive))
            {
                line = file.readLine();
                line = line.trimmed();
            }

            int firstQuote = line.indexOf("'");
            int lastQuote = line.lastIndexOf("'");

            if (!(firstQuote < 0 || lastQuote < 0 || firstQuote == lastQuote))
            {
                QDir currentFileFolder;
                {
                    QFileInfo fi(file.fileName());
                    currentFileFolder = fi.absoluteDir();
                }
                
                // Read include file name, and both relative and absolute path is supported
                QString includeFilename = line.mid(firstQuote + 1, lastQuote - firstQuote - 1);

                for (auto entry : pathAliasDefinitions)
                {
                    QString textToReplace = "$" + entry.first;
                    includeFilename.replace(textToReplace, entry.second);
                }

#ifdef WIN32
                if (includeFilename.startsWith('/'))
                {
                    // Absolute UNIX path, prefix on Windows
                    includeFilename = faultIncludeFileAbsolutePathPrefix + includeFilename;
                }
#endif

                QFileInfo fi(currentFileFolder, includeFilename);
                if (fi.exists())
                {
                    QString absoluteFilename = fi.canonicalFilePath();
                    QFile includeFile(absoluteFilename);
                    if (includeFile.open(QFile::ReadOnly))
                    {
                        //qDebug() << "Found include statement, and start parsing of\n  " << absoluteFilename;

                        if (!readFaultsAndParseIncludeStatementsRecursively(includeFile, 0, pathAliasDefinitions, faults, filenamesWithFaults, isEditKeywordDetected, faultIncludeFileAbsolutePathPrefix))
                        {
                            qDebug() << "Error when parsing include file : " << absoluteFilename;
                        }
                    }
                }
            }
        }
        else if (line.startsWith(faultsKeyword, Qt::CaseInsensitive))
        {
            if (!line.contains("/"))
            {
                readFaults(file, file.pos(), faults, isEditKeywordDetected);
                filenamesWithFaults->push_back(file.fileName());
            }
        }

        if (isEditKeywordDetected && *isEditKeywordDetected)
        {
            continueParsing = false;
        }

        if (file.atEnd())
        {
            continueParsing = false;
        }

    } while (continueParsing);
    
    return true;
}
Beispiel #25
0
 virtual bool Skip(int count) override
 {
     return m_file.seek(m_file.pos() + count);
 }
Beispiel #26
0
void BooFile::read()
{
    QFile file;
    mustOpenFile(mFileName, &file);

    file.seek(mStartPos);

    QString metaAuthor;
    QString metaTitle;
    QString metaSubject;
    QString metaKeywords;

    QString title;
    QList<PageSpec> pagesSpec;

    while (!file.atEnd())
    {
        QString line = QString::fromUtf8(file.readLine()).trimmed();

        if (line.startsWith("@PJL"))
        {
            QString command = line.section(' ', 1, 1, QString::SectionSkipEmpty).toUpper();


            // Boomaga commands ................................
            if (command == "BOOMAGA")
            {
                QString subCommand = line.section(' ', 2, -1, QString::SectionSkipEmpty)
                        .section('=', 0, 0, QString::SectionSkipEmpty)
                        .trimmed()
                        .toUpper();

                QString value = line.section('=', 1,-1, QString::SectionSkipEmpty).trimmed();
                if (value.startsWith('"') || value.startsWith('\''))
                    value = value.mid(1, value.length()-2);


                if (subCommand == "META_AUTHOR")
                    metaAuthor = value;

                else if (subCommand == "META_TITLE")
                    metaTitle = value;

                else if (subCommand == "META_SUBJECT")
                    metaSubject = value;

                else if (subCommand == "META_KEYWORDS")
                    metaKeywords = value;



                else if (subCommand == "JOB_TITLE")
                    title = value;

                else if (subCommand == "JOB_PAGES")
                    pagesSpec = PageSpec::readPagesSpec(value);

                else
                    qWarning() << QString("Unknown command '%1' in the line '%2'").arg(subCommand).arg(line);

            }
            // Boomaga commands ................................


            // PDF stream ......................................
            else if (command == "ENTER")
            {
                QString subCommand = line.section(' ', 2, -1, QString::SectionSkipEmpty).remove(' ').toUpper();

                if (subCommand == "LANGUAGE=PDF")
                {
                    qint64 startPos = file.pos();
                    qint64 endPos = 0;
                    while (!file.atEnd())
                    {
                        QByteArray buf = file.readLine();
                        if (buf.startsWith("\x1B%-12345X@PJL"))
                            break;

                        endPos = file.pos() - 1;
                    }

                    PdfFile pdf;
                    pdf.load(mFileName, startPos, endPos);

                    Job job;
                    job.setFileName(mFileName);
                    job.setFilePos(startPos, endPos);
                    job.setTitle(title);

                    Job pdfJob = pdf.jobs().first();

                    // remove wrong pages .................
                    {
                        int cnt = pdfJob.pageCount();
                        for (int i=pagesSpec.count()-1; i>=0; --i)
                        {
                            if (pagesSpec.at(i).pageNum >= cnt)
                                pagesSpec.removeAt(i);
                        }
                    }

                    QVector<int> pageNums;
                    pageNums.reserve(pagesSpec.count());
                    foreach(const PageSpec &spec, pagesSpec)
                        pageNums << spec.pageNum;

                    addPages(pdfJob, pageNums, &job);

                    for(int i=0; i<pagesSpec.count(); ++i)
                    {
                        const PageSpec &spec = pagesSpec.at(i);
                        ProjectPage *page = job.page(i);

                        if (spec.hidden)
                            page->setVisible(false);

                        if (spec.startBooklet)
                            page->setManualStartSubBooklet(true);

                        page->setManualRotation(spec.rotation);
                    }

                    mJobs << job;
                    title.clear();
                    pagesSpec.clear();
                }
            }
Beispiel #27
0
 bool spool(int64_t how_much){
   R_ASSERT(is_binary==true);
   return file()->seek(read_file->pos() + how_much);
 }
Beispiel #28
0
bool ccHObject::fromFile(QFile& in, short dataVersion, int flags)
{
	if (!fromFileNoChildren(in, dataVersion, flags))
		return false;

	//(serializable) child count (dataVersion>=20)
	uint32_t serializableCount = 0;
	if (in.read((char*)&serializableCount,4) < 0)
		return ReadError();

	//read serializable children (if any)
	for (uint32_t i = 0; i < serializableCount; ++i)
	{
		//read children class ID
		CC_CLASS_ENUM classID = ReadClassIDFromFile(in, dataVersion);
		if (classID == CC_TYPES::OBJECT)
			return false;

		//create corresponding child object
		ccHObject* child = New(classID);

		//specifc case of custom objects (defined by plugins)
		if (classID == CC_TYPES::CUSTOM_H_OBJECT)
		{
			//store current position
			size_t originalFilePos = in.pos();
			//we need to load the custom object as plain ccCustomHobject
			child->fromFileNoChildren(in, dataVersion, flags);
			//go back to original position
			in.seek(originalFilePos);
			//get custom object name and plugin name
			QString childName = child->getName();
			QString classId = child->getMetaData(ccCustomHObject::DefautMetaDataClassName()).toString();
			QString pluginId = child->getMetaData(ccCustomHObject::DefautMetaDataPluginName()).toString();
			//dont' need this instance anymore
			delete child;
			child = 0;

			// try to get a new object from external factories
			ccHObject* newChild = ccHObject::New(pluginId, classId);
			if (newChild) // found a plugin that can deserialize it
			{
				child = newChild;
			}
			else
			{
				ccLog::Warning(QString("[ccHObject::fromFile] Couldn't found any plugin able to deserialize custom object '%1' (class_ID = %2 / plugin_ID = %3").arg(childName).arg(classID).arg(pluginId));
				return false; // FIXME: for now simply return false. We may want to skip it but I'm not sure if there is a simple way of doing that
			}
		}

		assert(child && child->isSerializable());
		if (child)
		{
			if (child->fromFile(in, dataVersion, flags))
			{
				//FIXME
				//addChild(child,child->getFlagState(CC_FATHER_DEPENDENT));
				addChild(child);
			}
			else
			{
				//delete child; //we can't do this as the object might be invalid
				return false;
			}
		}
		else
		{
			return CorruptError();
		}
	}

	//read the selection behavior (dataVersion>=23)
	if (dataVersion >= 23)
	{
		if (in.read((char*)&m_selectionBehavior,sizeof(SelectionBehavior)) < 0)
			return ReadError();
	}
	else
	{
		m_selectionBehavior = SELECTION_AA_BBOX;
	}

	//read transformation history (dataVersion >= 45)
	if (dataVersion >= 45)
	{
		if (!m_glTransHistory.fromFile(in, dataVersion, flags))
		{
			return false;
		}
	}

	return true;
}
Beispiel #29
0
 virtual void BackUp(int count) override
 {
     m_file.seek(m_file.pos() - count);
 }