Esempio n. 1
0
	bool HTTPTracker::updateData(const QByteArray & data)
	{
//#define DEBUG_PRINT_RESPONSE
#ifdef DEBUG_PRINT_RESPONSE
		Out(SYS_TRK | LOG_DEBUG) << "Data : " << endl;
		Out(SYS_TRK | LOG_DEBUG) << QString(data) << endl;
#endif
		// search for dictionary, there might be random garbage infront of the data
		int i = 0;
		while (i < data.size())
		{
			if (data[i] == 'd')
				break;
			i++;
		}

		if (i == data.size())
		{
			failures++;
			failed(i18n("Invalid response from tracker"));
			return false;
		}

		BDecoder dec(data, false, i);
		BNode* n = 0;
		try
		{
			n = dec.decode();
		}
		catch (...)
		{
			failures++;
			failed(i18n("Invalid data from tracker"));
			return false;
		}

		if (!n || n->getType() != BNode::DICT)
		{
			failures++;
			failed(i18n("Invalid response from tracker"));
			return false;
		}

		BDictNode* dict = (BDictNode*)n;
		if (dict->getData("failure reason"))
		{
			BValueNode* vn = dict->getValue("failure reason");
			error = vn->data().toString();
			delete n;
			failures++;
			failed(error);
			return false;
		}

		if (dict->getData("warning message"))
		{
			BValueNode* vn = dict->getValue("warning message");
			warning = vn->data().toString();
		}
		else
			warning.clear();

		BValueNode* vn = dict->getValue("interval");

		// if no interval is specified, use 5 minutes
		if (vn)
			interval = vn->data().toInt();
		else
			interval = 5 * 60;

		vn = dict->getValue("incomplete");
		if (vn)
			leechers = vn->data().toInt();

		vn = dict->getValue("complete");
		if (vn)
			seeders = vn->data().toInt();

		BListNode* ln = dict->getList("peers");
		if (!ln)
		{
			// no list, it might however be a compact response
			vn = dict->getValue("peers");
			if (vn && vn->data().getType() == Value::STRING)
			{
				QByteArray arr = vn->data().toByteArray();
				for (int i = 0;i < arr.size();i += 6)
				{
					Uint8 buf[6];
					for (int j = 0;j < 6;j++)
						buf[j] = arr[i + j];

					Uint32 ip = ReadUint32(buf, 0);
					addPeer(net::Address(ip, ReadUint16(buf, 4)), false);
				}
			}
		}
		else
		{
			for (Uint32 i = 0;i < ln->getNumChildren();i++)
			{
				BDictNode* dict = dynamic_cast<BDictNode*>(ln->getChild(i));

				if (!dict)
					continue;

				BValueNode* ip_node = dict->getValue("ip");
				BValueNode* port_node = dict->getValue("port");

				if (!ip_node || !port_node)
					continue;

				net::Address addr(ip_node->data().toString(), port_node->data().toInt());
				addPeer(addr, false);
			}
		}

		// Check for IPv6 compact peers
		vn = dict->getValue("peers6");
		if (vn && vn->data().getType() == Value::STRING)
		{
			QByteArray arr = vn->data().toByteArray();
			for (int i = 0;i < arr.size();i += 18)
			{
				Q_IPV6ADDR ip;
				memcpy(ip.c, arr.data() + i, 16);
				quint16 port = ReadUint16((const Uint8*)arr.data() + i, 16);

				addPeer(net::Address(ip, port), false);
			}
		}

		delete n;
		return true;
	}
