Exemplo n.º 1
0
bool copyFileToStream(const QString& source, QDataStream& target)
{
	bool copySucceed = true;
	int  bytesread, byteswrite;
	if (source.isEmpty())
		return false;
	if (!QFile::exists(source))
		return false;
	if (!target.device()->isOpen() || !target.device()->isWritable())
		return false;
	QFile s(source);
	QByteArray bb( 65536, ' ' );
	if (bb.size() <= 0) // Check for memory allocation failure
		return false;
	if (s.open(QIODevice::ReadOnly))
	{
		bytesread = s.read( bb.data(), bb.size() );
		while (bytesread > 0)
		{
			byteswrite   = target.writeRawData(bb.data(), bytesread);
			copySucceed &= (byteswrite == bytesread);
			bytesread    = s.read( bb.data(), bb.size() );
		}
		copySucceed &= (s.error() == QFile::NoError);
		s.close();
	}
	return copySucceed;
}
static bool waitForAvailableBytes(QDataStream &stream, quint32 count)
{
    while (stream.device()->bytesAvailable() < count) {
        if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) {
            return false;
        }
    }
    return true;
}
Exemplo n.º 3
0
static qint32 rle_decode(QDataStream & abr, char *buffer, qint32 height)
{
    qint32 n;
    char ptmp;
    char ch;
    int i, j, c;
    short *cscanline_len;
    char *data = buffer;

    // read compressed size foreach scanline
    cscanline_len = new short[ height ];
    for (i = 0; i < height; i++) {
        // short
        abr >> cscanline_len[i];
    }

    // unpack each scanline data
    for (i = 0; i < height; i++) {
        for (j = 0; j < cscanline_len[i];) {
            // char
            if (!abr.device()->getChar(&ptmp)) {
                break;
            }
            n = ptmp;

            j++;
            if (n >= 128)     // force sign
                n -= 256;
            if (n < 0) {      // copy the following char -n + 1 times
                if (n == -128)  // it's a nop
                    continue;
                n = -n + 1;
                // char
                if (!abr.device()->getChar(&ch)) {
                    break;
                }

                j++;
                for (c = 0; c < n; c++, data++) {
                    *data = ch;
                }
            }
            else {
                // read the following n + 1 chars (no compr)
                for (c = 0; c < n + 1; c++, j++, data++) {
                    // char
                    if (!abr.device()->getChar(data))  {
                        break;
                    }
                }
            }
        }
    }
    delete [] cscanline_len;
    return 0;
}
Exemplo n.º 4
0
bool IconCacheCreator::writeSizeToCache(QDataStream &out, const QList<int> &sizes) {
    for (int i = 0; i < sizes.size(); i++) {
        //out << sizes.at(i);
        DPRINT("size: %d", out.device()->size());
        out.writeRawData((const char *)&(sizes.at(i)), sizeof(int));
        DPRINT("size: %d", out.device()->size());
    }

    return true;
}
Exemplo n.º 5
0
static qint32 find_sample_count_v6(QDataStream & abr, AbrInfo *abr_info)
{
    qint64 origin;
    qint32 sample_section_size;
    qint32 sample_section_end;
    qint32 samples = 0;
    qint32 data_start;

    qint32 brush_size;
    qint32 brush_end;

    if (!abr_supported_content(abr_info))
        return 0;

    origin = abr.device()->pos();

    if (!abr_reach_8BIM_section(abr, "samp")) {
        // reset to origin
        abr.device()->seek(origin);
        return 0;
    }

    // long
    abr >> sample_section_size;
    sample_section_end = sample_section_size + abr.device()->pos();

    if(sample_section_end < 0 || sample_section_end > abr.device()->size())
        return 0;

    data_start = abr.device()->pos();

    while ((!abr.atEnd()) && (abr.device()->pos() < sample_section_end)) {
        // read long
        abr >> brush_size;
        brush_end = brush_size;
        // complement to 4
        while (brush_end % 4 != 0) brush_end++;

        qint64 newPos = abr.device()->pos() + brush_end;
        if(newPos > 0 && newPos < abr.device()->size()) {
            abr.device()->seek(newPos);
        }
        else
            return 0;

        samples++;
    }

    // set stream to samples data
    abr.device()->seek(data_start);

    //dbgKrita <<"samples : "<< samples;
    return samples;
}
Exemplo n.º 6
0
void LYTTextBox::readFromDataStream(QDataStream &in) {
	qint64 saveStartPos = in.device()->pos();

	LYTPane::readFromDataStream(in);

	// the lengths are stored in bytes (not characters) and count the
	// zero terminator, and strings are UTF-16 (I think) so we need
	// to take it off here
	in >> (quint16&)bufferLength;
	bufferLength >>= 1;
	bufferLength--;

	quint16 stringLength;
	in >> (quint16&)stringLength;
	stringLength >>= 1;
	stringLength--;

	// read the material and font names
	quint16 materialNum, fontNum;
	in >> (quint16&)materialNum;
	in >> (quint16&)fontNum;

	materialName = m_layout.materials.getNameOfIndex(materialNum);
	fontName = m_layout.m_fontRefs.at(fontNum);

	in >> (quint8&)alignment;
	in >> (quint8&)alignmentOverride;

	in.skipRawData(2); // padding

	quint32 stringOffset;
	in >> (quint32&)stringOffset;

	ReadRGBA8Color(colour1, in);
	ReadRGBA8Color(colour2, in);

	in >> (float&)fontSizeX;
	in >> (float&)fontSizeY;
	in >> (float&)charSpace;
	in >> (float&)lineSpace;

	// read the textbox contents
	// subtract 8 to account for BinaryBlockHeader or whatever it's called
	in.device()->seek(saveStartPos + stringOffset - 8);

	ushort *rawText = new ushort[stringLength];

	for (int i = 0; i < stringLength; i++)
		in >> (quint16&)rawText[i];

	text.setUtf16(rawText, stringLength);
	delete[] rawText;
}
Exemplo n.º 7
0
void
KBuildServiceTypeFactory::save(QDataStream &str)
{
    KSycocaFactory::save(str);
#if 0 // not needed since don't have any additional index anymore
    int endOfFactoryData = str.device()->pos();

    // Update header (pass #3)
    saveHeader(str);

    // Seek to end.
    str.device()->seek(endOfFactoryData);
#endif
}
Exemplo n.º 8
0
void KBuildMimeTypeFactory::save(QDataStream &str)
{
    KSycocaFactory::save(str);

    str << (qint32) 0;

    const int endOfFactoryData = str.device()->pos();

    // Update header (pass #3)
    saveHeader(str);

    // Seek to end.
    str.device()->seek(endOfFactoryData);
}
Exemplo n.º 9
0
//************************************************************************************************
void tReportGuiGetListServerModels::ExeCommand(QDataStream &_in)
{

//    QStringList list;

//    int num=-1;
//    _in >> num;
//    for(int i=0; i<num;i++)
//    {
//        QString file="";
//        _in >> file;
//        list.push_back(file);
//    }

//    ((MainForm*)link)->LocalListFile(list);


//    ((MainForm*)link)->ServerListModels(list);
    _in.device()->seek(0);
    _in.device()->seek(54);


    QByteArray block;
    block=_in.device()->readAll();


    ((MainForm*)link)->SaveServerModelFiles(block);


//    ui->lwListModels->selectionModel()->setCurrentIndex(((MainForm*)link)->slm_server_list_models, QItemSelectionModel::ClearAndSelect);
    //((MainForm*)link)->slm_server_list_models->createIndex(((MainForm*)link)->NumCelServModel, 0);
//    QModelIndex MI=ui->lwListModels->currentIndex();
//    int N=MI.row();
//    if(N>0)
//    {
//    ((MainForm*)link)->OnServerModelClick(MI);
//    }

    /*
    QModelIndex MI=ui->lwListModels->currentIndex();

    int N=MI.row();
    if(N>0)
    {
    OnServerModelClick(MI);
    }
    */

}
Exemplo n.º 10
0
void OutgoingMessage::writeString(QDataStream &stream, QString string)
{
    QByteArray utf8_data = string.toUtf8();
    qint32 byte_count = utf8_data.size();
    stream << byte_count;
    stream.device()->write(utf8_data);
}
Exemplo n.º 11
0
void KGameProcessIO::sendAllMessages(QDataStream &stream,int msgid, quint32 receiver, quint32 sender, bool usermsg)
{
  qCDebug(GAMES_PRIVATE_KGAME) << "==============>  KGameProcessIO::sendMessage (usermsg="<<usermsg<<")";
  // if (!player()) return ;
  //if (!player()->isActive()) return ;

  if (usermsg)
  {
    msgid+=KGameMessage::IdUser;
  }

  qCDebug(GAMES_PRIVATE_KGAME) << "=============* ProcessIO (" << msgid << "," << receiver << "," << sender << ") ===========";

  QByteArray buffer;
  QDataStream ostream(&buffer,QIODevice::WriteOnly);
  QBuffer *device=(QBuffer *)stream.device();
  QByteArray data=device->buffer();;

  KGameMessage::createHeader(ostream,sender,receiver,msgid);
  // ostream.writeRawBytes(data.data()+device->at(),data.size()-device->at());
  ostream.writeRawData(data.data(),data.size());
  qCDebug(GAMES_PRIVATE_KGAME) << "   Adding user data from pos="<< device->pos() <<" amount=" << data.size() << "byte";
  //if (d->mMessageClient) d->mMessageClient->sendBroadcast(buffer);
  if (d->mProcessIO)
  {
    d->mProcessIO->send(buffer);
  }
}
Exemplo n.º 12
0
bool BinaryFormat::checkHeader(QDataStream &stream) const
{
    Q_UINT32 magic, version;

    stream >> magic >> version;

    QFile *file = dynamic_cast< QFile * >(stream.device());

    if(!file)
    {
        kdError() << i18n("Not a file?") << endl;
        return false;
    }

    if(magic != 0x2e93e)
    {
        kdError() << i18n("File '%1' is not binary format.").arg(file->name()) << endl;
        return false;
    }

    if(version != BINARY_FORMAT_VERSION)
    {
        kdError() << i18n("File '%1' is the wrong version.").arg(file->name()) << endl;
        return false;
    }

    return true;
}
Exemplo n.º 13
0
QString AbrStructParser::p_bool(QDataStream &buf){
    //# ord converts 1 byte number
    char byte;
    buf.device()->getChar(&byte);
    if (byte) return QString("1");
    else return QString("0");
}
QByteArray IQSMPPOptionalParameter<QString>::encode() const
{
    QByteArray result;
    //Если не устанавливали значения для данной опции, то вернем пустой массив, т.к. данная опция
    //не используется
    if (!_valueSets)
        return result;

    if (tag() == IQSMPP::UndefinedOptionalParameter)
        return result;
    if (maxLength() == 0)
        return result;

    QDataStream stream (&result, QIODevice::WriteOnly);
    stream << (quint16) tag();
    stream << (quint16) 0;

    //Запишим данные
    //Если это строка
    QByteArray stringBA = _value.toLatin1();
    const char * stringShar = stringBA.constData();
    int stringLength = stringBA.length();
    stream.writeRawData(stringShar, stringLength);
    if (_cOctetString)
        stream << (quint8)0x00;

    //Сохраним размер
    stream.device()->seek(2);
    stream << (quint16) result.size() - 4;

    return result;
}
Exemplo n.º 15
0
void writeVector(QDataStream& out, char ch, QVector<T> vec) {
    // Minimum number of bytes to consider compressing
    const int ATTEMPT_COMPRESSION_THRESHOLD_BYTES = 2000;

    out.device()->write(&ch, 1);
    out << (int32_t)vec.length();

    auto data { QByteArray::fromRawData((const char*)vec.constData(), vec.length() * sizeof(T)) };

    if (data.size() >= ATTEMPT_COMPRESSION_THRESHOLD_BYTES) {
        auto compressedDataWithLength { qCompress(data) };

        // qCompress packs a length uint32 at the beginning of the buffer, but the FBX format
        // does not expect it. This removes it.
        auto compressedData = QByteArray::fromRawData(
            compressedDataWithLength.constData() + sizeof(uint32_t), compressedDataWithLength.size() - sizeof(uint32_t));

        if (compressedData.size() < data.size()) {
            out << FBX_PROPERTY_COMPRESSED_FLAG;
            out << (int32_t)compressedData.size();
            out.writeRawData(compressedData.constData(), compressedData.size());
            return;
        }
    }

    out << FBX_PROPERTY_UNCOMPRESSED_FLAG;
    out << (int32_t)0;
    out.writeRawData(data.constData(), data.size());
}
Exemplo n.º 16
0
//отправление данных по всем кораблям
void MyServer::sendAllData(){
    //deleteShipButton->setEnabled(false);

    QByteArray block;
    QDataStream out (&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_5);

    out << quint16(0) << logNumbersOfRemovedShips.size();       //количество удаленных кораблей
    for(int k = 0; k < logNumbersOfRemovedShips.size(); k++){   //номер лога удаленного корабля
        out << logNumbersOfRemovedShips.at(k);                  //
    }

    logNumbersOfRemovedShips.clear();

    out << shipCounter;     //количество существующих на сервере кораблей

    //для всех кораблей
    for(int i=0; i < shipCounter; i++){

        generateData(shipList.at(i));   //генерируем новые данные

        out << shipList.at(i)->id
            << shipList.at(i)->startX
            << shipList.at(i)->startY
            << shipList.at(i)->courseAngle
            << shipList.at(i)->speed
            << shipList.at(i)->viewAngle
            << shipList.at(i)->viewLength
            << shipList.at(i)->pathLength
            << shipList.at(i)->time;



        QTextEdit *te = (QTextEdit*)txtStack->widget(i);        //получение указателя на лог текущего корабля
        te->append(QString("Id: %1").arg(shipList.at(i)->id+1));//вывод сгенерированной информации в лог

        if(shipList.at(i)->isNew){
            te->append(QString("Start X: %1\nStart Y: %2")
                       .arg(shipList.at(i)->startX)
                       .arg(shipList.at(i)->startY));
        }



        te->append(QString("Course angle: %1 deg\nSpeed: %2\nView angle: %3 deg\nViewLength: %4\nPath length: %5 m\nTime: %6 sec\n")
                       .arg(shipList.at(i)->courseAngle)
                       .arg(shipList.at(i)->speed).arg(shipList.at(i)->viewAngle)
                       .arg(shipList.at(i)->viewLength).arg(shipList.at(i)->pathLength).arg(shipList.at(i)->time/1000.0f));

        shipList.at(i)->isNew=0;
    }

    out.device()->seek(0);  //переход в начало блока
    out<<quint16(block.size()-sizeof(quint16)); //размер блока данных
    if(isClientConnected) socket->write(block);   //посылка клиенту, если он подключен
    block.clear();          //очистка используемого блока

    if(!deleteShipButton->isEnabled()&& shipCounter>0) deleteShipButton->setEnabled(true);
}
Exemplo n.º 17
0
// ------------------------------------------------------------------------ //
void RunModule::resetASICs()
{
    //if(dbg())
        msg()("Resetting VMMs...","RunModule::resetASICs");

    bool ok;
    QByteArray datagram;

    // send trigger mode to VMMAPP port
    int send_to_port = config().commSettings().vmmapp_port;

    // headers
    QString cmd, cmdType, cmdLength, msbCounter;
    cmd = "AA";
    cmdType = "AA";
    cmdLength = "FFFF";
    msbCounter = "0x80000000"; 

    for(const auto& ip : socket().ipList()) {
        datagram.clear();
        QDataStream out (&datagram, QIODevice::WriteOnly);
        out.device()->seek(0); //rewind

        socket().updateCommandCounter();

        ///////////////////////////
        // header info
        ///////////////////////////
        out << (quint32)(socket().commandCounter() + msbCounter.toUInt(&ok,16)) //[0,3]
            << (quint16) 0 //[4,5] 
            << (quint16) config().getHDMIChannelMap() //[6,7]
            << (quint8) cmd.toUInt(&ok,16) //[8]
            << (quint8) cmdType.toUInt(&ok,16) //[9]
            << (quint16) cmdLength.toUInt(&ok,16); //[10,11]

        ///////////////////////////
        // reset
        ///////////////////////////
        out << (quint32) 0 //[12,15]
            << (quint32) 128 //[16,19]
            << (quint32) 2; //[20,23]

        socket().SendDatagram(datagram, ip, send_to_port, "fec",
                                                "RunModule::resetASICs");
        bool readOK = true;
        readOK = socket().waitForReadyRead("fec");
        if(readOK) {
            if(dbg()) msg()("Processing replies...","RunModule::resetASICs");
            socket().processReply("fec", ip);
        } else {
            msg()("Timeout while waiting for replies from VMM",
                    "RunModule::resetASICs",true);
            socket().closeAndDisconnect("fec","RunModule::resetASICs");
            exit(1);
        }
    } // ip

    socket().closeAndDisconnect("fec", "RunModule::resetASICs");
}
Exemplo n.º 18
0
// ------------------------------------------------------------------------ //
void RunModule::s6clocks(int cktk, int ckbc, int ckbc_skew)
{
    if(dbg()) msg()("Setting S6 clocks...","RunModule::s6clocks");

    bool ok;
    QByteArray datagram;

    // send call to s6 port
    int send_to_port = config().commSettings().s6_port;

    QString cmd, msbCounter;
    cmd = "AAAAFFFF";
    msbCounter = "0x80000000";

    for(const auto& ip : socket().ipList()) {
        datagram.clear();
        QDataStream out (&datagram, QIODevice::WriteOnly);
        out.device()->seek(0); //rewind

        socket().updateCommandCounter();

        ////////////////////////////
        // header
        ////////////////////////////
        out << (quint32)(socket().commandCounter() + msbCounter.toUInt(&ok,16)) //[0,3]
            << (quint32) config().getHDMIChannelMap() //[4,7]
            << (quint32) cmd.toUInt(&ok,16); //[8,11]

        ////////////////////////////
        // command
        ////////////////////////////
        out << (quint32) 0 //[12,15]
            << (quint32) 6 //[16,19]
            << (quint32) (cktk*16) //[20,23]
            << (quint32) 7 //[24,27]
            << (quint32) ( ckbc + (ckbc_skew*16) ); //[28,31]

        socket().SendDatagram(datagram, ip, send_to_port, "fec",
                                            "RunModule::s6clocks");

        bool readOK = true;
        readOK = socket().waitForReadyRead("fec");
        if(readOK) {
            if(dbg()) msg()("Processing replies...","RunModule::s6clocks");
            socket().processReply("fec",ip);
        } else {
            msg()("Timout while waiting for replies from VMM",
                    "RunModule::s6clocks", true);
            socket().closeAndDisconnect("fec","RunModule::s6clocks");
            exit(1);
        }
    } // ip

    socket().closeAndDisconnect("fec","RunModule::s6clocks");

}
Exemplo n.º 19
0
QString readLinefromDataStream(QDataStream &s)
{
    QString ret = "";
    uchar charData;
    while (!s.atEnd())
    {
        s >> charData;
        if (charData == '\x0A')
            break;
        if (charData == '\x0D')
        {
            quint64 oldPos = s.device()->pos();
            s >> charData;
            if (charData != '\x0A')
                s.device()->seek(oldPos);
            break;
        }
        ret += QChar(charData);
    }
Exemplo n.º 20
0
KSycocaFactory::KSycocaFactory(KSycocaFactoryId factory_id)
    : m_resourceList(0), m_entryDict(0), m_str(0), d(new Private)
{
    if (!KSycoca::self()->isBuilding() && (m_str = KSycoca::self()->findFactory(factory_id))) {
        // Read position of index tables....
        qint32 i;
        (*m_str) >> i;
        d->m_sycocaDictOffset = i;
        (*m_str) >> i;
        d->m_beginEntryOffset = i;
        (*m_str) >> i;
        d->m_endEntryOffset = i;

        QDataStream* str = stream();
        int saveOffset = str->device()->pos();
        // Init index tables
        d->m_sycocaDict = new KSycocaDict(str, d->m_sycocaDictOffset);
        saveOffset = str->device()->seek(saveOffset);
    } else {
Exemplo n.º 21
0
// ------------------------------------------------------------------------ //
void RunModule::checkLinkStatus()
{
    if(dbg()) msg()("Checking link status...","RunModule::checkLinkStatus");

    bool ok;
    QByteArray datagram;

    // send call to vmmapp port
    int send_to_port = config().commSettings().vmmapp_port;

    // header
    QString cmd = "BBAAFFFF";
    QString msbCounter = "0x80000000"; 

    for(const auto& ip : socket().ipList()) {
        datagram.clear();
        QDataStream out (&datagram, QIODevice::WriteOnly);
        out.device()->seek(0); //rewind

        socket().updateCommandCounter();

        ////////////////////////////
        // header
        ////////////////////////////
        out << (quint32)(socket().commandCounter() + msbCounter.toUInt(&ok,16)) //[0,3]
            << (quint32) config().getHDMIChannelMap() //[4,7]
            << (quint32) cmd.toUInt(&ok,16); //[8,11]

        ////////////////////////////
        // command
        ////////////////////////////
        out << (quint32) 0 //[12,15]
            << (quint32) 16; //[16,19]

        socket().SendDatagram(datagram, ip, send_to_port, "fec",
                                                "RunModule::checkLinkStatus");

        bool readOK = true;
        readOK = socket().waitForReadyRead("fec");
        if(readOK) {
            emit checkLinks();
            //if(dbg()) msg()("Processing replies...","RunModule::checkLinkStatus");
            //socket().processReply("fec", ip);
        } else {
            msg()("Timeout while waiting for replies from VMM",
                    "RunModule::checkLinkStatus", true);
            socket().closeAndDisconnect("fec", "RunModule::checkLinkStatus");
            exit(1);
        }
    } // ip

    socket().closeAndDisconnect("fec", "RunModule::checkLinkStatus");

}
Exemplo n.º 22
0
static bool abr_reach_8BIM_section(QDataStream & abr, const QString name)
{
    char tag[4];
    char tagname[5];
    qint32 section_size = 0;
    int r;

    // find 8BIMname section
    while (!abr.atEnd()) {
        r = abr.readRawData(tag, 4);

        if (r != 4) {
            warnKrita << "Error: Cannot read 8BIM tag ";
            return false;
        }

        if (strncmp(tag, "8BIM", 4)) {
            warnKrita << "Error: Start tag not 8BIM but " << (int)tag[0] << (int)tag[1] << (int)tag[2] << (int)tag[3] << " at position " << abr.device()->pos();
            return false;
        }

        r = abr.readRawData(tagname, 4);

        if (r != 4) {
            warnKrita << "Error: Cannot read 8BIM tag name";
            return false;
        }
        tagname[4] = '\0';

        QString s1 = QString::fromLatin1(tagname, 4);

        if (!s1.compare(name)) {
            return true;
        }

        // long
        abr >> section_size;
        abr.device()->seek(abr.device()->pos() + section_size);
    }
    return true;
}
Exemplo n.º 23
0
static void outputLayoutWidgetsSubLayout( QMap<int, QStringList>& buddies,
					  UibIndexMap& objects,
					  UibStrTable& strings,
					  QDataStream& out, QDomElement elem )
{
    int subLayoutNo = -1;
    QCString name;
    QDomElement nameElem;

    QDomElement f = elem.firstChild().toElement();
    while ( !f.isNull() ) {
	QString tag = f.tagName();
	if ( tag == "grid" || tag == "hbox" || tag == "vbox" ) {
	    out << (Q_UINT8) Object_SubLayout;
	    subLayoutNo = outputObject( buddies, objects, strings, out, f,
					layoutForTag(tag) );
	} else if ( tag == "property" ) {
	    if ( f.attribute("name") == "name" ) {
		name = DomTool::elementToVariant( f, name ).asCString();
		nameElem = f;
	    }
	}
	f = f.nextSibling().toElement();
    }

    if ( subLayoutNo != -1 ) {
	/*
	  Remove the sub-layout's Object_End marker, append the grid
	  cell and the correct name property, and put the Object_End
	  marker back.
	*/
	out.device()->at( out.device()->at() - 1 );
	outputGridCell( out, elem );
	outputProperty( buddies, subLayoutNo, strings, out, nameElem );
	out << (Q_UINT8) Object_End;

	objects.setName( subLayoutNo, name );
    }
}
Exemplo n.º 24
0
bool IconCacheCreator::writeHashToCache(QDataStream &out, const QHash<QString, qint64> &hash, qint64 *ret) {
    QList<QString> keys = hash.keys();
    struct HashData *data = new HashData[keys.size()];
    DPRINT("keys size: %d", keys.size());

    for (int i = 0; i < keys.size(); i++) {
        data[i].key = out.device()->pos();
        out.writeRawData(qPrintable(keys.at(i)), keys.at(i).size() + 1);
        data[i].value = hash.value(keys.at(i), -1);
        DPRINT("value: %d", data[i].value);
    }

    *ret = out.device()->pos();

    for (int i = 0; i < keys.size(); i++) {
        DPRINT("hash value: %lld, %lld - %d", data[i].key, data[i].value, i);
        out.writeRawData((const char *)&(data[i].key), sizeof(qint64));
        out.writeRawData((const char *)&(data[i].value), sizeof(qint64));
    }

    delete[] data;
    return true;
}
Exemplo n.º 25
0
KServiceFactory::KServiceFactory()
    : KSycocaFactory( KST_KServiceFactory ),
    m_nameDict(0),
    m_relNameDict(0),
    m_menuIdDict(0)
{
    kServiceFactoryInstance->instanceCreated(this);
    m_offerListOffset = 0;
    m_nameDictOffset = 0;
    m_relNameDictOffset = 0;
    m_menuIdDictOffset = 0;
    if (!KSycoca::self()->isBuilding()) {
        QDataStream* str = stream();
        Q_ASSERT(str);
        if (!str)
            return;
        // Read Header
        qint32 i;
        (*str) >> i;
        m_nameDictOffset = i;
        (*str) >> i;
        m_relNameDictOffset = i;
        (*str) >> i;
        m_offerListOffset = i;
        (*str) >> i;
        m_menuIdDictOffset = i;

        const int saveOffset = str->device()->pos();
        // Init index tables
        m_nameDict = new KSycocaDict(str, m_nameDictOffset);
        // Init index tables
        m_relNameDict = new KSycocaDict(str, m_relNameDictOffset);
        // Init index tables
        m_menuIdDict = new KSycocaDict(str, m_menuIdDictOffset);
        str->device()->seek(saveOffset);
    }
Exemplo n.º 26
0
void OutgoingMessage::writeToStream(QDataStream &stream)
{
    // write body to a buffer so we can measure byte counts
    QByteArray message_body;
    QDataStream body_stream(&message_body, QIODevice::WriteOnly);
    writeMessageBody(body_stream);

    // write header
    const qint64 header_size = 9;
    qint8 _type = type();
    stream << _type;
    qint64 byte_count = message_body.size() + header_size;
    stream << byte_count;

    // write body
    stream.device()->write(message_body);
}
Exemplo n.º 27
0
bool ExternalFile::readItem( QDataStream& in, ItemData& itemData, DatFormat *datFormat, TibiaModule *tibiaModule, qint32 index, quint32& address, QString& error )
{
    QIODevice *device = in.device();
    if( !device )
        return false;

    quint8 type = 0;
    in >> type;

    if( type != ITEM_TYPE_ITEM && type != ITEM_TYPE_OUTFIT && type != ITEM_TYPE_EFFECT && type != ITEM_TYPE_PROJECTILE ) {
        error = QObject::tr( "Unknown Item type" );
        return false;
    }

    ItemData d_itemData;
    if( datFormat ) {
        if( !ItemFile::loadItem( datFormat, in, d_itemData, error ) )
            return false;
    }

    d_itemData.parent = ITEM_PARENT_EXTERNAL;
    d_itemData.type = type;

    address = 0;

    if( !device->atEnd() ) {
        quint32 spriteCount = 0, now = 0, offset = 0;
        in >> spriteCount;
        address = device->pos();
        now = device->pos();
        for( quint32 i = 0; i < spriteCount; i++ ) {
            device->seek( now );
            in >> offset;
            if ( offset == 0x00000000 || offset > device->size() ) { // Direct to an image that doesnt exist or out of boundaries
                now += sizeof( quint32 );
                continue;
            }

            QMutex mutex;
            mutex.lock();
            SharedResource *resource = &g_resourceHandler.addResource(RESOURCE_TYPE_SPRITE, index, i, tibiaModule);
            d_itemData.setSpriteResource(i, *resource);
            mutex.unlock();
            now += sizeof( quint32 );
        }
    }
Exemplo n.º 28
0
void CTcpClient::sendMessage(QString message, QString balise=QString::null)
{
    QString strMessage;
    QByteArray paquet;
    QDataStream out (&paquet, QIODevice::WriteOnly);

    if ((!balise.isNull()) && (!balise.isEmpty())){
        strMessage = "<" + balise + ">" + message + "</" + balise + ">";
    }
    else strMessage = message;

    out << (quint32)0;
    out << strMessage;
    out.device()->seek(0);
    out << (quint32) (paquet.size() - sizeof(quint32));

    write(paquet);
}
Exemplo n.º 29
0
void FBXWriter::encodeNode(QDataStream& out, const FBXNode& node) {
    auto device = out.device();
    auto nodeStartPos = device->pos();

    // endOffset (temporary, updated later)
    out << (FBXEndOffset)0;

    // Property count
    out << (FBXPropertyCount)node.properties.size();

    // Property list length (temporary, updated later)
    out << (FBXListLength)0;

    out << (quint8)node.name.size();
    out.writeRawData(node.name, node.name.size());

    auto nodePropertiesStartPos = device->pos();

    for (const auto& prop : node.properties) {
        encodeFBXProperty(out, prop);
    }

    // Go back and write property list length
    auto nodePropertiesEndPos = device->pos();
    device->seek(nodeStartPos + sizeof(FBXEndOffset) + sizeof(FBXPropertyCount));
    out << (FBXListLength)(nodePropertiesEndPos - nodePropertiesStartPos);

    device->seek(nodePropertiesEndPos);

    for (auto& child : node.children) {
        encodeNode(out, child);
    }

    if (node.children.length() > 0) {
        encodeNode(out, FBXNode());
    }

    // Go back and write actual endOffset
    auto nodeEndPos = device->pos();
    device->seek(nodeStartPos);
    out << (FBXEndOffset)(nodeEndPos);

    device->seek(nodeEndPos);
}
Exemplo n.º 30
0
void SrvCLI::sendRequest (const QString &command, const QString &params)
{
    // Neuen Block zum Senden erstellen
    QByteArray block;
    // Datasteam an den Block binden
    QDataStream out (&block, QIODevice::WriteOnly);
    // DataStream version setzen, hier aktuelle 4.6 = DataStream version 10
    out.setVersion(QDataStream::Qt_4_6);
    // Größe des Blockes erstmal mit 0 initieren und Aktion angeben
    out << quint64(0);
    out << command;
    out << params;
    // Wieder an die erste Stelle des Blockes springen und die Größe neu setzen
    out.device()->seek(0);
    out << quint64(block.size() - sizeof(quint64));
    // Block an das Socket schicken und senden
    this->sslSocket.write(block);
    this->sslSocket.waitForBytesWritten(1000);
    this->sslSocket.flush();
}