void CDatagrams::__FlushSendCache()
{
	if(!m_bActive)
	{
		return;
	}

	//QMutexLocker l(&m_pSection);
	ASSUME_LOCK(Datagrams.m_pSection);

	quint32 tNow = time(0);

	qint64 nToWrite = qint64(m_nUploadLimit) - qint64(m_mOutput.Usage());

	static TCPBandwidthMeter meter;

	// TODO: Maybe make it dynamic? So bad routers are automatically detected and settings adjusted?
	qint64 nMaxPPS = quazaaSettings.Connection.UDPOutLimitPPS - meter.Usage();

	if( nMaxPPS <= 0 )
	{
		systemLog.postLog( LogSeverity::Debug, Components::Network,
						   "UDP: PPS limit reached, ACKS: %d, Packets: %d, Average PPS: %u / %u",
						   m_AckCache.size(), m_SendCache.size(), meter.AvgUsage(), meter.Usage() );
		return;
	}

	while( nToWrite > 0 && !m_AckCache.isEmpty() && nMaxPPS > 0)
	{
		QPair< CEndPoint, char* > oAck = m_AckCache.takeFirst();
		m_pSocket->writeDatagram(oAck.second, sizeof(GND_HEADER), oAck.first, oAck.first.port());
		m_mOutput.Add(sizeof(GND_HEADER));
		nToWrite -= sizeof(GND_HEADER);
		delete (GND_HEADER*)oAck.second;
		nMaxPPS--;
		meter.Add(1);
	}

	QHostAddress nLastHost;

	// it can write slightly more than limit allows... that's ok
	while(nToWrite > 0 && !m_SendCache.isEmpty() && nMaxPPS > 0)
	{
		bool bSent = false;

		char* pPacket;
		quint32 nPacket;

		for(QLinkedList<DatagramOut*>::iterator itPacket = m_SendCache.begin(); itPacket != m_SendCache.end(); ++itPacket)
		{
			DatagramOut* pDatagramOut = *itPacket;

			if(pDatagramOut->m_oAddress == nLastHost)
			{
				continue;
			}

			// TODO: Check the firewall's UDP state. Could do 3 UDP states.
			if(pDatagramOut->getPacket(tNow, &pPacket, &nPacket, pDatagramOut->m_bAck && m_nInFrags > 0))
			{
#ifdef DEBUG_UDP
				systemLog.postLog(LogSeverity::Debug, "UDP sending to %s seq %u part %u count %u", pDatagramOut->m_oAddress.toString().toLocal8Bit().constData(), pDatagramOut->m_nSequence, ((GND_HEADER*)pPacket)->nPart, pDatagramOut->m_nCount);
#endif

				m_pSocket->writeDatagram(pPacket, nPacket, pDatagramOut->m_oAddress, pDatagramOut->m_oAddress.port());
				m_nOutFrags++;

				nLastHost = pDatagramOut->m_oAddress;

				if(nToWrite >= nPacket)
				{
					nToWrite -= nPacket;
				}
				else
				{
					nToWrite = 0;
				}

				m_mOutput.Add(nPacket);

				if(!pDatagramOut->m_bAck)
				{
					remove(pDatagramOut);
				}

				nMaxPPS--;
				meter.Add(1);

				bSent = true;

				break;
			}
		}

		if(m_SendCache.isEmpty() || !bSent)
		{
			break;
		}
	}

	while(!m_SendCache.isEmpty() && tNow - m_SendCache.back()->m_tSent > quazaaSettings.Gnutella2.UdpOutExpire)
	{
		remove(m_SendCache.back());
	}
}
Example #2
0
/*!
    \reimp
*/
qint64 QBuffer::size() const
{
    Q_D(const QBuffer);
    return qint64(d->buf->size());
}
Example #3
0
 void MainWindow::setPosition(int position)
 {
    player->setPosition(qint64(position));
 }