Esempio n. 2
0
static KLockFile::LockResult deleteStaleLock(const QString &lockFile, KDE_struct_stat &st_buf, bool &linkCountSupport, const KComponentData &componentData)
{
   // This is dangerous, we could be deleting a new lock instead of
   // the old stale one, let's be very careful

   // Create temp file
   KTemporaryFile *ktmpFile = new KTemporaryFile(componentData);
   ktmpFile->setFileTemplate(lockFile);
   if (!ktmpFile->open())
      return KLockFile::LockError;

   QByteArray lckFile = QFile::encodeName(lockFile);
   QByteArray tmpFile = QFile::encodeName(ktmpFile->fileName());
   delete ktmpFile;

   // link to lock file
   if (::link(lckFile, tmpFile) != 0)
      return KLockFile::LockFail; // Try again later

   // check if link count increased with exactly one
   // and if the lock file still matches
   KDE_struct_stat st_buf1;
   KDE_struct_stat st_buf2;
   memcpy(&st_buf1, &st_buf, sizeof(KDE_struct_stat));
   st_buf1.st_nlink++;
   if ((KDE_lstat(tmpFile, &st_buf2) == 0) && st_buf1 == st_buf2)
   {
      if ((KDE_lstat(lckFile, &st_buf2) == 0) && st_buf1 == st_buf2)
      {
         // - - if yes, delete lock file, delete temp file, retry lock
         qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
         ::unlink(lckFile);
         ::unlink(tmpFile);
         return KLockFile::LockOK;
      }
   }

   // SMBFS supports hardlinks by copying the file, as a result the above test will always fail
   if (linkCountSupport)
   {
      linkCountSupport = testLinkCountSupport(tmpFile);
   }

   if (!linkCountSupport)
   {
      // Without support for link counts we will have a little race condition
      qWarning("WARNING: deleting stale lockfile %s", lckFile.data());
      ::unlink(tmpFile);
      if (::unlink(lckFile) < 0) {
          qWarning("WARNING: Problem deleting stale lockfile %s: %s", lckFile.data(),
                  strerror(errno));
          return KLockFile::LockFail;
      }
      return KLockFile::LockOK;
   }

   // Failed to delete stale lock file
   qWarning("WARNING: Problem deleting stale lockfile %s", lckFile.data());
   ::unlink(tmpFile);
   return KLockFile::LockFail;
}
Esempio n. 3
0
qint64 RCCFileInfo::writeDataBlob(RCCResourceLibrary &lib, qint64 offset,
    QString *errorMessage)
{
    const bool text = (lib.m_format == RCCResourceLibrary::C_Code);

    //capture the offset
    m_dataOffset = offset;

    //find the data to be written
    QFile file(m_fileInfo.absoluteFilePath());
    if (!file.open(QFile::ReadOnly)) {
        *errorMessage = msgOpenReadFailed(m_fileInfo.absoluteFilePath(), file.errorString());
        return 0;
    }
    QByteArray data = file.readAll();

#ifndef QT_NO_COMPRESS
    // Check if compression is useful for this file
    if (m_compressLevel != 0 && data.size() != 0) {
        QByteArray compressed =
            qCompress(reinterpret_cast<uchar *>(data.data()), data.size(), m_compressLevel);

        int compressRatio = int(100.0 * (data.size() - compressed.size()) / data.size());
        if (compressRatio >= m_compressThreshold) {
            data = compressed;
            m_flags |= Compressed;
        }
    }
#endif // QT_NO_COMPRESS

    // some info
    if (text) {
        lib.writeString("  // ");
        lib.writeByteArray(m_fileInfo.absoluteFilePath().toLocal8Bit());
        lib.writeString("\n  ");
    }

    // write the length

    lib.writeNumber4(data.size());
    if (text)
        lib.writeString("\n  ");
    offset += 4;

    // write the payload
    const char *p = data.constData();
    if (text) {
        for (int i = data.size(), j = 0; --i >= 0; --j) {
            lib.writeHex(*p++);
            if (j == 0) {
                lib.writeString("\n  ");
                j = 16;
            }
        }
    } else {
        for (int i = data.size(); --i >= 0; )
           lib.writeChar(*p++);
    }
    offset += data.size();

    // done
    if (text)
        lib.writeString("\n  ");
    return offset;
}
Esempio n. 4
0
    void Core::run()
    {
        MrunningThreads.lock();
        ++runningThreads;
        MrunningThreads.unlock();
#ifdef DEBUG_CORE
        qlonglong debug;
        Mdebug.lock();
        debug=++debugcounter;
        Mdebug.unlock();
        qDebug()<<"core:run"<<" ID="<<debug;
#endif //DEBUG_CORE
        bool last = false;

        LoadTask task;

        MtileLoadQueue.lock();
        {
            if(tileLoadQueue.count() > 0)
            {
                task = tileLoadQueue.dequeue();
                {

                    last = (tileLoadQueue.count() == 0);
#ifdef DEBUG_CORE
                    qDebug()<<"TileLoadQueue: " << tileLoadQueue.count()<<" Point:"<<task.Pos.ToString()<<" ID="<<debug;;
#endif //DEBUG_CORE
                }
            }
        }
        MtileLoadQueue.unlock();

        if(task.HasValue())
            if(loaderLimit.tryAcquire(1,TLMaps::Instance()->Timeout))
            {
            MtileToload.lock();
            --tilesToload;
            MtileToload.unlock();
#ifdef DEBUG_CORE
            qDebug()<<"loadLimit semaphore aquired "<<loaderLimit.available()<<" ID="<<debug<<" TASK="<<task.Pos.ToString()<<" "<<task.Zoom;
#endif //DEBUG_CORE

            {

#ifdef DEBUG_CORE
                qDebug()<<"task as value, begining get"<<" ID="<<debug;;
#endif //DEBUG_CORE
                {
                    Tile* m = Matrix.TileAt(task.Pos);

                    if(m==0 || m->Overlays.count() == 0)
                    {
#ifdef DEBUG_CORE
                        qDebug()<<"Fill empty TileMatrix: " + task.ToString()<<" ID="<<debug;;
#endif //DEBUG_CORE

                        Tile* t = new Tile(task.Zoom, task.Pos);
                        QVector<MapType::Types> layers= TLMaps::Instance()->GetAllLayersOfType(GetMapType());

                        foreach(MapType::Types tl,layers)
                        {
                            int retry = 0;

                            do
                            {
                                QByteArray tileImage;

                                // tile number inversion(BottomLeft -> TopLeft) for pergo maps
                                if(tl == MapType::PergoTurkeyMap)
                                {
                                    tileImage = TLMaps::Instance()->GetImageFromServer(tl, Point(task.Pos.X(), maxOfTiles.Height() - task.Pos.Y()), task.Zoom);
                                }
                                else if(tl == MapType::UserImage)
                                {
                                    tileImage = TLMaps::Instance()->GetImageFromFile(tl, task.Pos, task.Zoom, userImageHorizontalScale, userImageVerticalScale, userImageLocation, Projection());
                                }
                                else // ok
                                {
#ifdef DEBUG_CORE
                                    qDebug()<<"start getting image"<<" ID="<<debug;
#endif //DEBUG_CORE
                                    tileImage = TLMaps::Instance()->GetImageFromServer(tl, task.Pos, task.Zoom);
#ifdef DEBUG_CORE
                                    qDebug()<<"Core::run:gotimage size:"<<tileImage.count()<<" ID="<<debug;
#endif //DEBUG_CORE
                                }

                                if(tileImage.length()!=0)
                                {
                                    Moverlays.lock();
                                    {
                                        t->Overlays.append(tileImage);
#ifdef DEBUG_CORE
                                        qDebug()<<"Core::run append tileImage:"<<tileImage.length()<<" to tile:"<<t->GetPos().ToString()<<" now has "<<t->Overlays.count()<<" overlays"<<" ID="<<debug;
#endif //DEBUG_CORE

                                    }
                                    Moverlays.unlock();

                                    break;
                                }
                                else if(TLMaps::Instance()->RetryLoadTile > 0)
                                {
#ifdef DEBUG_CORE
                                    qDebug()<<"ProcessLoadTask: " << task.ToString()<< " -> empty tile, retry " << retry<<" ID="<<debug;;
#endif //DEBUG_CORE
                                    {
                                        QWaitCondition wait;
                                        QMutex m;
                                        m.lock();
                                        wait.wait(&m,500);
                                    }
                                }
                            }
                            while((++retry < TLMaps::Instance()->RetryLoadTile) && (tl == MapType::UserImage));
                        }

                        if(t->Overlays.count() > 0)
                        {
                            Matrix.SetTileAt(task.Pos,t);
                            emit OnNeedInvalidation();

#ifdef DEBUG_CORE
                            qDebug()<<"Core::run add tile "<<t->GetPos().ToString()<<" to matrix index "<<task.Pos.ToString()<<" ID="<<debug;
                            qDebug()<<"Core::run matrix index "<<task.Pos.ToString()<<" as tile with "<<Matrix.TileAt(task.Pos)->Overlays.count()<<" ID="<<debug;
#endif //DEBUG_CORE
                        }
                        else
                        {
                            // emit OnTilesStillToLoad(tilesToload);

                            delete t;
                            t = 0;
                            emit OnNeedInvalidation();
                        }

                        // layers = null;
                    }
                }
        {
            auto chunk = data.mid(i, chunkSize);
            auto hash = hasher(chunk);
            hashes.append(hash);
        }

        return hashes;
    }
}

SCENARIO("Expected chunked buffer behaviour")
{
    GIVEN("Some data with hashes of each chunk and a chunked buffer")
    {
        using namespace downloading::chunked;
        QByteArray originalData = "abcdefg";

        const int chunkSize = 2;
        QVector<THash> hashes
                = hashData(originalData, chunkSize, HashingStrategy::xxHash);

        QBuffer target;
        target.open(QIODevice::WriteOnly);

        ChunkedBuffer buffer(
                    hashes, chunkSize,
                    HashingStrategy::xxHash, target);

        WHEN("Correct data is written in unequal parts")
        {
            buffer.open(QIODevice::WriteOnly);
Esempio n. 6
0
QString chromaprinter::calcFingerPrint(SoundSourceProxy& soundSource){
    soundSource.open();
    m_SampleRate = soundSource.getSampleRate();
    unsigned int length = soundSource.length();
    if (m_SampleRate == 0 ){
        qDebug() << "Skipping invalid file:" << soundSource.getFilename();
        return QString();
    }

    // this is worth 2min of audio, multiply by 2 because we have 2 channels
    // AcoustID only stores a fingerprint for the first two minutes of a song
    // on their server so we need only a fingerprint of the first two minutes
    // --kain88 July 2012
    m_NumSamples = 120*2*m_SampleRate;
    // check that the song is actually longer then the amount of audio we use
    if (m_NumSamples > length) {
        m_NumSamples = length;
    }

    SAMPLE *pData = new SAMPLE[m_NumSamples];
    QTime timerReadingFile;
    timerReadingFile.start();
    unsigned int read = soundSource.read(m_NumSamples, pData);

    if (read!=m_NumSamples) {
        qDebug() << "oh that's embarrasing I couldn't read the track";
        return QString();
    }
    qDebug("reading file took: %d ms" , timerReadingFile.elapsed());

    ChromaprintContext* ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
    // we have 2 channels in mixxx always
    chromaprint_start(ctx, m_SampleRate, 2);

    QTime timerGeneratingFingerPrint;
    timerGeneratingFingerPrint.start();
    int success = chromaprint_feed(ctx, pData, m_NumSamples);
    if (!success) {
        qDebug() << "could not generate fingerprint";
        delete pData;
        return QString();
    }
    chromaprint_finish(ctx);

    void* fprint = NULL;
    int size = 0;
    int ret = chromaprint_get_raw_fingerprint(ctx, &fprint, &size);
    QByteArray fingerprint;
    if (ret == 1) {
        void* encoded = NULL;
        int encoded_size = 0;
        chromaprint_encode_fingerprint(fprint, size,
                                       CHROMAPRINT_ALGORITHM_DEFAULT,
                                       &encoded,
                                       &encoded_size, 1);

        fingerprint.append(reinterpret_cast<char*>(encoded), encoded_size);

        chromaprint_dealloc(fprint);
        chromaprint_dealloc(encoded);
    }
    chromaprint_free(ctx);
    delete pData;

    qDebug("generating fingerprint took: %d ms" , timerGeneratingFingerPrint.elapsed());

    return fingerprint;
}
Esempio n. 7
0
void
DownloadJob::onDownloadProgress( qint64 rcvd, qint64 total )
{
    if ( m_reply == 0 )
        return;

    if ( rcvd >= m_fileSize && m_fileSize > 0 )
    {
        m_finished = true;
    }

    if ( state() == Paused )
        return;

    m_rcvdSize = rcvd;
    m_fileSize = total;

    qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
    if ( ( now - 50 > m_rcvdStamp ) || ( rcvd == total ) )
    {
        m_rcvdStamp = now;
        if ( ( m_rcvdSize - 16384 > m_rcvdEmit ) || ( rcvd == total ) )
        {
            m_rcvdEmit = m_rcvdSize;
            emit progress( progressPercentage() );
        }
    }

    if ( !m_file )
        return;

    if ( !m_file->isOpen() )
    {
        if ( m_tryResuming && checkForResumedFile() )
            return;

        if ( !m_file->open( QIODevice::WriteOnly ) )
        {
            tLog() << Q_FUNC_INFO << "Failed opening file:" << m_file->fileName();
            setState( Failed );
            return;
        }
    }

    QByteArray data = m_reply->readAll();
    if ( data.isEmpty() )
        return;

    if ( m_file->write( data ) < 0 )
    {
        tLog() << Q_FUNC_INFO << "Failed writing to file:" << data.length();
        onDownloadError( QNetworkReply::UnknownContentError );
        return;
    }

    if ( m_rcvdSize >= m_fileSize && m_fileSize > 0 )
    {
        onDownloadFinished();
    }
    else if ( m_reply->isFinished() && m_reply->bytesAvailable() == 0 )
    {
        if ( ( m_fileSize > 0 && m_rcvdSize < m_fileSize ) || m_rcvdSize == 0 )
        {
            onDownloadError( QNetworkReply::UnknownContentError );
            return;
        }
    }
}
void ServerSocketInterface::readClient()
{
    QByteArray data = socket->readAll();
    servatrice->incRxBytes(data.size());
    inputBuffer.append(data);

    do {
        if (!messageInProgress) {
            if (inputBuffer.size() >= 4) {
                messageLength =   (((quint32) (unsigned char) inputBuffer[0]) << 24)
                                + (((quint32) (unsigned char) inputBuffer[1]) << 16)
                                + (((quint32) (unsigned char) inputBuffer[2]) << 8)
                                + ((quint32) (unsigned char) inputBuffer[3]);
                inputBuffer.remove(0, 4);
                messageInProgress = true;
            } else
                return;
        }
        if (inputBuffer.size() < messageLength)
            return;

        CommandContainer newCommandContainer;
        try {
            newCommandContainer.ParseFromArray(inputBuffer.data(), messageLength);
        }
        catch(std::exception &e) {
            qDebug() << "Caught std::exception in" << __FILE__ << __LINE__ << 
#ifdef _MSC_VER // Visual Studio
                __FUNCTION__;
#else
                __PRETTY_FUNCTION__;
#endif
            qDebug() << "Exception:" << e.what();
            qDebug() << "Message coming from:" << getAddress();
            qDebug() << "Message length:" << messageLength;
            qDebug() << "Message content:" << inputBuffer.toHex();
        }
        catch(...) {
            qDebug() << "Unhandled exception in" << __FILE__ << __LINE__ <<
#ifdef _MSC_VER // Visual Studio
                __FUNCTION__;
#else
                __PRETTY_FUNCTION__;
#endif
            qDebug() << "Message coming from:" << getAddress();
        }

        inputBuffer.remove(0, messageLength);
        messageInProgress = false;

        // dirty hack to make v13 client display the correct error message
        if (handshakeStarted)
            processCommandContainer(newCommandContainer);
        else if (!newCommandContainer.has_cmd_id()) {
            handshakeStarted = true;
            if (!initSession())
                prepareDestroy();
        }
        // end of hack
    } while (!inputBuffer.isEmpty());
}
Esempio n. 9
0
//! Returns a collection of information of the players, enemies, eggs and collectables that are sent periodically to the client.
QByteArray* LogicEngine::getActualPositions()
{
    QByteArray* positions = new QByteArray;

    positions->append( (char) level->getEnemies()->size() );

    for(int i = 0; i < level->getEnemies()->size(); i++)
    {
        // ID
        positions->append( '\0' ); // ID ANCORA DA FARE

        // X  COORDINATE
        int x = level->getEnemies()->at(i)->getX();

        int t1 = x / (256);
        int t2 = x % (256);

        positions->append( (char) t1 );
        positions->append( (char) t2 );

        // Y COORDINATE
        x = level->getEnemies()->at(i)->getY();

        t1 = x / 256;
        t2 = x % 256;

        positions->append( (char) t1 );
        positions->append( (char) t2 );

        // REST
        positions->append( (char) level->getEnemies()->at(i)->getDirectionX() );
        positions->append( (char) level->getEnemies()->at(i)->getDirectionY() );
        positions->append( (char) level->getEnemies()->at(i)->isVisible() );
    }


    int players = 0;

    for(int i = 0; i < clientList->size(); i++)
    {
        if(clientList->at(i)->player != NULL)
            players++;
    }

    positions->append( (char) players );

    for(int i = 0; i < clientList->size(); i++)
    {
        if(clientList->at(i)->player == NULL)
            continue;

        // ID
        positions->append( (char) clientList->at(i)->id );

        // X  COORDINATE
        int x = clientList->at(i)->player->getX();

        int t1 = x / 256;
        int t2 = x % 256;

        positions->append( (char) t1 );
        positions->append( (char) t2 );

        // Y COORDINATE
        x = clientList->at(i)->player->getY();

        if(x < 0)
        {
            x *= -1;
            x += 1000;
        }

        t1 = x / 256;
        t2 = x % 256;

        positions->append( (char) t1 );
        positions->append( (char) t2 );

        // REST

        int dirX = 0;

        if (clientList->at(i)->player->getVelocityX() != 0){
        	dirX = clientList->at(i)->player->getDirectionX();
        }

        positions->append( (char) dirX );
        positions->append( (char) clientList->at(i)->player->getDirectionY() );

        positions->append( (char) clientList->at(i)->player->getLife() );

        // Points
        x = clientList->at(i)->player->getPoints();
        t1 = x / 256;
        t2 = x % 256;
        positions->append( (char) t1 );
        positions->append( (char) t2 );

        positions->append( (char) clientList->at(i)->player->getEggs() );

        positions->append( (char) clientList->at(i)->player->isVisible() );
    }

    // Reserve position for size
    positions->append( '\0' );

    int pos = positions->size() -1;

    int eggs = 0;

    for(int i = 0; i < clientList->size(); i++)
    {
        if(clientList->at(i)->player == NULL)
            continue;

        for(int j = 0; j < NO_OF_EGGS; j++)
        {
            if(clientList->at(i)->eggs[j]->isVisible())
            {
                eggs++;

                // X  COORDINATE
                int x =  clientList->at(i)->eggs[j]->getX();

                int t1 = x / 256;
                int t2 = x % 256;

                positions->append( (char) t1 );
                positions->append( (char) t2 );

                // Y COORDINATE
                x = clientList->at(i)->eggs[j]->getY();

                t1 = x / 256;
                t2 = x % 256;

                positions->append( (char) t1 );
                positions->append( (char) t2 );

                // REST
                positions->append( (char) clientList->at(i)->eggs[j]->isVisible() );
            }
        }
    }

    (*positions)[pos] = (char) eggs;


    // Collectables
    positions->append( (char) level->getCollects()->size() );

    for(int i = 0; i < level->getCollects()->size(); i++)
    {
        positions->append( (char) level->getCollects()->at(i)->isVisible() );
    }

    return  positions;
}
Esempio n. 10
0
//  Do some basic timing tests and report the results
void runTimingTests() {
    //  How long does it take to make a call to get the time?
    const int numTests = 1000000;
    int* iResults = (int*)malloc(sizeof(int) * numTests);
    float fTest = 1.0;
    float* fResults = (float*)malloc(sizeof(float) * numTests);
    QElapsedTimer startTime;
    startTime.start();
    float elapsedUsecs;

    float NSEC_TO_USEC = 1.0f / 1000.0f;
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "QElapsedTimer::nsecElapsed() usecs: %f", (double)elapsedUsecs);

    // Test sleep functions for accuracy
    startTime.start();
    QThread::msleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "QThread::msleep(1) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    QThread::sleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "QThread::sleep(1) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    usleep(1);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "usleep(1) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    usleep(10);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "usleep(10) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    usleep(100);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "usleep(100) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    usleep(1000);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "usleep(1000) ms: %f", (double)(elapsedUsecs / 1000.0f));

    startTime.start();
    usleep(15000);
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "usleep(15000) ms: %f", (double)(elapsedUsecs / 1000.0f));

    // Random number generation
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        iResults[i] = rand();
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "rand() stored in array usecs: %f, first result:%d",
            (double)(elapsedUsecs / numTests), iResults[0]);

    // Random number generation using randFloat()
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        fResults[i] = randFloat();
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "randFloat() stored in array usecs: %f, first result: %f",
            (double)(elapsedUsecs / numTests), (double)(fResults[0]));

    free(iResults);
    free(fResults);

    //  PowF function
    fTest = 1145323.2342f;
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        fTest = powf(fTest, 0.5f);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "powf(f, 0.5) usecs: %f", (double)(elapsedUsecs / (float) numTests));

    //  Vector Math
    float distance;
    glm::vec3 pointA(randVector()), pointB(randVector());
    startTime.start();
    for (int i = 0; i < numTests; i++) {
        //glm::vec3 temp = pointA - pointB;
        //float distanceSquared = glm::dot(temp, temp);
        distance = glm::distance(pointA, pointB);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "vector math usecs: %f [%f usecs total for %d tests], last result:%f",
            (double)(elapsedUsecs / (float) numTests), (double)elapsedUsecs, numTests, (double)distance);

    //  Vec3 test
    glm::vec3 vecA(randVector()), vecB(randVector());
    float result;

    startTime.start();
    for (int i = 0; i < numTests; i++) {
        glm::vec3 temp = vecA-vecB;
        result = glm::dot(temp,temp);
    }
    elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
    qCDebug(interfaceapp, "vec3 assign and dot() usecs: %f, last result:%f",
            (double)(elapsedUsecs / numTests), (double)result);


    quint64 BYTE_CODE_MAX_TEST_VALUE = 99999999;
    quint64 BYTE_CODE_TESTS_SKIP = 999;

    QByteArray extraJunk;
    const int EXTRA_JUNK_SIZE = 200;
    extraJunk.append((unsigned char)255);
    for (int i = 0; i < EXTRA_JUNK_SIZE; i++) {
        extraJunk.append(QString("junk"));
    }

    {
        startTime.start();
        quint64 tests = 0;
        quint64 failed = 0;
        for (quint64 value = 0; value < BYTE_CODE_MAX_TEST_VALUE; value += BYTE_CODE_TESTS_SKIP) {
            quint64 valueA = value; // usecTimestampNow();
            ByteCountCoded<quint64> codedValueA = valueA;
            QByteArray codedValueABuffer = codedValueA;
            codedValueABuffer.append(extraJunk);
            ByteCountCoded<quint64> decodedValueA;
            decodedValueA.decode(codedValueABuffer);
            quint64 valueADecoded = decodedValueA;
            tests++;
            if (valueA != valueADecoded) {
                qDebug() << "FAILED! value:" << valueA << "decoded:" << valueADecoded;
                failed++;
            }

        }
        elapsedUsecs = (float)startTime.nsecsElapsed() * NSEC_TO_USEC;
        qCDebug(interfaceapp) << "ByteCountCoded<quint64> usecs: " << elapsedUsecs
                                << "per test:" << (double) (elapsedUsecs / tests)
                                << "tests:" << tests
                                << "failed:" << failed;
    }
}
Esempio n. 11
0
void XByteArray::setData(QByteArray data)
{
    _data = data;
    _changedData = QByteArray(data.length(), char(0));
}
Esempio n. 12
0
void FileWatcher::saveFile(QString file) {
    QFileInfo fileInfo(file);

    // If we have a dbi import file
    QLOG_DEBUG() << fileInfo.dir().absolutePath() + QDir::separator();
    QLOG_DEBUG() << global.fileManager.getDbiDirPath();
    if ((fileInfo.dir().absolutePath() + QDir::separator()) == global.fileManager.getDbiDirPath()) {
        BatchImport importer;
        importer.import(file);
        emit(nnexImported());
        QFile f(file);
        f.remove();
        return;
    }


    // If we have a user-import file
    QFile f(file);
    f.open(QIODevice::ReadOnly);
    QByteArray data = f.readAll();
    f.close();
    if (f.size() == 0)
        return;

    Note newNote;
    NoteTable ntable(global.db);
    ConfigStore cs(global.db);
    qint32 lid = cs.incrementLidCounter();

    QCryptographicHash md5hash(QCryptographicHash::Md5);
    QByteArray hash = md5hash.hash(data, QCryptographicHash::Md5);

    // * Start setting up the new note
    newNote.guid = QString::number(lid);
    newNote.title = file;

    NotebookTable bookTable(global.db);
    QString notebook;
    bookTable.getGuid(notebook, notebookLid);
    newNote.notebookGuid = notebook;

    QString newNoteBody = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")+
           QString("<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">")+
           QString("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\">");

    MimeReference mimeRef;
    QString mime = mimeRef.getMimeFromFileName(file);
    QString enMedia =QString("<en-media hash=\"") +hash.toHex() +QString("\" border=\"0\"")
            +QString(" type=\"" +mime +"\" ")
            +QString("/>");
    newNoteBody.append(enMedia + QString("</en-note>"));
    newNote.content = newNoteBody;
    newNote.active = true;
    newNote.created = QDateTime::currentMSecsSinceEpoch();;
    newNote.updated = newNote.created;
    newNote.updateSequenceNum = 0;
    NoteAttributes na;
    na.sourceURL = "file://" + file;
    newNote.attributes = na;

    qint32 noteLid = lid;
    ntable.add(lid, newNote, true);
    QString noteGuid = ntable.getGuid(lid);
    lid = cs.incrementLidCounter();


    // Start creating the new resource
    Resource newRes;
    Data d;
    d.body = data;
    d.bodyHash = hash;
    d.size = data.size();
    newRes.data = d;
    newRes.mime = mime;
    ResourceAttributes ra;
    ra.fileName = file;
    if (mime.startsWith("image", Qt::CaseInsensitive) || mime.endsWith("pdf", Qt::CaseInsensitive))
        ra.attachment = false;
    else
        ra.attachment = true;
    newRes.active = true;
    newRes.guid = QString::number(lid);
    newRes.noteGuid = noteGuid;
    newRes.updateSequenceNum = 0;
    ResourceTable restable(global.db);
    restable.add(lid, newRes, true, noteLid);

    emit(fileImported(noteLid, lid));

    if (scanType == FileWatcher::ImportDelete) {
        QLOG_DEBUG() << f.remove();
    }
}
Esempio n. 13
0
String String::format(const char *format, ...)
{
#if PLATFORM(QT)
    // Use QString::vsprintf to avoid the locale dependent formatting of vsnprintf.
    // https://bugs.webkit.org/show_bug.cgi?id=18994
    va_list args;
    va_start(args, format);

    QString buffer;
    buffer.vsprintf(format, args);

    va_end(args);

    QByteArray ba = buffer.toUtf8();
    return StringImpl::create(ba.constData(), ba.length());

#elif OS(WINCE)
    va_list args;
    va_start(args, format);

    Vector<char, 256> buffer;

    int bufferSize = 256;
    buffer.resize(bufferSize);
    for (;;) {
        int written = vsnprintf(buffer.data(), bufferSize, format, args);
        va_end(args);

        if (written == 0)
            return String("");
        if (written > 0)
            return StringImpl::create(buffer.data(), written);
        
        bufferSize <<= 1;
        buffer.resize(bufferSize);
        va_start(args, format);
    }

#else
    va_list args;
    va_start(args, format);

    Vector<char, 256> buffer;

    // Do the format once to get the length.
#if COMPILER(MSVC) && !PLATFORM(OLYMPIA)
    int result = _vscprintf(format, args);
#else
    char ch;
    int result = vsnprintf(&ch, 1, format, args);
    // We need to call va_end() and then va_start() again here, as the
    // contents of args is undefined after the call to vsnprintf
    // according to http://man.cx/snprintf(3)
    //
    // Not calling va_end/va_start here happens to work on lots of
    // systems, but fails e.g. on 64bit Linux.
    va_end(args);
    va_start(args, format);
#endif

    if (result == 0)
        return String("");
    if (result < 0)
        return String();
    unsigned len = result;
    buffer.grow(len + 1);
    
    // Now do the formatting again, guaranteed to fit.
    vsnprintf(buffer.data(), buffer.size(), format, args);

    va_end(args);
    
    return StringImpl::create(buffer.data(), len);
#endif
}
Esempio n. 14
0
static QString generateInterfaceXml(const QMetaObject *mo, int flags, int methodOffset, int propOffset)
{
    QString retval;

    // start with properties:
    if (flags & (QDBusConnection::ExportScriptableProperties |
                 QDBusConnection::ExportNonScriptableProperties)) {
        for (int i = propOffset; i < mo->propertyCount(); ++i) {
            static const char *accessvalues[] = {0, "read", "write", "readwrite"};

            QMetaProperty mp = mo->property(i);

            if (!((mp.isScriptable() && (flags & QDBusConnection::ExportScriptableProperties)) ||
                  (!mp.isScriptable() && (flags & QDBusConnection::ExportNonScriptableProperties))))
                continue;

            int access = 0;
            if (mp.isReadable())
                access |= 1;
            if (mp.isWritable())
                access |= 2;

            int typeId = qDBusNameToTypeId(mp.typeName());
            if (!typeId)
                continue;
            const char *signature = QDBusMetaType::typeToSignature(typeId);
            if (!signature)
                continue;

            retval += QString::fromLatin1("    <property name=\"%1\" type=\"%2\" access=\"%3\"")
                      .arg(QLatin1String(mp.name()))
                      .arg(QLatin1String(signature))
                      .arg(QLatin1String(accessvalues[access]));

            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName(QVariant::Type(typeId));
                retval += QString::fromLatin1(">\n      <annotation name=\"com.trolltech.QtDBus.QtTypeName\" value=\"%3\"/>\n    </property>\n")
                          .arg(typeNameToXml(typeName));
            } else {
                retval += QLatin1String("/>\n");
            }
        }
    }

    // now add methods:
    for (int i = methodOffset; i < mo->methodCount(); ++i) {
        QMetaMethod mm = mo->method(i);
        QByteArray signature = mm.signature();
        int paren = signature.indexOf('(');

        bool isSignal;
        if (mm.methodType() == QMetaMethod::Signal)
            // adding a signal
            isSignal = true;
        else if (mm.methodType() == QMetaMethod::Slot && mm.access() == QMetaMethod::Public)
            isSignal = false;
        else
            continue;           // neither signal nor public slot

        if (isSignal && !(flags & (QDBusConnection::ExportScriptableSignals |
                                   QDBusConnection::ExportNonScriptableSignals)))
            continue;           // we're not exporting any signals
        if (!isSignal && !(flags & (QDBusConnection::ExportScriptableSlots |
                                    QDBusConnection::ExportNonScriptableSlots)))
            continue;           // we're not exporting any slots

        QString xml = QString::fromLatin1("    <%1 name=\"%2\">\n")
                      .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"))
                      .arg(QLatin1String(signature.left(paren)));

        // check the return type first
        int typeId = qDBusNameToTypeId(mm.typeName());
        if (typeId) {
            const char *typeName = QDBusMetaType::typeToSignature(typeId);
            if (typeName) {
                xml += QString::fromLatin1("      <arg type=\"%1\" direction=\"out\"/>\n")
                       .arg(typeNameToXml(typeName));

                // do we need to describe this argument?
                if (QDBusMetaType::signatureToType(typeName) == QVariant::Invalid)
                    xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.Out0\" value=\"%1\"/>\n")
                           .arg(typeNameToXml(mm.typeName()));
            } else
                continue;
        }
        else if (*mm.typeName())
            continue;           // wasn't a valid type

        QList<QByteArray> names = mm.parameterNames();
        QList<int> types;
        int inputCount = qDBusParametersForMethod(mm, types);
        if (inputCount == -1)
            continue;           // invalid form
        if (isSignal && inputCount + 1 != types.count())
            continue;           // signal with output arguments?
        if (isSignal && types.at(inputCount) == QDBusMetaTypeId::message)
            continue;           // signal with QDBusMessage argument?
        if (isSignal && mm.attributes() & QMetaMethod::Cloned)
            continue;           // cloned signal?

        int j;
        bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
        for (j = 1; j < types.count(); ++j) {
            // input parameter for a slot or output for a signal
            if (types.at(j) == QDBusMetaTypeId::message) {
                isScriptable = true;
                continue;
            }

            QString name;
            if (!names.at(j - 1).isEmpty())
                name = QString::fromLatin1("name=\"%1\" ").arg(QLatin1String(names.at(j - 1)));

            bool isOutput = isSignal || j > inputCount;

            const char *signature = QDBusMetaType::typeToSignature(types.at(j));
            xml += QString::fromLatin1("      <arg %1type=\"%2\" direction=\"%3\"/>\n")
                   .arg(name)
                   .arg(QLatin1String(signature))
                   .arg(isOutput ? QLatin1String("out") : QLatin1String("in"));

            // do we need to describe this argument?
            if (QDBusMetaType::signatureToType(signature) == QVariant::Invalid) {
                const char *typeName = QVariant::typeToName( QVariant::Type(types.at(j)) );
                xml += QString::fromLatin1("      <annotation name=\"com.trolltech.QtDBus.QtTypeName.%1%2\" value=\"%3\"/>\n")
                       .arg(isOutput ? QLatin1String("Out") : QLatin1String("In"))
                       .arg(isOutput && !isSignal ? j - inputCount : j - 1)
                       .arg(typeNameToXml(typeName));
            }
        }

        int wantedMask;
        if (isScriptable)
            wantedMask = isSignal ? QDBusConnection::ExportScriptableSignals
                                  : QDBusConnection::ExportScriptableSlots;
        else
            wantedMask = isSignal ? QDBusConnection::ExportNonScriptableSignals
                                  : QDBusConnection::ExportNonScriptableSlots;
        if ((flags & wantedMask) != wantedMask)
            continue;

        if (qDBusCheckAsyncTag(mm.tag()))
            // add the no-reply annotation
            xml += QLatin1String("      <annotation name=\"" ANNOTATION_NO_WAIT "\""
                                 " value=\"true\"/>\n");

        retval += xml;
        retval += QString::fromLatin1("    </%1>\n")
                  .arg(isSignal ? QLatin1String("signal") : QLatin1String("method"));
    }

    return retval;
}
Esempio n. 15
0
QByteArray AES::encode(QByteArray &input, bool _encode)
{
    QByteArray output;
    uint _size = input.size();
    int STATE_SIZE = 16;

    switch(keyLength)
    {
        default:
        case B128: Nk = 4; Nr = 10; break;
        case B192: Nk = 6; Nr = 12; break;
        case B256: Nk = 8; Nr = 14; break;
    }

    uint8_t out[16];

    //input with padding
    uint8_t _in[16];

    uint8_t *in = reinterpret_cast<uint8_t *>(input.data());
    uint8_t *key = reinterpret_cast<uint8_t *>(aes_key.data());

    uint8_t *w = new uint8_t[ Nb * (Nr +  1) * 4 ];

    int offset = 0;

    key_expansion(key,  w);
    while(offset + STATE_SIZE <= _size)
    {
        if(_encode)
            cipher(in, out, w);
        else
            inv_cipher(in ,out, w);

        output.append(reinterpret_cast<const char *>(out), 16);

        in += STATE_SIZE;
        offset += STATE_SIZE;
    }

    int remains = _size - offset;

    // PKCS#7 padding (see http://tools.ietf.org/html/rfc5652#section-6.3) for details

    if(_encode)
    {
        for(int j = 0; j < STATE_SIZE ; j++)
        {
            if(j < remains)
            {
                _in[j] = in[j];
            }else{
                _in[j] = STATE_SIZE - remains;
            }
        }

        cipher(_in, out, w);
        output.append(reinterpret_cast<const char *>(out), 16);
    }

    if(_encode)
        output.resize(offset + STATE_SIZE);
    else
        output.resize(offset);
    delete [] w;
    return output;
}
Esempio n. 16
0
QByteArray AES::update_CFB(const QByteArray &input, bool _encode)
{
    uint8_t *in = (uint8_t*)(input.data());
    uint8_t *iv = reinterpret_cast<uint8_t *>(aes_iv.data());
    uint8_t *key = reinterpret_cast<uint8_t *>(aes_key.data());

    QByteArray output;
    uint _size = input.size();
    int STATE_SIZE = 16;
    int offset = 0;

    switch(keyLength)
    {
        default:
        case B128: Nk = 4; Nr = 10; break;
        case B192: Nk = 6; Nr = 12; break;
        case B256: Nk = 8; Nr = 14; break;
    }

    uint8_t *w = new uint8_t[ Nb * (Nr +  1) * 4 ];

    key_expansion(key,  w);

    uint8_t out[16];
    uint8_t xor_out[16];
    // for encode
    memcpy(xor_out, iv, sizeof(uint8_t) * STATE_SIZE);

    while(offset + STATE_SIZE <= _size)
    {
        if(_encode)
        {
            cipher(xor_out, out, w);
            XOR(out, in, STATE_SIZE, xor_out);
            output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);

            in += STATE_SIZE;
            offset += STATE_SIZE;
        }else{
            if(offset == 0)
            {
                cipher(iv, out, w);
                XOR(out, in, STATE_SIZE, xor_out);
                output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);
                offset += STATE_SIZE;
            }
            else
            {
                cipher(in, out, w);
                in += STATE_SIZE;
                XOR(out, in, STATE_SIZE, xor_out);
                output.append(reinterpret_cast<const char *>(xor_out), STATE_SIZE);
                offset += STATE_SIZE;
            }
        }
    }

    // cipher remains
    int remains = _size - offset;
    if(_encode){
        cipher(xor_out, out, w);
        XOR(out, in , remains , xor_out);
        output.append(reinterpret_cast<const char*>(xor_out), remains);
    }else{
        if(offset == 0)
        {
            cipher(iv, out, w);
            XOR(out, in, remains, xor_out);
            output.append(reinterpret_cast<const char*>(xor_out), remains);
        }else
        {
            cipher(in ,out ,w);
            in += STATE_SIZE;
            XOR(out, in , remains, xor_out);
            output.append(reinterpret_cast<const char*>(xor_out), remains);
        }

    }

    delete [] w;

    output.resize(_size);

    return output;
}
Esempio n. 17
0
void FileUploader::sendNext() {
	if (sentSize >= MaxUploadFileParallelSize || queue.isEmpty()) return;

	Queue::iterator i = uploading ? queue.find(uploading) : queue.begin();
	if (!uploading) {
		uploading = i.key();
	} else if (i == queue.end()) {
		i = queue.begin(); 
		uploading = i.key();
	}
	if (i->media.parts.isEmpty()) {
		if (i->docSentParts >= i->docPartsCount) {
			if (requestsSent.isEmpty() && docRequestsSent.isEmpty()) {
				if (i->media.type == ToPreparePhoto) {
					emit photoReady(uploading, MTP_inputFile(MTP_long(i->media.id), MTP_int(i->partsCount), MTP_string(i->media.filename), MTP_string(i->media.jpeg_md5)));
				} else if (i->media.type == ToPrepareDocument) {
					QByteArray docMd5(32, Qt::Uninitialized);
					hashMd5Hex(i->docHash.result(), docMd5.data());

					MTPInputFile doc = (i->docSize > UseBigFilesFrom) ? MTP_inputFileBig(MTP_long(i->media.id), MTP_int(i->docPartsCount), MTP_string(i->media.filename)) : MTP_inputFile(MTP_long(i->media.id), MTP_int(i->docPartsCount), MTP_string(i->media.filename), MTP_string(docMd5));
					if (i->partsCount) {
						emit thumbDocumentReady(uploading, doc, MTP_inputFile(MTP_long(i->media.jpeg_id), MTP_int(i->partsCount), MTP_string(i->media.filename), MTP_string(i->media.jpeg_md5)));
					} else {
						emit documentReady(uploading, doc);
					}
				}
				queue.remove(uploading);
				uploading = 0;
				sendNext();
			}
			return;
		}

		QByteArray toSend;
		if (i->media.data.isEmpty()) {
			if (!i->docFile) {
				i->docFile.reset(new QFile(i->media.file));
				if (!i->docFile->open(QIODevice::ReadOnly)) {
					currentFailed();
					return;
				}
			}
			toSend = i->docFile->read(i->docPartSize);
			if (i->docSize <= UseBigFilesFrom) {
				i->docHash.feed(toSend.constData(), toSend.size());
			}
		} else {
			toSend = i->media.data.mid(i->docSentParts * i->docPartSize, i->docPartSize);
		}
		if (toSend.size() > i->docPartSize || (toSend.size() < i->docPartSize && i->docSentParts + 1 != i->docPartsCount)) {
			currentFailed();
			return;
		}
		mtpRequestId requestId;
		if (i->docSize > UseBigFilesFrom) {
			requestId = MTP::send(MTPupload_SaveBigFilePart(MTP_long(i->media.id), MTP_int(i->docSentParts), MTP_int(i->docPartsCount), MTP_string(toSend)), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::upl);
		} else {
			requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(i->media.id), MTP_int(i->docSentParts), MTP_string(toSend)), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::upl);
		}
		docRequestsSent.insert(requestId, i->docSentParts);
		sentSize += i->docPartSize;

		i->docSentParts++;
	} else {
		LocalFileParts::iterator part = i->media.parts.begin();
	
		mtpRequestId requestId = MTP::send(MTPupload_SaveFilePart(MTP_long(i->media.jpeg_id), MTP_int(part.key()), MTP_string(part.value())), rpcDone(&FileUploader::partLoaded), rpcFail(&FileUploader::partFailed), MTP::upl);
		requestsSent.insert(requestId, part.value());
		sentSize += part.value().size();

		i->media.parts.erase(part);
	}
	nextTimer.start(UploadRequestInterval);
}
Esempio n. 18
0
/*!
    \internal
*/
bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
{
    Q_Q(QFSFileEngine);

    if (openMode & QIODevice::Unbuffered) {
        int flags = openModeToOpenFlags(openMode);

        // Try to open the file in unbuffered mode.
        do {
            fd = QT_OPEN(fileEntry.nativeFilePath().constData(), flags, 0666);
        } while (fd == -1 && errno == EINTR);

        // On failure, return and report the error.
        if (fd == -1) {
            q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                        qt_error_string(errno));
            return false;
        }

        if (!(openMode & QIODevice::WriteOnly)) {
            // we don't need this check if we tried to open for writing because then
            // we had received EISDIR anyway.
            if (QFileSystemEngine::fillMetaData(fd, metaData)
                    && metaData.isDirectory()) {
                q->setError(QFile::OpenError, msgOpenDirectory());
                QT_CLOSE(fd);
                return false;
            }
        }

        // Seek to the end when in Append mode.
        if (flags & QFile::Append) {
            int ret;
            do {
                ret = QT_LSEEK(fd, 0, SEEK_END);
            } while (ret == -1 && errno == EINTR);

            if (ret == -1) {
                q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                            qt_error_string(int(errno)));
                return false;
            }
        }

        fh = 0;
    } else {
        QByteArray fopenMode = openModeToFopenMode(openMode, fileEntry, metaData);

        // Try to open the file in buffered mode.
        do {
            fh = QT_FOPEN(fileEntry.nativeFilePath().constData(), fopenMode.constData());
        } while (!fh && errno == EINTR);

        // On failure, return and report the error.
        if (!fh) {
            q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                        qt_error_string(int(errno)));
            return false;
        }

        if (!(openMode & QIODevice::WriteOnly)) {
            // we don't need this check if we tried to open for writing because then
            // we had received EISDIR anyway.
            if (QFileSystemEngine::fillMetaData(QT_FILENO(fh), metaData)
                    && metaData.isDirectory()) {
                q->setError(QFile::OpenError, msgOpenDirectory());
                fclose(fh);
                return false;
            }
        }

        setCloseOnExec(fileno(fh)); // ignore failure

        // Seek to the end when in Append mode.
        if (openMode & QIODevice::Append) {
            int ret;
            do {
                ret = QT_FSEEK(fh, 0, SEEK_END);
            } while (ret == -1 && errno == EINTR);

            if (ret == -1) {
                q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError,
                            qt_error_string(int(errno)));
                return false;
            }
        }

        fd = -1;
    }

    closeFileHandle = true;
    return true;
}
Esempio n. 19
0
void RichTextHtmlEdit::insertFromMimeData(const QMimeData *source) {
	QString uri;
	QString title;
	QRegExp newline(QLatin1String("[\\r\\n]"));

#ifndef QT_NO_DEBUG
	qWarning() << "RichTextHtmlEdit::insertFromMimeData" << source->formats();
	foreach(const QString &format, source->formats())
		qWarning() << format << decodeMimeString(source->data(format));
#endif

	if (source->hasImage()) {
		QImage img = qvariant_cast<QImage>(source->imageData());
		QString html = Log::imageToImg(img);
		if (! html.isEmpty())
			insertHtml(html);
		return;
	}

	QString mozurl = decodeMimeString(source->data(QLatin1String("text/x-moz-url")));
	if (! mozurl.isEmpty()) {
		QStringList lines = mozurl.split(newline);
		qWarning() << mozurl << lines;
		if (lines.count() >= 2) {
			uri = lines.at(0);
			title = lines.at(1);
		}
	}

	if (uri.isEmpty())
		uri = decodeMimeString(source->data(QLatin1String("text/x-moz-url-data")));
	if (title.isEmpty())
		title = decodeMimeString(source->data(QLatin1String("text/x-moz-url-desc")));

	if (uri.isEmpty()) {
		QStringList urls;
#ifdef Q_OS_WIN
		urls = decodeMimeString(source->data(QLatin1String("application/x-qt-windows-mime;value=\"UniformResourceLocatorW\""))).split(newline);
		if (urls.isEmpty())
#endif
			urls = decodeMimeString(source->data(QLatin1String("text/uri-list"))).split(newline);
		if (! urls.isEmpty())
			uri = urls.at(0);
		uri = urls.at(0).trimmed();
	}

	if (uri.isEmpty()) {
		QUrl url(source->text(), QUrl::StrictMode);
		if (url.isValid() && ! url.isRelative()) {
			uri = url.toString();
		}
	}

#ifdef Q_OS_WIN
	if (title.isEmpty() && source->hasFormat(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""))) {
		QByteArray qba = source->data(QLatin1String("application/x-qt-windows-mime;value=\"FileGroupDescriptorW\""));
		if (qba.length() == sizeof(FILEGROUPDESCRIPTORW)) {
			const FILEGROUPDESCRIPTORW *ptr = reinterpret_cast<const FILEGROUPDESCRIPTORW *>(qba.constData());
			title = QString::fromWCharArray(ptr->fgd[0].cFileName);
			if (title.endsWith(QLatin1String(".url"), Qt::CaseInsensitive))
				title = title.left(title.length() - 4);
		}
	}
