Example #1
0
bool Dispatcher::initiateTTHSearch(QByteArray tth)
{
    // Dispatch to forwarding peers
    QList<QHostAddress> forwardingPeers = networkTopology->getForwardingPeers(3);
    QListIterator<QHostAddress> it(forwardingPeers);
    while(it.hasNext())
    {
        QHostAddress h = it.next();
        sendTTHSearchForwardRequest(h, tth);
    }

    // Dispatch in own bucket if bootstrapped broadcast or multicast
    QByteArray datagram;
    datagram.reserve(26);
    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        datagram.append(MulticastPacket);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        datagram.append(BroadcastPacket);
    else
        return false;
    datagram.append(TTHSearchRequestPacket);

    datagram.append(tth);
    // TODO: Uncomment in version 0.1.10, this breaks compatibility with 0.1.8 release
    //       Parsing of this tag added in 0.1.9
    //datagram.append(quint32ToByteArray(tthSearchId));
    tthSearchId++;

    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        sendMulticastRawDatagram(datagram);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        sendBroadcastRawDatagram(datagram);

    return true;
}
Example #2
0
void EditBookmarksDialog::accept() {
  // save bookmarks
  // it's easier to recreate the whole bookmark file than
  // to manipulate FmBookmarks object. So here we generate the file directly.
  QByteArray buf;
  buf.reserve(4096);
  for(int row = 0; ; ++row) {
    QTreeWidgetItem* item = ui->treeWidget->topLevelItem(row);
    if(!item)
      break;
    QString name = item->data(0, Qt::DisplayRole).toString();
    QString path = item->data(1, Qt::DisplayRole).toString();
    QUrl url = QUrl::fromUserInput(path);
    buf.append(url.toEncoded());
    buf.append(' ');
    buf.append(name.toUtf8());
    buf.append('\n');
  }

  // FIXME: should we support Qt or KDE specific bookmarks in the future?
  char* outputFile = g_build_filename(g_get_home_dir(), ".gtk-bookmarks", NULL);
  // we use glib API here because the API is atomic.
  g_file_set_contents(outputFile, buf.constData(), buf.length(), NULL);
  g_free(outputFile);
  QDialog::accept();
}
Example #3
0
QByteArray Util::base32encode(const QByteArray &in) {
	QByteArray rc;
	rc.reserve(cyoBase32EncodeGetLength(in.length()));
	rc.resize(cyoBase32Encode(rc.data(), in.constData(), in.length()));

	return rc;
}
QProcessEnvironment PokyRunner::Private::updateEnvironment(const QProcessEnvironment &environment)
{
    QProcessEnvironment env(environment);
    QProcess proc;
    QStringList args;
    args << QLatin1String("-c")
         << QString(QLatin1String(". \"%1\"; env")).arg(envFile);

    proc.start(QLatin1String("sh"), args);
    if (!proc.waitForFinished(5000))
    {
        qWarning() << "[PokyRunner]: Failed to retrieve poky environment from" << envFile;
        proc.kill();
    }
    QByteArray buff;
    buff.reserve(4096);
    qint64 len;

    while ((len = proc.readLine(buff.data(), 4096)) > 0)
    {
        buff.resize(len - 1);
        QString line = QString::fromLatin1(buff);
        int idx = line.indexOf(QLatin1Char('='));
        if (idx < 0)
            qWarning() << "[PokyRunner]: Corrupted output" << line;
        else
            env.insert(line.left(idx), line.mid(idx + 1));
    }
    return env;
}
QByteArray QMetaObject_normalizedSignatureQt47(const char *method)
{
    QByteArray result;
    if (!method || !*method)
        return result;
    int len = int(strlen(method));
    QVarLengthArray<char> stackbuf(len + 1);
    char *d = stackbuf.data();
    qRemoveWhitespace(method, d);

    result.reserve(len);

    int argdepth = 0;
    int templdepth = 0;
    while (*d) {
        if (argdepth == 1)
            d = qNormalizeTypeQt47(d, templdepth, result);
        if (*d == '(')
            ++argdepth;
        if (*d == ')')
            --argdepth;
        result += *d++;
    }

    return result;
}
Example #6
0
QString AMCImporter::readImage(const QString& format_) {
  if(m_failed) {
    return QString();
  }
  quint32 l = readInt();
  if(l == 0) {
    return QString();
  }
  if(l > AMC_MAX_STRING_SIZE) {
    myDebug() << "string is too long:" << l;
    m_failed = true;
    return QString();
  }
  QVector<char> buffer(l+1);
  m_ds.readRawData(buffer.data(), l);
  QByteArray bytes;
  bytes.reserve(l);
  qCopy(buffer.data(), buffer.data() + l, bytes.begin());
  QImage img = QImage::fromData(bytes);
  if(img.isNull()) {
    myDebug() << "null image";
    return QString();
  }
  QString format = QLatin1String("PNG");
  if(format_ == QLatin1String(".jpg")) {
    format = QLatin1String("JPEG");
  } else if(format_ == QLatin1String(".gif")) {
    format = QLatin1String("GIF");
  }
  return ImageFactory::addImage(img, format);
}
Example #7
0
QByteArray KConfigGroupPrivate::serializeList(const QList<QByteArray> &list)
{
    QByteArray value = "";

    if (!list.isEmpty()) {
        QList<QByteArray>::ConstIterator it = list.constBegin();
        const QList<QByteArray>::ConstIterator end = list.constEnd();

        value = QByteArray(*it).replace('\\', "\\\\").replace(',', "\\,");

        while (++it != end) {
            // In the loop, so it is not done when there is only one element.
            // Doing it repeatedly is a pretty cheap operation.
            value.reserve(4096);

            value += ',';
            value += QByteArray(*it).replace('\\', "\\\\").replace(',', "\\,");
        }

        // To be able to distinguish an empty list from a list with one empty element.
        if (value.isEmpty())
            value = "\\0";
    }

    return value;
}
qint64 CryptFileDevice::readData(char *data, qint64 len)
{
    if (!m_encrypted)
    {
        qint64 fileRead = m_device->read(data, len);
        return fileRead;
    }

    if (len == 0)
        return m_device->read(data, len);

    QByteArray ba;
    ba.reserve(len);
    do {
        qint64 maxSize = len - ba.length();

        qint64 size = readBlock(maxSize, ba);

        if (size == 0)
            break;
    } while (ba.length() < len);

    if (ba.isEmpty())
        return 0;

    memcpy(data, ba.data(), ba.length());

    return ba.length();
}
Example #9
0
void Discovery::_gotPacket() {
	QHostAddress address;
	QByteArray buff;
	quint16 port;

	while (mSock.hasPendingDatagrams()) {
		qint64 size = mSock.pendingDatagramSize();
		buff.reserve(size);

		buff.resize(mSock.readDatagram(buff.data(), size, &address, &port));

		if (buff.startsWith("BSYNC\0")) {
			/// @todo Use some other means to distinguish between tracker TrackerResponse and Announce
			if (port == 3000) {
				TrackerResponse resp = TrackerResponse::fromBinary(buff);
				emit gotTrackerResponse(resp);
			}
			else {
				Announce req = Announce::fromBinary(buff);
				emit gotPeerResponse(req, address, port);
			}
		}
		else {

		}
		emit gotPacket(buff, address, port);
	}
}
QByteArray PHISHtmlGeneric::effectStyle() const
{
    QByteArray arr;
    arr.reserve( 400 );
    if ( _it->hasGraphicEffect() ) {
        if ( _it->effect()->graphicsType()==PHIEffect::GTShadow ) {
            arr+=textShadowStyle();
            if ( arr.isEmpty() ) {
                QColor c;
                qreal xOff, yOff, radius;
                _it->effect()->shadow( c, xOff, yOff, radius );
                arr+=boxShadowKeyword()+':'+QByteArray::number( static_cast<int>(xOff) )+"px ";
                arr+=QByteArray::number( static_cast<int>(yOff) )+"px ";
                arr+=QByteArray::number( static_cast<int>(radius) )+"px ";
                arr+=c.name().toLatin1()+';';
            }
        }
    }
    QTransform t=transformation();
    if ( t.isIdentity() ) return arr;
    arr+=transformOriginKeyword()+":0 0;";
    arr+=transformKeyword()+":matrix("+QByteArray::number( t.m11(), 'f' )
        +','+QByteArray::number( t.m12(), 'f' )+','+QByteArray::number( t.m21(), 'f' )
        +','+QByteArray::number( t.m22(), 'f' )+','+QByteArray::number( static_cast<int>(t.m31()) )
        +','+QByteArray::number( static_cast<int>(t.m32()) )+");";
    return arr;
}
Example #11
0
    // complementary
    foreach(U2Region complementaryRegion, regionsComplementary){
        translatedSeq.clear();

        U2SequenceImporter importer;
        importer.startSequence(stateInfo, dbiRef, U2ObjectDbi::ROOT_FOLDER, seqObj->getSequenceName()+ " " + resultName + QString(" %1").arg(currentSeq) + " complementary", false);

        QByteArray complementarySeq;
        char* complSeq = NULL;

        int blockCounter = 0;
        qint64 end = complementaryRegion.endPos() - 1  - complementaryRegion.length / 3 * 3;

        for(qint64 i = complementaryRegion.endPos() - 1 ; i > end ;i-=3, blockCounter += 3){
            if( (blockCounter % NUM_DB_READ) == 0 ){
                importer.addBlock(translatedSeq.constData(), translatedSeq.size(), stateInfo);
                complementarySeq.clear();
                seq.clear();
                translatedSeq.clear();
                seq = seqObj->getSequenceData(U2Region(qMax(end + 1, static_cast<qint64>(i - NUM_DB_READ + 1)), qMin(static_cast<qint64>(NUM_DB_READ), i - end)), stateInfo);
                CHECK_OP(stateInfo, );
                complementarySeq.reserve(seq.size());
                complSeq = complementarySeq.data();
                TextUtils::translate(complTT->getOne2OneMapper(), seq, seq.size(), complSeq);
                TextUtils::reverse(complSeq, seq.size());
                blockCounter = 0;

            }
            SAFE_POINT(complSeq != NULL, "complSeq is NULL", );
            translatedSeq.append(aminoTT->translate3to1(complSeq[blockCounter], complSeq[blockCounter + 1], complSeq[blockCounter + 2]));
        }
Example #12
0
QByteArray dehuffman(QByteArray data, MainWindow *mainWindow)
{
	QHash<quint8, QBitArray> codes;
	qint32 size;
	QBitArray bits;
	{
		QDataStream stream(data);
		stream >> codes >> size >> bits;
		Q_ASSERT(stream.status() == QDataStream::Ok);
	}

	QHash<QBitArray, quint8> table;
	for (int i = 0; i < tableSize; ++i)
		if (codes.contains(i))	table[codes[i]] = i;

	QByteArray result;
	result.reserve(data.size());

	int index = 0;
	for (int i = 0; i < size; ++i)
	{
		mainWindow->setProgress(qRound(static_cast<qreal>(100 * i) / size));

		QBitArray b;
		while (!table.contains(b))
		{
			b.resize(b.size() + 1);
			if (bits[index])	b.setBit(b.size() - 1);
			++index;
		}
		result.append(table[b]);
	}

	return result;
}
Example #13
0
// forward the CID ping to own bucket on request
void Dispatcher::handleReceivedCIDPingForwardRequest(QHostAddress &fromAddr, QByteArray &data)
{
    data.remove(0, 2);
    QByteArray tmp = data.mid(0, 4);
    QHostAddress allegedFromHost = QHostAddress(getQuint32FromByteArray(&tmp));
    if (fromAddr != allegedFromHost)
        return;

    QByteArray datagram;
    datagram.reserve(30);
    switch(networkBootstrap->getBootstrapStatus())
    {
    case NETWORK_MCAST:
        datagram.append(MulticastPacket);
        datagram.append(CIDPingForwardedPacket);
        datagram.append(data);
        sendMulticastRawDatagram(datagram);
        break;
    case NETWORK_BCAST:
        datagram.append(BroadcastPacket);
        datagram.append(CIDPingForwardedPacket);
        datagram.append(data);
        sendBroadcastRawDatagram(datagram);
        break;
    }
}
Example #14
0
void Dispatcher::handleReceivedTTHSearchForwardRequest(QHostAddress &fromAddr, QByteArray &datagram)
{
    QByteArray tmp = datagram.mid(2, 4);
    QHostAddress allegedFromHost = QHostAddress(getQuint32FromByteArray(&tmp));
    if (fromAddr != allegedFromHost)
        return;

    QByteArray searchToForward;
    searchToForward.reserve(30);
    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        searchToForward.append(MulticastPacket);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        searchToForward.append(BroadcastPacket);

    searchToForward.append(TTHSearchRequestPacket);
    searchToForward.append(datagram.mid(2));
    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        sendMulticastRawDatagram(searchToForward);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        sendBroadcastRawDatagram(searchToForward);
    // else drop silently

    handleReceivedTTHSearchQuestion(fromAddr, datagram);

    emit searchForwardReceived(); // stats
    //qDebug() << "Dispatcher::handleReceivedTTHSearchForwardRequest() from alleged datagram" << fromAddr << allegedFromHost << datagram.toBase64();
}
Example #15
0
bool Emu::saveState(const QString &statePath)
{
	emsl.save = true;

	QByteArray data;
	data.reserve(10*1024*1024);

	QDataStream s(&data, QIODevice::WriteOnly);
	s.setByteOrder(QDataStream::LittleEndian);
	s.setFloatingPointPrecision(QDataStream::SinglePrecision);
	if (!saveInternal(&s))
		return false;

	QFile file(statePath);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		emsl.error = tr("Could not open file for writing.");
		return false;
	}

	s.setDevice(&file);
	s << frame().copy(videoSrcRect().toRect());
	QByteArray compressed = qCompress(data);
	bool ok = (file.write(compressed) == compressed.size());
	file.close();
	if (!ok)
		file.remove();
	return ok;
}
Example #16
0
bool BinTreeNodeReader::fillArrayFromRawStream(QByteArray& buffer, quint32 len)
{
    char data[1025];

    buffer.clear();
    buffer.reserve(len);

    int needToRead = len;
    while (needToRead > 0)
    {
        int bytesRead = socket->read(data,(needToRead > 1024) ? 1024 : needToRead);

        if (bytesRead < 0)
            throw IOException(socket->error());

        qApp->processEvents();

        if (bytesRead == 0)
           socket->waitForReadyRead(READ_TIMEOUT);
        else
        {
            needToRead -= bytesRead;
            buffer.append(data,bytesRead);
        }
    }

    return true;
}
Example #17
0
bool Emu::saveInternal(QDataStream *stream)
{
	QByteArray ba;
	ba.reserve(1024 * 1024 * 2);

	QDataStream baStream(&ba, QIODevice::WriteOnly);
	baStream.setByteOrder(QDataStream::LittleEndian);
	baStream.setFloatingPointPrecision(QDataStream::SinglePrecision);

	emsl.stream = &baStream;
	emsl.currAddr.clear();
	emsl.currGroup.clear();
	emsl.allAddr.clear();
	emsl.error.clear();

	emConf.sl();
	sl();

	bool succeded = emsl.error.isEmpty();
	if (succeded) {
		*stream << emsl.allAddr;
		*stream << ba;
	}
	return succeded;
}
Example #18
0
    QByteArray write(Haar::SignatureData* const data)
    {
        QByteArray array;
        array.reserve(sizeof(qint32) + 3*sizeof(double) + 3*sizeof(qint32)*Haar::NumberOfCoefficients);
        QDataStream stream(&array, QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_4_3);

        // write version
        stream << (qint32)Version;

        // write averages
        for (int i=0; i<3; ++i)
        {
            stream << data->avg[i];
        }

        // write coefficients
        for (int i=0; i<3; ++i)
        {
            for (int j=0; j<Haar::NumberOfCoefficients; ++j)
            {
                stream << data->sig[i][j];
            }
        }

        return array;
    }