Example #4
0
void PropagateUploadFileQNAM::startNextChunk()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    if (! _jobs.isEmpty() &&  _currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        // We return now and when the _jobs will be finished we will proceed the last chunk
        return;
    }
    quint64 fileSize = _item._size;
    QMap<QByteArray, QByteArray> headers;
    headers["OC-Total-Length"] = QByteArray::number(fileSize);
    headers["OC-Async"] = "1";
    headers["Content-Type"] = "application/octet-stream";
    headers["X-OC-Mtime"] = QByteArray::number(qint64(_item._modtime));
    if (!_item._etag.isEmpty() && _item._etag != "empty_etag" &&
            _item._instruction != CSYNC_INSTRUCTION_NEW  // On new files never send a If-Match
            ) {
        // We add quotes because the owncloud server always add quotes around the etag, and
        //  csync_owncloud.c's owncloud_file_id always strip the quotes.
        headers["If-Match"] = '"' + _item._etag + '"';
    }

    QString path = _item._file;
    UploadDevice *device = 0;
    if (_chunkCount > 1) {
        int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
        // XOR with chunk size to make sure everything goes well if chunk size change between runs
        uint transid = _transferId ^ chunkSize();
        path +=  QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);
        headers["OC-Chunked"] = "1";
        int currentChunkSize = chunkSize();
        if (sendingChunk == _chunkCount - 1) { // last chunk
            currentChunkSize = (fileSize % chunkSize());
            if( currentChunkSize == 0 ) { // if the last chunk pretents to be 0, its actually the full chunk size.
                currentChunkSize = chunkSize();
            }
        }
        device = new UploadDevice(_file, chunkSize() * quint64(sendingChunk), currentChunkSize, &_propagator->_bandwidthManager);
    } else {
        device = new UploadDevice(_file, 0, fileSize, &_propagator->_bandwidthManager);
    }

    bool isOpen = true;
    if (!device->isOpen()) {
        isOpen = device->open(QIODevice::ReadOnly);
    }

    if( isOpen ) {
        PUTFileJob* job = new PUTFileJob(AccountManager::instance()->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk);
        _jobs.append(job);
        job->setTimeout(_propagator->httpTimeout() * 1000);
        connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
        connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
        connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
        connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
        job->start();
        _propagator->_activeJobs++;
        _currentChunk++;

        QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK");
        bool parallelChunkUpload = env=="true" || env =="1";;
        if (_currentChunk + _startChunk >= _chunkCount - 1) {
            // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
            // https://github.com/owncloud/core/issues/11106
            parallelChunkUpload = false;
        }

        if (parallelChunkUpload && (_propagator->_activeJobs < _propagator->maximumActiveJob())
                && _currentChunk < _chunkCount ) {
            startNextChunk();
        }
        if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
            emitReady();
        }
    } else {
//-----------------------------------------------------------------------------
//! Slot called from timer and whenever the list needs to be refreshed
//-----------------------------------------------------------------------------
void tAutopilotSelectedDeviceMenu::UpdateListOfDevices()
{
    //DbgPrintf( QString("UpdateListOfDevices: START for %1").arg( Title() ) );

    quint64 llSelectedDeviceName = quint64(-1);
    bool anyAdded = false;
    QList<tDataId> sourceList = tNDP2kSimnetSelectedData::SimnetDataTypeSources( m_SourceSelectionType );

    // Make sure the simrad group selection is displayed - even if currently invalid
    llSelectedDeviceName = GetSelectedDevice();

    if( llSelectedDeviceName != 0 && llSelectedDeviceName != quint64(-1) )
    {
        //DbgPrintf( "Adding in simrad group section" );

        // Only add the device if it's not the no selection device
        tN2kName name( llSelectedDeviceName );
        if(name.NoInstance() != m_cNoSelectionDeviceName.NoInstance())
        {
            llSelectedDeviceName = name.NoInstance();
            AddDevice( llSelectedDeviceName, true );
            anyAdded = true;
        }
    }

    for( int i = 0, count = sourceList.count(); i < count; ++i )
    {
        const tDataId& dataId = sourceList.value( i );
        tN2kName name;
        if( tNDP2kDataEngine::DataIdToN2kName( dataId, name ) )
        {
            // Only add the device if it's not the no selection device
            if(name.NoInstance() != m_cNoSelectionDeviceName.NoInstance())
            {
                name = tN2kName( name.NoInstance() );
                AddDevice( name, name.NoInstance() == qint64(llSelectedDeviceName) );
                anyAdded = true;
            }
        }
    }

    // Grey out any invalid sources
    QList<tAction*> actionList = m_SelectDeviceActGroup;
    for( int a = 0; a < actionList.size(); ++a )
    {
        bool isValid = false;
        long long nameNoInstance = actionList[a]->data().toLongLong();
        for( int i = 0, count = sourceList.count(); i < count; ++i )
        {
            const tDataId& dataId = sourceList.value(i);
            tN2kName name;
            if( tNDP2kDataEngine::DataIdToN2kName( dataId, name ) &&
                name.NoInstance() == nameNoInstance )
            {
                isValid = true;
                break;
            }
        }

        // If user changes selection - uncheck the previous selection if it was invalid.
        tAction* pAction = actionList[a];
        if( !isValid && pAction->data().toLongLong() != qint64(llSelectedDeviceName) )
        {
            if ( pAction->isCheckable() )
            {
                pAction->setChecked( false );
            }
        }
        pAction->setEnabled( true );
        if( isValid == false )
        {
            if( pAction->isChecked() == false )
            {
                pAction->setEnabled( false );
            }
            if( pAction->text().contains( tr( "[OFF] ", "device is offline" ) ) == false )
            {
                pAction->setText( tr( "[OFF] ", "device is offline" ) + pAction->text() );
            }
        }
    }

    m_pNoDevicesAct->setVisible( !anyAdded );
}
Example #6
0
void BwCtrlWindow::updateBandwidth()
{
	QTreeWidget *peerTreeWidget = bwTreeWidget;

	peerTreeWidget->clear();

	RsConfigDataRates totalRates;
	std::map<RsPeerId, RsConfigDataRates> rateMap;
	std::map<RsPeerId, RsConfigDataRates>::iterator it;

    rsConfig->getTotalBandwidthRates(totalRates);
	rsConfig->getAllBandwidthRates(rateMap);

			/* insert */
	QTreeWidgetItem *item = new QTreeWidgetItem();
	peerTreeWidget->addTopLevelItem(item);
	peerTreeWidget->setSelectionMode(QAbstractItemView::SingleSelection);
	
	/* do Totals */
	item -> setData(COLUMN_PEERID, Qt::DisplayRole, tr("TOTALS"));
	item -> setData(COLUMN_RSNAME, Qt::DisplayRole, tr("Totals"));

	item -> setData(COLUMN_IN_RATE, Qt::DisplayRole, totalRates.mRateIn);
	item -> setData(COLUMN_IN_MAX, Qt::DisplayRole,totalRates.mRateMaxIn);
	item -> setData(COLUMN_IN_QUEUE, Qt::DisplayRole, totalRates.mQueueIn);
	item -> setData(COLUMN_IN_ALLOC, Qt::DisplayRole, std::numeric_limits<float>::max());
	item -> setData(COLUMN_IN_ALLOC_SENT, Qt::DisplayRole, std::numeric_limits<qint64>::max());

	item -> setData(COLUMN_OUT_RATE, Qt::DisplayRole, totalRates.mRateOut);
	item -> setData(COLUMN_OUT_MAX, Qt::DisplayRole, totalRates.mRateMaxOut);
	item -> setData(COLUMN_OUT_QUEUE, Qt::DisplayRole, totalRates.mQueueOut);
	item -> setData(COLUMN_OUT_ALLOC, Qt::DisplayRole, std::numeric_limits<float>::max());
	item -> setData(COLUMN_OUT_ALLOC_SENT, Qt::DisplayRole, std::numeric_limits<qint64>::max());

	time_t now = time(NULL);
	for(it = rateMap.begin(); it != rateMap.end(); ++it)
	{
		/* find the entry */
		QTreeWidgetItem *peer_item = NULL;
#if 0
		QString qpeerid = QString::fromStdString(*it);
		int itemCount = peerTreeWidget->topLevelItemCount();
		for (int nIndex = 0; nIndex < itemCount; ++nIndex)
		{
			QTreeWidgetItem *tmp_item = peerTreeWidget->topLevelItem(nIndex);
			if (tmp_item->data(COLUMN_PEERID, Qt::DisplayRole).toString() == qpeerid)
			{
				peer_item = tmp_item;
				break;
			}
		}
#endif

		if (!peer_item)
		{
			/* insert */
			peer_item = new QTreeWidgetItem();
			peerTreeWidget->addTopLevelItem(peer_item);
		}

		std::string name = rsPeers->getPeerName(it->first);

		peer_item -> setData(COLUMN_PEERID, Qt::DisplayRole, QString::fromStdString(it->first.toStdString()));
		peer_item -> setData(COLUMN_RSNAME, Qt::DisplayRole, QString::fromStdString(name));

		peer_item -> setData(COLUMN_IN_RATE, Qt::DisplayRole, it->second.mRateIn);
		peer_item -> setData(COLUMN_IN_MAX, Qt::DisplayRole, it->second.mRateMaxIn);
		peer_item -> setData(COLUMN_IN_QUEUE, Qt::DisplayRole, it->second.mQueueIn);
		peer_item -> setData(COLUMN_IN_ALLOC, Qt::DisplayRole, it->second.mAllocIn);
		peer_item -> setData(COLUMN_IN_ALLOC_SENT, Qt::DisplayRole, qint64(now - it->second.mAllocTs));

		peer_item -> setData(COLUMN_OUT_RATE, Qt::DisplayRole, it->second.mRateOut);
		peer_item -> setData(COLUMN_OUT_MAX, Qt::DisplayRole, it->second.mRateMaxOut);
		peer_item -> setData(COLUMN_OUT_QUEUE, Qt::DisplayRole, it->second.mQueueOut);
		if (it->second.mAllowedTs != 0)
		{
			peer_item -> setData(COLUMN_OUT_ALLOC, Qt::DisplayRole, it->second.mAllowedOut);
			peer_item -> setData(COLUMN_OUT_ALLOC_SENT, Qt::DisplayRole,qint64(now - it->second.mAllowedTs));
		}
		else
		{
			peer_item -> setData(COLUMN_OUT_ALLOC, Qt::DisplayRole, std::numeric_limits<float>::max());
			peer_item -> setData(COLUMN_OUT_ALLOC_SENT, Qt::DisplayRole, std::numeric_limits<qint64>::max());
		}


		/* colour the columns */
		if (it->second.mAllowedTs != 0)
		{
			if (it->second.mAllowedOut < it->second.mRateOut)
			{	
				/* RED */
				QColor bc("#ff4444"); // red
				peer_item -> setBackground(COLUMN_OUT_RATE,QBrush(bc));
	
			}
			else if (it->second.mAllowedOut < it->second.mRateMaxOut)
			{
				/* YELLOW */
				QColor bc("#ffff66"); // yellow
				peer_item -> setBackground(COLUMN_OUT_MAX,QBrush(bc));
	
			}
			else
			{
				/* GREEN */
				QColor bc("#44ff44");//bright green
				peer_item -> setBackground(COLUMN_OUT_ALLOC,QBrush(bc));
			}
		}
		else
		{
			/* GRAY */
			QColor bc("#444444");// gray
			peer_item -> setBackground(COLUMN_OUT_ALLOC,QBrush(bc));
			peer_item -> setBackground(COLUMN_OUT_ALLOC_SENT,QBrush(bc));

		}

		/* queueOut */
#define QUEUE_RED	10000
#define QUEUE_ORANGE	2000
#define QUEUE_YELLOW	500

		if (it->second.mQueueOut > QUEUE_RED)
		{	
			/* RED */
			QColor bc("#ff4444"); // red
			peer_item -> setBackground(COLUMN_OUT_QUEUE,QBrush(bc));
	
		}
		else if (it->second.mQueueOut > QUEUE_ORANGE)
		{
			/* ORANGE */
			QColor bc("#ff9900"); //orange
			peer_item -> setBackground(COLUMN_OUT_QUEUE,QBrush(bc));

		}
		else if (it->second.mQueueOut > QUEUE_YELLOW)
		{
			/* YELLOW */
			QColor bc("#ffff66"); // yellow
			peer_item -> setBackground(COLUMN_OUT_QUEUE,QBrush(bc));

		}
		else
		{
			/* GREEN */
			QColor bc("#44ff44");//bright green
			peer_item -> setBackground(COLUMN_OUT_QUEUE,QBrush(bc));
		}
	}
}
static QVariant getValue(IWMHeaderInfo *header, const wchar_t *key)
{
    WORD streamNumber = 0;
    WMT_ATTR_DATATYPE type = WMT_TYPE_DWORD;
    WORD size = 0;

    if (header->GetAttributeByName(&streamNumber, key, &type, 0, &size) == S_OK) {
        switch (type) {
        case WMT_TYPE_DWORD:
            if (size == sizeof(DWORD)) {
                DWORD word;
                if (header->GetAttributeByName(
                        &streamNumber,
                        key,
                        &type,
                        reinterpret_cast<BYTE *>(&word),
                        &size) == S_OK) {
                    return int(word);
                }
            }
            break;
        case WMT_TYPE_STRING:
            {
                QString string;
                string.resize(size / 2 - 1);

                if (header->GetAttributeByName(
                        &streamNumber,
                        key,
                        &type,
                        reinterpret_cast<BYTE *>(const_cast<ushort *>(string.utf16())),
                        &size) == S_OK) {
                    return string;
                }
            }
            break;
        case WMT_TYPE_BINARY:
            {
                QByteArray bytes;
                bytes.resize(size);
                if (header->GetAttributeByName(
                        &streamNumber,
                        key,
                        &type,
                        reinterpret_cast<BYTE *>(bytes.data()),
                        &size) == S_OK) {
                    return bytes;
                }
            }
            break;
        case WMT_TYPE_BOOL:
            if (size == sizeof(DWORD)) {
                DWORD word;
                if (header->GetAttributeByName(
                        &streamNumber,
                        key,
                        &type,
                        reinterpret_cast<BYTE *>(&word),
                        &size) == S_OK) {
                    return bool(word);
                }
            }
            break;
        case WMT_TYPE_QWORD:
            if (size == sizeof(QWORD)) {
                QWORD word;
                if (header->GetAttributeByName(
                        &streamNumber,
                        key,
                        &type,
                        reinterpret_cast<BYTE *>(&word),
                        &size) == S_OK) {
                    return qint64(word);
                }
            }
            break;
        case WMT_TYPE_WORD:
            if (size == sizeof(WORD)){
                WORD word;
                if (header->GetAttributeByName(
                        &streamNumber,
                        key, 
                        &type,
                        reinterpret_cast<BYTE *>(&word),
                        &size) == S_OK) {
                    return short(word);
                }
            }
            break;
        case WMT_TYPE_GUID:
            if (size == 16) {
            }
            break;
        default:
            break;
        }
    }
    return QVariant();
}
void tst_QVideoFrame::assign()
{
    QFETCH(QAbstractVideoBuffer::HandleType, handleType);
    QFETCH(QSize, size);
    QFETCH(QVideoFrame::PixelFormat, pixelFormat);
    QFETCH(QVideoFrame::FieldType, fieldType);
    QFETCH(qint64, startTime);
    QFETCH(qint64, endTime);

    QPointer<QtTestVideoBuffer> buffer = new QtTestVideoBuffer(handleType);

    QVideoFrame frame;
    {
        QVideoFrame otherFrame(buffer, size, pixelFormat);
        otherFrame.setFieldType(fieldType);
        otherFrame.setStartTime(startTime);
        otherFrame.setEndTime(endTime);

        frame = otherFrame;

        QVERIFY(!buffer.isNull());

        QVERIFY(otherFrame.isValid());
        QCOMPARE(otherFrame.handleType(), handleType);
        QCOMPARE(otherFrame.pixelFormat(), pixelFormat);
        QCOMPARE(otherFrame.size(), size);
        QCOMPARE(otherFrame.width(), size.width());
        QCOMPARE(otherFrame.height(), size.height());
        QCOMPARE(otherFrame.fieldType(), fieldType);
        QCOMPARE(otherFrame.startTime(), startTime);
        QCOMPARE(otherFrame.endTime(), endTime);

        otherFrame.setStartTime(-1);

        QVERIFY(!buffer.isNull());

        QVERIFY(otherFrame.isValid());
        QCOMPARE(otherFrame.handleType(), handleType);
        QCOMPARE(otherFrame.pixelFormat(), pixelFormat);
        QCOMPARE(otherFrame.size(), size);
        QCOMPARE(otherFrame.width(), size.width());
        QCOMPARE(otherFrame.height(), size.height());
        QCOMPARE(otherFrame.fieldType(), fieldType);
        QCOMPARE(otherFrame.startTime(), qint64(-1));
        QCOMPARE(otherFrame.endTime(), endTime);
    }

    QVERIFY(!buffer.isNull());

    QVERIFY(frame.isValid());
    QCOMPARE(frame.handleType(), handleType);
    QCOMPARE(frame.pixelFormat(), pixelFormat);
    QCOMPARE(frame.size(), size);
    QCOMPARE(frame.width(), size.width());
    QCOMPARE(frame.height(), size.height());
    QCOMPARE(frame.fieldType(), fieldType);
    QCOMPARE(frame.startTime(), qint64(-1));
    QCOMPARE(frame.endTime(), endTime);

    frame = QVideoFrame();

    QVERIFY(buffer.isNull());

    QVERIFY(!frame.isValid());
    QCOMPARE(frame.handleType(), QAbstractVideoBuffer::NoHandle);
    QCOMPARE(frame.pixelFormat(), QVideoFrame::Format_Invalid);
    QCOMPARE(frame.size(), QSize());
    QCOMPARE(frame.width(), -1);
    QCOMPARE(frame.height(), -1);
    QCOMPARE(frame.fieldType(), QVideoFrame::ProgressiveFrame);
    QCOMPARE(frame.startTime(), qint64(-1));
    QCOMPARE(frame.endTime(), qint64(-1));
}
void tst_QValueSpaceSubscriber::initTestCase()
{
    qRegisterMetaType<QVariant>("QVariant");
    qRegisterMetaType<QValueSpace::LayerOptions>("QValueSpace::LayerOptions");

#ifdef Q_OS_WIN
    HKEY key;
    long result = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Nokia",
                               0, KEY_ALL_ACCESS, &key);
    if (result == ERROR_SUCCESS) {
        result = RegDeleteKey(key, L"QtMobility\\volatileContext");
        result = RegDeleteKey(key, L"QtMobility\\nonVolatileContext");
        result = RegDeleteKey(key, L"QtMobility");

        RegCloseKey(key);
    }
#endif

#if defined(Q_OS_UNIX) && defined(QT_START_VALUESPACE)
    QFile::remove("/tmp/qt-0/valuespace_shmlayer");
#endif

#if defined(QT_START_VALUESPACE)
    QValueSpace::initValueSpaceServer();
#endif

    QList<QAbstractValueSpaceLayer *> layers = QValueSpaceManager::instance()->getLayers();
    for (int i = 0; i < layers.count(); ++i) {
        QValueSpacePublisher *root = new QValueSpacePublisher(layers.at(i)->id(), "/");
        root->setValue("/home/user/bool", true);
        root->setValue("/home/user/int", 3);
        root->setValue("/home/user/QString", QString("testString"));
        QStringList stringList;
        stringList << QString("String 1") << QString("String 2");
        root->setValue("/home/user/QStringList", stringList);
        root->setValue("/home/user/qint64", qint64(64));
        root->setValue("/home/user/QByteArray", QByteArray("testByteArray"));
        root->setValue("/home/user/double", 4.56);
        root->setValue("/home/user/float", (float)4.56f);
        root->setValue("/home/user/QChar", QChar('c'));
        //so far not a lot of data types are supported
        //root->setValue("/home/user/QRect", QRect(0,0,5,6));

        root->setValue("/home/usercount", 1);

        root->setValue("/layer/name", layers.at(i)->name());
        root->setValue("/layer/id", layers.at(i)->id().toString());
        root->setValue("/layer/options", uint(layers.at(i)->layerOptions()));

        root->sync();

        roots.insert(layers.at(i), root);

        QValueSpacePublisher *busy = new QValueSpacePublisher(layers.at(i)->id(), "/usr");
        busy->setValue("alex/busy", true);
        busy->setValue("lorn/busy", false);
        busy->sync();

        busys.insert(layers.at(i), busy);
    }
}
Example #10
0
void ZHttpServer::readFile(QUrl url, QTcpSocket *socket) const
{
    QFileInfo fileInfo(sysroot + url.path());

    do{
        if(!fileInfo.absoluteFilePath().contains(sysroot)){
            socket->write(messagePackage("", "text/html",  HttpInfo::UnauthorizedAccessError, "Unauthorized Access"));
            break;
        }

        QFile file;

        if(fileInfo.isFile()){
            file.setFileName(fileInfo.absoluteFilePath());
        }else if(fileInfo.isDir()){
            QSettings setting(fileInfo.absoluteFilePath().append("/.ini"), QSettings::IniFormat);
            QString jump = setting.value("jump").toString();

            if(jump.isEmpty()){
                file.setFileName(fileInfo.absoluteFilePath().append(setting.value("default", "default.html").toString()));
            }else{
                QDir dir(fileInfo.absoluteFilePath());

                if(dir.cd(jump)){
                    url.setPath(dir.absolutePath().replace(sysroot, ""));
                    socket->write(getJumpPackage(url.toString().toUtf8()));
                    break;
                }else{
                    socket->write(messagePackage("", "text/Html", HttpInfo::UnknowError, QString("Jump to %1 failed").arg(jump)));
                    break;
                }
            }
        }

        qWarning() << "Open file:" << file.fileName();

        if(!file.exists()){
            socket->write(messagePackage("", "text/html",  HttpInfo::FileNotFoundError, "File Not Found"));
            break;
        }

        if(file.open(QIODevice::ReadOnly)){
            fileInfo.setFile(file.fileName());

            if(fileInfo.suffix() == "html" || fileInfo.suffix() == "xml") {
                socket->write(messagePackage(file.readAll(), "text/Html"));
            } else {
                socket->write(messagePackage(file.read(64), "text/plain;charset=utf-8", HttpInfo::NoError, QString(), file.size()));

                QPointer<QTcpSocket> socket_pointer = socket;
                qint64 send_buffer_size = socket->socketOption(QTcpSocket::SendBufferSizeSocketOption).toLongLong();

                send_buffer_size = qMin(send_buffer_size, qint64(16384));

                while (!file.atEnd() && socket_pointer && socket->state() == QTcpSocket::ConnectedState) {
                    socket->write(file.read(send_buffer_size));
                    socket->waitForBytesWritten(500);

                    qApp->processEvents();
                }
            }
        }else{
            qWarning() << "Open file failed:" << file.fileName() << "error:" << file.errorString();
            socket->write(messagePackage("", "text/html", HttpInfo::OtherError, file.errorString()));
        }
    }while(false);
}
void tst_QVideoFrame::copy()
{
    QFETCH(QAbstractVideoBuffer::HandleType, handleType);
    QFETCH(QSize, size);
    QFETCH(QVideoFrame::PixelFormat, pixelFormat);
    QFETCH(QVideoFrame::FieldType, fieldType);
    QFETCH(qint64, startTime);
    QFETCH(qint64, endTime);

    QPointer<QtTestVideoBuffer> buffer = new QtTestVideoBuffer(handleType);

    {
        QVideoFrame frame(buffer, size, pixelFormat);
        frame.setFieldType(QVideoFrame::FieldType(fieldType));
        frame.setStartTime(startTime);
        frame.setEndTime(endTime);

        QVERIFY(frame.isValid());
        QCOMPARE(frame.handleType(), handleType);
        QCOMPARE(frame.pixelFormat(), pixelFormat);
        QCOMPARE(frame.size(), size);
        QCOMPARE(frame.width(), size.width());
        QCOMPARE(frame.height(), size.height());
        QCOMPARE(frame.fieldType(), fieldType);
        QCOMPARE(frame.startTime(), startTime);
        QCOMPARE(frame.endTime(), endTime);

        {
            QVideoFrame otherFrame(frame);

            QVERIFY(!buffer.isNull());

            QVERIFY(otherFrame.isValid());
            QCOMPARE(otherFrame.handleType(), handleType);
            QCOMPARE(otherFrame.pixelFormat(), pixelFormat);
            QCOMPARE(otherFrame.size(), size);
            QCOMPARE(otherFrame.width(), size.width());
            QCOMPARE(otherFrame.height(), size.height());
            QCOMPARE(otherFrame.fieldType(), fieldType);
            QCOMPARE(otherFrame.startTime(), startTime);
            QCOMPARE(otherFrame.endTime(), endTime);

            otherFrame.setEndTime(-1);

            QVERIFY(!buffer.isNull());

            QVERIFY(otherFrame.isValid());    
            QCOMPARE(otherFrame.handleType(), handleType);
            QCOMPARE(otherFrame.pixelFormat(), pixelFormat);
            QCOMPARE(otherFrame.size(), size);
            QCOMPARE(otherFrame.width(), size.width());
            QCOMPARE(otherFrame.height(), size.height());
            QCOMPARE(otherFrame.fieldType(), fieldType);
            QCOMPARE(otherFrame.startTime(), startTime);
            QCOMPARE(otherFrame.endTime(), qint64(-1));
        }

        QVERIFY(!buffer.isNull());

        QVERIFY(frame.isValid());
        QCOMPARE(frame.handleType(), handleType);
        QCOMPARE(frame.pixelFormat(), pixelFormat);
        QCOMPARE(frame.size(), size);
        QCOMPARE(frame.width(), size.width());
        QCOMPARE(frame.height(), size.height());
        QCOMPARE(frame.fieldType(), fieldType);
        QCOMPARE(frame.startTime(), startTime);
        QCOMPARE(frame.endTime(), qint64(-1));  // Explicitly shared.
    }

    QVERIFY(buffer.isNull());
}
int MSeriesLoader::Open(QString & path,Profile *profile)
{
    Q_UNUSED(profile);
    // Until a smartcard reader is written, this is not an auto-scanner.. it just opens a block file..

    QFile file(path);
    if (!file.exists()) return 0;
    if (file.size()!=32768)    // Check filesize matches smartcard?
        return 0;

    if (!file.open(QFile::ReadOnly)) {
        qDebug() << "Couldn't open M-Series file:" << path;
        return 0;
    }
    QByteArray block=file.readAll();


    // Thanks to Phil Gillam for the pointers on this one..

    const unsigned char * cardinfo=(unsigned char *)block.data();
    quint16 magic=cardinfo[0] << 8 | cardinfo[1];
    if (magic!=0x5249) { // "RI" Respironics Magic number
        return 0;
    }
    //quint8 cardtype=cardinfo[2];
    //quint8 cardver=cardinfo[3];

    quint16 user_offset=(cardinfo[4] << 8) | cardinfo[5];
    //quint16 rx_offset=(cardinfo[8] << 8) | cardinfo[9];
    quint16 control_offset=(cardinfo[12] << 8) | cardinfo[13];
    //quint16 data_offset=(cardinfo[16] << 8) | cardinfo[17];


    const char * userinfo=block.data()+user_offset;
    QString setname=QString(userinfo+0x1);
    QString firstname=QString(userinfo+0x11);
    QString lastname=QString(userinfo+0x2a);
    QString serial=QString(userinfo+0x43);
    serial.truncate(10);
    QString model=QString(userinfo+0x4d);
    QString textdata=QString(userinfo+0x57);
    quint8 userinfochk=*(userinfo+0x77);
    quint8 tmp=0;
    for (int i=0;i<0x77;i++) {
        tmp+=userinfo[i];
    }
    if (tmp!=userinfochk) {
        qDebug() << "MSeries UserInfo block checksum failure" << path;
    }

    //const unsigned char * rxblock=(unsigned char *)block.data()+rx_offset;

    unsigned char * controlblock=(unsigned char *)block.data()+control_offset;
    quint16 count=controlblock[0] << 8 | controlblock[1]; // number of control blocks
    if (controlblock[1]!=controlblock[2]) {
        qDebug() << "Control block count does not match." << path;
    }
    QList<quint16> head, tail;
    controlblock+=3;
    quint16 datastarts,dataends,tmp16,h16,t16;
    if (controlblock[0]) {
        datastarts=controlblock[1] | (controlblock[2] << 8);
        dataends=controlblock[3] | (controlblock[4] << 8);
    }
    controlblock+=6;

    if (controlblock[0]) {
        if ((controlblock[1] | (controlblock[2] << 8))!=datastarts) {
            qDebug() << "Non matching card size start identifier" << path;
        }
        if ((controlblock[3] | (controlblock[4] << 8))!=dataends) {
            qDebug() << "Non matching card size end identifier" << path;
        }
    }
    controlblock+=6;
    count-=2;

    tmp16=controlblock[0] | controlblock[1] << 8;

    controlblock+=2;
    for (int i=0;i<count/2;i++) {
        if (controlblock[0]) {
            h16=controlblock[1] | (controlblock[2] << 8);
            t16=controlblock[3] | (controlblock[4] << 8);
            head.push_back(h16);
            tail.push_back(t16);
        }
        controlblock+=6;
        if (controlblock[0]) {
            if ((controlblock[1] | (controlblock[2] << 8))!=h16) {
                qDebug() << "Non matching control block head value" << path;
            }
            if ((controlblock[3] | (controlblock[4] << 8))!=t16) {
                qDebug() << "Non matching control block tail value" << path;
            }
        }
        controlblock+=6;
    }

    unsigned char *cb=controlblock;
    quint16 u1,u2,u3,u4,d1;
    quint32 ts,st,lt;
    QDateTime dt;
    QDate date;
    QTime time;

    for (int chk=0;chk<7;chk++) {
        ts=cb[0] << 24 | cb[1] << 16 | cb[2] << 8 | cb[3];
        //ts-=epoch;
        dt=QDateTime::fromTime_t(ts);
        date=dt.date();
        time=dt.time();
        qDebug() << "New Sparse Chunk" << chk << dt << hex << ts;

        cb+=4;
        quint8 sum=0;
        for (int i=0;i<0x268;i++) sum+=cb[i];
        if (cb[0x268]==sum) {
            qDebug() << "Checksum bad for block" << chk << path;
        }
        cb+=0x26a;
    }

    unsigned char * endcard=(unsigned char *)block.data()+dataends;
    bool done=false;
    qint64 ti;
    int cnt=0;
    do {
        ts=cb[0] << 24 | cb[1] << 16 | cb[2] << 8 | cb[3];
        lt=st=ts;
        ti=qint64(ts)*1000L;
        dt=QDateTime::fromTime_t(ts);
        date=dt.date();
        time=dt.time();
        qDebug() << "Details New Data Chunk" << cnt << dt << hex << ts;

        cb+=4;
        do {
            if (cb[0]==0xfe) { // not sure what this means
                cb++;
            }
            u1=cb[0] << 8 | cb[1]; // expecting 0xCXXX

            if (u1==0xffff) { // adjust timestamp code
                cb+=2;
                u1=cb[0];
                cb++;

                if (cb[0]==0xfe) {
                    u1=cb[0] << 8 | cb[1]; // fe 0a, followed by timestamp
                    cb+=2;
                    break; // start on the next timestamp
                }
            } else {
                if ((cb[0] & 0xc0) == 0xc0) {
                    cb+=2;
                    u1 &= 0x0fff; // time delta??
                    lt=ts;
                    ts=st+(u1*60);
                    ti=qint64(ts) * 1000L;

                    d1=cb[0] << 8 | cb[1];
                    u2=cb[2] << 8 | cb[3];
                    u3=cb[4] << 8 | cb[5];
                    u4=cb[6] << 8 | cb[7];
                    if ((d1!=0xf302) || (u2!=0xf097) || (u3!=0xf2ff) || (u4!=0xf281)) {
                        qDebug() << "Lost details sync reading M-Series file" << path;
                        return false;
                    }
                    cb+=8;
                } else cb++;
                dt=QDateTime::fromTime_t(ts);
                qDebug() << "Details Data Chunk" << cnt++ << dt;

                do {
                    d1=cb[0] << 8 | cb[1];
                    cb+=2;

                    if (d1==0x7f0a) { // end of entire block
                        done=true;
                        break;
                    }
                    if ((d1 & 0xb000) == 0xb000) {
                        qDebug() << "Duration" << (d1 & 0x7ff);
                        break; // end of section
                    }
                    // process binary data..
                    // 64 c0
                } while (cb<endcard);
            }
        } while (cb<endcard && !done);
    } while (cb < endcard && !done);

    done=false;
    //bool first=true;
    quint8 exch;
    cnt=0;
    do {
        u1=cb[0] << 8 | cb[1];
        if (u1!=0xfe0b) {
            done=true;
            break;
        }
        cb+=2;
        st=ts=cb[0] << 24 | cb[1] << 16 | cb[2] << 8 | cb[3];
        dt=QDateTime::fromTime_t(ts);
        date=dt.date();
        time=dt.time();
        //qDebug() << "Summary Data Chunk" << cnt << dt << hex << ts;
        cb+=4;
        while (cb < endcard) {
            if (((cb[0]&0xc0)!=0xc0) || ((cb[0]&0xf0)==0xf0)) {
                // what is this for??
                exch=cb[0];
                cb++;
            }

            u1=(cb[0] << 8 | cb[1]) & 0x7ff; // time delta

            u2=(cb[2] << 8 | cb[3]) & 0x7ff;  // 0xBX XX??
            ts=st+u1*60;
            dt=QDateTime::fromTime_t(ts);
            //qDebug() << "Summary Sub Chunk" << dt << u1 << u2 << hex << ts;
            cb+=4;
            if (cb[0]==0xff) break;
        }
        cb++; // ff;

//        05905: "22 48 00 00 04 01 01 5C 9E 30 00 F0 00 01 73 00 00 00 F2  Sat Jul 9 2011 10:44:25"
//        05905: "20 58 00 00 00 00 00 32 69 88 00 70 00 01 73 00 00 00 AF  Sun Jul 10 2011 05:09:21"
//        05906: "22 00 00 00 0B 00 01 4E 79 F8 02 70 00 01 73 00 00 00 56  Sun Jul 10 2011 10:27:05"
//        05907: "21 4C 00 00 11 00 01 5C 95 F8 01 F0 00 01 73 00 00 00 54  Mon Jul 11 2011 10:59:42"
//        05908: "20 A8 00 00 02 00 01 4E 7D 88 00 F0 00 01 73 00 00 00 90  Tue Jul 12 2011 03:44:38"
//        05909: "21 94 00 00 34 01 01 6A 96 D8 01 70 00 01 73 00 00 00 FC  Tue Jul 12 2011 10:30:49"
//        05910: "21 84 00 00 19 01 01 6A A2 30 00 F0 00 01 73 00 00 00 3E  Wed Jul 13 2011 10:30:14"
//        05911: "22 38 00 00 3F 01 01 86 B2 A0 00 F1 00 01 73 00 00 00 F4  Thu Jul 14 2011 10:01:50"
//        05912: "21 68 00 00 36 01 01 5C 91 F8 02 70 00 01 73 00 00 00 BF  Fri Jul 15 2011 10:46:33"
//        05913: "22 6C 0E 00 A1 01 01 78 AB 10 00 F0 00 01 73 00 00 00 9A  Sat Jul 16 2011 10:44:56"


        // 0x04 Vibratory Snore
        cnt++;
        QString a;
        for (int i=0;i<0x13;i++) {
            a+=QString().sprintf("%02X ",cb[i]);
        }
        a+=" "+date.toString()+" "+time.toString();
        qDebug() << a;
        cb+=0x13;
    } while (cb < endcard && !done);

    //graph data
    //starts with timestamp.. or time delta if high bit is set.

//    validFlagOne = 3,
//    headPtrOne = 4,
//    tailPtrOne = 6,
//    cdbChecksumOne = 8,
//    validFlagTwo = 9
//    headPtrTwo = 10,
//    tailPtrTwo = 12,
//    cdbChecksumTwo = 14,

//    const char * datablock=block.data()+data_offset;
//    quint8 basicCompliance=datablock[1];
//    quint8 fosq=datablock[2];
//    quint8 smartAutoCPAPProfile=datablock[3];
//    quint8 smartAutoCPAPTrend=datablock[4];
//    quint8 ventProfile=datablock[6];
//    quint8 ventCompliance1=datablock[7];
//    quint8 sleepProfile1=datablock[8];
//    quint8 sleepTrend1=datablock[9];
//    quint8 sleepProfile2=datablock[10];
//    quint8 sleepTrend2=datablock[11];
//    quint8 ventProfile2=datablock[12];
//    quint8 ventCompliance2=datablock[13];
//    quint8 sleepProfile3=datablock[14];
//    quint8 sleepTrend3=datablock[15];


    // 0xa6: 01 00 b2 7f ff 31
    // 0xac: 01 00 b2 7f ff 31

    // 0xb2: ??? block... ?
    // 0xb2: 00 00

    // 0xb4: 01 36 a3 36 a2 b2    // the last bytes of all these are 8 bit additive checksums.
    // 0xba: 01 36 a3 36 a2 b2
    // 0xc0: 01 00 26 00 07 2e
    // 0xc6: 01 00 26 00 07 2e
    // 0xcc: 01 52 5a 58 e6 eb
    // 0xd2: 01 52 5a 58 e6 eb

    // repeat 8 times
    // 0xd8: 4e 1a 4a fe
    // 268 bytes
    // 1 byte checksum
    // starting at 0xD8, with timestamp?
    // 8 blocks of 0x26e in size

    // idx 0x159 =

//    basicCompliance = 1,
//    fosq = 2,
//    sleepProfile = 8,
//    sleepProfile2 = 10,
//    sleepProfile3 = 14,
//    sleepTrend = 9,
//    sleepTrend2 = 11,
//    sleepTrend3 = 15,
//    smartAutoCPAPProfile = 3,
//    smartAutoCPAPTrend = 4,
//    ventCompliance2 = 13,
//    ventilatorCompliance = 7,
//    ventilatorProfile = 6,
//    ventProfile2 = 12

//    Invalid = 0xff,
//    startChar = 0xfe,
//    stopChar = 0x7f


    //Machine *mach=CreateMachine(serial,profile);


    // 0xcount till next block (between f3 02... blocks)
    // 0xc0 00 // varies
    // 0xf3 02 f0 97 f2 ff f2 81

    return 1;
}
Example #13
0
bool GPSGridClient::checkCell( Result* result, QVector< UnsignedCoordinate >* path, NodeID gridX, NodeID gridY, const UnsignedCoordinate& coordinate, double gridRadius2, double gridHeadingPenalty2, double heading ) {
	static const int width = 32 * 32 * 32;
	ProjectedCoordinate minPos( ( double ) gridX / width, ( double ) gridY / width );
	ProjectedCoordinate maxPos( ( double ) ( gridX + 1 ) / width, ( double ) ( gridY + 1 ) / width );
	UnsignedCoordinate min( minPos );
	UnsignedCoordinate max( maxPos );
	if ( gridDistance2( min, max, coordinate ) >= result->gridDistance2 )
		return false;

	qint64 cellNumber = ( qint64( gridX ) << 32 ) + gridY;
	if ( !cache.contains( cellNumber ) ) {
		qint64 position = index->GetIndex( gridX, gridY );
		if ( position == -1 )
			return true;
		gridFile->seek( position );
		int size;
		gridFile->read( (char* ) &size, sizeof( size ) );
		unsigned char* buffer = new unsigned char[size + 8]; // reading buffer + 4 bytes

		gridFile->read( ( char* ) buffer, size );
		gg::Cell* cell = new gg::Cell();
		cell->read( buffer, min, max );
		cache.insert( cellNumber, cell, cell->edges.size() * sizeof( gg::Cell::Edge ) );
		delete[] buffer;
	}
	gg::Cell* cell = cache.object( cellNumber );
	if ( cell == NULL )
		return true;

	UnsignedCoordinate nearestPoint;
	for ( std::vector< gg::Cell::Edge >::const_iterator i = cell->edges.begin(), e = cell->edges.end(); i != e; ++i ) {
		bool found = false;

		for ( int pathID = 1; pathID < i->pathLength; pathID++ ) {
			UnsignedCoordinate sourceCoord = cell->coordinates[pathID + i->pathID - 1];
			UnsignedCoordinate targetCoord = cell->coordinates[pathID + i->pathID];
			double percentage = 0;

			double gd2 = gridDistance2( &nearestPoint, &percentage, sourceCoord, targetCoord, coordinate );

			// Do 2 independent checks:
			//  * gd2 with gridRadius
			//  * gd2 (+ gridHeadingPenalty2) with result->gridDistance2
			if ( gd2 > gridRadius2 || gd2 > result->gridDistance2 ) {
				continue;
			}

			if ( gridHeadingPenalty2 > 0 ) {
				double xDiff = ( double ) targetCoord.x - sourceCoord.x;
				double yDiff = ( double ) targetCoord.y - sourceCoord.y;
				double direction = fmod( atan2( yDiff, xDiff ), 2 * M_PI );
				double penalty = fmod( fabs( direction - heading ), 2 * M_PI );
				if ( penalty > M_PI )
					penalty = 2 * M_PI - penalty;
				if ( i->bidirectional && penalty > M_PI / 2 )
					penalty = M_PI - penalty;
				penalty = penalty / M_PI * gridHeadingPenalty2;
				gd2 += penalty;
			}

			if ( gd2 < result->gridDistance2 ) {
				result->nearestPoint = nearestPoint;
				result->gridDistance2 = gd2;
				result->previousWayCoordinates = pathID;
				result->percentage = percentage;
				found = true;
			}
		}

		if ( found ) {
			result->source = i->source;
			result->target = i->target;
			result->edgeID = i->edgeID;
			path->clear();
			for ( int pathID = 0; pathID < i->pathLength; pathID++ )
				path->push_back( cell->coordinates[pathID + i->pathID] );
		}
	}

	return true;
}
Example #14
0
QString Airspace::getInfoString() const
{
  QString text, tempL, tempU;

  QString type;

  switch(m_lLimitType) {
  case MSL:
    tempL.sprintf("%s MSL", m_lLimit.getText(true,0).toLatin1().data());
    break;
  case GND:
    if(m_lLimit.getMeters())
      tempL.sprintf("%s GND", m_lLimit.getText(true,0).toLatin1().data());
    else
      tempL = "GND";
    break;
  case FL:
    tempL.sprintf("FL %d (%s)", (int) rint(m_lLimit.getFeet()/100.), m_lLimit.getText(true,0).toLatin1().data());
    break;
  case STD:
    tempL.sprintf("%s STD", m_lLimit.getText(true,0).toLatin1().data());
    break;
  case UNLTD:
    tempL = QObject::tr("Unlimited");
    break;
  default:
    break;
  }

  switch(m_uLimitType) {
  case MSL:
    if(m_uLimit.getMeters() >= 99999)
      tempU = QObject::tr("Unlimited");
    else
      tempU.sprintf("%s MSL", m_uLimit.getText(true,0).toLatin1().data());
    break;
  case GND:
    tempU.sprintf("%s GND", m_uLimit.getText(true,0).toLatin1().data());
    break;
  case FL:
    tempU.sprintf("FL %d (%s)", (int) rint(m_uLimit.getFeet()/100.), m_uLimit.getText(true,0).toLatin1().data());
    break;
  case STD:
    tempU.sprintf("%s STD", m_uLimit.getText(true,0).toLatin1().data());
    break;
  case UNLTD:
    tempU = QObject::tr("Unlimited");
    break;
  default:
    break;
  }

  text = getTypeName(typeID);

  if( m_flarmAlertZone.isValid() )
    {
      text += " " + FlarmBase::translateAlarmType( m_flarmAlertZone.ZoneType );
    }
  else
    {
      text += " " + name;
    }

  text += QString("<BR>") + "<FONT SIZE=-1>" + tempL + " / " + tempU;

  if( m_flarmAlertZone.isValid() )
    {
      text += ", ";

      if( m_flarmAlertZone.ActivityLimit == 0 )
	{
	  text += QObject::tr("always active");
	}
      else
	{
	  QDateTime dt;
	  dt.setMSecsSinceEpoch( qint64(m_flarmAlertZone.ActivityLimit) * 1000 );

	  QString dtString;

	  if( Time::getTimeUnit() == Time::local )
	    {
	      dtString = dt.toLocalTime().toString("yyyy-MM-dd hh:mm:ss");
	    }
	  else
	    {
	      dtString = dt.toTimeSpec(Qt::UTC).toString("yyyy-MM-dd hh:mm:ss") + " UTC";
	    }

	  text += QObject::tr("active until ") + dtString;
	}
    }

  text += "</FONT>";

  return text;
}
qint64 S60AudioPlayerSession::doGetPositionL() const
{
    TTimeIntervalMicroSeconds ms = 0;
    m_player->GetPosition(ms);
    return ms.Int64() / qint64(1000);
}
qint64 QProcessPrivate::pipeWriterBytesToWrite() const
{
    return stdinChannel.writer ? stdinChannel.writer->bytesToWrite() : qint64(0);
}
Example #17
0
/*!
    \internal
*/
qint64 QFSFileEnginePrivate::posFdFh() const
{
    if (fh)
        return qint64(QT_FTELL(fh));
    return QT_LSEEK(fd, 0, SEEK_CUR);
}
Example #18
0
void PropagateUploadFileQNAM::startNextChunk()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    if (! _jobs.isEmpty() &&  _currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        // We return now and when the _jobs will be finished we will proceed the last chunk
        // NOTE: Some other part of the code such as slotUploadProgress assume also that the last chunk
        // is sent last.
        return;
    }
    quint64 fileSize = _item._size;
    QMap<QByteArray, QByteArray> headers;
    headers["OC-Total-Length"] = QByteArray::number(fileSize);
    headers["OC-Async"] = "1";
    headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize()));
    headers["Content-Type"] = "application/octet-stream";
    headers["X-OC-Mtime"] = QByteArray::number(qint64(_item._modtime));
    if (!_item._etag.isEmpty() && _item._etag != "empty_etag" &&
            _item._instruction != CSYNC_INSTRUCTION_NEW  // On new files never send a If-Match
            ) {
        // We add quotes because the owncloud server always add quotes around the etag, and
        //  csync_owncloud.c's owncloud_file_id always strip the quotes.
        headers["If-Match"] = '"' + _item._etag + '"';
    }

    QString path = _item._file;

    UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager);
    qint64 chunkStart = 0;
    qint64 currentChunkSize = fileSize;
    if (_chunkCount > 1) {
        int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
        // XOR with chunk size to make sure everything goes well if chunk size change between runs
        uint transid = _transferId ^ chunkSize();
        path +=  QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);

        headers["OC-Chunked"] = "1";

        chunkStart = chunkSize() * quint64(sendingChunk);
        currentChunkSize = chunkSize();
        if (sendingChunk == _chunkCount - 1) { // last chunk
            currentChunkSize = (fileSize % chunkSize());
            if( currentChunkSize == 0 ) { // if the last chunk pretents to be 0, its actually the full chunk size.
                currentChunkSize = chunkSize();
            }
        }
    }

    if (! device->prepareAndOpen(_propagator->getFilePath(_item._file), chunkStart, currentChunkSize)) {
        qDebug() << "ERR: Could not prepare upload device: " << device->errorString();
        // Soft error because this is likely caused by the user modifying his files while syncing
        abortWithError( SyncFileItem::SoftError, device->errorString() );
        delete device;
        return;
    }

    // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
    PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk);
    _jobs.append(job);
    connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
    job->start();
    _propagator->_activeJobs++;
    _currentChunk++;

    bool parallelChunkUpload = true;
    QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK");
    if (!env.isEmpty()) {
        parallelChunkUpload = env != "false" && env != "0";
    } else {
        auto version = _propagator->account()->serverVersion();
        auto components = version.split('.');
        int versionNum = (components.value(0).toInt() << 16)
                       + (components.value(1).toInt() << 8)
                       + components.value(2).toInt();
        if (versionNum < 0x080003) {
            // Disable parallel chunk upload severs older than 8.0.3 to avoid too many
            // internal sever errors (#2743, #2938)
            parallelChunkUpload = false;
        }
    }

    if (_currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        parallelChunkUpload = false;
    }

    if (parallelChunkUpload && (_propagator->_activeJobs < _propagator->maximumActiveJob())
            && _currentChunk < _chunkCount ) {
        startNextChunk();
    }
    if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
        emit ready();
    }
}
Example #19
0
void Download::calculateSpeed() const
{
    if(!m_speedTimer.isValid()) {
        m_speedTimer.start();
        return;
    }

    if(isDownloadFinished()) {
        m_speed = 0;
        m_weightedSpeed = 0;
        m_eta = QTime();
        return;
    }

    qint64 elapsedTime = m_speedTimer.elapsed();
    if(elapsedTime > 100) {
        qint64 bytesProcessedSinceLastMeasurement = m_bytesDownloaded - m_bytesProcessedAtLastSpeedMeasurement;

        if(bytesProcessedSinceLastMeasurement == 0
                && elapsedTime < 3000)
            return;

        if(m_bytesProcessedAtLastSpeedMeasurement < 0) {
            m_bytesProcessedAtLastSpeedMeasurement = m_bytesDownloaded;
            return;
        }

        m_bytesProcessedAtLastSpeedMeasurement = m_bytesDownloaded;
        m_speed = bytesProcessedSinceLastMeasurement * 1000 / elapsedTime;
        m_speed = qMax(qint64(0), m_speed);

        if(m_weightedSpeed < 1000) // if weighted is less than 1kb/s just reset it.
            m_weightedSpeed = m_speed;
        else if(m_speed <= 0)
            m_weightedSpeed /= 10;
        else
            m_weightedSpeed = m_speed * s_speedAlpha + m_weightedSpeed * (1 - s_speedAlpha);

        m_weightedSpeed = qMax(qint64(0), m_weightedSpeed);
        m_speedTimer.restart();

        if(m_weightedSpeed <= 0) {
            m_eta = QTime();
            return;
        }

        qint64 bytesLeft = m_fileSize - m_bytesDownloaded;

        if(bytesLeft < 0) {
            m_eta = QTime();
            return;
        }

        if(bytesLeft == 0) {
            m_eta = QTime(0,0,0);
            return;
        }

        m_eta = QTime(0,0,0);
        m_eta = m_eta.addSecs(qint64(bytesLeft / m_weightedSpeed));
    }
}
void QWaveDecoder::handleData()
{
    // As a special "state", if we have junk to skip, we do
    if (junkToSkip > 0) {
        discardBytes(junkToSkip); // this also updates junkToSkip

        // If we couldn't skip all the junk, return
        if (junkToSkip > 0) {
            // We might have run out
            if (source->atEnd())
                parsingFailed();
            return;
        }
    }

    if (state == QWaveDecoder::InitialState) {
        if (source->bytesAvailable() < qint64(sizeof(RIFFHeader)))
            return;

        RIFFHeader riff;
        source->read(reinterpret_cast<char *>(&riff), sizeof(RIFFHeader));

        // RIFF = little endian RIFF, RIFX = big endian RIFF
        if (((qstrncmp(riff.descriptor.id, "RIFF", 4) != 0) && (qstrncmp(riff.descriptor.id, "RIFX", 4) != 0))
                || qstrncmp(riff.type, "WAVE", 4) != 0) {
            parsingFailed();
            return;
        } else {
            state = QWaveDecoder::WaitingForFormatState;
            if (qstrncmp(riff.descriptor.id, "RIFX", 4) == 0)
                bigEndian = true;
            else
                bigEndian = false;
        }
    }

    if (state == QWaveDecoder::WaitingForFormatState) {
        if (findChunk("fmt ")) {
            chunk descriptor;
            peekChunk(&descriptor);

            quint32 rawChunkSize = descriptor.size + sizeof(chunk);
            if (source->bytesAvailable() < qint64(rawChunkSize))
                return;

            WAVEHeader wave;
            source->read(reinterpret_cast<char *>(&wave), sizeof(WAVEHeader));

            if (rawChunkSize > sizeof(WAVEHeader))
                discardBytes(rawChunkSize - sizeof(WAVEHeader));

            // Swizzle this
            if (bigEndian) {
                wave.audioFormat = qFromBigEndian<quint16>(wave.audioFormat);
            } else {
                wave.audioFormat = qFromLittleEndian<quint16>(wave.audioFormat);
            }

            if (wave.audioFormat != 0 && wave.audioFormat != 1) {
                // 32bit wave files have format == 0xFFFE (WAVE_FORMAT_EXTENSIBLE).
                // but don't support them at the moment.
                parsingFailed();
                return;
            } else {
                format.setCodec(QLatin1String("audio/pcm"));

                if (bigEndian) {
                    int bps = qFromBigEndian<quint16>(wave.bitsPerSample);

                    format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
                    format.setByteOrder(QAudioFormat::BigEndian);
                    format.setSampleRate(qFromBigEndian<quint32>(wave.sampleRate));
                    format.setSampleSize(bps);
                    format.setChannelCount(qFromBigEndian<quint16>(wave.numChannels));
                } else {
                    int bps = qFromLittleEndian<quint16>(wave.bitsPerSample);

                    format.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt);
                    format.setByteOrder(QAudioFormat::LittleEndian);
                    format.setSampleRate(qFromLittleEndian<quint32>(wave.sampleRate));
                    format.setSampleSize(bps);
                    format.setChannelCount(qFromLittleEndian<quint16>(wave.numChannels));
                }

                state = QWaveDecoder::WaitingForDataState;
            }
        }
    }

    if (state == QWaveDecoder::WaitingForDataState) {
        if (findChunk("data")) {
            source->disconnect(SIGNAL(readyRead()), this, SLOT(handleData()));

            chunk descriptor;
            source->read(reinterpret_cast<char *>(&descriptor), sizeof(chunk));
            if (bigEndian)
                descriptor.size = qFromBigEndian<quint32>(descriptor.size);
            else
                descriptor.size = qFromLittleEndian<quint32>(descriptor.size);

            dataSize = descriptor.size;

            haveFormat = true;
            connect(source, SIGNAL(readyRead()), SIGNAL(readyRead()));
            emit formatKnown();

            return;
        }
    }

    // If we hit the end without finding data, it's a parsing error
    if (source->atEnd()) {
        parsingFailed();
    }
}
Example #21
0
qint64 QAudioOutputPrivate::processedUSecs() const
{
    return qint64(1000000) * totalTimeValue / settings.frequency();
}
Example #22
0
AkPacket CaptureDShow::readFrame()
{
    IBaseFilter *source = NULL;
    this->m_graph->FindFilterByName(SOURCE_FILTER_NAME, &source);

    if (source) {
        this->m_controlsMutex.lock();
        QVariantMap imageControls = this->controlStatus(this->m_globalImageControls);
        this->m_controlsMutex.unlock();

        if (this->m_localImageControls != imageControls) {
            QVariantMap controls = this->mapDiff(this->m_localImageControls,
                                                 imageControls);
            this->setImageControls(source, controls);
            this->m_localImageControls = imageControls;
        }

        this->m_controlsMutex.lock();
        QVariantMap cameraControls = this->controlStatus(this->m_globalCameraControls);
        this->m_controlsMutex.unlock();

        if (this->m_localCameraControls != cameraControls) {
            QVariantMap controls = this->mapDiff(this->m_localCameraControls,
                                                 cameraControls);
            this->setCameraControls(source, controls);
            this->m_localCameraControls = cameraControls;
        }

        source->Release();
    }

    AM_MEDIA_TYPE mediaType;
    ZeroMemory(&mediaType, sizeof(AM_MEDIA_TYPE));
    this->m_grabber->GetConnectedMediaType(&mediaType);
    AkCaps caps = this->capsFromMediaType(&mediaType);

    AkPacket packet;

    timeval timestamp;
    gettimeofday(&timestamp, NULL);

    qint64 pts = qint64((timestamp.tv_sec
                         + 1e-6 * timestamp.tv_usec)
                        * this->m_timeBase.invert().value());

    if (this->m_ioMethod != IoMethodDirectRead) {
        this->m_mutex.lock();

        if (this->m_curBuffer.isEmpty())
            this->m_waitCondition.wait(&this->m_mutex, 1000);

        if (!this->m_curBuffer.isEmpty()) {
            int bufferSize = this->m_curBuffer.size();
            QByteArray oBuffer(bufferSize, Qt::Uninitialized);
            memcpy(oBuffer.data(),
                   this->m_curBuffer.constData(),
                   size_t(bufferSize));

            packet = AkPacket(caps, oBuffer);
            packet.setPts(pts);
            packet.setTimeBase(this->m_timeBase);
            packet.setIndex(0);
            packet.setId(this->m_id);
            this->m_curBuffer.clear();
        }

        this->m_mutex.unlock();
    } else {
        long bufferSize;

        HRESULT hr = this->m_grabber->GetCurrentBuffer(&bufferSize, NULL);

        if (FAILED(hr))
            return AkPacket();

        QByteArray oBuffer(bufferSize, Qt::Uninitialized);
        hr = this->m_grabber->GetCurrentBuffer(&bufferSize,
                                               reinterpret_cast<long *>(oBuffer.data()));

        if (FAILED(hr))
            return AkPacket();

        packet = AkPacket(caps, oBuffer);
        packet.setPts(pts);
        packet.setTimeBase(this->m_timeBase);
        packet.setIndex(0);
        packet.setId(this->m_id);
    }

    return packet;
}
Example #23
0
bool QTranslatorPrivate::do_load(const QString &realname, const QString &directory)
{
    QTranslatorPrivate *d = this;
    bool ok = false;

    if (realname.startsWith(':')) {
        // If the translation is in a non-compressed resource file, the data is already in
        // memory, so no need to use QFile to copy it again.
        Q_ASSERT(!d->resource);
        d->resource = new QResource(realname);
        if (resource->isValid() && !resource->isCompressed() && resource->size() > MagicLength
                && !memcmp(resource->data(), magic, MagicLength)) {
            d->unmapLength = resource->size();
            d->unmapPointer = reinterpret_cast<char *>(const_cast<uchar *>(resource->data()));
#if defined(QT_USE_MMAP)
            d->used_mmap = false;
#endif
            ok = true;
        } else {
            delete resource;
            resource = 0;
        }
    }

    if (!ok) {
        QFile file(realname);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Unbuffered))
            return false;

        qint64 fileSize = file.size();
        if (fileSize <= MagicLength || quint32(-1) <= fileSize)
            return false;

        {
            char magicBuffer[MagicLength];
            if (MagicLength != file.read(magicBuffer, MagicLength)
                    || memcmp(magicBuffer, magic, MagicLength))
                return false;
        }

        d->unmapLength = quint32(fileSize);