#endif

	if (! uri.isEmpty()) {
		if (title.isEmpty())
			title = uri;
		uri = Qt::escape(uri);
		title = Qt::escape(title);

		insertHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(uri, title));
		return;
	}

	QString html = decodeMimeString(source->data(QLatin1String("text/html")));
	if (! html.isEmpty()) {
		insertHtml(html);
		return;
	}

	QTextEdit::insertFromMimeData(source);
}
bool QgsDelimitedTextProvider::nextFeature( QgsFeature& feature )
{
  // before we do anything else, assume that there's something wrong with
  // the feature
  feature.setValid( false );
  while ( ! mStream->atEnd() )
  {
    double x = 0.0;
    double y = 0.0;
    QString line = mStream->readLine(); // Default local 8 bit encoding

    // lex the tokens from the current data line
    QStringList tokens;
    if ( mDelimiterType == "regexp" )
      tokens = line.split( mDelimiterRegexp );
    else
      tokens = line.split( mDelimiter );

    bool xOk = false;
    bool yOk = false;

    // Skip indexing malformed lines.
    if ( attributeFields.size() == tokens.size() )
    {
      x = tokens[mXFieldIndex].toDouble( &xOk );
      y = tokens[mYFieldIndex].toDouble( &yOk );
    }

    if ( !( xOk && yOk ) )
    {
      // Accumulate any lines that weren't ok, to report on them
      // later, and look at the next line in the file, but only if
      // we need to.
      QgsDebugMsg( "Malformed line : " + line );
      if ( mShowInvalidLines )
        mInvalidLines << line;

      continue;
    }

    // Give every valid line in the file an id, even if it's not
    // in the current extent or bounds.
    ++mFid;             // increment to next feature ID

    // skip the feature if it's out of current bounds
    if ( ! boundsCheck( x, y ) )
      continue;

    // at this point, one way or another, the current feature values
    // are valid
    feature.setValid( true );

    feature.setFeatureId( mFid );

    QByteArray  buffer;
    QDataStream s( &buffer, static_cast<QIODevice::OpenMode>( QIODevice::WriteOnly ) ); // open on buffers's data

    switch ( QgsApplication::endian() )
    {
      case QgsApplication::NDR :
        // we're on a little-endian platform, so tell the data
        // stream to use that
        s.setByteOrder( QDataStream::LittleEndian );
        s << ( quint8 )1; // 1 is for little-endian
        break;
      case QgsApplication::XDR :
        // don't change byte order since QDataStream is big endian by default
        s << ( quint8 )0; // 0 is for big-endian
        break;
      default :
        qDebug( "%s:%d unknown endian", __FILE__, __LINE__ );
        //delete [] geometry;
        return false;
    }

    s << ( quint32 )QGis::WKBPoint;
    s << x;
    s << y;

    unsigned char* geometry = new unsigned char[buffer.size()];
    memcpy( geometry, buffer.data(), buffer.size() );

    feature.setGeometryAndOwnership( geometry, sizeof( wkbPoint ) );

    for ( QgsAttributeList::const_iterator i = mAttributesToFetch.begin();
          i != mAttributesToFetch.end();
          ++i )
    {
      QVariant val;
      switch ( attributeFields[*i].type() )
      {
        case QVariant::Int:
          val = QVariant( tokens[*i].toInt() );
          break;
        case QVariant::Double:
          val = QVariant( tokens[*i].toDouble() );
          break;
        default:
          val = QVariant( tokens[*i] );
          break;
      }
      feature.addAttribute( *i, val );
    }

    // We have a good line, so return
    return true;

  } // ! textStream EOF

  // End of the file. If there are any lines that couldn't be
  // loaded, display them now.

  if ( mShowInvalidLines && !mInvalidLines.isEmpty() )
  {
    mShowInvalidLines = false;
    QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Error" ) );
    output->setMessage( tr( "Note: the following lines were not loaded because Qgis was "
                            "unable to determine values for the x and y coordinates:\n" ),
                        QgsMessageOutput::MessageText );

    output->appendMessage( "Start of invalid lines." );
    for ( int i = 0; i < mInvalidLines.size(); ++i )
      output->appendMessage( mInvalidLines.at( i ) );
    output->appendMessage( "End of invalid lines." );

    output->showMessage();

    // We no longer need these lines.
    mInvalidLines.empty();
  }

  return false;

} // nextFeature
Esempio n. 21
0
GCC_DIAG_UNUSED_PRIVATE_FIELD_OFF
//// /opt/local/include/QtGui/qmime.h:119:10: warning: private field 'type' is not used [-Wunused-private-field]
#include <QKeyEvent>
GCC_DIAG_UNUSED_PRIVATE_FIELD_ON
#include <QtCore/QCoreApplication>
#include <QApplication>
#include <QHBoxLayout> // in QtGui on Qt4, in QtWidgets on Qt5
#include <QVBoxLayout> // in QtGui on Qt4, in QtWidgets on Qt5
#include <QtCore/QThread>
#include <QtCore/QSettings>
#include <QtCore/QDebug>