Example #19
0
bool writeToTempFile(const std::string& data,const std::string& tempDir,std::string& r_outputFile) {
	const std::string fNameTemplate("fileXXXXXX");
	QByteArray templateFileName;
	templateFileName.reserve(tempDir.length() + fNameTemplate.length() + 2);
	templateFileName += QByteArray::fromRawData(tempDir.c_str(), tempDir.size());
	templateFileName += QByteArray::fromRawData(fNameTemplate.c_str(), fNameTemplate.size());

	int fd = mkstemp(templateFileName.data());
	r_outputFile = std::string(templateFileName.data(), templateFileName.size());
	if (fd == -1)
		return false;

	//ssize_t write(int fildes, const void *buf, size_t nbyte);
	ssize_t nwritten = 0;
	ssize_t totalsize = data.size();
	const char * ptr = data.data();
	while (nwritten < totalsize) {
		int r = write(fd,ptr+nwritten,totalsize-nwritten);
		if (r < 0) {
			//fatal error
			break;
		}
		nwritten += r;
	}
	close(fd);
	return (nwritten == totalsize);
}
Example #20
0
QByteArray GdbMi::escapeCString(const QByteArray &ba)
{
    QByteArray ret;
    ret.reserve(ba.length() * 2);
    for (int i = 0; i < ba.length(); ++i) {
        const uchar c = ba.at(i);
        switch (c) {
            case '\\': ret += "\\\\"; break;
            case '\a': ret += "\\a"; break;
            case '\b': ret += "\\b"; break;
            case '\f': ret += "\\f"; break;
            case '\n': ret += "\\n"; break;
            case '\r': ret += "\\r"; break;
            case '\t': ret += "\\t"; break;
            case '\v': ret += "\\v"; break;
            case '"': ret += "\\\""; break;
            default:
                if (c < 32 || c == 127) {
                    ret += '\\';
                    ret += ('0' + (c >> 6));
                    ret += ('0' + ((c >> 3) & 7));
                    ret += ('0' + (c & 7));
                } else {
                    ret += c;
                }
        }
/**
 * Redirects the standard output (prime numbers or prime k-tuplets) of
 * the primeSieveProcess_ to the TextEdit.
 */
void PrimeSieveGUI::printProcessOutput() {
  QByteArray buffer;
  buffer.reserve(PRINT_BUFFER_SIZE + 256);
  while (ui->cancelButton->isEnabled() && primeSieveProcess_->canReadLine()) {
    buffer.clear();
    while (primeSieveProcess_->canReadLine() && buffer.size() < PRINT_BUFFER_SIZE)
      buffer.append(primeSieveProcess_->readLine(256));
    // remove "\r\n" or '\n', '\r' at the back
    while (buffer.endsWith('\n') ||
           buffer.endsWith('\r'))
      buffer.chop(1);
    if (!buffer.isEmpty())
      ui->textEdit->appendPlainText(buffer);
/// @brief   Keep the GUI responsive.
/// @bug     processEvents() crashes on Windows with MSVC 2010 and Qt 5 beta.
/// @warning QApplication::processEvents() must not be used on
///          operating systems that use signal recursion (like Linux
///          X11) otherwise the stack will explode!
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_IOS)
    QApplication::processEvents();
#else
    ui->textEdit->repaint();
#endif
  }
}
Example #22
0
    void PCMThread::run()
    {
        try
        {
            init ();

            while (!quit_)
            {
                QByteArray bytes;
                bytes.reserve (periodSize_ * spSettings_->frameSize_);
                snd_pcm_sframes_t nframes;

                while ( (nframes = snd_pcm_readi (*spPCMHandle_, bytes.data(),
                                                  periodSize_)) < 0)
                {
                    snd_pcm_prepare (*spPCMHandle_);
                    emit sigDebug ("<<<<<<<<<<<<<<< Buffer Overrun >>>>>>>>>>>>>>>");
                }

                bytes.resize (nframes * spSettings_->frameSize_);
                emit sigTimeSeriesReady (bytes);
            }
        }
        catch
            (const std::exception& e)
        {
            emit sigError (QString {"pcm error: "} + e.what());
        }
    }
bool QNetworkAccessFileBackend::readMoreFromFile()
{
    qint64 wantToRead;
    while ((wantToRead = nextDownstreamBlockSize()) > 0) {
        // ### FIXME!!
        // Obtain a pointer from the ringbuffer!
        // Avoid extra copy
        QByteArray data;
        data.reserve(wantToRead);
        qint64 actuallyRead = file.read(data.data(), wantToRead);
        if (actuallyRead <= 0) {
            // EOF or error
            if (file.error() != QFile::NoError) {
                QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Read error reading from %1: %2")
                              .arg(url().toString(), file.errorString());
                error(QNetworkReply::ProtocolFailure, msg);

                finished();
                return false;
            }

            finished();
            return true;
        }

        data.resize(actuallyRead);
        totalBytes += actuallyRead;

        QByteDataBuffer list;
        list.append(data);
        data.clear(); // important because of implicit sharing!
        writeDownstreamData(list);
    }
    return true;
}
Example #24
0
	char* toString(const MapColor& c)
	{
		auto spot_method = QTest::toString(c.getSpotColorMethod());
		auto cmyk_method = QTest::toString(c.getCmykColorMethod());
		auto rgb_method  = QTest::toString(c.getRgbColorMethod());
		
		QByteArray ba;
		ba.reserve(1000);
		ba += "MapColor(";
		ba += QByteArray::number(c.getPriority());
		ba += " ";
		ba += c.getName().toLocal8Bit();
		ba += " (SPOT: ";
		ba += spot_method;
		ba += " ";
		ba += c.getSpotColorName().toLocal8Bit();
		ba += (c.getKnockout() ? " k.o." : " ---");
		ba += " [";
		ba += QByteArray::number(c.getOpacity()*100.0,'f',0);
		ba += "] CMYK: ";
		ba += cmyk_method;
		const MapColorCmyk& cmyk = c.getCmyk();
		ba += QString::fromLatin1(" %1/%2/%3/%4").arg(cmyk.c*100.0,0,'f',1).arg(cmyk.m*100.0,0,'f',1).arg(cmyk.y*100.0,0,'f',1).arg(cmyk.k*100.0,0,'f',1).toLocal8Bit();
		ba += " RGB: ";
		ba += rgb_method;
		const MapColorRgb& rgb = c.getRgb();
		ba += QString::fromLatin1(" %1/%2/%3").arg(rgb.r*255.0,0,'f',0).arg(rgb.g*255.0,0,'f',0).arg(rgb.b*255.0,0,'f',0).toLocal8Bit();
		ba += ")";
		
		delete [] spot_method;
		delete [] cmyk_method;
		delete [] rgb_method;
		
		return qstrdup(ba.data());
	}
Example #25
0
const QByteArray mailAddress::getStr () const
{
  QByteArray retVal;
  retVal.reserve( 128 ); // Should be generally big enough

  if ( !rawFullName.isEmpty() ) {
    QByteArray tmpName( rawFullName );
    KMime::addQuotes( tmpName, false );
    retVal = tmpName + ' ';
  }
  if ( !user.isEmpty() ) {
    retVal += '<';
    retVal += user;
    if ( !host.isEmpty() ) {
      retVal += '@';
      retVal += host;
    }
    retVal += '>';
  }
  if ( !rawComment.isEmpty() ) {
    retVal += " (" + rawComment + ')';
  }
  //kDebug() << retVal;
  return retVal;
}
Example #26
0
/** Pack this exception into a binary QByteArray - this packs the exception
    with its type information */
QByteArray exception::pack() const
{
    QByteArray data;

    //reserve 128K of space for the exception (should be way
    //more than enough!)
    data.reserve( 128 * 1024 );

    QDataStream ds(&data, QIODevice::WriteOnly);

    //get the ID number of this type
    int id = QMetaType::type( this->what() );

    if ( id == 0 or not QMetaType::isRegistered(id) )
        throw SireError::unknown_type(QObject::tr(
                                          "The exception with type \"%1\" does not appear to have been "
                                          "registered with QMetaType. It cannot be streamed! (%2, %3)")
                                      .arg(this->what()).arg(id).arg(QMetaType::isRegistered(id)), CODELOC);

    //save the object type name
    ds << QString(this->what());

    //use the QMetaType streaming function to save this table
    if (not QMetaType::save(ds, id, this))
        throw SireError::program_bug(QObject::tr(
                                         "There was an error saving the exception of type \"%1\". "
                                         "Has the programmer added a RegisterMetaType for this exception?")
                                     .arg(this->what()), CODELOC);

    return data;
}
Example #27
0
void tst_QIODevice::readLine()
{
    QFETCH(QByteArray, data);
    QBuffer buffer(&data);
    QVERIFY(buffer.open(QIODevice::ReadWrite));
    QVERIFY(buffer.canReadLine());

    int linelen = data.indexOf('\n') + 1;
    QByteArray line;
    line.reserve(linelen + 100);

    int result = buffer.readLine(line.data(), linelen + 100);
    QCOMPARE(result, linelen);

    // try the exact length of the line (plus terminating \0)
    QVERIFY(buffer.seek(0));
    result = buffer.readLine(line.data(), linelen + 1);
    QCOMPARE(result, linelen);

    // try with a line length limit
    QVERIFY(buffer.seek(0));
    line = buffer.readLine(linelen + 100);
    QCOMPARE(line.size(), linelen);

    // try without a length limit
    QVERIFY(buffer.seek(0));
    line = buffer.readLine();
    QCOMPARE(line.size(), linelen);
}
Example #28
0
  bool CHttpThread::convertToBinary(QByteArray& array, const CProtocol& protocol)
  {

    array.reserve(protocol.getSize());
    convertToBinary(array, protocol.getVersion());
    convertToBinary(array, protocol.getSize());
    convertToBinary(array, protocol.getIdConcentrator());
    convertToBinary(array, protocol.getIdPackage());
    convertToBinary(array, protocol.getType());

    switch(protocol.getType()){
    case MONITOR_DATA:
      convertToBinary(array, std::dynamic_pointer_cast<CMonitorData>(protocol.getMessage()));
      break;

    case CONFIGURATION_RESPONSE:
      convertToBinary(array, std::dynamic_pointer_cast<CConfigurationResponse>(protocol.getMessage()));
      break;

    case SERVER_REQUEST:
      convertToBinary(array, std::dynamic_pointer_cast<CServerRequest>(protocol.getMessage()));
      break;
    case SERVER_MONITOR_RESPONSE:
      // typ protokolu server -> concentrator
      return false;
      break;
    }
    convertToBinary(array, protocol.getCRC());


    return true;
  }
void readFromStreamLX(QMimeData* aData,RReadStream& aStream)
{
    // This function both leaves and throws exceptions. There must be no destructor
    // dependencies between cleanup styles, and no cleanup stack dependencies on stacked objects.
    TCardinality mimeTypeCount;
    aStream >> mimeTypeCount;
    for (int i = 0; i< mimeTypeCount;i++)
    {
        // mime type
        TCardinality mimeTypeSize;
        aStream >> mimeTypeSize;
        HBufC* mimeTypeBuf = HBufC::NewLC(aStream,mimeTypeSize);
        QString mimeType = QString::fromUtf16(mimeTypeBuf->Des().Ptr(),mimeTypeBuf->Length());
        CleanupStack::PopAndDestroy(mimeTypeBuf);
        // mime data
        TCardinality dataSize;
        aStream >> dataSize;
        QByteArray ba;
        ba.reserve(dataSize);
        aStream.ReadL(reinterpret_cast<uchar*>(ba.data_ptr()->data),dataSize);
        ba.data_ptr()->size = dataSize;
        qDebug() << "paste from clipboard mime: " << mimeType << " data: " << ba;
        aData->setData(mimeType,ba);
    }
}
Example #30
0
void Dispatcher::handleReceivedSearchForwardRequest(QHostAddress &fromAddr, QByteArray &datagram)
{
    QByteArray tmp = datagram.mid(2, 4);
    QHostAddress allegedFromHost = QHostAddress(getQuint32FromByteArray(&tmp));
    if (fromAddr != allegedFromHost)
        return;

    QByteArray searchToForward;
    searchToForward.reserve(200);
    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        searchToForward.append(MulticastPacket);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        searchToForward.append(BroadcastPacket);

    searchToForward.append(SearchRequestPacket);
    searchToForward.append(datagram.mid(2));
    if (networkBootstrap->getBootstrapStatus() == NETWORK_MCAST)
        sendMulticastRawDatagram(searchToForward);
    else if (networkBootstrap->getBootstrapStatus() == NETWORK_BCAST)
        sendBroadcastRawDatagram(searchToForward);
    // else drop silently

    // handle search question while here, in case we don't hear ourselves broadcast it.
    // TODO: add duplicate search killer with moving window somewhere in this mess.
    handleReceivedSearchQuestion(fromAddr, datagram);

    emit searchForwardReceived(); // stats
}