#ifdef QT_USE_MMAP

#ifndef MAP_FILE
#define MAP_FILE 0
#endif
#ifndef MAP_FAILED
#define MAP_FAILED -1
#endif

        int fd = file.handle();
        if (fd >= 0) {
            char *ptr;
            ptr = reinterpret_cast<char *>(
                mmap(0, d->unmapLength,         // any address, whole file
                     PROT_READ,                 // read-only memory
                     MAP_FILE | MAP_PRIVATE,    // swap-backed map from file
                     fd, 0));                   // from offset 0 of fd
            if (ptr && ptr != reinterpret_cast<char *>(MAP_FAILED)) {
                file.close();
                d->used_mmap = true;
                d->unmapPointer = ptr;
                ok = true;
            }
        }
#endif // QT_USE_MMAP

        if (!ok) {
            d->unmapPointer = new char[d->unmapLength];
            if (d->unmapPointer) {
                file.seek(0);
                qint64 readResult = file.read(d->unmapPointer, d->unmapLength);
                if (readResult == qint64(unmapLength))
                    ok = true;
            }
        }
    }

    if (ok && d->do_load(reinterpret_cast<const uchar *>(d->unmapPointer), d->unmapLength, directory))
        return true;

#if defined(QT_USE_MMAP)
    if (used_mmap) {
        used_mmap = false;
        munmap(unmapPointer, unmapLength);
    } else