#include "Engine/AppManager.h" // appPTR
#include "Engine/Knob.h"
#include "Engine/Utils.h" // convertFromPlainText

#include "Gui/AnimationModuleBase.h"
#include "Gui/AnimationModuleSelectionModel.h"
#include "Gui/AnimationModuleView.h"
#include "Gui/DialogButtonBox.h"
#include "Gui/LineEdit.h" // LineEdit
#include "Gui/SpinBox.h" // SpinBox
#include "Gui/Button.h" // Button
#include "Gui/SequenceFileDialog.h" // SequenceFileDialog
#include "Gui/GuiApplicationManager.h"
#include "Gui/Label.h" // Label
#include "Gui/AnimationModuleUndoRedo.h"

NATRON_NAMESPACE_ENTER

ImportExportCurveDialog::ImportExportCurveDialog(bool isExportDialog,
                                                 const std::vector<CurveGuiPtr > & curves,
                                                 Gui* gui,
                                                 QWidget* parent)
    : QDialog(parent)
    , _gui(gui)
    , _isExportDialog(isExportDialog)
    , _mainLayout(0)
    , _fileContainer(0)
    , _fileLayout(0)
    , _fileLabel(0)
    , _fileLineEdit(0)
    , _fileBrowseButton(0)
    , _startContainer(0)
    , _startLayout(0)
    , _startLabel(0)
    , _startLineEdit(0)
    , _incrContainer(0)
    , _incrLayout(0)
    , _incrLabel(0)
    , _incrLineEdit(0)
    , _endContainer(0)
    , _endLayout(0)
    , _endLabel(0)
    , _endLineEdit(0)
    , _curveColumns()
    , _buttonBox(0)
{
    // always running in the main thread
    assert( qApp && qApp->thread() == QThread::currentThread() );

    bool integerIncrement = false;
    double xstart = -std::numeric_limits<double>::infinity();
    double xend = std::numeric_limits<double>::infinity();
    for (size_t i = 0; i < curves.size(); ++i) {
        integerIncrement |= curves[i]->areKeyFramesTimeClampedToIntegers();
        std::pair<double,double> xrange = curves[i]->getInternalCurve()->getXRange();
        xstart = std::max(xstart, xrange.first);
        xend = std::min(xend, xrange.second);
    }
    if (xstart == -std::numeric_limits<double>::infinity()) {
        xstart = std::min(0., xend - 1.);
    }
    if (xend == std::numeric_limits<double>::infinity()) {
        xend = std::max(xstart + 1., 1.);
    }
    _mainLayout = new QVBoxLayout(this);
    _mainLayout->setContentsMargins(0, TO_DPIX(3), 0, 0);
    _mainLayout->setSpacing(TO_DPIX(2));
    setLayout(_mainLayout);

    //////File
    _fileContainer = new QWidget(this);
    _fileLayout = new QHBoxLayout(_fileContainer);
    _fileLabel = new Label(tr("File:"), _fileContainer);
    _fileLayout->addWidget(_fileLabel);
    _fileLineEdit = new LineEdit(_fileContainer);
    _fileLineEdit->setPlaceholderText( tr("File path...") );
    _fileLineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    _fileLayout->addWidget(_fileLineEdit);
    _fileBrowseButton = new Button(_fileContainer);
    QPixmap pix;
    appPTR->getIcon(NATRON_PIXMAP_OPEN_FILE, &pix);
    _fileBrowseButton->setIcon( QIcon(pix) );
    QObject::connect( _fileBrowseButton, SIGNAL(clicked()), this, SLOT(open_file()) );
    _fileLayout->addWidget(_fileBrowseButton);
    _mainLayout->addWidget(_fileContainer);

    //////x start value
    _startContainer = new QWidget(this);
    _startLayout = new QHBoxLayout(_startContainer);
    _startLabel = new Label(tr("X start value:"), _startContainer);
    _startLayout->addWidget(_startLabel);
    _startLineEdit = new LineEdit(_startContainer);
    _startLineEdit->setText(QString::number(xstart,'g',10));
    _startLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X of the first value in the ASCII file. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
    _startLayout->addWidget(_startLineEdit);
    _mainLayout->addWidget(_startContainer);

    //////x increment
    _incrContainer = new QWidget(this);
    _incrLayout = new QHBoxLayout(_incrContainer);
    _incrLabel = new Label(tr("X increment:"), _incrContainer);
    _incrLayout->addWidget(_incrLabel);
    _incrLineEdit = new LineEdit(_incrContainer);
    if (xstart == 0. && xend == 1.) {
        _incrLineEdit->setText(QString::fromUtf8("1./255"));
    } else {
        _incrLineEdit->setText(QString::number(1));
    }
    _incrLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X increment between two consecutive values. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
    _incrLayout->addWidget(_incrLineEdit);
    _mainLayout->addWidget(_incrContainer);

    //////x end value
    if (isExportDialog) {
        _endContainer = new QWidget(this);
        _endLayout = new QHBoxLayout(_endContainer);
        _endLabel = new Label(tr("X end value:"), _endContainer);
        _endLabel->setFont( QApplication::font() ); // necessary, or the labels will get the default font size
        _endLayout->addWidget(_endLabel);
        _endLineEdit = new LineEdit(_endContainer);
        _endLineEdit->setText(QString::number(xend,'g',10));
        _incrLineEdit->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("The X of the last value in the ASCII file. This can be a python expression."), NATRON_NAMESPACE::WhiteSpaceNormal) );
        _endLayout->addWidget(_endLineEdit);
        _mainLayout->addWidget(_endContainer);
    }

    ////curves columns
    for (U32 i = 0; i < curves.size(); ++i) {
        CurveColumn column;
        column._curve = curves[i];
        column._curveContainer = new QWidget(this);
        column._curveLayout = new QHBoxLayout(column._curveContainer);
        column._curveLabel = new Label( tr("%1 column:").arg( curves[i]->getName() ) );
        column._curveLabel->setFont( QApplication::font() ); // necessary, or the labels will get the default font size
        column._curveLayout->addWidget(column._curveLabel);
        column._curveSpinBox = new SpinBox(column._curveContainer, SpinBox::eSpinBoxTypeInt);
        column._curveSpinBox->setValue( (double)i + 1. );
        column._curveLayout->addWidget(column._curveSpinBox);
        _curveColumns.push_back(column);
        _mainLayout->addWidget(column._curveContainer);
    }
    /////buttons
    _buttonBox = new DialogButtonBox(QDialogButtonBox::StandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel), Qt::Horizontal, this);
    QObject::connect( _buttonBox, SIGNAL(rejected()), this, SLOT(reject()) );
    QObject::connect( _buttonBox, SIGNAL(accepted()), this, SLOT(accept()) );
    _mainLayout->addWidget(_buttonBox);

    QSettings settings( QString::fromUtf8(NATRON_ORGANIZATION_NAME), QString::fromUtf8(NATRON_APPLICATION_NAME) );
    QByteArray state;
    if (isExportDialog) {
        state = settings.value( QLatin1String("CurveWidgetExportDialog") ).toByteArray();
    } else {
        state = settings.value( QLatin1String("CurveWidgetImportDialog") ).toByteArray();
    }
    if ( !state.isEmpty() ) {
        restoreState(state);
    }
}
Esempio n. 22
0
inline void KNMusicLyricsDownloader::networkProcess(int type,
                                                    const QString &url,
                                                    QByteArray &responseData,
                                                    const QByteArray &parameter,
                                                    const QVariant &cookie,
                                                    const QString &referer)
{
    //Stop the timer.
    m_timeout->stop();
    //Clear the data first.
    responseData.clear();
    m_networkManager->clearAccessCache();
    //Generate the request.
    QNetworkRequest currentRequest;
    //Set the data to request.
    currentRequest.setUrl(QUrl(url));
    if(!cookie.isNull())
    {
        currentRequest.setHeader(QNetworkRequest::CookieHeader,
                                 cookie);
    }
    if(!referer.isEmpty())
    {
        currentRequest.setRawHeader("Referer", referer.toStdString().data());
        currentRequest.setRawHeader("Origin", referer.toStdString().data());
    }
    //Generate the reply and quit handler.
    QNetworkReply *currentReply=nullptr;
    KNConnectionHandler quiterHandle;
    //Wait for response, using the event loop, generate the loop.
    QEventLoop stuckWaitingLoop;
    //Link the finished and timeout counter to quit loop.
    quiterHandle+=connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
                          &stuckWaitingLoop, SLOT(quit()));
    quiterHandle+=connect(m_timeout, SIGNAL(timeout()),
                          &stuckWaitingLoop, SLOT(quit()));
    //Do GET.
    switch(type)
    {
    case Post:
    {
        currentRequest.setHeader(QNetworkRequest::ContentTypeHeader,
                                 "application/x-www-form-urlencoded");
        currentRequest.setHeader(QNetworkRequest::ContentLengthHeader,
                                 parameter.size());
        currentReply=m_networkManager->post(currentRequest, parameter);
        break;
    }
    case Get:
    {
        currentReply=m_networkManager->get(currentRequest);
        break;
    }
    }
    //Start counting.
    m_timeout->start();
    //Start loop.
    stuckWaitingLoop.exec();
    //Disconnect all the links.
    quiterHandle.disconnectAll();
    //Check if there's reply.
    if(currentReply==nullptr)
    {
        return;
    }
    //Get the data.
    responseData=currentReply->readAll();
    //Clear the reply.
    delete currentReply;
}
Esempio n. 23
0
void KJavaAppletServer::slotJavaRequest( const QByteArray& qb )
{
    // qb should be one command only without the length string,
    // we parse out the command and it's meaning here...
    QString cmd;
    QStringList args;
    int index = 0;
    const int qb_size = qb.size();

    //get the command code
    const char cmd_code = qb[ index++ ];
    ++index; //skip the next sep

    //get contextID
    QString contextID;
    while( qb[index] != 0 && index < qb_size )
    {
        contextID += qb[ index++ ];
    }
    bool ok;
    const int ID_num = contextID.toInt( &ok ); // context id or kio job id
    /*if (d->locked_context > -1 &&
        ID_num != d->locked_context &&
        (cmd_code == KJAS_JAVASCRIPT_EVENT ||
         cmd_code == KJAS_APPLET_STATE ||
         cmd_code == KJAS_APPLET_FAILED))
    {
        / * Don't allow requests from other contexts if we're waiting
         * on a return value that can trigger JavaScript events
         * /
        d->java_requests.push_back(qb);
        return;
    }*/
    ++index; //skip the sep

    if (cmd_code == KJAS_PUT_DATA) {
        // rest of the data is for kio put
        if (ok) {
            KIOJobMap::iterator it = d->kiojobs.find( ID_num );
            if (ok && it != d->kiojobs.end()) {
                QByteArray qba;
                qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1);
                it.value()->data(qba);
                qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1);
            }
            kDebug(6100) << "PutData(" << ID_num << ") size=" << qb.size() - index;
        } else
            kError(6100) << "PutData error " << ok << endl;
        return;
    }
    //now parse out the arguments
    while( index < qb_size )
    {
        int sep_pos = qb.indexOf( (char) 0, index );
        if (sep_pos < 0) {
            kError(6100) << "Missing separation byte" << endl;
            sep_pos = qb_size;
        }
        //kDebug(6100) << "KJavaAppletServer::slotJavaRequest: "<< QString::fromLocal8Bit( qb.data() + index, sep_pos - index );
        args.append( QString::fromLocal8Bit( qb.data() + index, sep_pos - index ) );
        index = sep_pos + 1; //skip the sep
    }
    //here I should find the context and call the method directly
    //instead of emitting signals
    switch( cmd_code )
    {
        case KJAS_SHOW_DOCUMENT:
            cmd = QLatin1String( "showdocument" );
            break;

        case KJAS_SHOW_URLINFRAME:
            cmd = QLatin1String( "showurlinframe" );
            break;

        case KJAS_SHOW_STATUS:
            cmd = QLatin1String( "showstatus" );
            break;

        case KJAS_RESIZE_APPLET:
            cmd = QLatin1String( "resizeapplet" );
            break;

        case KJAS_GET_URLDATA:
            if (ok && !args.empty() ) {
                d->kiojobs.insert(ID_num, new KJavaDownloader(ID_num, args.first()));
                kDebug(6100) << "GetURLData(" << ID_num << ") url=" << args.first();
            } else
                kError(6100) << "GetURLData error " << ok << " args:" << args.size() << endl;
            return;
        case KJAS_PUT_URLDATA:
            if (ok && !args.empty()) {
                KJavaUploader* const job = new KJavaUploader(ID_num, args.first());
                d->kiojobs.insert(ID_num, job);
                job->start();
                kDebug(6100) << "PutURLData(" << ID_num << ") url=" << args.first();
            } else
                kError(6100) << "PutURLData error " << ok << " args:" << args.size() << endl;
            return;
        case KJAS_DATA_COMMAND:
            if (ok && !args.empty()) {
                const int cmd = args.first().toInt( &ok );
                KIOJobMap::iterator it = d->kiojobs.find( ID_num );
                if (ok && it != d->kiojobs.end())
                    it.value()->jobCommand( cmd );
                kDebug(6100) << "KIO Data command: " << ID_num << " " << args.first();
            } else
                kError(6100) << "KIO Data command error " << ok << " args:" << args.size() << endl;
            return;
        case KJAS_JAVASCRIPT_EVENT:
            cmd = QLatin1String( "JS_Event" );

            if(!args.empty()) {
                 kDebug(6100) << "Javascript request: "<< contextID
                              << " code: " << args[0] << endl;
            } else {
                kError(6100) << "Expected args not to be empty!" << endl;
            }

            break;
        case KJAS_GET_MEMBER:
        case KJAS_PUT_MEMBER:
        case KJAS_CALL_MEMBER: {
            if(!args.empty()) {
                const int ticket = args[0].toInt();
                JSStack::iterator it = d->jsstack.find(ticket);
                if (it != d->jsstack.end()) {
                    kDebug(6100) << "slotJavaRequest: " << ticket;
                    args.pop_front();
                    it.value()->args.operator=(args); // just in case ..
                    it.value()->ready = true;
                    it.value()->exit = true;
                } else
                    kDebug(6100) << "Error: Missed return member data";
            } else {
                kError(6100) << "Expected args not to be empty!" << endl;
            }
            return;
        }
        case KJAS_AUDIOCLIP_PLAY:
            cmd = QLatin1String( "audioclip_play" );
            if(!args.empty())
                kDebug(6100) << "Audio Play: url=" << args[0];
            else
                kError(6100) << "Expected args not to be empty!" << endl;

            break;
        case KJAS_AUDIOCLIP_LOOP:
            cmd = QLatin1String( "audioclip_loop" );
            if(!args.empty())
                kDebug(6100) << "Audio Loop: url=" << args[0];
            else
                kError(6100) << "Expected args not to be empty!" << endl;

            break;
        case KJAS_AUDIOCLIP_STOP:
            cmd = QLatin1String( "audioclip_stop" );
            if(!args.empty())
                kDebug(6100) << "Audio Stop: url=" << args[0];
            else
                kError(6100) << "Expected args not to be empty!" << endl;

            break;
        case KJAS_APPLET_STATE:
            if(args.size() > 1)
                kDebug(6100) << "Applet State Notification for Applet " << args[0] << ". New state=" << args[1];
            else
                kError(6100) << "Expected args not to be empty!" << endl;

            cmd = QLatin1String( "AppletStateNotification" );
            break;
        case KJAS_APPLET_FAILED:
            if(args.size() > 1)
                kDebug(6100) << "Applet " << args[0] << " Failed: " << args[1];
            else
                kError(6100) << "Expected args not to be empty!" << endl;

            cmd = QLatin1String( "AppletFailed" );
            break;
        case KJAS_SECURITY_CONFIRM: {
            if (KSSL::doesSSLWork() && !d->kssl)
                d->kssl = new KSSL;
            QStringList sl;
            QString answer( "invalid" );

            if (!d->kssl) {
                answer = "nossl";
            } else if (args.size() > 2) {
                const int certsnr = args[1].toInt();
                Q_ASSERT(args.size() > certsnr + 1);
                QString text;
                QList<KSSLCertificate *> certs;
                for (int i = certsnr - 1; i >= 0; --i) {
                    const QByteArray &arg = args[i + 2].toAscii();
                    KSSLCertificate * cert = KSSLCertificate::fromString(arg.constData());
                    if (cert) {
                        certs.prepend(cert);
                        if (cert->isSigner())
                            text += i18n("Signed by (validation: %1)", KSSLCertificate::verifyText(cert->validate()));
                        else
                            text += i18n("Certificate (validation: %1)", KSSLCertificate::verifyText(cert->validate()));
                        text += "\n";
                        QString subject = cert->getSubject() + QChar('\n');
                        QRegExp reg(QString("/[A-Z]+="));
                        int pos = 0;
                        while ((pos = subject.indexOf(reg, pos)) > -1)
                            subject.replace(pos, 1, QString("\n    "));
                        text += subject.mid(1);
                    }
                }
                kDebug(6100) << "Security confirm " << args.first() << certs.count();
                if ( !certs.isEmpty() ) {
                    KSSLCertChain chain;
                    chain.setChain( certs );
                    if ( chain.isValid() )
                        answer = PermissionDialog( qApp->activeWindow() ).exec( text, args[0] );
                }
                qDeleteAll(certs);
            }
            sl.push_front( answer );
            sl.push_front( QString::number(ID_num) );
            process->send( KJAS_SECURITY_CONFIRM, sl );
            return;
        }
        default:
            return;
            break;
    }


    if( !ok )
    {
        kError(6100) << "could not parse out contextID to call command on" << endl;
        return;
    }

    KJavaAppletContext* const context = d->contexts[ ID_num ];
    if( context )
        context->processCmd( cmd, args );
    else if (cmd != "AppletStateNotification")
        kError(6100) << "no context object for this id" << endl;
}
Esempio n. 24
0
void UPnpSearchTask::SendMsg( MSocketDevice  *pSocket,
                              QString         sST,
                              QString         sUDN )
{
    QString sUSN;

    if (( sUDN.length() > 0) && ( sUDN != sST ))
        sUSN = sUDN + "::" + sST;
    else
        sUSN = sST;

    QString sDate = MythDate::current().toString( "d MMM yyyy hh:mm:ss" );

    QString sData = QString ( "CACHE-CONTROL: max-age=%1\r\n"
                              "DATE: %2\r\n"
                              "EXT:\r\n"
                              "Server: %3\r\n"
                              "ST: %4\r\n"
                              "USN: %5\r\n"
                              "Content-Length: 0\r\n\r\n" )
                              .arg( m_nMaxAge    )
                              .arg( sDate )
                              .arg( HttpServer::GetServerVersion() )
                              .arg( sST )
                              .arg( sUSN );

#if 0
    LOG(VB_UPNP, LOG_DEBUG, QString("UPnpSearchTask::SendMsg : %1 : %2 ")
                        .arg(sST) .arg(sUSN));

    LOG(VB_UPNP, LOG_DEBUG,
        QString("UPnpSearchTask::SendMsg    m_PeerAddress = %1 Port=%2")
                        .arg(m_PeerAddress.toString()) .arg(m_nPeerPort));
#endif

    for ( QStringList::Iterator it  = m_addressList.begin(); 
                                it != m_addressList.end(); 
                              ++it ) 
    {
        QString ipaddress = *it;

        // If this looks like an IPv6 address, then enclose it in []'s
        if (ipaddress.contains(":"))
            ipaddress = "[" + ipaddress + "]";

        QString sHeader = QString ( "HTTP/1.1 200 OK\r\n"
                                    "LOCATION: http://%1:%2/getDeviceDesc\r\n" )
                            .arg( ipaddress )
                            .arg( m_nServicePort);


        QString  sPacket  = sHeader + sData;
        QByteArray scPacket = sPacket.toUtf8();

        // ------------------------------------------------------------------
        // Send Packet to UDP Socket (Send same packet twice)
        // ------------------------------------------------------------------

        pSocket->writeBlock( scPacket, scPacket.length(), m_PeerAddress,
                             m_nPeerPort );
        usleep( random() % 250000 );
        pSocket->writeBlock( scPacket, scPacket.length(), m_PeerAddress,
                             m_nPeerPort );
    }
}
Esempio n. 25
0
QList<HeaderPath> GccToolChain::gccHeaderPaths(const Utils::FileName &gcc, const QStringList &env, const QString &sysrootPath)
{
    QList<HeaderPath> systemHeaderPaths;
    QStringList arguments;
    if (!sysrootPath.isEmpty())
        arguments.append(QString::fromLatin1("--sysroot=%1").arg(sysrootPath));
    arguments << QLatin1String("-xc++")
              << QLatin1String("-E")
              << QLatin1String("-v")
              << QLatin1String("-");

    QByteArray line;
    QByteArray data = runGcc(gcc, arguments, env);
    QBuffer cpp(&data);
    cpp.open(QIODevice::ReadOnly);
    while (cpp.canReadLine()) {
        line = cpp.readLine();
        if (line.startsWith("#include"))
            break;
    }

    if (!line.isEmpty() && line.startsWith("#include")) {
        HeaderPath::Kind kind = HeaderPath::UserHeaderPath;
        while (cpp.canReadLine()) {
            line = cpp.readLine();
            if (line.startsWith("#include")) {
                kind = HeaderPath::GlobalHeaderPath;
            } else if (! line.isEmpty() && QChar(QLatin1Char(line.at(0))).isSpace()) {
                HeaderPath::Kind thisHeaderKind = kind;

                line = line.trimmed();

                const int index = line.indexOf(" (framework directory)");
                if (index != -1) {
                    line.truncate(index);
                    thisHeaderKind = HeaderPath::FrameworkHeaderPath;
                }

                systemHeaderPaths.append(HeaderPath(QFile::decodeName(line), thisHeaderKind));
            } else if (line.startsWith("End of search list.")) {
                break;
            } else {
                qWarning("%s: Ignoring line: %s", __FUNCTION__, line.constData());
            }
        }
    }
    return systemHeaderPaths;
}
Esempio n. 26
0
void WLQuery::Process()
{
    if (!Configuration::HuggleConfiguration->GlobalConfig_Whitelist.size())
    {
        // there is no whitelist in config for this wiki
        Syslog::HuggleLogs->ErrorLog("Unable to process WL request, there is no whitelist server defined");
        this->Result = new QueryResult();
        this->Result->ErrorMessage = "Invalid URL";
        this->Result->Failed = true;
        this->Status = Huggle::StatusInError;
        return;
    }
    this->StartTime = QDateTime::currentDateTime();
    this->Status = StatusProcessing;
    this->Result = new QueryResult();
    QUrl url(Configuration::HuggleConfiguration->GlobalConfig_Whitelist
             + "?action=read&wp="
             + Configuration::HuggleConfiguration->Project->WhiteList);
    switch (this->Type)
    {
        case WLQueryType_ReadWL:
            break;
        case WLQueryType_SuspWL:
            url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist +
                       "susp.php?action=insert&" + this->Parameters);
            break;
        case WLQueryType_WriteWL:
            url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist + "?action=save&user="******"huggle_" + Configuration::HuggleConfiguration->SystemConfig_Username) +
                      "&wp=" + Configuration::HuggleConfiguration->Project->WhiteList);
            break;
    }
    QString params = "";
    QByteArray data;
    if (this->Type == WLQueryType_WriteWL)
    {
        QString whitelist = "";
        int p = 0;
        while (p < Configuration::HuggleConfiguration->NewWhitelist.count())
        {
            if (Configuration::HuggleConfiguration->NewWhitelist.at(p) != "")
            {
                whitelist += Configuration::HuggleConfiguration->NewWhitelist.at(p) + "|";
            }
            p++;
        }
        if (whitelist.endsWith("|"))
        {
            whitelist = whitelist.mid(0, whitelist.length() - 1);
        }
        whitelist += "||EOW||";
        params = "wl=" + QUrl::toPercentEncoding(whitelist);
        data = params.toUtf8();
        long size = (long)data.size();
        Syslog::HuggleLogs->DebugLog("Sending whitelist data of size: " + QString::number(size) + " byte");
    }
    QNetworkRequest request(url);
    if (this->Type == WLQueryType_ReadWL)
    {
        this->r = Query::NetworkManager->get(request);
    } else
    {
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        this->r = Query::NetworkManager->post(request, data);
    }
    QObject::connect(this->r, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
    QObject::connect(this->r, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
    QObject::connect(this->r, SIGNAL(finished()), this, SLOT(Finished()));
    QObject::connect(this->r, SIGNAL(readyRead()), this, SLOT(ReadData()));
}
Esempio n. 27
0
/*!
    Returns a string representation of the \a field value for the
    database. This is used, for example, when constructing INSERT and
    UPDATE statements.

    The default implementation returns the value formatted as a string
    according to the following rules:

    \list

    \li If \a field is character data, the value is returned enclosed
    in single quotation marks, which is appropriate for many SQL
    databases. Any embedded single-quote characters are escaped
    (replaced with two single-quote characters). If \a trimStrings is
    true (the default is false), all trailing whitespace is trimmed
    from the field.

    \li If \a field is date/time data, the value is formatted in ISO
    format and enclosed in single quotation marks. If the date/time
    data is invalid, "NULL" is returned.

    \li If \a field is \l{QByteArray}{bytearray} data, and the
    driver can edit binary fields, the value is formatted as a
    hexadecimal string.

    \li For any other field type, toString() is called on its value
    and the result of this is returned.

    \endlist

    \sa QVariant::toString()

*/
QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const
{
    const QLatin1String nullTxt("NULL");

    QString r;
    if (field.isNull())
        r = nullTxt;
    else {
        switch (field.type()) {
        case QVariant::Int:
        case QVariant::UInt:
            if (field.value().type() == QVariant::Bool)
                r = field.value().toBool() ? QLatin1String("1") : QLatin1String("0");
            else
                r = field.value().toString();
            break;
#ifndef QT_NO_DATESTRING
	case QVariant::Date:
            if (field.value().toDate().isValid())
                r = QLatin1Char('\'') + field.value().toDate().toString(Qt::ISODate)
                    + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::Time:
            if (field.value().toTime().isValid())
                r =  QLatin1Char('\'') + field.value().toTime().toString(Qt::ISODate)
                     + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::DateTime:
            if (field.value().toDateTime().isValid())
                r = QLatin1Char('\'') +
                    field.value().toDateTime().toString(Qt::ISODate) + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
#endif
        case QVariant::String:
        case QVariant::Char:
        {
            QString result = field.value().toString();
            if (trimStrings) {
                int end = result.length();
                while (end && result.at(end-1).isSpace()) /* skip white space from end */
                    end--;
                result.truncate(end);
            }
            /* escape the "'" character */
            result.replace(QLatin1Char('\''), QLatin1String("''"));
            r = QLatin1Char('\'') + result + QLatin1Char('\'');
            break;
        }
        case QVariant::Bool:
            r = QString::number(field.value().toBool());
            break;
        case QVariant::ByteArray : {
            if (hasFeature(BLOB)) {
                QByteArray ba = field.value().toByteArray();
                QString res;
                static const char hexchars[] = "0123456789abcdef";
                for (int i = 0; i < ba.size(); ++i) {
                    uchar s = (uchar) ba[i];
                    res += QLatin1Char(hexchars[s >> 4]);
                    res += QLatin1Char(hexchars[s & 0x0f]);
                }
                r = QLatin1Char('\'') + res +  QLatin1Char('\'');
                break;
            }
        }
        default:
            r = field.value().toString();
            break;
        }
    }
    return r;
}
Esempio n. 28
0
//
// Update Headpose in Game.
//
void FTNServer::sendHeadposeToGame() {
int no_bytes;
QHostAddress sender;
quint16 senderPort;

	//
	// Create UDP-sockets if they don't exist already.
	// They must be created here, because they must be in the Tracker thread (Tracker::run())
	//
	if (inSocket == 0) {
		qDebug() << "FTNServer::sendHeadposeToGame creating sockets";
		inSocket = new QUdpSocket();
		// Connect the inSocket to the port, to receive messages
		if (!inSocket->bind(QHostAddress::Any, destPort+1)) {
			qDebug() << "FTNServer::writePendingDatagrams says: unable to bind inSocket!";
			delete inSocket;
			inSocket = 0;
		}
	}

	if (outSocket == 0) {
		outSocket = new QUdpSocket();
	}

	//
	// Copy the Raw measurements directly to the client.
	//
	TestData.x = virtPosX;
	TestData.y = virtPosY;
	TestData.z = virtPosZ;
	TestData.pitch = virtRotX;
	TestData.yaw = virtRotY;
	TestData.roll = virtRotZ;

	//
	// Try to send an UDP-message to the receiver
	//

	//! [1]
	no_bytes = outSocket->writeDatagram((const char *) &TestData, sizeof( TestData ), destIP, destPort);
	if ( no_bytes > 0) {
//		qDebug() << "FTNServer::writePendingDatagrams says: bytes send =" << no_bytes << sizeof( double );
	}
	else {
		qDebug() << "FTNServer::writePendingDatagrams says: nothing sent!";
	}

	//
	// Receiver may send data, so we must read that here.
	//
	if (inSocket != 0) {
		while (inSocket->hasPendingDatagrams()) {

			QByteArray datagram;
			datagram.resize(inSocket->pendingDatagramSize());

			inSocket->readDatagram( (char * ) &cmd, sizeof(cmd), &sender, &senderPort);

			fg_cmd = cmd;									// Let's just accept that command for now...
			if ( cmd > 0 ) {
				qDebug() << "FTNServer::sendHeadposeToGame hasPendingDatagrams, cmd = " << cmd;
				headTracker->handleGameCommand ( cmd );		// Send it upstream, for the Tracker to handle
			}
		}
	}
}
Esempio n. 29
-1
bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) ||  bytes.contains( "301 Moved" ) )
      {
        return true;
      }
    }
  }

  return false;
}
Esempio n. 30
-3
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
    if (PaymentServer::certStore == NULL)
        atexit(PaymentServer::freeCertStore);
    else
        freeCertStore();

    // Unit tests mostly use this, to pass in fake root CAs:
    if (_store)
    {
        PaymentServer::certStore = _store;
        return;
    }

    // Normal execution, use either -rootcertificates or system certs:
    PaymentServer::certStore = X509_STORE_new();

    // Note: use "-system-" default here so that users can pass -rootcertificates=""
    // and get 'I don't like X.509 certificates, don't trust anybody' behavior:
    QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));

    if (certFile.isEmpty())
        return; // Empty store

    QList<QSslCertificate> certList;

    if (certFile != "-system-")
    {
        certList = QSslCertificate::fromPath(certFile);
        // Use those certificates when fetching payment requests, too:
        QSslSocket::setDefaultCaCertificates(certList);
    }
    else
        certList = QSslSocket::systemCaCertificates ();

    int nRootCerts = 0;
    const QDateTime currentTime = QDateTime::currentDateTime();
    foreach (const QSslCertificate& cert, certList)
    {
        if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
            ReportInvalidCertificate(cert);
            continue;
        }
#if QT_VERSION >= 0x050000
        if (cert.isBlacklisted()) {
            ReportInvalidCertificate(cert);
            continue;
        }
#endif
        QByteArray certData = cert.toDer();
        const unsigned char *data = (const unsigned char *)certData.data();

        X509* x509 = d2i_X509(0, &data, certData.size());
        if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
        {
            // Note: X509_STORE_free will free the X509* objects when
            // the PaymentServer is destroyed
            ++nRootCerts;
        }
        else
        {
            ReportInvalidCertificate(cert);
            continue;
        }
    }
    qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";

    // Project for another day:
    // Fetch certificate revocation lists, and add them to certStore.
    // Issues to consider:
    //   performance (start a thread to fetch in background?)
    //   privacy (fetch through tor/proxy so IP address isn't revealed)
    //   would it be easier to just use a compiled-in blacklist?
    //    or use Qt's blacklist?
    //   "certificate stapling" with server-side caching is more efficient
}