Esempio n. 1
0
QVariant MacProtocol::fieldData(int index, FieldAttrib attrib,
        int streamIndex) const
{
    switch (index)
    {
        case mac_dstAddr:
        {
            int u;
            quint64 dstMac = 0;

            switch (data.dst_mac_mode())
            {
                case OstProto::Mac::e_mm_fixed:
                    dstMac = data.dst_mac();
                    break;
                case OstProto::Mac::e_mm_inc:
                    u = (streamIndex % data.dst_mac_count()) * 
                        data.dst_mac_step(); 
                    dstMac = data.dst_mac() + u;
                    break;
                case OstProto::Mac::e_mm_dec:
                    u = (streamIndex % data.dst_mac_count()) * 
                        data.dst_mac_step(); 
                    dstMac = data.dst_mac() - u;
                    break;
                case OstProto::Mac::e_mm_resolve:
                    if (forResolve_)
                        dstMac = 0;
                    else {
                        forResolve_ = true;
                        dstMac = mpStream->neighborMacAddress(streamIndex);
                        forResolve_ = false;
                    }
                    break;
                default:
                    qWarning("Unhandled dstMac_mode %d", data.dst_mac_mode());
            }

            switch(attrib)
            {
                case FieldName:            
                    return QString("Desination");
                case FieldValue:
                    return dstMac;
                case FieldTextValue:
                    return uintToMacStr(dstMac);
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(8);
                    qToBigEndian(dstMac, (uchar*) fv.data());
                    fv.remove(0, 2);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case mac_srcAddr:
        {
            int u;
            quint64 srcMac = 0;

            switch (data.src_mac_mode())
            {
                case OstProto::Mac::e_mm_fixed:
                    srcMac = data.src_mac();
                    break;
                case OstProto::Mac::e_mm_inc:
                    u = (streamIndex % data.src_mac_count()) * 
                        data.src_mac_step(); 
                    srcMac = data.src_mac() + u;
                    break;
                case OstProto::Mac::e_mm_dec:
                    u = (streamIndex % data.src_mac_count()) * 
                        data.src_mac_step(); 
                    srcMac = data.src_mac() - u;
                    break;
                case OstProto::Mac::e_mm_resolve:
                    if (forResolve_)
                        srcMac = 0;
                    else {
                        forResolve_ = true;
                        srcMac = mpStream->deviceMacAddress(streamIndex);
                        forResolve_ = false;
                    }
                    break;
                default:
                    qWarning("Unhandled srcMac_mode %d", data.src_mac_mode());
            }

            switch(attrib)
            {
                case FieldName:            
                    return QString("Source");
                case FieldValue:
                    return srcMac;
                case FieldTextValue:
                    return uintToMacStr(srcMac);
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(8);
                    qToBigEndian(srcMac, (uchar*) fv.data());
                    fv.remove(0, 2);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }

        // Meta fields
        case mac_dstMacMode:
            switch(attrib)
            {
                case FieldValue: return data.dst_mac_mode();
                default: break;
            }
            break;
        case mac_dstMacCount:
            switch(attrib)
            {
                case FieldValue: return data.dst_mac_count();
                default: break;
            }
            break;
        case mac_dstMacStep:
            switch(attrib)
            {
                case FieldValue: return data.dst_mac_step();
                default: break;
            }
            break;
        case mac_srcMacMode:
            switch(attrib)
            {
                case FieldValue: return data.src_mac_mode();
                default: break;
            }
            break;
        case mac_srcMacCount:
            switch(attrib)
            {
                case FieldValue: return data.src_mac_count();
                default: break;
            }
            break;
        case mac_srcMacStep:
            switch(attrib)
            {
                case FieldValue: return data.src_mac_step();
                default: break;
            }
            break;
        default:
            break;
    }

    return AbstractProtocol::fieldData(index, attrib, streamIndex);
}
Esempio n. 2
0
bool Q3Process::start( QStringList *env )
{
#if defined(QT_Q3PROCESS_DEBUG)
    qDebug( "Q3Process::start()" );
#endif
    reset();

    if ( _arguments.isEmpty() )
        return false;

    // Open the pipes.  Make non-inheritable copies of input write and output
    // read handles to avoid non-closable handles (this is done by the
    // DuplicateHandle() call).
    SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
#ifndef Q_OS_WINCE
    // I guess there is no stdin stdout and stderr on Q_OS_WINCE to dup
    // CreatePipe and DupilcateHandle aren't available for Q_OS_WINCE
    HANDLE tmpStdin, tmpStdout, tmpStderr;
    if ( comms & Stdin ) {
        if ( !CreatePipe( &d->pipeStdin[0], &tmpStdin, &secAtt, 0 ) ) {
            d->closeHandles();
            return false;
        }
        if ( !DuplicateHandle( GetCurrentProcess(), tmpStdin, GetCurrentProcess(), &d->pipeStdin[1], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
            d->closeHandles();
            return false;
        }
        if ( !CloseHandle( tmpStdin ) ) {
            d->closeHandles();
            return false;
        }
    }
    if ( comms & Stdout ) {
        if ( !CreatePipe( &tmpStdout, &d->pipeStdout[1], &secAtt, 0 ) ) {
            d->closeHandles();
            return false;
        }
        if ( !DuplicateHandle( GetCurrentProcess(), tmpStdout, GetCurrentProcess(), &d->pipeStdout[0], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
            d->closeHandles();
            return false;
        }
        if ( !CloseHandle( tmpStdout ) ) {
            d->closeHandles();
            return false;
        }
    }
    if ( comms & Stderr ) {
        if ( !CreatePipe( &tmpStderr, &d->pipeStderr[1], &secAtt, 0 ) ) {
            d->closeHandles();
            return false;
        }
        if ( !DuplicateHandle( GetCurrentProcess(), tmpStderr, GetCurrentProcess(), &d->pipeStderr[0], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
            d->closeHandles();
            return false;
        }
        if ( !CloseHandle( tmpStderr ) ) {
            d->closeHandles();
            return false;
        }
    }
    if ( comms & DupStderr ) {
        CloseHandle( d->pipeStderr[1] );
        d->pipeStderr[1] = d->pipeStdout[1];
    }
#endif

    // construct the arguments for CreateProcess()
    QString args;
    QString appName;
    QStringList::Iterator it = _arguments.begin();
    args = *it;
    ++it;
    if ( args.endsWith( QLatin1String(".bat") ) && args.contains( QLatin1Char(' ') ) ) {
        // CreateProcess() seems to have a strange semantics (see also
        // http://www.experts-exchange.com/Programming/Programming_Platforms/Win_Prog/Q_11138647.html):
        // If you start a batch file with spaces in the filename, the first
        // argument to CreateProcess() must be the name of the batchfile
        // without quotes, but the second argument must start with the same
        // argument with quotes included. But if the same approach is used for
        // .exe files, it doesn't work.
        appName = args;
        args = QLatin1Char('"') + args + QLatin1Char('"');
    }
    for ( ; it != _arguments.end(); ++it ) {
        QString tmp = *it;
        // escape a single " because the arguments will be parsed
        tmp.replace( QLatin1Char('\"'), QLatin1String("\\\"") );
        if ( tmp.isEmpty() || tmp.contains( QLatin1Char(' ') ) || tmp.contains( QLatin1Char('\t') ) ) {
            // The argument must not end with a \ since this would be interpreted
            // as escaping the quote -- rather put the \ behind the quote: e.g.
            // rather use "foo"\ than "foo\"
            QString endQuote( QLatin1String("\"") );
            int i = tmp.length();
            while ( i>0 && tmp.at( i-1 ) == QLatin1Char('\\') ) {
                --i;
                endQuote += QLatin1Char('\\');
            }
            args += QLatin1String(" \"") + tmp.left( i ) + endQuote;
        } else {
            args += QLatin1Char(' ') + tmp;
        }
    }
#if defined(QT_Q3PROCESS_DEBUG)
    qDebug( "Q3Process::start(): args [%s]", args.latin1() );
#endif

    // CreateProcess()
    bool success;
    d->newPid();

    STARTUPINFOW startupInfo = {
        sizeof( STARTUPINFO ), 0, 0, 0,
        (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
        0, 0, 0,
        STARTF_USESTDHANDLES,
        0, 0, 0,
        d->pipeStdin[0], d->pipeStdout[1], d->pipeStderr[1]
    };
    wchar_t *applicationName;
    if ( appName.isNull() )
        applicationName = 0;
    else
        applicationName = _wcsdup( (wchar_t*)appName.utf16() );
    wchar_t *commandLine = _wcsdup( (wchar_t*)args.utf16() );
    QByteArray envlist;
    if ( env != 0 ) {
        int pos = 0;
        // add PATH if necessary (for DLL loading)
        QByteArray path = qgetenv( "PATH" );
        if ( env->grep( QRegExp(QLatin1String("^PATH="),FALSE) ).empty() && !path.isNull() ) {
            QString tmp = QString::fromLatin1("PATH=%1").arg(QLatin1String(path.constData()));
            uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
            envlist.resize( envlist.size() + tmpSize );
            memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
            pos += tmpSize;
        }
        // add the user environment
        for ( QStringList::Iterator it = env->begin(); it != env->end(); it++ ) {
            QString tmp = *it;
            uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
            envlist.resize( envlist.size() + tmpSize );
            memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
            pos += tmpSize;
        }
        // add the 2 terminating 0 (actually 4, just to be on the safe side)
        envlist.resize( envlist.size()+4 );
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
    }
    success = CreateProcess( applicationName, commandLine,
                             0, 0, TRUE, ( comms == 0 ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW )
#ifndef Q_OS_WINCE
                             | CREATE_UNICODE_ENVIRONMENT
#endif
                             , env == 0 ? 0 : envlist.data(),
                             (wchar_t*)QDir::toNativeSeparators(workingDir.absPath()).utf16(),
                             &startupInfo, d->pid );

    free( applicationName );
    free( commandLine );

    if  ( !success ) {
        d->deletePid();
        return false;
    }

#ifndef Q_OS_WINCE
    if ( comms & Stdin )
        CloseHandle( d->pipeStdin[0] );
    if ( comms & Stdout )
        CloseHandle( d->pipeStdout[1] );
    if ( (comms & Stderr) && !(comms & DupStderr) )
        CloseHandle( d->pipeStderr[1] );
#endif

    if ( ioRedirection || notifyOnExit ) {
        d->lookup->start( 100 );
    }

    // cleanup and return
    return true;
}
Esempio n. 3
0
void QPF::addGlyphs(QFontEngine *fe, const QList<CharacterRange> &ranges)
{
    const quint16 glyphCount = fe->glyphCount();

    QByteArray gmap;
    gmap.resize(glyphCount * sizeof(quint32));
    gmap.fill(char(0xff));
    //qDebug() << "glyphCount" << glyphCount;

    QByteArray glyphs;
    if (options & RenderGlyphs) {
        // this is only a rough estimation
        glyphs.reserve(glyphCount 
                * (sizeof(QFontEngineQPF::Glyph) 
                    + qRound(fe->maxCharWidth() * (fe->ascent() + fe->descent()).toReal())));

        QGlyphLayoutArray<10> layout;

        foreach (CharacterRange range, ranges) {
            if (debugVerbosity > 2)
                qDebug() << "rendering range from" << range.start << "to" << range.end;
            for (uint uc = range.start; uc <= range.end; ++uc) {
                QChar ch(uc);
                int nglyphs = 10;
                if (!fe->stringToCMap(&ch, 1, &layout, &nglyphs, /*flags*/ 0))
                    continue;

                if (nglyphs != 1)
                    continue;

                const quint32 glyphIndex = layout.glyphs[0];

                if (!glyphIndex)
                    continue;

                Q_ASSERT(glyphIndex < glyphCount);

                QImage img = fe->alphaMapForGlyph(glyphIndex).convertToFormat(QImage::Format_Indexed8);
                glyph_metrics_t metrics = fe->boundingBox(glyphIndex);

                const quint32 oldSize = glyphs.size();
                glyphs.resize(glyphs.size() + sizeof(QFontEngineQPF::Glyph) + img.byteCount());
                uchar *data = reinterpret_cast<uchar *>(glyphs.data() + oldSize);

                uchar *gmapPtr = reinterpret_cast<uchar *>(gmap.data() + glyphIndex * sizeof(quint32));
                qToBigEndian(oldSize, gmapPtr);

                QFontEngineQPF::Glyph *glyph = reinterpret_cast<QFontEngineQPF::Glyph *>(data);
                glyph->width = img.width();
                glyph->height = img.height();
                glyph->bytesPerLine = img.bytesPerLine();
                glyph->x = qRound(metrics.x);
                glyph->y = qRound(metrics.y);
                glyph->advance = qRound(metrics.xoff);
                data += sizeof(QFontEngineQPF::Glyph);

                if (debugVerbosity && uc >= 'A' && uc <= 'z' || debugVerbosity > 1) {
                    qDebug() << "adding glyph with index" << glyphIndex << " uc =" << char(uc) << ":\n"
                        << "    glyph->x =" << glyph->x << "rounded from" << metrics.x << "\n"
                        << "    glyph->y =" << glyph->y << "rounded from" << metrics.y << "\n"
                        << "    width =" << glyph->width << "height =" << glyph->height
                        << "    advance =" << glyph->advance << "rounded from" << metrics.xoff
                        ;
                }

                memcpy(data, img.bits(), img.byteCount());
            }
        }
    }
Esempio n. 4
0
void QgsSimpleLine3DSymbolHandler::makeEntity( Qt3DCore::QEntity *parent, const Qgs3DRenderContext &context, LineData &out, bool selected )
{
  if ( out.indexes.isEmpty() )
    return;

  // material (only ambient color is used for the color)

  Qt3DExtras::QPhongMaterial *mat = _material( mSymbol );
  if ( selected )
  {
    // update the material with selection colors
    mat->setAmbient( context.map().selectionColor() );
  }

  // geometry renderer

  QByteArray vertexBufferData;
  vertexBufferData.resize( out.vertices.size() * 3 * sizeof( float ) );
  float *rawVertexArray = reinterpret_cast<float *>( vertexBufferData.data() );
  int idx = 0;
  for ( const auto &v : qgis::as_const( out.vertices ) )
  {
    rawVertexArray[idx++] = v.x();
    rawVertexArray[idx++] = v.y();
    rawVertexArray[idx++] = v.z();
  }

  QByteArray indexBufferData;
  indexBufferData.resize( out.indexes.size() * sizeof( int ) );
  unsigned int *rawIndexArray = reinterpret_cast<unsigned int *>( indexBufferData.data() );
  idx = 0;
  for ( unsigned int indexVal : qgis::as_const( out.indexes ) )
  {
    rawIndexArray[idx++] = indexVal;
  }

  Qt3DCore::QEntity *entity = new Qt3DCore::QEntity;

  Qt3DRender::QBuffer *vertexBuffer = new Qt3DRender::QBuffer( Qt3DRender::QBuffer::VertexBuffer, entity );
  vertexBuffer->setData( vertexBufferData );

  Qt3DRender::QBuffer *indexBuffer = new Qt3DRender::QBuffer( Qt3DRender::QBuffer::IndexBuffer, entity );
  indexBuffer->setData( indexBufferData );

  Qt3DRender::QAttribute *positionAttribute = new Qt3DRender::QAttribute( entity );
  positionAttribute->setAttributeType( Qt3DRender::QAttribute::VertexAttribute );
  positionAttribute->setBuffer( vertexBuffer );
  positionAttribute->setVertexBaseType( Qt3DRender::QAttribute::Float );
  positionAttribute->setVertexSize( 3 );
  positionAttribute->setName( Qt3DRender::QAttribute::defaultPositionAttributeName() );

  Qt3DRender::QAttribute *indexAttribute = new Qt3DRender::QAttribute( entity );
  indexAttribute->setAttributeType( Qt3DRender::QAttribute::IndexAttribute );
  indexAttribute->setBuffer( indexBuffer );
  indexAttribute->setVertexBaseType( Qt3DRender::QAttribute::UnsignedInt );

  Qt3DRender::QGeometry *geom = new Qt3DRender::QGeometry;
  geom->addAttribute( positionAttribute );
  geom->addAttribute( indexAttribute );

  Qt3DRender::QGeometryRenderer *renderer = new Qt3DRender::QGeometryRenderer;
  renderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::LineStrip );
  renderer->setGeometry( geom );
  renderer->setVertexCount( out.vertices.count() );
  renderer->setPrimitiveRestartEnabled( true );
  renderer->setRestartIndexValue( 0 );

  // make entity
  entity->addComponent( renderer );
  entity->addComponent( mat );
  entity->setParent( parent );
}
Esempio n. 5
0
void PsUpdateDownloader::unpackUpdate() {
    QByteArray packed;
	if (!outputFile.open(QIODevice::ReadOnly)) {
		LOG(("Update Error: cant read updates file!"));
		return fatalFail();
	}
#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif
	QByteArray compressed = outputFile.readAll();
	int32 compressedLen = compressed.size() - hSize;
	if (compressedLen <= 0) {
		LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
		return fatalFail();
	}
	outputFile.close();

	QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyDirPath = cWorkingDir() + qsl("tupdates/ready");
	deleteDir(tempDirPath);
	deleteDir(readyDirPath);

	QDir tempDir(tempDirPath), readyDir(readyDirPath);
	if (tempDir.exists() || readyDir.exists()) {
		LOG(("Update Error: cant clear tupdates/temp or tupdates/ready dir!"));
		return fatalFail();
	}

	uchar sha1Buffer[20];
	bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
	if (!goodSha1) {
		LOG(("Update Error: bad SHA1 hash of update file!"));
		return fatalFail();
	}

	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(UpdatesPublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		LOG(("Update Error: cant read public rsa key!"));
		return fatalFail();
	}
    if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		LOG(("Update Error: bad RSA signature of update file!"));
		return fatalFail();
    }
	RSA_free(pbKey);

	QByteArray uncompressed;

	int32 uncompressedLen;
	memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	uncompressed.resize(uncompressedLen);

	size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
		return fatalFail();
	}
#else
	lzma_stream stream = LZMA_STREAM_INIT;

	lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
		return fatalFail();
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)uncompressed.data();

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
		return fatalFail();
	} else if (stream.avail_out) {
		LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
		return fatalFail();
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
			case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
			case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
			case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res));
		return fatalFail();
	}
#endif

	tempDir.mkdir(tempDir.absolutePath());

	quint32 version;
	{
		QBuffer buffer(&uncompressed);
		buffer.open(QIODevice::ReadOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		stream >> version;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}
        if (int32(version) <= AppVersion) {
			LOG(("Update Error: downloaded version %1 is not greater, than mine %2").arg(version).arg(AppVersion));
			return fatalFail();
		}

		quint32 filesCount;
		stream >> filesCount;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read files count from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}
		if (!filesCount) {
			LOG(("Update Error: update is empty!"));
			return fatalFail();
		}
		for (uint32 i = 0; i < filesCount; ++i) {
			QString relativeName;
			quint32 fileSize;
			QByteArray fileInnerData;
			bool executable = false;

			stream >> relativeName >> fileSize >> fileInnerData;
#if defined Q_OS_MAC || defined Q_OS_LINUX
			stream >> executable;
#endif
			if (stream.status() != QDataStream::Ok) {
				LOG(("Update Error: cant read file from downloaded stream, status: %1").arg(stream.status()));
				return fatalFail();
			}
			if (fileSize != quint32(fileInnerData.size())) {
				LOG(("Update Error: bad file size %1 not matching data size %2").arg(fileSize).arg(fileInnerData.size()));
				return fatalFail();
			}

			QFile f(tempDirPath + '/' + relativeName);
			if (!QDir().mkpath(QFileInfo(f).absolutePath())) {
				LOG(("Update Error: cant mkpath for file '%1'").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			if (!f.open(QIODevice::WriteOnly)) {
				LOG(("Update Error: cant open file '%1' for writing").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			if (f.write(fileInnerData) != fileSize) {
				f.close();
				LOG(("Update Error: cant write file '%1'").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			f.close();
			if (executable) {
				QFileDevice::Permissions p = f.permissions();
				p |= QFileDevice::ExeOwner | QFileDevice::ExeUser | QFileDevice::ExeGroup | QFileDevice::ExeOther;
				f.setPermissions(p);
			}
		}

		// create tdata/version file
		tempDir.mkdir(QDir(tempDirPath + qsl("/tdata")).absolutePath());
		std::wstring versionString = ((version % 1000) ? QString("%1.%2.%3").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000)).arg(int(version % 1000)) : QString("%1.%2").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000))).toStdWString();

		VerInt versionNum = VerInt(version), versionLen = VerInt(versionString.size() * sizeof(VerChar));
		VerChar versionStr[32];
		memcpy(versionStr, versionString.c_str(), versionLen);

		QFile fVersion(tempDirPath + qsl("/tdata/version"));		
		if (!fVersion.open(QIODevice::WriteOnly)) {
			LOG(("Update Error: cant write version file '%1'").arg(tempDirPath + qsl("/version")));
			return fatalFail();
		}
		fVersion.write((const char*)&versionNum, sizeof(VerInt));
		fVersion.write((const char*)&versionLen, sizeof(VerInt));
		fVersion.write((const char*)&versionStr[0], versionLen);
		fVersion.close();
	}
	
	if (!tempDir.rename(tempDir.absolutePath(), readyDir.absolutePath())) {
		LOG(("Update Error: cant rename temp dir '%1' to ready dir '%2'").arg(tempDir.absolutePath()).arg(readyDir.absolutePath()));
		return fatalFail();
	}
	deleteDir(tempDirPath);
	outputFile.remove();

    emit App::app()->updateReady();
}
Esempio n. 6
0
bool EPSHandler::read(QImage *image)
{
    kDebug(399) << "kimgio EPS: starting...";

    FILE * ghostfd;
    int x1, y1, x2, y2;
    //QTime dt;
    //dt.start();

    QString cmdBuf;
    QString tmp;

    QIODevice* io = device();
    quint32 ps_offset, ps_size;

    // find start of PostScript code
    if ( !seekToCodeStart(io, ps_offset, ps_size) )
        return false;

    // find bounding box
    if ( !bbox (io, &x1, &y1, &x2, &y2)) {
        kError(399) << "kimgio EPS: no bounding box found!" << endl;
        return false;
    }

    QTemporaryFile tmpFile;
    if( !tmpFile.open() ) {
        kError(399) << "kimgio EPS: no temp file!" << endl;
        return false;
    }

    // x1, y1 -> translation
    // x2, y2 -> new size

    x2 -= x1;
    y2 -= y1;
    //kDebug(399) << "origin point: " << x1 << "," << y1 << "  size:" << x2 << "," << y2;
    double xScale = 1.0;
    double yScale = 1.0;
    int wantedWidth = x2;
    int wantedHeight = y2;

    // create GS command line

    cmdBuf = "gs -sOutputFile=";
    cmdBuf += tmpFile.fileName();
    cmdBuf += " -q -g";
    tmp.setNum( wantedWidth );
    cmdBuf += tmp;
    tmp.setNum( wantedHeight );
    cmdBuf += 'x';
    cmdBuf += tmp;
    cmdBuf += " -dSAFER -dPARANOIDSAFER -dNOPAUSE -sDEVICE=ppm -c "
              "0 0 moveto "
              "1000 0 lineto "
              "1000 1000 lineto "
              "0 1000 lineto "
              "1 1 254 255 div setrgbcolor fill "
              "0 0 0 setrgbcolor - -c showpage quit";

    // run ghostview

    ghostfd = popen (QFile::encodeName(cmdBuf), "w");

    if ( ghostfd == 0 ) {
        kError(399) << "kimgio EPS: no GhostScript?" << endl;
        return false;
    }

    fprintf (ghostfd, "\n%d %d translate\n", -qRound(x1*xScale), -qRound(y1*yScale));

    // write image to gs

    io->reset(); // Go back to start of file to give all the file to GhostScript
    if (ps_offset>0L) // We have an offset
        io->seek(ps_offset);
    QByteArray buffer ( io->readAll() );

    // If we have no MS-DOS EPS file or if the size seems wrong, then choose the buffer size
    if (ps_size<=0 || ps_size>(unsigned int)buffer.size())
        ps_size=buffer.size();

    fwrite(buffer.data(), sizeof(char), ps_size, ghostfd);
    buffer.resize(0);

    pclose ( ghostfd );

    // load image
    if( image->load (tmpFile.fileName()) ) {
        kDebug(399) << "kimgio EPS: success!";
        //kDebug(399) << "Loading EPS took " << (float)(dt.elapsed()) / 1000 << " seconds";
        return true;
    }

    kError(399) << "kimgio EPS: no image!" << endl;
    return false;
}
Esempio n. 7
0
bool KArchive::addLocalFile( const QString& fileName, const QString& destName )
{
    QFileInfo fileInfo( fileName );
    if ( !fileInfo.isFile() && !fileInfo.isSymLink() )
    {
        kWarning() << fileName << "doesn't exist or is not a regular file.";
        return false;
    }

    KDE_struct_stat fi;
    if (KDE::lstat(fileName,&fi) == -1) {
        kWarning() << "stat'ing" << fileName
        	<< "failed:" << strerror(errno);
        return false;
    }

    if (fileInfo.isSymLink()) {
        QString symLinkTarget;
        // Do NOT use fileInfo.readLink() for unix symlinks!
        // It returns the -full- path to the target, while we want the target string "as is".
#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX)
        const QByteArray encodedFileName = QFile::encodeName(fileName);
        QByteArray s;
#if defined(PATH_MAX)
        s.resize(PATH_MAX+1);
#else
        int path_max = pathconf(encodedFileName.data(), _PC_PATH_MAX);
        if (path_max <= 0) {
            path_max = 4096;
        }
        s.resize(path_max);
#endif
        int len = readlink(encodedFileName.data(), s.data(), s.size() - 1);
        if ( len >= 0 ) {
            s[len] = '\0';
            symLinkTarget = QFile::decodeName(s);
        }
#endif
        if (symLinkTarget.isEmpty()) // Mac or Windows
            symLinkTarget = fileInfo.symLinkTarget();
        return writeSymLink(destName, symLinkTarget, fileInfo.owner(),
                            fileInfo.group(), fi.st_mode, fi.st_atime, fi.st_mtime,
                            fi.st_ctime);
    }/*end if*/

    qint64 size = fileInfo.size();

    // the file must be opened before prepareWriting is called, otherwise
    // if the opening fails, no content will follow the already written
    // header and the tar file is effectively f*cked up
    QFile file( fileName );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
        kWarning() << "couldn't open file " << fileName;
        return false;
    }

    if ( !prepareWriting( destName, fileInfo.owner(), fileInfo.group(), size,
    		fi.st_mode, fi.st_atime, fi.st_mtime, fi.st_ctime ) )
    {
        kWarning() << " prepareWriting" << destName << "failed";
        return false;
    }

    // Read and write data in chunks to minimize memory usage
    QByteArray array;
    array.resize( int( qMin( qint64( 1024 * 1024 ), size ) ) );
    qint64 n;
    qint64 total = 0;
    while ( ( n = file.read( array.data(), array.size() ) ) > 0 )
    {
        if ( !writeData( array.data(), n ) )
        {
            kWarning() << "writeData failed";
            return false;
        }
        total += n;
    }
    Q_ASSERT( total == size );

    if ( !finishWriting( size ) )
    {
        kWarning() << "finishWriting failed";
        return false;
    }
    return true;
}
Esempio n. 8
0
void CNetRender::ProcessData(QTcpSocket *socket, sMessage *inMsg)
{
	// beware: payload points to char, first cast to target type pointer, then dereference
	// *(qint32*)msg->payload

	//------------------------- CLIENT ------------------------
	if(IsClient())
	{
		switch ((netCommand)inMsg->command)
		{
		case netRender_VERSION:
		{
			sMessage outMsg;
			if(*(qint32*)inMsg->payload.data() == version)
			{
				WriteLog("NetRender - version matches (" + QString::number(version) + "), connection established");

				if(systemData.noGui)
				{
					QTextStream out(stdout);
					out << "NetRender - version matches (" + QString::number(version) + "), connection established\n";
				}

				// server version matches, send worker count
				outMsg.command = netRender_WORKER;
				QDataStream stream(&outMsg.payload, QIODevice::WriteOnly);
				stream << workerCount;
				QString machineName = QHostInfo::localHostName();
				stream << (qint32)machineName.toUtf8().size();
				stream.writeRawData(machineName.toUtf8().data(), machineName.toUtf8().size());
				status = netRender_READY;
				emit NewStatusClient();
			}
			else
			{
				qWarning() << "CNetRender - version mismatch! client version: " << version << ", server: " << *(qint32*)inMsg->payload.data();
				outMsg.command = netRender_BAD;
			}
			SendData(clientSocket, outMsg);
			break;
			}
			case netRender_STOP:
			{
				status = netRender_READY;
				gMainInterface->stopRequest = true;
				emit NotifyStatus();
				WriteLog("CNetRender - STOP");
				break;
			}
			case netRender_STATUS:
			{
				emit NotifyStatus();
				break;
			}
			case netRender_JOB:
			{
				if (inMsg->id == actualId)
				{
					WriteLog("NetRender - received new job");
					QDataStream stream(&inMsg->payload, QIODevice::ReadOnly);
					QByteArray buffer;
					qint32 size;
					status = netRender_WORKING;
					emit NotifyStatus();

					// read settings
					stream >> size;
					buffer.resize(size);
					stream.readRawData(buffer.data(), size);
					settingsText = QString::fromUtf8(buffer.data(), buffer.size());

					// read textures
					for (int i = 0; i < textures.textureList.size(); i++)
					{
						stream >> size;
						if (size > 0)
						{
							buffer.resize(size);
							stream.readRawData(buffer.data(), size);
							textures.textureList[i]->FromQByteArray(buffer);
						}
					}

					cSettings parSettings(cSettings::formatCondensedText);
					parSettings.BeQuiet(true);
					parSettings.LoadFromString(settingsText);
					parSettings.Decode(gPar, gParFractal);

					if(!systemData.noGui)
					{
						gMainInterface->SynchronizeInterface(gPar, gParFractal, cInterface::write);
						gMainInterface->StartRender(true);
					}
					else
					{
						//in noGui mode it must be started as separate thread to be able to process event loop
						gMainInterface->headless = new cHeadless;

						QThread *thread = new QThread; //deleted by deleteLater()
						gMainInterface->headless->moveToThread(thread);
						QObject::connect(thread, SIGNAL(started()), gMainInterface->headless, SLOT(slotNetRender()));
						thread->setObjectName("RenderJob");
						thread->start();

						QObject::connect(gMainInterface->headless, SIGNAL(finished()), gMainInterface->headless, SLOT(deleteLater()));
						QObject::connect(gMainInterface->headless, SIGNAL(finished()), thread, SLOT(quit()));
						QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
					}
				}
				else
				{
					WriteLog("NetRender - received JOB message with wrong id");
				}
				break;
			}
			case netRender_RENDER:
			{
				if (inMsg->id == actualId)
				{
					QDataStream stream(&inMsg->payload, QIODevice::ReadOnly);
					qint32 doneSize;
					stream >> doneSize;
					QList<int> done;
					for (int i = 0; i < doneSize; i++)
					{
						qint32 line;
						stream >> line;
						done.append(line);
					}

					emit ToDoListArrived(done);
				}
				else
				{
Esempio n. 9
0
void AssignmentClient::readPendingDatagrams() {
    NodeList* nodeList = NodeList::getInstance();
    
    QByteArray receivedPacket;
    HifiSockAddr senderSockAddr;
    
    while (nodeList->getNodeSocket().hasPendingDatagrams()) {
        receivedPacket.resize(nodeList->getNodeSocket().pendingDatagramSize());
        nodeList->getNodeSocket().readDatagram(receivedPacket.data(), receivedPacket.size(),
                                               senderSockAddr.getAddressPointer(), senderSockAddr.getPortPointer());
        
        if (packetVersionMatch(receivedPacket)) {
            if (_currentAssignment) {
                // have the threaded current assignment handle this datagram
                QMetaObject::invokeMethod(_currentAssignment, "processDatagram", Qt::QueuedConnection,
                                          Q_ARG(QByteArray, receivedPacket),
                                          Q_ARG(HifiSockAddr, senderSockAddr));
            } else if (packetTypeForPacket(receivedPacket) == PacketTypeCreateAssignment) {
                
                if (_currentAssignment) {
                    qDebug() << "Dropping received assignment since we are currently running one.";
                } else {
                    // construct the deployed assignment from the packet data
                    _currentAssignment = AssignmentFactory::unpackAssignment(receivedPacket);
                    
                    if (_currentAssignment) {
                        qDebug() << "Received an assignment -" << *_currentAssignment;
                        
                        // switch our nodelist domain IP and port to whoever sent us the assignment
                        
                        nodeList->setDomainSockAddr(senderSockAddr);
                        nodeList->setOwnerUUID(_currentAssignment->getUUID());
                        
                        qDebug() << "Destination IP for assignment is" << nodeList->getDomainIP().toString();
                        
                        // start the deployed assignment
                        QThread* workerThread = new QThread(this);
                        
                        connect(workerThread, SIGNAL(started()), _currentAssignment, SLOT(run()));
                        
                        connect(_currentAssignment, SIGNAL(finished()), this, SLOT(assignmentCompleted()));
                        connect(_currentAssignment, SIGNAL(finished()), workerThread, SLOT(quit()));
                        connect(_currentAssignment, SIGNAL(finished()), _currentAssignment, SLOT(deleteLater()));
                        connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
                        
                        _currentAssignment->moveToThread(workerThread);
                        
                        // move the NodeList to the thread used for the _current assignment
                        nodeList->moveToThread(workerThread);
                        
                        // Starts an event loop, and emits workerThread->started()
                        workerThread->start();
                    } else {
                        qDebug() << "Received an assignment that could not be unpacked. Re-requesting.";
                    }
                }
            } else {
                // have the NodeList attempt to handle it
                nodeList->processNodeData(senderSockAddr, receivedPacket);
            }
        }
    }
}
Esempio n. 10
0
/**
 * @brief SingleApplication::SingleApplication
 *  Constructor. Checks and fires up LocalServer or closes the program
 *  if another instance already exists
 * @param argc
 * @param argv
 */
SingleApplication::SingleApplication(QStringList &args)
{
  _shouldContinue = false; // By default this is not the main process

  socket = new QUdpSocket();
  QUdpSocket acceptor;
  acceptor.bind(QHostAddress::LocalHost, 58488, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress);

  // Attempt to connect to the LocalServer
  socket->connectToHost(QHostAddress::LocalHost, 58487);
  QString isServerRuns;
  if(socket->waitForConnected(100))
  {
      socket->write(QString("CMD:Is editor running?").toUtf8());
      socket->flush();
      if(acceptor.waitForReadyRead(100))
      {
          //QByteArray dataGram;//Yes, I'm runs!
          QByteArray datagram;
          datagram.resize(acceptor.pendingDatagramSize());
          QHostAddress sender;
          quint16 senderPort;
          acceptor.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
          if(QString::fromUtf8(datagram)=="Yes, I'm runs!")
          {
              isServerRuns="Yes!";
          }
      }
  }

  if(args.contains("--force-run", Qt::CaseInsensitive))
  {
      isServerRuns.clear();
      args.removeAll("--force-run");
  }
  _arguments = args;

  if(!isServerRuns.isEmpty())
  {
    QString str = QString("CMD:showUp");
    QByteArray bytes;
    for(int i=1; i<_arguments.size(); i++)
    {
       str.append(QString("\n%1").arg(_arguments[i]));
    }
    bytes = str.toUtf8();
    socket->write(bytes);
    socket->flush();
    QThread::msleep(100);
    socket->close();
  }
  else
  {
    // The attempt was insuccessful, so we continue the program
    _shouldContinue = true;
    server = new LocalServer();
    server->start();
    QObject::connect(server, SIGNAL(showUp()), this, SLOT(slotShowUp()));
    QObject::connect(server, SIGNAL(dataReceived(QString)), this, SLOT(slotOpenFile(QString)));
    QObject::connect(server, SIGNAL(acceptedCommand(QString)), this, SLOT(slotAcceptedCommand(QString)));
    QObject::connect(this, SIGNAL(stopServer()), server, SLOT(stopServer()));
  }
}
Esempio n. 11
0
CQueryHit* CQueryHit::ReadPacket(G2Packet *pPacket, QSharedPointer<QueryHitInfo> pHitInfo)
{
	if( !pPacket->m_bCompound )
        return 0;

	pPacket->m_nPosition = 0; // reset packet position

    bool bHaveHits = false;
    bool bFirstHit = true;

    CQueryHit* pThisHit = new CQueryHit();

	try
	{
		char szType[9], szTypeX[9];
		quint32 nLength = 0, nLengthX = 0, nNext = 0, nNextX = 0;
		bool bCompound = false;

		while( pPacket->ReadPacket(&szType[0], nLength, &bCompound) )
		{
			nNext = pPacket->m_nPosition + nLength;

			if( strcmp("H", szType) == 0 && bCompound )
			{
				CQueryHit* pHit = (bFirstHit ? pThisHit : new CQueryHit());

				if( !bFirstHit )
				{
					CQueryHit* pPrevHit = pThisHit;
					while( pPrevHit->m_pNext != 0 )
					{
						pPrevHit = pPrevHit->m_pNext;
					}
					pPrevHit->m_pNext = pHit;
				}

				bool bHaveSize = false;
				QByteArray baTemp;
				bool bHaveDN = false;
				bool bHaveURN = false;

				while( pPacket->m_nPosition < nNext && pPacket->ReadPacket(&szTypeX[0], nLengthX))
				{
					nNextX = pPacket->m_nPosition + nLengthX;

					if( strcmp("URN", szTypeX) == 0 )
					{
						QString sURN;
						char hashBuff[256];
						sURN = pPacket->ReadString();

						if( nLengthX >= 44u && sURN.compare("bp") == 0 )
						{
							pPacket->Read(&hashBuff[0], CSHA1::ByteCount());
							if( pHit->m_oSha1.FromRawData(&hashBuff[0], CSHA1::ByteCount()) )
							{
								bHaveURN = true;
							}
							else
							{
								pHit->m_oSha1.Clear();
							}
						}
						else if( nLengthX >= CSHA1::ByteCount() + 5u && sURN.compare("sha1") == 0 )
						{
							pPacket->Read(&hashBuff[0], CSHA1::ByteCount());
							if( pHit->m_oSha1.FromRawData(&hashBuff[0], CSHA1::ByteCount()) )
							{
								bHaveURN = true;
							}
							else
							{
								pHit->m_oSha1.Clear();
							}
						}


					}
					else if( strcmp("URL", szTypeX) == 0 && nLengthX )
					{
						// if url empty - try uri-res resolver or a node do not have this object
						// bez sensu...
						pHit->m_sURL = pPacket->ReadString();
					}
					else if( strcmp("DN", szTypeX) == 0 )
					{
						if( bHaveSize )
						{
							pHit->m_sDescriptiveName = pPacket->ReadString(nLengthX);
						}
						else if( nLengthX > 4 )
						{
							baTemp.resize(4);
							pPacket->Read(baTemp.data(), 4);
							pHit->m_sDescriptiveName = pPacket->ReadString(nLengthX - 4);
						}

						bHaveDN = true;
					}
					else if( strcmp("MD", szTypeX) == 0 )
					{
						pHit->m_sMetadata = pPacket->ReadString();
					}
					else if( strcmp("SZ", szTypeX) == 0 && nLengthX >= 4 )
					{
						if( nLengthX >= 8 )
						{
							if( !baTemp.isEmpty() )
							{
								pHit->m_sDescriptiveName.prepend(baTemp);
							}
							pHit->m_nObjectSize = pPacket->ReadIntLE<quint64>();
							bHaveSize = true;
						}
						else if( nLengthX >= 4 )
						{
							if( !baTemp.isEmpty() )
							{
								pHit->m_sDescriptiveName.prepend(baTemp);
							}
							pHit->m_nObjectSize = pPacket->ReadIntLE<quint32>();
							bHaveSize = true;
						}
					}
					else if( strcmp("CSC", szTypeX) == 0 && nLengthX >= 2 )
					{
						pHit->m_nCachedSources = pPacket->ReadIntLE<quint16>();
					}
					else if( strcmp("PART", szTypeX) == 0 && nLengthX >= 4 )
					{
						pHit->m_bIsPartial = true;
						pHit->m_nPartialBytesAvailable = pPacket->ReadIntLE<quint32>();
					}
					pPacket->m_nPosition = nNextX;
				}

				if( !bHaveSize && baTemp.size() == 4 )
				{
					pHit->m_nObjectSize = qFromLittleEndian(*(quint32*)baTemp.constData());
				}
				else
				{
					pHit->m_sDescriptiveName.prepend(baTemp);
				}

				if( bHaveURN && bHaveDN )
				{
					bFirstHit = false;
					bHaveHits = true;
				}
				else
				{
					if( !bFirstHit )
					{
						// może teraz się nie wywali...
						// można by było to lepiej zrobić...
						for( CQueryHit* pTest = pThisHit; pTest != 0; pTest = pTest->m_pNext )
						{
							if( pTest->m_pNext == pHit )
							{
								pTest->m_pNext = 0;
								break;
							}
						}
						pHit->Delete();
					}
				}
			}

			pPacket->m_nPosition = nNext;
		}
	}
	catch(...) // packet incomplete, packet error, parser takes care of stream end
	{
		qDebug() << "EXCEPTION IN QUERY HIT PARSING!";
		if( pThisHit )
		{
			pThisHit->Delete();
		}
		//throw;
		return 0;
	}

	// we already know query hit informations, so don't reparse them
	if( !bHaveHits )
	{
		pThisHit->Delete();
		return 0;
	}

    CQueryHit* pHit = pThisHit;

    while( pHit != 0 )
    {
        pHit->m_pHitInfo = pHitInfo;

        pHit = pHit->m_pNext;
    }


    // TODO: sprawdzic poprawnosc hita... (Validate hit)

    pHit = pThisHit;

    while( pHit != 0 )
    {
        pHit->ResolveURLs();
        pHit = pHit->m_pNext;
    }

    return pThisHit;
}
Esempio n. 12
0
bool MailFolder::compact(unsigned level)
{
    // sync first so that you are sure the database is ok
    sync();

    if ( level ) {
        qDebug("Folder compressing isn't yet available.");
    }

    QCString mboxInfo;
    mboxInfo = "From - " + QDateTime::currentDateTime().toString() + "\r\n";

    QFile descriptorFile( getDescriptorFileName() );
    if ( !descriptorFile.open(IO_ReadOnly) )
        return false;

    QFile newDescriptorFile( getDescriptorFileName()+"new" );
    if ( !newDescriptorFile.open(IO_WriteOnly) )
        return false;

    QFile messageFile( getMessagesFileName() );
    if ( !messageFile.open(IO_ReadOnly) )
        return false;

    QFile newMessageFile( getMessagesFileName()+"new" );
    if ( !newMessageFile.open(IO_WriteOnly) )
        return false;

    IndexClass * index = 0L;
    QByteArray buffer;

    for (QDictIterator<IndexClass> it(indexCollection); it.current(); ++it) {
        index = it.current();

        if ( !index->getDescriptorLength() ||
                !index->getUniblockLength() ) {
            qDebug("The index file seems to be broken :(");
            indexCollection.remove( index->getID() );
            continue;
        }

        // read the descriptor
        buffer.resize( index->getDescriptorLength() );
        descriptorFile.at( index->getDescriptorOffset() );
        descriptorFile.readBlock(buffer.data(), buffer.size());

        // write the descriptor
        index->setDescriptorOffset( newDescriptorFile.at() );
        newDescriptorFile.writeBlock( buffer );

        // read the message
        buffer.resize( index->getUniblockLength() );
        messageFile.at( index->getUniblockOffset() );
        messageFile.readBlock(buffer.data(), buffer.size());

        // write the message
        // The MBOX line isn't right but the line isn't used too.
        // So, I decided to just store only the current date.
        newMessageFile.writeBlock((const char *)mboxInfo, mboxInfo.length());
        index->setUniblockOffset(newMessageFile.at(), true);

        newMessageFile.writeBlock( buffer );
        newMessageFile.writeBlock("\r\n", 2);
    }

    descriptorFile.close();
    newDescriptorFile.close();
    messageFile.close();
    newMessageFile.close();

    buffer.truncate(0);

    // replace the old files
    descriptorFile.remove();
    messageFile.remove();

    QDir folder( getStorageDevice() );
    folder.rename( newDescriptorFile.name(), getDescriptorFileName(), true );
    folder.rename( newMessageFile.name(), getMessagesFileName(), true );

    saveIndex();

    return true;
}
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt.nokia.com/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt.nokia.com/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by NOKIA");
QByteArray y = x.toLower();
// y == "qt by nokia"
//! [30]


//! [31]
QByteArray x("Qt by NOKIA");
QByteArray y = x.toUpper();
// y == "QT BY NOKIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()]
strcpy(data, text.data());
delete [] data; 
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1]
strcpy(data, text.data());
delete [] data;
//! [47]

}
void CSwordModuleInfo::buildIndex() {

    m_cancelIndexing = false;

    try {
        //Without this we don't get strongs, lemmas, etc
        backend()->setFilterOptions ( CBTConfig::getFilterOptionDefaults() );
        //make sure we reset all important filter options which influcence the plain filters.
        // turn on these options, they are needed for the EntryAttributes population
        backend()->setOption( CSwordModuleInfo::strongNumbers,  true );
        backend()->setOption( CSwordModuleInfo::morphTags,  true );
        backend()->setOption( CSwordModuleInfo::footnotes,  true );
        backend()->setOption( CSwordModuleInfo::headings,  true );
        // we don't want the following in the text, the do not carry searchable information
        backend()->setOption( CSwordModuleInfo::morphSegmentation,  false );
        backend()->setOption( CSwordModuleInfo::scriptureReferences,  false );
        backend()->setOption( CSwordModuleInfo::redLetterWords,  false );

        // do not use any stop words
        const TCHAR* stop_words[]  = { NULL };
        lucene::analysis::standard::StandardAnalyzer an( (const TCHAR**)stop_words );
        QString index = getModuleStandardIndexLocation();

        QDir dir("/");
        dir.mkpath( getGlobalBaseIndexLocation() );
        dir.mkpath( getModuleBaseIndexLocation() );
        dir.mkpath( getModuleStandardIndexLocation() );

        if (lucene::index::IndexReader::indexExists(index.toAscii().constData())) {
            if (lucene::index::IndexReader::isLocked(index.toAscii().constData()) ) {
                lucene::index::IndexReader::unlock(index.toAscii().constData());
            }
        }

        boost::scoped_ptr<lucene::index::IndexWriter> writer( new lucene::index::IndexWriter(index.toAscii().constData(), &an, true) ); //always create a new index
        writer->setMaxFieldLength(BT_MAX_LUCENE_FIELD_LENGTH);
        writer->setUseCompoundFile(true); //merge segments into a single file
        writer->setMinMergeDocs(1000);

        *m_module = sword::TOP;
        unsigned long verseLowIndex = m_module->Index();
        *m_module = sword::BOTTOM;
        unsigned long verseHighIndex = m_module->Index();

        //verseLowIndex is not 0 in all cases (i.e. NT-only modules)
        unsigned long verseIndex = verseLowIndex + 1;
        unsigned long verseSpan = verseHighIndex - verseLowIndex;

        //Index() is not implemented properly for lexicons, so we use a
        //workaround.
        if (type() == CSwordModuleInfo::Lexicon) {
            verseIndex = 0;
            verseLowIndex = 0;
            verseSpan = ((CSwordLexiconModuleInfo*)this)->entries()->size();
        }

        emit indexingProgress(0);

        sword::SWKey* key = m_module->getKey();
        //VerseKey for bibles
        sword::VerseKey* vk = dynamic_cast<sword::VerseKey*>(key);

        if (vk) {
            // we have to be sure to insert the english key into the index, otherwise we'd be in trouble if the language changes
            vk->setLocale("en_US");
            //If we have a verse based module, we want to include the pre-chapter etc. headings in the search
            vk->Headings(1);
        }

        //holds UTF-8 data and is faster than QString.
        QByteArray textBuffer;

        // we start with the first module entry, key is automatically updated
        // because key is a pointer to the modules key
        m_module->setSkipConsecutiveLinks(true);

        wchar_t wcharBuffer[BT_MAX_LUCENE_FIELD_LENGTH + 1];

        for (*m_module = sword::TOP; !(m_module->Error()) && !m_cancelIndexing; (*m_module)++) {

            // Also index Chapter 0 and Verse 0, because they might have information in the entry attributes
            // We used to just put their content into the textBuffer and continue to the next verse, but
            // with entry attributes this doesn't work any more.
            // Hits in the search dialog will show up as 1:1 (instead of 0)

            boost::scoped_ptr<lucene::document::Document> doc(new lucene::document::Document());

            //index the key
            lucene_utf8towcs(wcharBuffer, key->getText(), BT_MAX_LUCENE_FIELD_LENGTH);

            //doc->add(*lucene::document::Field::UnIndexed((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer));
            doc->add(*(new lucene::document::Field((const TCHAR*)_T("key"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_YES | lucene::document::Field::INDEX_NO)));

            // index the main text
            //at this point we have to make sure we disabled the strongs and the other options
            //so the plain filters won't include the numbers somehow.
            lucene_utf8towcs(wcharBuffer, (const char*) textBuffer.append(m_module->StripText()), BT_MAX_LUCENE_FIELD_LENGTH);
            doc->add(*(new lucene::document::Field((const TCHAR*)_T("content"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
            textBuffer.resize(0); //clean up

            // index attributes
            sword::AttributeList::iterator attListI;
            sword::AttributeValue::iterator attValueI;
            // Footnotes
            for (attListI = m_module->getEntryAttributes()["Footnote"].begin();
                    attListI != m_module->getEntryAttributes()["Footnote"].end();
                    attListI++) {
                lucene_utf8towcs(wcharBuffer, attListI->second["body"], BT_MAX_LUCENE_FIELD_LENGTH);
                //doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("footnote"), wcharBuffer));
                doc->add(*(new lucene::document::Field((const TCHAR*)_T("footnote"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
            } // for attListI

            // Headings
            for (attValueI = m_module->getEntryAttributes()["Heading"]["Preverse"].begin();
                    attValueI != m_module->getEntryAttributes()["Heading"]["Preverse"].end();
                    attValueI++) {
                lucene_utf8towcs(wcharBuffer, attValueI->second, BT_MAX_LUCENE_FIELD_LENGTH);
                //doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("heading"), wcharBuffer));
                doc->add(*(new lucene::document::Field((const TCHAR*)_T("heading"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
            } // for attValueI

            // Strongs/Morphs
            for (attListI = m_module->getEntryAttributes()["Word"].begin();
                    attListI != m_module->getEntryAttributes()["Word"].end();
                    attListI++) {
                // for each attribute
                if (attListI->second["LemmaClass"] == "strong") {
                    lucene_utf8towcs(wcharBuffer, attListI->second["Lemma"], BT_MAX_LUCENE_FIELD_LENGTH);
                    //doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("strong"), wcharBuffer));
                    doc->add(*(new lucene::document::Field((const TCHAR*)_T("strong"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
                    //qWarning("Adding strong %s", attListI->second["Lemma"].c_str());
                }
                if (attListI->second.find("Morph") != attListI->second.end()) {
                    lucene_utf8towcs(wcharBuffer, attListI->second["Morph"], BT_MAX_LUCENE_FIELD_LENGTH);
                    //doc->add(*lucene::document::Field::UnStored((const TCHAR*)_T("morph"), wcharBuffer));
                    doc->add(*(new lucene::document::Field((const TCHAR*)_T("morph"), (const TCHAR*)wcharBuffer, lucene::document::Field::STORE_NO | lucene::document::Field::INDEX_TOKENIZED)));
                }
            } // for attListI

            writer->addDocument(doc.get());
            //Index() is not implemented properly for lexicons, so we use a
            //workaround.
            if (type() == CSwordModuleInfo::Lexicon) {
                verseIndex++;
            }
            else {
                verseIndex = m_module->Index();
            }

            if (verseIndex % 200 == 0) {
                int indexingProgressValue;
                if (verseSpan == 0) { //prevent division by zero
                    //m_indexingProgress.setValue( QVariant(0) );
                    indexingProgressValue = 0;
                }
                else {
                    //m_indexingProgress.setValue( QVariant((int)((100*(verseIndex-verseLowIndex))/(verseHighIndex-verseLowIndex))) );
                    indexingProgressValue = (int)((100 * (verseIndex - verseLowIndex)) / (verseSpan));
                }
                //m_indexingProgress.activate();
                emit indexingProgress(indexingProgressValue);
            }
        }

        if (!m_cancelIndexing) {
            writer->optimize();
        }
        writer->close();

        if (m_cancelIndexing) {
            deleteIndex();
            m_cancelIndexing = false;
        }
        else {
            QSettings module_config(getModuleBaseIndexLocation() + QString("/bibletime-index.conf"), QSettings::IniFormat);
            if (hasVersion()) module_config.setValue("module-version", config(CSwordModuleInfo::ModuleVersion) );
            module_config.setValue("index-version", INDEX_VERSION);
            emit hasIndexChanged(true);
        }
    }
    catch (...) {
        qWarning("CLucene exception occurred while indexing");
        util::showWarning(0, QCoreApplication::tr("Indexing aborted"), QCoreApplication::tr("An internal error occurred while building the index."));
        deleteIndex();
        m_cancelIndexing = false;
    }
}
Esempio n. 15
0
// NOTE: some additional optimizations to consider.
//    1) use the view frustum to cull those avatars that are out of view. Since avatar data doesn't need to be present
//       if the avatar is not in view or in the keyhole.
void AvatarMixer::broadcastAvatarData() {

    int idleTime = QDateTime::currentMSecsSinceEpoch() - _lastFrameTimestamp;

    ++_numStatFrames;

    const float STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.10f;
    const float BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD = 0.20f;

    const float RATIO_BACK_OFF = 0.02f;

    const int TRAILING_AVERAGE_FRAMES = 100;
    int framesSinceCutoffEvent = TRAILING_AVERAGE_FRAMES;

    const float CURRENT_FRAME_RATIO = 1.0f / TRAILING_AVERAGE_FRAMES;
    const float PREVIOUS_FRAMES_RATIO = 1.0f - CURRENT_FRAME_RATIO;

    _trailingSleepRatio = (PREVIOUS_FRAMES_RATIO * _trailingSleepRatio)
                          + (idleTime * CURRENT_FRAME_RATIO / (float) AVATAR_DATA_SEND_INTERVAL_MSECS);

    float lastCutoffRatio = _performanceThrottlingRatio;
    bool hasRatioChanged = false;

    if (framesSinceCutoffEvent >= TRAILING_AVERAGE_FRAMES) {
        if (_trailingSleepRatio <= STRUGGLE_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD) {
            // we're struggling - change our min required loudness to reduce some load
            _performanceThrottlingRatio = _performanceThrottlingRatio + (0.5f * (1.0f - _performanceThrottlingRatio));

            qDebug() << "Mixer is struggling, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was"
                     << lastCutoffRatio << "and is now" << _performanceThrottlingRatio;
            hasRatioChanged = true;
        } else if (_trailingSleepRatio >= BACK_OFF_TRIGGER_SLEEP_PERCENTAGE_THRESHOLD && _performanceThrottlingRatio != 0) {
            // we've recovered and can back off the required loudness
            _performanceThrottlingRatio = _performanceThrottlingRatio - RATIO_BACK_OFF;

            if (_performanceThrottlingRatio < 0) {
                _performanceThrottlingRatio = 0;
            }

            qDebug() << "Mixer is recovering, sleeping" << _trailingSleepRatio * 100 << "% of frame time. Old cutoff was"
                     << lastCutoffRatio << "and is now" << _performanceThrottlingRatio;
            hasRatioChanged = true;
        }

        if (hasRatioChanged) {
            framesSinceCutoffEvent = 0;
        }
    }

    if (!hasRatioChanged) {
        ++framesSinceCutoffEvent;
    }

    static QByteArray mixedAvatarByteArray;

    int numPacketHeaderBytes = populatePacketHeader(mixedAvatarByteArray, PacketTypeBulkAvatarData);

    NodeList* nodeList = NodeList::getInstance();

    AvatarMixerClientData* nodeData = NULL;
    AvatarMixerClientData* otherNodeData = NULL;

    foreach (const SharedNodePointer& node, nodeList->getNodeHash()) {
        if (node->getLinkedData() && node->getType() == NodeType::Agent && node->getActiveSocket()
                && (nodeData = reinterpret_cast<AvatarMixerClientData*>(node->getLinkedData()))->getMutex().tryLock()) {
            ++_sumListeners;

            // reset packet pointers for this node
            mixedAvatarByteArray.resize(numPacketHeaderBytes);

            AvatarData& avatar = nodeData->getAvatar();
            glm::vec3 myPosition = avatar.getPosition();

            // this is an AGENT we have received head data from
            // send back a packet with other active node data to this node
            foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) {
                if (otherNode->getLinkedData() && otherNode->getUUID() != node->getUUID()
                        && (otherNodeData = reinterpret_cast<AvatarMixerClientData*>(otherNode->getLinkedData()))->getMutex().tryLock()) {

                    AvatarMixerClientData* otherNodeData = reinterpret_cast<AvatarMixerClientData*>(otherNode->getLinkedData());
                    AvatarData& otherAvatar = otherNodeData->getAvatar();
                    glm::vec3 otherPosition = otherAvatar.getPosition();

                    float distanceToAvatar = glm::length(myPosition - otherPosition);
                    //  The full rate distance is the distance at which EVERY update will be sent for this avatar
                    //  at a distance of twice the full rate distance, there will be a 50% chance of sending this avatar's update
                    const float FULL_RATE_DISTANCE = 2.0f;

                    //  Decide whether to send this avatar's data based on it's distance from us
                    if ((_performanceThrottlingRatio == 0 || randFloat() < (1.0f - _performanceThrottlingRatio))
                            && (distanceToAvatar == 0.0f || randFloat() < FULL_RATE_DISTANCE / distanceToAvatar)) {
                        QByteArray avatarByteArray;
                        avatarByteArray.append(otherNode->getUUID().toRfc4122());
                        avatarByteArray.append(otherAvatar.toByteArray());

                        if (avatarByteArray.size() + mixedAvatarByteArray.size() > MAX_PACKET_SIZE) {
                            nodeList->writeDatagram(mixedAvatarByteArray, node);

                            // reset the packet
                            mixedAvatarByteArray.resize(numPacketHeaderBytes);
                        }

                        // copy the avatar into the mixedAvatarByteArray packet
                        mixedAvatarByteArray.append(avatarByteArray);

                        // if the receiving avatar has just connected make sure we send out the mesh and billboard
                        // for this avatar (assuming they exist)
                        bool forceSend = !nodeData->checkAndSetHasReceivedFirstPackets();

                        // we will also force a send of billboard or identity packet
                        // if either has changed in the last frame

                        if (otherNodeData->getBillboardChangeTimestamp() > 0
                                && (forceSend
                                    || otherNodeData->getBillboardChangeTimestamp() > _lastFrameTimestamp
                                    || randFloat() < BILLBOARD_AND_IDENTITY_SEND_PROBABILITY)) {
                            QByteArray billboardPacket = byteArrayWithPopulatedHeader(PacketTypeAvatarBillboard);
                            billboardPacket.append(otherNode->getUUID().toRfc4122());
                            billboardPacket.append(otherNodeData->getAvatar().getBillboard());
                            nodeList->writeDatagram(billboardPacket, node);

                            ++_sumBillboardPackets;
                        }

                        if (otherNodeData->getIdentityChangeTimestamp() > 0
                                && (forceSend
                                    || otherNodeData->getIdentityChangeTimestamp() > _lastFrameTimestamp
                                    || randFloat() < BILLBOARD_AND_IDENTITY_SEND_PROBABILITY)) {

                            QByteArray identityPacket = byteArrayWithPopulatedHeader(PacketTypeAvatarIdentity);

                            QByteArray individualData = otherNodeData->getAvatar().identityByteArray();
                            individualData.replace(0, NUM_BYTES_RFC4122_UUID, otherNode->getUUID().toRfc4122());
                            identityPacket.append(individualData);

                            nodeList->writeDatagram(identityPacket, node);

                            ++_sumIdentityPackets;
                        }
                    }

                    otherNodeData->getMutex().unlock();
                }
            }

            nodeList->writeDatagram(mixedAvatarByteArray, node);

            nodeData->getMutex().unlock();
        }
    }
Esempio n. 16
0
void SSDP::ProcessData( MSocketDevice *pSocket )
{
    long nBytes = 0;
    long nRead  = 0;

    while ((nBytes = pSocket->bytesAvailable()) > 0)
    {
        QByteArray buffer;
        buffer.resize(nBytes);

        nRead = pSocket->readBlock( buffer.data(), nBytes );

        QHostAddress  peerAddress = pSocket->peerAddress();
        quint16       peerPort    = pSocket->peerPort   ();

        // ------------------------------------------------------------------
        QString     str          = QString(buffer.constData());
        QStringList lines        = str.split("\r\n", QString::SkipEmptyParts);
        QString     sRequestLine = lines.size() ? lines[0] : "";

        lines.pop_front();

        // ------------------------------------------------------------------
        // Parse request Type
        // ------------------------------------------------------------------

        VERBOSE(VB_UPNP+VB_EXTRA,
                QString( "SSDP::ProcessData - requestLine: %1" )
                .arg( sRequestLine ));

        SSDPRequestType eType = ProcessRequestLine( sRequestLine );

        // ------------------------------------------------------------------
        // Read Headers into map
        // ------------------------------------------------------------------

        QStringMap  headers;

        for ( QStringList::Iterator it = lines.begin();
                                    it != lines.end(); ++it ) 
        {
            QString sLine  = *it;
            QString sName  = sLine.section( ':', 0, 0 ).trimmed();
            QString sValue = sLine.section( ':', 1 );

            sValue.truncate( sValue.length() );  //-2

            if ((sName.length() != 0) && (sValue.length() !=0))
                headers.insert( sName.toLower(), sValue.trimmed() );
        }

//        pSocket->SetDestAddress( peerAddress, peerPort );

        // --------------------------------------------------------------
        // See if this is a valid request
        // --------------------------------------------------------------

        switch( eType )
        {
            case SSDP_MSearch:
            {
                // ----------------------------------------------------------
                // If we haven't enabled notifications yet, then we don't 
                // want to answer search requests.
                // ----------------------------------------------------------

                if (m_pNotifyTask != NULL)
                    ProcessSearchRequest( headers, peerAddress, peerPort ); 

                break;
            }

            case SSDP_MSearchResp:
                ProcessSearchResponse( headers); 
                break;

            case SSDP_Notify:
                ProcessNotify( headers ); 
                break;

            case SSDP_Unknown:
            default:
                VERBOSE(VB_UPNP, "SSPD::ProcessData - Unknown request Type.");
                break;
        }
    }

}
Esempio n. 17
0
double Equalizer::filter(QByteArray &data, bool flush)
{
	if (canFilter)
	{
		mutex.lock();

		if (!flush)
		{
			float *samples = (float *)data.data();
			const int size = data.size() / sizeof(float);
			for (int c = 0; c < chn; ++c) //Buforowanie danych
				for (int i = 0; i < size; i += chn)
					input[c].append(samples[c+i]);
		}
		else for (int c = 0; c < chn; ++c) //Dokładanie ciszy
			input[c].resize(FFT_SIZE);

		data.clear();
		const int chunks = input.at(0).size() / FFT_SIZE_2 - 1;
		if (chunks > 0) //Jeżeli jest wystarczająca ilość danych
		{
			data.resize(chn * sizeof(float) * FFT_SIZE_2 * chunks);
			float *samples = (float *)data.data();
			for (int c = 0; c < chn; ++c)
			{
				int pos = c;
				while (input.at(c).size() >= FFT_SIZE)
				{
					for (int i = 0; i < FFT_SIZE; ++i)
						complex[i] = (FFTComplex){ input.at(c).at(i), 0.0f };
					if (!flush)
						input[c].remove(0, FFT_SIZE_2);
					else
						input[c].clear();

					fft_calc(fftIn, complex);
					for (int i = 0; i < FFT_SIZE_2; ++i)
					{
						complex[           i].re *= f.at(i) * preamp;
						complex[           i].im *= f.at(i) * preamp;
						complex[FFT_SIZE-1-i].re *= f.at(i) * preamp;
						complex[FFT_SIZE-1-i].im *= f.at(i) * preamp;
					}
					fft_calc(fftOut, complex);

					if (last_samples.at(c).isEmpty())
					{
						for (int i = 0; i < FFT_SIZE_2; ++i, pos += chn)
							samples[pos] = complex[i].re / FFT_SIZE;
						last_samples[c].resize(FFT_SIZE_2);
					}
					else for (int i = 0; i < FFT_SIZE_2; ++i, pos += chn)
						samples[pos] = (complex[i].re / FFT_SIZE) * wind_f.at(i) + last_samples.at(c).at(i);

					for (int i = FFT_SIZE_2; i < FFT_SIZE; ++i)
						last_samples[c][i-FFT_SIZE_2] = (complex[i].re / FFT_SIZE) * wind_f.at(i);
				}
			}
		}

		mutex.unlock();
		return FFT_SIZE / (double)srate;
	}
	return 0.0;
}
Esempio n. 18
0
    void FastoHexEdit::paintEvent(QPaintEvent *event)
    {
        if(mode_ == HEX_MODE){
            QPainter painter(viewport());

            QSize areaSize = viewport()->size();
            QSize widgetSize = fullSize();

            const int charW = charWidth();
            const int charH = charHeight();

            int firstLineIdx = verticalScrollBar()->value();
            int lastLineIdx = firstLineIdx + areaSize.height() / charH;

            const QRect rect = stableRect(event->rect());
            const int yPosStart = rect.top();
            const int xPosStart = rect.left();
            const int yPosEnd = rect.bottom();
            const int xPosEnd = rect.right();

            const int wid = xPosEnd - xPosStart;
            const int height = yPosEnd - yPosStart;
            const int widchars = wid - TextMarginXY * 2;
            const int acharInLine = asciiCharInLine(widchars);
            if(acharInLine <= 0){
                return;
            }

            const int xPosAscii = widchars/4 * 3; //line pos
            const int xPosAsciiStart = xPosAscii + TextMarginXY;

            int indexCount = data_.size() / acharInLine;
            if(lastLineIdx > indexCount) {
                lastLineIdx = indexCount;
                if(data_.size() % acharInLine){
                    lastLineIdx++;
                }
            }
            verticalScrollBar()->setPageStep(areaSize.height() / charH);
            verticalScrollBar()->setRange(0, (widgetSize.height() - areaSize.height()) / charH + 1);

            painter.setPen(Qt::gray);
            painter.drawLine(xPosAscii, yPosStart, xPosAscii, yPosEnd);

            painter.setPen(Qt::black);

            int size = data_.size();
            for (int lineIdx = firstLineIdx, yPos = yPosStart; lineIdx < lastLineIdx; lineIdx += 1, yPos += charH) {
                QByteArray part = data_.begin() + (lineIdx * acharInLine);
                int part_size = size / acharInLine ? acharInLine : size % acharInLine;
                part.resize(part_size);
                size -= part_size;
                QByteArray hex = part.toHex();

                painter.setBackgroundMode(Qt::OpaqueMode);
                for(int xPos = xPosStart, i = 0; i < hex.size(); i++, xPos += 3 * charW) {
                    QString val = hex.mid(i * 2, 2);
                    QRect hexrect(xPos, yPos, 3 * charW, charH);
                    painter.drawText(hexrect, Qt::AlignLeft, val);
                    char ch = part[i];
                    if ((ch < 0x20) || (ch > 0x7e)){
                        part[i] = '.';
                    }
                }

                painter.setBackgroundMode(Qt::TransparentMode);
                QRect asciirect(xPosAsciiStart, yPos, acharInLine * charW, charH);
                painter.drawText(asciirect, Qt::AlignLeft, part);
            }
        }
        else{
            base_class::paintEvent(event);
        }
    }
Esempio n. 19
0
CustomMesh::CustomMesh(const MatrixX3f &tMatVert, const MatrixX3f tMatNorm, const MatrixX3i &tMatTris, const Vector3f &tVecOffset)
: Qt3DRender::QGeometryRenderer()
, m_iNumVert(tMatVert.rows())
{
    Qt3DRender::QGeometry* customGeometry = new Qt3DRender::QGeometry(this);

    m_pVertexDataBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry);//QSharedPointer<Qt3DRender::QBuffer>(new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry));
    m_pNormalDataBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry);//QSharedPointer<Qt3DRender::QBuffer>(new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry));
    m_pColorDataBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry);//QSharedPointer<Qt3DRender::QBuffer>(new Qt3DRender::QBuffer(Qt3DRender::QBuffer::VertexBuffer, customGeometry));
    m_pIndexDataBuffer = new Qt3DRender::QBuffer(Qt3DRender::QBuffer::IndexBuffer, customGeometry);//QSharedPointer<Qt3DRender::QBuffer>(new Qt3DRender::QBuffer(Qt3DRender::QBuffer::IndexBuffer, customGeometry));

    //Fill vertexBuffer with data which hold the vertices, normals and colors
    QByteArray vertexBufferData;
    vertexBufferData.resize(tMatVert.rows() * 3 * (int)sizeof(float));
    float *rawVertexArray = reinterpret_cast<float *>(vertexBufferData.data());

    QByteArray normalBufferData;
    normalBufferData.resize(tMatVert.rows() * 3 * (int)sizeof(float));
    float *rawNormalArray = reinterpret_cast<float *>(normalBufferData.data());

    QByteArray colorBufferData;
    colorBufferData.resize(tMatVert.rows() * 3 * (int)sizeof(float));
    float *rawColorArray = reinterpret_cast<float *>(colorBufferData.data());

    int idxVert = 0;
    int idxNorm = 0;
    int idxColor = 0;

    for(int i = 0; i<tMatVert.rows(); i++) {
        //Vertex
        rawVertexArray[idxVert++] = tMatVert(i,0) + tVecOffset(0);
        rawVertexArray[idxVert++] = tMatVert(i,1) + tVecOffset(1);
        rawVertexArray[idxVert++] = tMatVert(i,2) + tVecOffset(2);

        //Normal
        rawNormalArray[idxNorm++] = tMatNorm(i,0);
        rawNormalArray[idxNorm++] = tMatNorm(i,1);
        rawNormalArray[idxNorm++] = tMatNorm(i,2);

        //Color (this is the default color and will be used until the updateVertColor function was called)
        rawColorArray[idxColor++] = 0.5f;
        rawColorArray[idxColor++] = 0.2f;
        rawColorArray[idxColor++] = 0.2f;
    }

    //Fill indexBufferData with data which holds the triangulation information (faces/tris)
    QByteArray indexBufferData;
    indexBufferData.resize(tMatTris.rows() * 3 * (int)sizeof(uint));
    uint *rawIndexArray = reinterpret_cast<uint *>(indexBufferData.data());
    int idxTris = 0;

    for(int i = 0; i<tMatTris.rows(); i++) {
        //Faces/Tris
        rawIndexArray[idxTris++] = tMatTris(i,0);
        rawIndexArray[idxTris++] = tMatTris(i,1);
        rawIndexArray[idxTris++] = tMatTris(i,2);
    }

    //Set data to buffers
    m_pVertexDataBuffer->setData(vertexBufferData);
    m_pNormalDataBuffer->setData(normalBufferData);
    m_pColorDataBuffer->setData(colorBufferData);
    m_pIndexDataBuffer->setData(indexBufferData);

    // Attributes
    Qt3DRender::QAttribute *positionAttribute = new Qt3DRender::QAttribute();
    positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
    positionAttribute->setBuffer(m_pVertexDataBuffer);
    positionAttribute->setDataType(Qt3DRender::QAttribute::Float);
    positionAttribute->setDataSize(3);
    positionAttribute->setByteOffset(0);
    positionAttribute->setByteStride(3 * sizeof(float));
    positionAttribute->setCount(tMatVert.rows());
    positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());

    Qt3DRender::QAttribute *normalAttribute = new Qt3DRender::QAttribute();
    normalAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
    normalAttribute->setBuffer(m_pNormalDataBuffer);
    normalAttribute->setDataType(Qt3DRender::QAttribute::Float);
    normalAttribute->setDataSize(3);
    normalAttribute->setByteOffset(0);
    normalAttribute->setByteStride(3 * sizeof(float));
    normalAttribute->setCount(tMatVert.rows());
    normalAttribute->setName(Qt3DRender::QAttribute::defaultNormalAttributeName());

    Qt3DRender::QAttribute *colorAttribute = new Qt3DRender::QAttribute();
    colorAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
    colorAttribute->setBuffer(m_pColorDataBuffer);
    colorAttribute->setDataType(Qt3DRender::QAttribute::Float);
    colorAttribute->setDataSize(3);
    colorAttribute->setByteOffset(0);
    colorAttribute->setByteStride(3 * sizeof(float));
    colorAttribute->setCount(tMatVert.rows());
    colorAttribute->setName(Qt3DRender::QAttribute::defaultColorAttributeName());

    Qt3DRender::QAttribute *indexAttribute = new Qt3DRender::QAttribute();
    indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
    indexAttribute->setBuffer(m_pIndexDataBuffer);
    indexAttribute->setDataType(Qt3DRender::QAttribute::UnsignedInt);
    indexAttribute->setDataSize(1);
    indexAttribute->setByteOffset(0);
    indexAttribute->setByteStride(0);
    indexAttribute->setCount(tMatTris.rows());

    customGeometry->addAttribute(positionAttribute);
    customGeometry->addAttribute(normalAttribute);
    customGeometry->addAttribute(colorAttribute);
    customGeometry->addAttribute(indexAttribute);

    this->setInstanceCount(1);
    this->setBaseVertex(0);
    this->setBaseInstance(0);
    this->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles);
    this->setGeometry(customGeometry);

    this->setPrimitiveCount(tMatTris.rows()*3);
}
Esempio n. 20
0
/*1. 收到come报文:
 *   { 加入用户列表,返回receiveCome报文 }
 *2. 收到receiveCome报文:
 *   { 将对方用户名和ip加入用户列表 }
 *3. 收到leave报文:
 *   { 根据对方ip从用户列表去除 }
 *4. 收到talk报文:
 *   { 更新聊天内容 }
*/
void ChatWindow::onReadyRead()
{
    QByteArray bytes;
    bytes.resize(_receiver->pendingDatagramSize());
    _receiver->readDatagram(bytes.data(),bytes.size());
    QDataStream in(&bytes,QIODevice::ReadOnly);
    quint16 size; int type;
    in>>size>>type;
    switch(type)
    {
    case _TypeCome:{
        //收到 某人进入聊天室的消息
        QString user,ip;
        in>>user>>ip;
        if(ip!=getIPv4()){
            //不把本机加入聊天室的消息再次显示到聊天文本块
            //不然就显示两次了
            updateAllContents("",QString("!report: ").append(user).append(" join"));
            addOne(user,ip);
            QByteArray response=pack_ResponseCome(_username,getIPv4());
            _sender->writeDatagram(response,response.length(),QHostAddress::Broadcast,_port);
        }
        break;
    }
    case _TypeResponseCome:{
        //收到 某人响应你的进入 的消息(因为你进入聊天室时会广播消息给所有人)
        QString user,ip;
        in>>user>>ip;
        int N=static_cast<int>(_ipList.size());
        int index=-1;
        for(int i=0;i<N;i++)
        {
            if(QString(_ipList[i])==ip)
            {
                index=i;
                break;
            }
        }
        if(index==-1)
            addOne(user,ip);
        break;
    }
    case _TypeLeave:{
        //收到某人离开聊天室的消息
        QString user,ip;
        in>>user>>ip;
        if(user!="")
            removeOne(user,ip);
        break;
    }
    case _TypeTalk:{
        //收到某人说了什么话的消息
        QString user,str;
        in>>user>>str;
        if(user!=_username)
            updateAllContents(user,str);
        break;
    }
    }
    //递归接收消息
    if(_receiver->pendingDatagramSize()>0)
        onReadyRead();
}
Esempio n. 21
0
static QByteArray createEnvBlock(const ProcessEnvironment &environment)
{
    QByteArray envlist;
    if (!environment.isEmpty()) {
        ProcessEnvironment copy = environment;

        const QString pathKey(QLatin1String("Path"));
        if (copy.contains(pathKey)) {
            // PATH has been altered.
            // It must be set in this environment to start the correct executable.
            // ### Note that this doesn't work if a batch file is supposed to shadow an exe or com.
            if (!qSetEnvironmentVariable(pathKey, environment.value(pathKey)))
                qWarning("jom: setting PATH failed");
        } else {
            // add PATH (for DLL loading)
            QString path = qGetEnvironmentVariable(L"PATH");
            if (!path.isEmpty())
                copy.insert(pathKey, path);
        }

        // add systemroot if needed
        const ProcessEnvironmentKey rootKey(QLatin1String("SystemRoot"));
        if (!copy.contains(rootKey)) {
            QString systemRoot = qGetEnvironmentVariable(L"SystemRoot");
            if (!systemRoot.isEmpty())
                copy.insert(rootKey, systemRoot);
        }

        int pos = 0;
        ProcessEnvironment::const_iterator it = copy.constBegin();
        const ProcessEnvironment::const_iterator end = copy.constEnd();

        static const wchar_t equal = L'=';
        static const wchar_t nul = L'\0';

        for ( ; it != end; ++it) {
            const QString &keystr = it.key().toQString();
            uint tmpSize = sizeof(wchar_t) * (keystr.length() + it.value().length() + 2);
            // ignore empty strings
            if (tmpSize == sizeof(wchar_t) * 2)
                continue;
            envlist.resize(envlist.size() + tmpSize);

            tmpSize = keystr.length() * sizeof(wchar_t);
            memcpy(envlist.data() + pos, keystr.utf16(), tmpSize);
            pos += tmpSize;

            memcpy(envlist.data()+pos, &equal, sizeof(wchar_t));
            pos += sizeof(wchar_t);

            tmpSize = it.value().length() * sizeof(wchar_t);
            memcpy(envlist.data()+pos, it.value().utf16(), tmpSize);
            pos += tmpSize;

            memcpy(envlist.data()+pos, &nul, sizeof(wchar_t));
            pos += sizeof(wchar_t);
        }
        // add the 2 terminating 0 (actually 4, just to be on the safe side)
        envlist.resize( envlist.size()+4 );
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
    }
    return envlist;
}
/**
 * @brief Initiate the device by configuring the registers depending on operating mode and
 * sampling frequency.
 *
 *
 */
void EcgCapture::init(OperatingMode mode, Frequency freq)
{
    if (!bcm2835_init()) {
            qDebug() << ("Could not init bcm2835 in EcgCapture") << endl;
           exit(EXIT_FAILURE);
    }

    spiInit();

    QByteArray CMREFCTL;
    CMREFCTL.resize(4);

    QByteArray FILTCTL;
    FILTCTL.resize(4);

    QByteArray FRMCTL;
    FRMCTL.resize(4);

    QByteArray ECGCTL;
    ECGCTL.resize(4);

    QByteArray RESPCTL;
    RESPCTL.resize(4);

    QByteArray TESTTONE;
    TESTTONE.resize(4);

    QByteArray LOFFCTL;
    LOFFCTL.resize(4);

    //Configure registers depending on source
    switch (mode) {
    case ecgCapture:
        //CMREFCTL is set to 0x85E0000A
        CMREFCTL[0] = 0x85;
        CMREFCTL[1] = 0xE0;
        CMREFCTL[2] = 0x00;
        CMREFCTL[3] = 0x4A; //0x0A for the first board, 0x4A for the REV_A board

        //FILTCTL is set to 0x8B000000
        FILTCTL[0] = 0x8B;
        FILTCTL[1] = 0x00;
        FILTCTL[2] = 0x00;
        FILTCTL[3] = 0x00;

        //FRMCTL is set to 0x8A1FCE00
        FRMCTL[0] = 0x8A;
        FRMCTL[1] = 0x1F;
        FRMCTL[2] = 0xC6; //CE = pace disabled, C6 = pace disabled LOFF enabled
        FRMCTL[3] = 0x00;

        LOFFCTL[0] = 0x82;
        LOFFCTL[1] = 0x00;
        LOFFCTL[2] = 0x00;
        LOFFCTL[3] = 0x15;

        //ECGCTL is set to 0x81F800AE
        ECGCTL[0] = 0x81;
        ECGCTL[1] = 0xF8;
        ECGCTL[2] = 0x00;
        ECGCTL[3] = 0xAE;

        //RESPCTL is set to 0x83002099
        RESPCTL[0] = 0x83;
        RESPCTL[1] = 0x00;
        RESPCTL[2] = 0x20;
        RESPCTL[3] = 0x99;
        break;
    case testToneSquare:
        //CMREFCTL is set to 0x8500000B
        CMREFCTL[0] = 0x85;
        CMREFCTL[1] = 0x00;
        CMREFCTL[2] = 0x00;
        CMREFCTL[3] = 0x0B;

        //TESTTONE is set to 0x88F8001D
        TESTTONE[0] = 0x88;
        TESTTONE[1] = 0xF8;
        TESTTONE[2] = 0x00;
        TESTTONE[3] = 0x1D;

        //FILTCTL is set to 0x8B000008
        FILTCTL[0] = 0x8B;
        FILTCTL[1] = 0x00;
        FILTCTL[2] = 0x00;
        FILTCTL[3] = 0x1D;

        //FRMCTL is set to 0x8A1FCE10
        FRMCTL[0] = 0x8A;
        FRMCTL[1] = 0x1F;
        FRMCTL[2] = 0xCE;
        FRMCTL[3] = 0x10;

        //ECGCTL is set to 0x81F800AE
        ECGCTL[0] = 0x81;
        ECGCTL[1] = 0xF8;
        ECGCTL[2] = 0x00;
        ECGCTL[3] = 0xAE;
        break;
    case testToneLowFreqSin:
        //CMREFCTL is set to 0x8500000B
        CMREFCTL[0] = 0x85;
        CMREFCTL[1] = 0x00;
        CMREFCTL[2] = 0x00;
        CMREFCTL[3] = 0x0B;

        //TESTTONE is set to 0x88F80005
        TESTTONE[0] = 0x88;
        TESTTONE[1] = 0xF8;
        TESTTONE[2] = 0x00;
        TESTTONE[3] = 0x05;

        //FILTCTL is set to 0x8B000008
        FILTCTL[0] = 0x8B;
        FILTCTL[1] = 0x00;
        FILTCTL[2] = 0x00;
        FILTCTL[3] = 0x08;

        //FRMCTL is set to 0x8A1FCE10
        FRMCTL[0] = 0x8A;
        FRMCTL[1] = 0x1F;
        FRMCTL[2] = 0xCE;
        FRMCTL[3] = 0x10;

        //ECGCTL is set to 0x81F800AE
        ECGCTL[0] = 0x81;
        ECGCTL[1] = 0xF8;
        ECGCTL[2] = 0x00;
        ECGCTL[3] = 0xAE;
        break;
    case testToneHighFreqSin:
        //CMREFCTL is set to 0x8500000B
        CMREFCTL[0] = 0x85;
        CMREFCTL[1] = 0x00;
        CMREFCTL[2] = 0x00;
        CMREFCTL[3] = 0x0B;

        //TESTTONE is set to 0x88F8000D
        TESTTONE[0] = 0x88;
        TESTTONE[1] = 0xF8;
        TESTTONE[2] = 0x00;
        TESTTONE[3] = 0x0D;

        //FILTCTL is set to 0x8B000008
        FILTCTL[0] = 0x8B;
        FILTCTL[1] = 0x00;
        FILTCTL[2] = 0x00;
        FILTCTL[3] = 0x08;

        //FRMCTL is set to 0x8A1FCE10
        FRMCTL[0] = 0x8A;
        FRMCTL[1] = 0x1F;
        FRMCTL[2] = 0xCE;
        FRMCTL[3] = 0x10;

        //ECGCTL is set to 0x81F800AE
        ECGCTL[0] = 0x81;
        ECGCTL[1] = 0xF8;
        ECGCTL[2] = 0x00;
        ECGCTL[3] = 0xAE;
        break;
    default:
        break;
    }

    //Set sampling frequency
    switch (freq) {
    case lowFreq:
        FRMCTL[3] = FRMCTL[3] & 0xF3;
        FRMCTL[3] = FRMCTL[3] | 0x0C;
        qDebug()<<"Low freq";
        break;
    case midFreq:
        FRMCTL[3] = FRMCTL[3] & 0xF3;
        FRMCTL[3] = FRMCTL[3] | 0x04;
        qDebug()<<"Mid freq";
        break;
    case highFreq:
        FRMCTL[3] = FRMCTL[3] & 0xF3;
        FRMCTL[3] = FRMCTL[3] | 0x00;
        qDebug()<<"High freq";
        break;
    default:
        break;
    }

    if (mode == ecgCapture) {
        setReg(CMREFCTL);
        setReg(FILTCTL);
        setReg(FRMCTL);
        setReg(ECGCTL);
        setReg(RESPCTL);
        setReg(LOFFCTL);
        leadMode = digital;
        nFrames = 7;
    } else {
        setReg(CMREFCTL);
        setReg(TESTTONE);
        setReg(FILTCTL);
        setReg(FRMCTL);
        setReg(ECGCTL);
        leadMode = electrode;
        nFrames = 6;
    }
}
Esempio n. 23
0
DIGESTMD5Response::DIGESTMD5Response(const QByteArray& challenge, const QString& service, const QString& host, const QString& arealm, const QString& user, const QString& authz,  const QByteArray& password, const RandomNumberGenerator& rand) : isValid_(true)
{
	QString realm = arealm;

	// get props
	DIGESTMD5PropList in;
	if(!in.fromString(challenge)) {
		isValid_ = false;
		return;
	}
	//qDebug() << (QString("simplesasl.cpp: IN: %1").arg(QString(in.toString())));

	// make a cnonce
	QByteArray a;
	a.resize(32);
	for(int n = 0; n < (int)a.size(); ++n) {
		a[n] = (char) rand.generateNumberBetween(0, 255); 
	}
	QByteArray cnonce = Base64::encode(a).toLatin1();

	// make other variables
	if (realm.isEmpty()) {
		realm = QString::fromUtf8(in.get("realm"));
	}
	QByteArray nonce = in.get("nonce");
	QByteArray nc = "00000001";
	QByteArray uri = service.toUtf8() + '/' + host.toUtf8();
	QByteArray qop = "auth";

	// build 'response'
	QByteArray X = user.toUtf8() + ':' + realm.toUtf8() + ':' + password;
	QByteArray Y = QCA::Hash("md5").hash(X).toByteArray();
	QByteArray tmp = ':' + nonce + ':' + cnonce;
	if (!authz.isEmpty())
		tmp += ':' + authz.toUtf8();
	//qDebug() << (QString(tmp));

	QByteArray A1(Y + tmp);
	QByteArray A2 = QByteArray("AUTHENTICATE:") + uri;
	QByteArray HA1 = QCA::Hash("md5").hashToString(A1).toLatin1();
	QByteArray HA2 = QCA::Hash("md5").hashToString(A2).toLatin1();
	QByteArray KD = HA1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + HA2;
	QByteArray Z = QCA::Hash("md5").hashToString(KD).toLatin1();

	//qDebug() << QString("simplesasl.cpp: A1 = %1").arg(QString(A1));
	//qDebug() << QString("simplesasl.cpp: A2 = %1").arg(QString(A2));
	//qDebug() << QString("simplesasl.cpp: KD = %1").arg(QString(KD));

	// build output
	DIGESTMD5PropList out;
	out.set("username", user.toUtf8());
	if (!realm.isEmpty())
		out.set("realm", realm.toUtf8());
	out.set("nonce", nonce);
	out.set("cnonce", cnonce);
	out.set("nc", nc);
	//out.set("serv-type", service.toUtf8());
	//out.set("host", host.toUtf8());
	out.set("digest-uri", uri);
	out.set("qop", qop);
	out.set("response", Z);
	out.set("charset", "utf-8");
	if (!authz.isEmpty())
		out.set("authzid", authz.toUtf8());
	value_  = out.toString();
}
Esempio n. 24
0
QT_BEGIN_NAMESPACE

#include "ppkeywords.cpp"
#include "keywords.cpp"

// transform \r\n into \n
// \r into \n (os9 style)
// backslash-newlines into newlines
static QByteArray cleaned(const QByteArray &input)
{
    QByteArray result;
    result.reserve(input.size());
    const char *data = input.constData();
    char *output = result.data();

    int newlines = 0;
    while (*data) {
        while (*data && is_space(*data))
            ++data;
        bool takeLine = (*data == '#');
        if (*data == '%' && *(data+1) == ':') {
            takeLine = true;
            ++data;
        }
        if (takeLine) {
            *output = '#';
            ++output;
            do ++data; while (*data && is_space(*data));
        }
        while (*data) {
            // handle \\\n, \\\r\n and \\\r
            if (*data == '\\') {
                if (*(data + 1) == '\r') {
                    ++data;
                }
                if (*data && (*(data + 1) == '\n' || (*data) == '\r')) {
                    ++newlines;
                    data += 1;
                    if (*data != '\r')
                        data += 1;
                    continue;
                }
            } else if (*data == '\r' && *(data + 1) == '\n') { // reduce \r\n to \n
                ++data;
            }

            char ch = *data;
            if (ch == '\r') // os9: replace \r with \n
                ch = '\n';
            *output = ch;
            ++output;

            if (*data == '\n') {
                // output additional newlines to keep the correct line-numbering
                // for the lines following the backslash-newline sequence(s)
                while (newlines) {
                    *output = '\n';
                    ++output;
                    --newlines;
                }
                ++data;
                break;
            }
            ++data;
        }
    }
    result.resize(output - result.constData());
    return result;
}
Esempio n. 25
0
void    Plugin::_loadCertificate()
{
    QFile            file(this->crtFile);
    gnutls_datum_t   datum;
    size_t           size = 2048;
    QByteArray       data;
    gnutls_privkey_t privkey;
    gnutls_pubkey_t  pubkey;
    gnutls_pubkey_t  pubkeyCrt;
    int              error;
    QMap<char *, QByteArray> oid;
    gnutls_digest_algorithm_t digest;

    if (!file.open(QIODevice::ReadWrite))
        throw Properties("error", "Unable to open the certificate file").add("file", this->crtFile);
    ASSERT_INIT(gnutls_x509_crt_init(&this->crt), "crt");
    ASSERT(gnutls_privkey_init(&privkey));
    ASSERT(gnutls_privkey_import_x509(privkey, this->key, 0));
    ASSERT(gnutls_pubkey_init(&pubkey));
    ASSERT(gnutls_pubkey_import_privkey(pubkey, privkey, 0, 0));
    // Verifies that the certificate is valid
    if (file.size() > 0)
    {
        ASSERT(gnutls_pubkey_init(&pubkeyCrt));
        data = file.readAll();
        datum.size = data.size();
        datum.data = (unsigned char *)data.data();
        if (gnutls_x509_crt_import(this->crt, &datum, GNUTLS_X509_FMT_PEM) != GNUTLS_E_SUCCESS)
            file.resize(0);
        else if (gnutls_x509_crt_get_expiration_time(this->crt) < ::time(NULL) + CRT_EXPIRATION_REGEN)
            file.resize(0);
        else if (gnutls_pubkey_import_x509(pubkeyCrt, this->crt, 0) != GNUTLS_E_SUCCESS)
            file.resize(0);
        // Ensures that the public keys of the certificate and the private key match
        size_t size1 = size, size2 = size;
        QByteArray pub1((int)size1, 0), pub2((int)size2, 0);
        if (gnutls_pubkey_export(pubkey, GNUTLS_X509_FMT_PEM, pub1.data(), &size1) != GNUTLS_E_SUCCESS
            || gnutls_pubkey_export(pubkeyCrt, GNUTLS_X509_FMT_PEM, pub2.data(), &size2) != GNUTLS_E_SUCCESS
            || size1 != size2 || pub1 != pub2)
            file.resize(0);
        gnutls_pubkey_deinit(pubkeyCrt);
    }
    // Generates a new certificate
    if (file.size() == 0)
    {
        gnutls_x509_crt_deinit(this->crt);
        this->init.removeAll("crt");
        ASSERT_INIT(gnutls_x509_crt_init(&this->crt), "crt");
        LOG_INFO("Generating a new certificate", "Plugin", "_generateCertificate");
        oid.insert((char *)GNUTLS_OID_X520_COMMON_NAME, "LightBird");
        oid.insert((char *)GNUTLS_OID_X520_ORGANIZATION_NAME, "LightBird");
        QMapIterator<char *, QByteArray> it(oid);
        while (it.hasNext())
            ASSERT(gnutls_x509_crt_set_dn_by_oid(this->crt, it.key(), 0, it.value().data(), it.next().value().size()));
        ASSERT(gnutls_x509_crt_set_pubkey(this->crt, pubkey));
        data = this->_generateSerial();
        ASSERT(gnutls_x509_crt_set_serial(this->crt, data.data(), data.size()));
        ASSERT(gnutls_x509_crt_set_activation_time(this->crt, ::time(NULL)));
        ASSERT(gnutls_x509_crt_set_expiration_time(this->crt, ::time(NULL) + CRT_EXPIRATION));
        ASSERT(gnutls_x509_crt_set_basic_constraints(this->crt, 0, -1));
        ASSERT(gnutls_x509_crt_set_key_purpose_oid(this->crt, GNUTLS_KP_TLS_WWW_SERVER, 0));
        ASSERT(gnutls_x509_crt_set_key_usage(this->crt, GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT));
        data.resize((int)size);
        ASSERT(gnutls_x509_crt_get_key_id(this->crt, 0, (unsigned char *)data.data(), &size));
        ASSERT(gnutls_x509_crt_set_subject_key_id(this->crt, (unsigned char *)data.data(), size));
        ASSERT(gnutls_x509_crt_set_version(this->crt, 3));
        ASSERT(gnutls_pubkey_get_preferred_hash_algorithm(pubkey, &digest, NULL));
        ASSERT(gnutls_x509_crt_privkey_sign(this->crt, this->crt, privkey, digest, 0));
        size = data.size();
        ASSERT(gnutls_x509_crt_export(this->crt, GNUTLS_X509_FMT_PEM, data.data(), &size));
        data.resize((int)size);
        file.write(data);
    }
    gnutls_pubkey_deinit(pubkey);
    gnutls_privkey_deinit(privkey);
}
Esempio n. 26
0
// IRIX 6.x
void qt_parseSpoolInterface(QList<QPrinterDescription> *printers)
{
    QDir lp(QLatin1String("/usr/spool/lp/interface"));
    if (!lp.exists())
        return;
    QFileInfoList files = lp.entryInfoList();
    if(files.isEmpty())
        return;

    for (int i = 0; i < files.size(); ++i) {
        QFileInfo printer = files.at(i);

        if (!printer.isFile())
            continue;

        // parse out some information
        QFile configFile(printer.filePath());
        if (!configFile.open(QIODevice::ReadOnly))
            continue;

        QByteArray line;
        line.resize(1025);
        QString namePrinter;
        QString hostName;
        QString hostPrinter;
        QString printerType;

        QString nameKey(QLatin1String("NAME="));
        QString typeKey(QLatin1String("TYPE="));
        QString hostKey(QLatin1String("HOSTNAME="));
        QString hostPrinterKey(QLatin1String("HOSTPRINTER="));

        while (!configFile.atEnd() &&
                (configFile.readLine(line.data(), 1024)) > 0) {
            QString uline = QString::fromLocal8Bit(line);
            if (uline.startsWith(typeKey) ) {
                printerType = uline.mid(nameKey.length());
                printerType = printerType.simplified();
            } else if (uline.startsWith(hostKey)) {
                hostName = uline.mid(hostKey.length());
                hostName = hostName.simplified();
            } else if (uline.startsWith(hostPrinterKey)) {
                hostPrinter = uline.mid(hostPrinterKey.length());
                hostPrinter = hostPrinter.simplified();
            } else if (uline.startsWith(nameKey)) {
                namePrinter = uline.mid(nameKey.length());
                namePrinter = namePrinter.simplified();
            }
        }
        configFile.close();

        printerType = printerType.trimmed();
        if (printerType.indexOf(QLatin1String("postscript"), 0, Qt::CaseInsensitive) < 0)
            continue;

        int ii = 0;
        while ((ii = namePrinter.indexOf(QLatin1Char('"'), ii)) >= 0)
            namePrinter.remove(ii, 1);

        if (hostName.isEmpty() || hostPrinter.isEmpty()) {
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 QLatin1String(""), namePrinter);
        } else {
            QString comment;
            comment = namePrinter;
            comment += QLatin1String(" (");
            comment += hostPrinter;
            comment += QLatin1Char(')');
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 hostName, comment);
        }
    }
}
Esempio n. 27
0
void QV8Worker::serialize(QByteArray &data, v8::Handle<v8::Value> v, QV8Engine *engine)
{
    if (v.IsEmpty()) {
    } else if (v->IsUndefined()) {
        push(data, valueheader(WorkerUndefined));
    } else if (v->IsNull()) {
        push(data, valueheader(WorkerNull));
    } else if (v->IsTrue()) {
        push(data, valueheader(WorkerTrue));
    } else if (v->IsFalse()) {
        push(data, valueheader(WorkerFalse));
    } else if (v->IsString()) {
        v8::Handle<v8::String> string = v->ToString();
        int length = string->Length() + 1;
        if (length > 0xFFFFFF) {
            push(data, valueheader(WorkerUndefined));
            return;
        }
        int utf16size = ALIGN(length * sizeof(uint16_t));

        reserve(data, utf16size + sizeof(quint32));
        push(data, valueheader(WorkerString, length));
        
        int offset = data.size();
        data.resize(data.size() + utf16size);
        char *buffer = data.data() + offset;

        string->Write((uint16_t*)buffer);
    } else if (v->IsFunction()) {
        // XXX TODO: Implement passing function objects between the main and
        // worker scripts
        push(data, valueheader(WorkerUndefined));
    } else if (v->IsArray()) {
        v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(v);
        uint32_t length = array->Length();
        if (length > 0xFFFFFF) {
            push(data, valueheader(WorkerUndefined));
            return;
        }
        reserve(data, sizeof(quint32) + length * sizeof(quint32));
        push(data, valueheader(WorkerArray, length));
        for (uint32_t ii = 0; ii < length; ++ii)
            serialize(data, array->Get(ii), engine);
    } else if (v->IsInt32()) {
        reserve(data, 2 * sizeof(quint32));
        push(data, valueheader(WorkerInt32));
        push(data, (quint32)v->Int32Value());
    } else if (v->IsUint32()) {
        reserve(data, 2 * sizeof(quint32));
        push(data, valueheader(WorkerUint32));
        push(data, v->Uint32Value());
    } else if (v->IsNumber()) {
        reserve(data, sizeof(quint32) + sizeof(double));
        push(data, valueheader(WorkerNumber));
        push(data, v->NumberValue());
    } else if (v->IsDate()) {
        reserve(data, sizeof(quint32) + sizeof(double));
        push(data, valueheader(WorkerDate));
        push(data, v8::Handle<v8::Date>::Cast(v)->NumberValue());
    } else if (v->IsRegExp()) {
        v8::Handle<v8::RegExp> regexp = v8::Handle<v8::RegExp>::Cast(v);
        quint32 flags = regexp->GetFlags();
        v8::Local<v8::String> source = regexp->GetSource();

        int length = source->Length() + 1;
        if (length > 0xFFFFFF) {
            push(data, valueheader(WorkerUndefined));
            return;
        }
        int utf16size = ALIGN(length * sizeof(uint16_t));

        reserve(data, sizeof(quint32) + utf16size);
        push(data, valueheader(WorkerRegexp, flags));
        push(data, (quint32)length);
        int offset = data.size();
        data.resize(data.size() + utf16size);
        char *buffer = data.data() + offset;

        source->Write((uint16_t*)buffer);
    } else if (v->IsObject() && !v->ToObject()->GetExternalResource()) {
        v8::Handle<v8::Object> object = v->ToObject();
        v8::Local<v8::Array> properties = engine->getOwnPropertyNames(object);
        quint32 length = properties->Length();
        if (length > 0xFFFFFF) {
            push(data, valueheader(WorkerUndefined));
            return;
        }
        push(data, valueheader(WorkerObject, length));
        v8::TryCatch tc;
        for (quint32 ii = 0; ii < length; ++ii) {
            v8::Local<v8::String> str = properties->Get(ii)->ToString();
            serialize(data, str, engine);

            v8::Local<v8::Value> val = object->Get(str);
            if (tc.HasCaught()) {
                serialize(data, v8::Undefined(), engine);
                tc.Reset();
            } else {
                serialize(data, val, engine);
            }
        }
    } else if (engine->isQObject(v)) {
        // XXX TODO: Generalize passing objects between the main thread and worker scripts so 
        // that others can trivially plug in their elements.
        QDeclarativeListModel *lm = qobject_cast<QDeclarativeListModel *>(engine->toQObject(v));
        if (lm && lm->agent()) {
            QDeclarativeListModelWorkerAgent *agent = lm->agent();
            agent->addref();
            push(data, valueheader(WorkerListModel));
            push(data, (void *)agent);
            return;
        } 
        // No other QObject's are allowed to be sent
        push(data, valueheader(WorkerUndefined));
    } else {
        push(data, valueheader(WorkerUndefined));
    }
}
Esempio n. 28
0
int qt_getLprPrinters(QList<QPrinterDescription>& printers)
{
    QByteArray etcLpDefault;
    qt_parsePrintcap(&printers, QLatin1String("/etc/printcap"));
    qt_parseEtcLpMember(&printers);
    qt_parseSpoolInterface(&printers);
    qt_parseQconfig(&printers);

    QFileInfo f;
    f.setFile(QLatin1String("/etc/lp/printers"));
    if (f.isDir()) {
        qt_parseEtcLpPrinters(&printers);
        QFile def(QLatin1String("/etc/lp/default"));
        if (def.open(QIODevice::ReadOnly)) {
            etcLpDefault.resize(1025);
            if (def.readLine(etcLpDefault.data(), 1024) > 0) {
                QRegExp rx(QLatin1String("^(\\S+)"));
                if (rx.indexIn(QString::fromLatin1(etcLpDefault)) != -1)
                    etcLpDefault = rx.cap(1).toAscii();
            }
        }
    }

    char *def = 0;
    f.setFile(QLatin1String("/etc/nsswitch.conf"));
    if (f.isFile()) {
        def = qt_parseNsswitchConf(&printers);
    } else {
        f.setFile(QLatin1String("/etc/printers.conf"));
        if (f.isFile())
            def = qt_parsePrintersConf(&printers);
    }

    if (def) {
        etcLpDefault = def;
        delete [] def;
    }

    QString homePrintersDefault = qt_getDefaultFromHomePrinters();

    // all printers hopefully known.  try to find a good default
    QString dollarPrinter;
    {
        dollarPrinter = QString::fromLocal8Bit(qgetenv("PRINTER"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("LPDEST"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("NPRINTER"));
        if (dollarPrinter.isEmpty())
            dollarPrinter = QString::fromLocal8Bit(qgetenv("NGPRINTER"));
#ifndef QT_NO_PRINTDIALOG
        if (!dollarPrinter.isEmpty())
            qt_perhapsAddPrinter(&printers, dollarPrinter,
                                 QPrintDialog::tr("unknown"),
                                 QLatin1String(""));
#endif
    }

    QRegExp ps(QLatin1String("[^a-z]ps(?:[^a-z]|$)"));
    QRegExp lp(QLatin1String("[^a-z]lp(?:[^a-z]|$)"));

    int quality = 0;
    int best = 0;
    for (int i = 0; i < printers.size(); ++i) {
        QString name = printers.at(i).name;
        QString comment = printers.at(i).comment;
        if (quality < 5 && name == dollarPrinter) {
            best = i;
            quality = 5;
        } else if (quality < 4 && !homePrintersDefault.isEmpty() &&
                   name == homePrintersDefault) {
            best = i;
            quality = 4;
        } else if (quality < 3 && !etcLpDefault.isEmpty() &&
                    name == QLatin1String(etcLpDefault)) {
            best = i;
            quality = 3;
        } else if (quality < 2 &&
                    (name == QLatin1String("ps") ||
                     ps.indexIn(comment) != -1)) {
            best = i;
            quality = 2;
        } else if (quality < 1 &&
                    (name == QLatin1String("lp") ||
                     lp.indexIn(comment) > -1)) {
            best = i;
            quality = 1;
        }
    }

    return best;
}
Esempio n. 29
0
static void parseAttributeValues(sdp_data_t *data, int indentation, QByteArray &xmlOutput)
{
    if (!data)
        return;

    const int length = indentation*2 + 1;
    QByteArray indentString(length, ' ');

    char snBuffer[BUFFER_SIZE];

    xmlOutput.append(indentString);

    // deal with every dtd type
    switch (data->dtd) {
    case SDP_DATA_NIL:
        xmlOutput.append("<nil/>\n");
        break;
    case SDP_UINT8:
        qsnprintf(snBuffer, BUFFER_SIZE, "<uint8 value=\"0x%02x\"/>\n", data->val.uint8);
        xmlOutput.append(snBuffer);
        break;
    case SDP_UINT16:
        qsnprintf(snBuffer, BUFFER_SIZE, "<uint16 value=\"0x%04x\"/>\n", data->val.uint16);
        xmlOutput.append(snBuffer);
        break;
    case SDP_UINT32:
        qsnprintf(snBuffer, BUFFER_SIZE, "<uint32 value=\"0x%08x\"/>\n", data->val.uint32);
        xmlOutput.append(snBuffer);
        break;
    case SDP_UINT64:
        qsnprintf(snBuffer, BUFFER_SIZE, "<uint64 value=\"0x%016x\"/>\n", data->val.uint64);
        xmlOutput.append(snBuffer);
        break;
    case SDP_UINT128:
        xmlOutput.append("<uint128 value=\"0x");
        for (int i = 0; i < 16; i++)
            ::sprintf(&snBuffer[i * 2], "%02x", data->val.uint128.data[i]);
        xmlOutput.append(snBuffer);
        xmlOutput.append("\"/>\n");
        break;
    case SDP_INT8:
        qsnprintf(snBuffer, BUFFER_SIZE, "<int8 value=\"%d\"/>/n", data->val.int8);
        xmlOutput.append(snBuffer);
        break;
    case SDP_INT16:
        qsnprintf(snBuffer, BUFFER_SIZE, "<int16 value=\"%d\"/>/n", data->val.int16);
        xmlOutput.append(snBuffer);
        break;
    case SDP_INT32:
        qsnprintf(snBuffer, BUFFER_SIZE, "<int32 value=\"%d\"/>/n", data->val.int32);
        xmlOutput.append(snBuffer);
        break;
    case SDP_INT64:
        qsnprintf(snBuffer, BUFFER_SIZE, "<int64 value=\"%d\"/>/n", data->val.int64);
        xmlOutput.append(snBuffer);
        break;
    case SDP_INT128:
        xmlOutput.append("<int128 value=\"0x");
        for (int i = 0; i < 16; i++)
            ::sprintf(&snBuffer[i * 2], "%02x", data->val.int128.data[i]);
        xmlOutput.append(snBuffer);
        xmlOutput.append("\"/>\n");
        break;
    case SDP_UUID_UNSPEC:
        break;
    case SDP_UUID16:
    case SDP_UUID32:
        xmlOutput.append("<uuid value=\"0x");
        sdp_uuid2strn(&(data->val.uuid), snBuffer, BUFFER_SIZE);
        xmlOutput.append(snBuffer);
        xmlOutput.append("\"/>\n");
        break;
    case SDP_UUID128:
        xmlOutput.append("<uuid value=\"");
        sdp_uuid2strn(&(data->val.uuid), snBuffer, BUFFER_SIZE);
        xmlOutput.append(snBuffer);
        xmlOutput.append("\"/>\n");
        break;
    case SDP_TEXT_STR_UNSPEC:
        break;
    case SDP_TEXT_STR8:
    case SDP_TEXT_STR16:
    case SDP_TEXT_STR32:
    {
        xmlOutput.append("<text ");
        QByteArray text = QByteArray::fromRawData(data->val.str, data->unitSize);

        bool hasNonPrintableChar = false;
        for (int i = 0; i < text.count(); i++) {
            if (text[i] == '\0') {
                text.resize(i); // cut trailing content
                break;
            } else if (!isprint(text[i])) {
                hasNonPrintableChar = true;
                text.resize(text.indexOf('\0')); // cut trailing content
                break;
            }
        }

        if (hasNonPrintableChar) {
            xmlOutput.append("encoding=\"hex\" value=\"");
            xmlOutput.append(text.toHex());
        } else {
            text.replace('&', "&amp;");
            text.replace('<', "&lt;");
            text.replace('>', "&gt;");
            text.replace('"', "&quot;");

            xmlOutput.append("value=\"");
            xmlOutput.append(text);
        }

        xmlOutput.append("\"/>\n");
        break;
    }
    case SDP_BOOL:
        if (data->val.uint8)
            xmlOutput.append("<boolean value=\"true\"/>\n");
        else
            xmlOutput.append("<boolean value=\"false\"/>\n");
        break;
    case SDP_SEQ_UNSPEC:
        break;
    case SDP_SEQ8:
    case SDP_SEQ16:
    case SDP_SEQ32:
        xmlOutput.append("<sequence>\n");
        parseAttributeValues(data->val.dataseq, indentation + 1, xmlOutput);
        xmlOutput.append(indentString);
        xmlOutput.append("</sequence>\n");
        break;
    case SDP_ALT_UNSPEC:
        break;
    case SDP_ALT8:
    case SDP_ALT16:
    case SDP_ALT32:
        xmlOutput.append("<alternate>\n");
        parseAttributeValues(data->val.dataseq, indentation + 1, xmlOutput);
        xmlOutput.append(indentString);
        xmlOutput.append("</alternate>\n");
        break;
    case SDP_URL_STR_UNSPEC:
        break;
    case SDP_URL_STR8:
    case SDP_URL_STR16:
    case SDP_URL_STR32:
        strncpy(snBuffer, data->val.str, data->unitSize - 1);
        xmlOutput.append("<url value=\"");
        xmlOutput.append(snBuffer);
        xmlOutput.append("\"/>\n");
        break;
    default:
        fprintf(stderr, "Unknown dtd type\n");
    }

    parseAttributeValues(data->next, indentation, xmlOutput);
}
Esempio n. 30
0
void QAesWrap::initPadding(const QByteArray & in,QByteArray & out,AesMode mode,PaddingMode pad) const
{
    int size = in.size();
    int last = size % AES_BLOCK_SIZE;
    const BYTE * data = (unsigned char *)in.data();
    if (last == 0) {
        out.resize(size);
        if (mode == AES_ECB) {
            ecbencrypt(data,size,0,out);
        } else {
            aes_encrypt_cbc(data,size,0,(unsigned char *)out.data(),mpass,mbit,msalt);
        }
        return;
    }
    int blocks = size / AES_BLOCK_SIZE;

    BYTE datablocks[AES_BLOCK_SIZE] = {0};
    memcpy(datablocks,(data + blocks * AES_BLOCK_SIZE),last);

    uchar ch = uchar(AES_BLOCK_SIZE - last);

    switch (pad) {
    case ANSIX923:
    case PKCS7:
    {
        size  = blocks * AES_BLOCK_SIZE;
        out.resize((blocks +1) * AES_BLOCK_SIZE);
        if (pad == ANSIX923) {
            memset(&datablocks[last],0,(ch -1));
            datablocks[AES_BLOCK_SIZE -1] = ch;
        } else {
            memset(&datablocks[last],ch,ch);
        }

        if (mode == AES_ECB) {
            ecbencrypt(data,size,datablocks,out);
        } else {
            aes_encrypt_cbc(data,size,datablocks,(unsigned char *)out.data(),mpass,mbit,msalt);
        }
    }
    break;
    default:
    {
        if (blocks <= 0) {
            out = in;
            return;
        }
        out.resize(size);
        size  = blocks * AES_BLOCK_SIZE;
        if (mode == AES_ECB) {
            ecbencrypt(data,size,0,out);
        } else {
            aes_encrypt_cbc(data,size,0,(unsigned char *)out.data(),mpass,mbit,msalt);
        }
        for (int i = 0,j = size; i < last; ++i, ++j) {
            out[j] = datablocks[i];
        }
    }
    break;
    }
}