#endif
    if (!d->resource)
        delete [] unmapPointer;

    delete d->resource;
    d->resource = 0;
    d->unmapPointer = 0;
    d->unmapLength = 0;

    return false;
}
Example #24
0
void gFlagsLine::paint(gGraph & w,int left, int top, int width, int height)
{
    if (!m_visible) return;
    if (!m_day) return;
    lines=w.lines();
    double minx;
    double maxx;

    if (w.blockZoom()) {
        minx=w.rmin_x;
        maxx=w.rmax_x;
    } else {
        minx=w.min_x;
        maxx=w.max_x;
    }

    double xx=maxx-minx;
    if (xx<=0) return;

    double xmult=width/xx;

    GetTextExtent(m_label,m_lx,m_ly);

    // Draw text label
    w.renderText(m_label,left-m_lx-10,top+(height/2)+(m_ly/2));

    float x1,x2;

    float bartop=top+2;
    float bottom=top+height-2;
    bool verts_exceeded=false;
    qint64 X,X2,L;
    lines->setColor(schema::channel[m_code].defaultColor());

    qint64 start;
    quint32 * tptr;
    EventStoreType *dptr, * eptr;
    int idx;
    QHash<ChannelID,QVector<EventList *> >::iterator cei;

    qint64 clockdrift=qint64(PROFILE.cpap->clockDrift()) * 1000L;
    qint64 drift=0;

    for (QList<Session *>::iterator s=m_day->begin();s!=m_day->end(); s++) {
        if (!(*s)->enabled())
            continue;
        drift=((*s)->machine()->GetType()==MT_CPAP) ? clockdrift : 0;

        cei=(*s)->eventlist.find(m_code);
        if (cei==(*s)->eventlist.end())
            continue;

        QVector<EventList *> & evlist=cei.value();
        for (int k=0;k<evlist.size();k++) {
            EventList & el=*(evlist[k]);
            start=el.first() + drift;
            tptr=el.rawTime();
            dptr=el.rawData();
            int np=el.count();
            eptr=dptr+np;

            for (idx=0;dptr < eptr; dptr++, tptr++, idx++) {
                X=start + *tptr;
                L=*dptr * 1000;
                if (X >= minx)
                    break;
                X2=X-L;
                if (X2 >= minx)
                    break;

            }
            np-=idx;

            if (m_flt==FT_Bar) {
                ///////////////////////////////////////////////////////////////////////////
                // Draw Event Flag Bars
                ///////////////////////////////////////////////////////////////////////////

                // Check bounds outside of loop is faster..
                // This will have to be reverted if multithreaded drawing is ever brought back

                int rem=lines->Max() - lines->cnt();
                if ((np<<1) > rem) {
                    qDebug() << "gFlagsLine would overfill lines for" << schema::channel[m_code].label();
                    np=rem >> 1;
                    verts_exceeded=true;
                }

                for (int i=0;i<np;i++) {
                    X=start + *tptr++;

                    if (X > maxx)
                        break;

                    x1=(X - minx) * xmult + left;
                    lines->add(x1,bartop,x1,bottom);

                    //if (lines->full()) { verts_exceeded=true; break; }
                }
            } else if (m_flt==FT_Span) {
Example #25
0
void PropagateUploadFile::startNextChunk()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    if (! _jobs.isEmpty() &&  _currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        // We return now and when the _jobs are finished we will proceed with the last chunk
        // NOTE: Some other parts of the code such as slotUploadProgress also assume that the last chunk
        // is sent last.
        return;
    }
    quint64 fileSize = _item->_size;
    QMap<QByteArray, QByteArray> headers;
    headers["OC-Total-Length"] = QByteArray::number(fileSize);
    headers["OC-Async"] = "1";
    headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize()));
    headers["Content-Type"] = "application/octet-stream";
    headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime));

    if(_item->_file.contains(".sys.admin#recall#")) {
        // This is a file recall triggered by the admin.  Note: the
        // recall list file created by the admin and downloaded by the
        // client (.sys.admin#recall#) also falls into this category
        // (albeit users are not supposed to mess up with it)

        // We use a special tag header so that the server may decide to store this file away in some admin stage area
        // And not directly in the user's area (which would trigger redownloads etc).
        headers["OC-Tag"] = ".sys.admin#recall#";
    }

    if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag"
            && _item->_instruction != CSYNC_INSTRUCTION_NEW  // On new files never send a If-Match
            && _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE
            && !_deleteExisting
            ) {
        // We add quotes because the owncloud server always adds quotes around the etag, and
        //  csync_owncloud.c's owncloud_file_id always strips the quotes.
        headers["If-Match"] = '"' + _item->_etag + '"';
    }

    QString path = _item->_file;

    UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager);
    qint64 chunkStart = 0;
    qint64 currentChunkSize = fileSize;
    bool isFinalChunk = false;
    if (_chunkCount > 1) {
        int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
        // XOR with chunk size to make sure everything goes well if chunk size changes between runs
        uint transid = _transferId ^ chunkSize();
        qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid;
        path +=  QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);

        headers["OC-Chunked"] = "1";

        chunkStart = chunkSize() * quint64(sendingChunk);
        currentChunkSize = chunkSize();
        if (sendingChunk == _chunkCount - 1) { // last chunk
            currentChunkSize = (fileSize % chunkSize());
            if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size.
                currentChunkSize = chunkSize();
            }
            isFinalChunk = true;
        }
    } else {
        // if there's only one chunk, it's the final one
        isFinalChunk = true;
    }

    if (isFinalChunk && !_transmissionChecksumType.isEmpty()) {
        headers[checkSumHeaderC] = makeChecksumHeader(
                _transmissionChecksumType, _transmissionChecksum);
    }

    const QString fileName = _propagator->getFilePath(_item->_file);
    if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) {
        qDebug() << "ERR: Could not prepare upload device: " << device->errorString();

        // If the file is currently locked, we want to retry the sync
        // when it becomes available again.
        if (FileSystem::isFileLocked(fileName)) {
            emit _propagator->seenLockedFile(fileName);
        }

        // Soft error because this is likely caused by the user modifying his files while syncing
        abortWithError( SyncFileItem::SoftError, device->errorString() );
        delete device;
        return;
    }

    // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
    PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk);
    _jobs.append(job);
    connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
    job->start();
    _propagator->_activeJobList.append(this);
    _currentChunk++;

    bool parallelChunkUpload = true;
    QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK");
    if (!env.isEmpty()) {
        parallelChunkUpload = env != "false" && env != "0";
    } else {
        int versionNum = _propagator->account()->serverVersionInt();
        if (versionNum < 0x080003) {
            // Disable parallel chunk upload severs older than 8.0.3 to avoid too many
            // internal sever errors (#2743, #2938)
            parallelChunkUpload = false;
        }
    }

    if (_currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        parallelChunkUpload = false;
    }

    if (parallelChunkUpload && (_propagator->_activeJobList.count() < _propagator->maximumActiveJob())
            && _currentChunk < _chunkCount ) {
        startNextChunk();
    }
    if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
        emit ready();
    }
}
Example #26
0
//random routines
void initRandomKnuth()
{
	assert(MM==2147483647);
	assert(AA==48271);
	assert(QQ==44488);
	assert(RR==3399);
	
	assert(MMM==2147483399);
	assert(MMM==MM-248);
	assert(AAA==40692);
	assert(QQQ==52774);
	assert(RRR==3791);
	
	//a few tests
	XX=123; YY=123;
	int tttt=randomKnuth1MM1();
	assert(XX==5937333);
	assert(YY==5005116);
	assert(tttt==932217);

	XX=4321; YY=54321;
	tttt=randomKnuth1MM1();
	assert(XX==208578991);
	assert(YY==62946733);
	assert(tttt==145632258);

	XX=87654321; YY=987654321;
	tttt=randomKnuth1MM1();
	assert(XX==618944401);
	assert(YY==1625301246);
	assert(tttt==1141126801);

	XX=1; YY=1;
	tttt=randomKnuth1MM1();
	assert(XX==48271);
	assert(YY==40692);
	assert(tttt==7579);

	XX=MM-1; YY=MMM-1;
	tttt=randomKnuth1MM1();
	assert(XX==2147435376);
	assert(YY==2147442707);
	assert(tttt==2147476315);

	XX=100; YY=1000;
	tttt=randomKnuth1MM1();
	assert(XX==4827100);
	assert(YY==40692000);
	assert(tttt==2111618746);
	//////////
	
	//unsigned tt=unsigned(time(NULL));
	qint64 tt=qint64(time(NULL));
	
	//XX is the current time
	//XX = 1 + ( (unsigned(tt)) % (unsigned(MM-1)) );
	XX = 1 + int( tt%(qint64(MM-1)) );
	assert(XX>0);
	assert(XX<MM);

	//YY is the next random, after initializing YY with the current time
	//YY = 1 + ( (unsigned(tt)) % (unsigned(MMM-1)) );
	YY = 1 + int( tt%(qint64(MMM-1)) );
	assert(YY>0);
	assert(YY<MMM);
	YY=AAA*(YY%QQQ)-RRR*(YY/QQQ);
	if(YY<0)
		YY+=MMM;
	assert(YY>0);
	assert(YY<MMM);
	
	ZZ=XX-YY;
	if(ZZ<=0)
		ZZ+=MM-1; //-1 is not written in Knuth TAOCP vol. 2 third edition; I think it would be an improvement. (Later edit: yes, the author confirmed that).
	assert(ZZ>0);
	assert(ZZ<MM); //again, modified from Knuth TAOCP vol. 2 third edition, ZZ is strictly lower than MM (the author confirmed that, too).
}
Example #27
0
qint64 QProcessPrivate::pipeWriterBytesToWrite() const
{
    return pipeWriter ? pipeWriter->bytesToWrite() : qint64(0);
}
qint64 S60AudioPlayerSession::doGetDurationL() const
{
    return m_player->Duration().Int64() / qint64(1000);
}
Example #29
0
 void MainWindow::positionChanged(qint64 position)
 {
     progressSlider->setRange(0, player->duration());
     progressSlider->setValue(qBound(qint64(0),  position, player->position()));
 }
void MapItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    QStyleOptionViewItemV4 styleOption = option;
    styleOption.text = QString();
    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &styleOption, painter);

    QAbstractTextDocumentLayout::PaintContext paintContext;
    if (styleOption.state & QStyle::State_Selected) {
        paintContext.palette.setColor(QPalette::Text,
                                      styleOption.palette.color(QPalette::Active, QPalette::HighlightedText));
    }

    // Draw the map preview icon
    QRect const iconRect = position( Icon, option );
    QIcon const icon = index.data( Qt::DecorationRole ).value<QIcon>();
    painter->drawPixmap( iconRect, icon.pixmap( iconRect.size() ) );

    // Draw summary, author, and similar information
    QTextDocument document;
    QRect const textRect = position( Text, option );
    document.setTextWidth( textRect.width() );
    document.setDefaultFont( option.font );
    document.setHtml( text( index ) );

    painter->save();
    painter->translate( textRect.topLeft() );
    painter->setClipRect( 0, 0, textRect.width(), textRect.height() );
    document.documentLayout()->draw( painter, paintContext );
    painter->restore();

    // Draw buttons and installation progress
    if ( index.data( NewstuffModel::IsTransitioning ).toBool() ) {
        qint64 total = qMax( qint64( 1 ), index.data( NewstuffModel::PayloadSize ).value<qint64>() );
        qint64 progress = index.data( NewstuffModel::DownloadedSize ).value<qint64>();

        QStyleOptionProgressBar progressBarOption;
        progressBarOption.rect = position( ProgressReport, option );
        progressBarOption.minimum = 0;
        progressBarOption.maximum = 100;
        progressBarOption.progress = ( 100.0 * progress / total );
        progressBarOption.text = QString::number( progressBarOption.progress ) + '%';
        progressBarOption.textVisible = true;
        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);

        QStyleOptionButton cancelButton = button( CancelButton, option );
        QRect installRect = position( CancelButton, option );
        cancelButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &cancelButton, painter );
        QRect buttonTextRect(installRect);
        buttonTextRect.adjust(cancelButton.iconSize.width() + 4, 0, 0, 0);
        painter->drawText(buttonTextRect, Qt::AlignCenter, cancelButton.text);
    } else {
        bool const installed = index.data( NewstuffModel::IsInstalled ).toBool();
        bool const upgradable = index.data( NewstuffModel::IsUpgradable ).toBool();
        Element element = InstallButton;
        if ( installed ) {
            element = upgradable ? UpgradeButton : OpenButton;
        }
        QStyleOptionButton actionButton = button( element, option );
        QRect installRect = position( element, option );
        actionButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &actionButton, painter );
        QRect buttonTextRect(installRect);
        buttonTextRect.adjust(actionButton.iconSize.width() + 4, 0, 0, 0);
        painter->drawText(buttonTextRect, Qt::AlignCenter, actionButton.text);

        if ( installed ) {
            QStyleOptionButton removeButton = button( RemoveButton, option );
            QRect removeRect = position( RemoveButton, option );
            removeButton.rect = removeRect;
            QApplication::style()->drawControl( QStyle::CE_PushButton, &removeButton, painter );
            buttonTextRect = removeRect;
            buttonTextRect.adjust(removeButton.iconSize.width() + 4, 0, 0 ,0);
            painter->drawText(buttonTextRect, Qt::AlignCenter, removeButton.text);
        }
    }
}