void test_setFromRawData()
	{
		char rawData[] = "hello world!";

		QByteArray ba;
		QByteArray::DataPtr oldDataPtr = ba.data_ptr();
		ba.setRawData(rawData, 5);
		QVERIFY(oldDataPtr != ba.data_ptr());
		oldDataPtr = ba.data_ptr();
		ba.setRawData(rawData + 6, 5);
		// Start using QByteArray::setRawData directly if the following QVERIFY fails.
		// This would mean that the QByteArray::setRawData behavior has been changed to the
		// desired one where switching from one raw data to another does not cause a
		// QByteArray data block reallocation. Qt5 maybe?
		QVERIFY(oldDataPtr != ba.data_ptr());

		// Go ahead and do tests on our replacement setFromRawData.
		ba = QByteArray();
		oldDataPtr = ba.data_ptr();
		QVERIFY(ba.data_ptr()->ref > 1); // Should be the multi-referenced shared null.
		Pillow::ByteArrayHelpers::setFromRawData(ba, rawData, 0, 5);
		QVERIFY(ba.data_ptr() != oldDataPtr);
		QVERIFY(ba.data_ptr()->ref == 1);
		QVERIFY(rawData[5] != '\0');
		QCOMPARE(ba, QByteArray("hello"));

		// Calling out setFromRawData on a string that is already detached should not reallocate the
		// QByteArray data block, as opposed to QByteArray::setRawData.
		oldDataPtr = ba.data_ptr();
		Pillow::ByteArrayHelpers::setFromRawData(ba, rawData, 6, 5);
		QVERIFY(ba.data_ptr() == oldDataPtr);
		QVERIFY(ba.data_ptr()->ref == 1);
		QVERIFY(rawData[11] != '\0');
		QCOMPARE(ba, QByteArray("world"));
	}
QByteArray CryptData::encode(QString& txt, QString password)
{

    if (lib_init == 0) {
        return password.toUtf8();
    }

    DATA_BLOB DataIn;
    QByteArray passwordArray{password.toUtf8()};
    DataIn.pbData = (BYTE*)passwordArray.data();
    DataIn.cbData = passwordArray.size() + 1;

    DATA_BLOB Entropy;
    QByteArray txtArray{txt.toUtf8()};
    Entropy.pbData = (BYTE*)txtArray.data();
    Entropy.cbData = txtArray.size() + 1;


    DATA_BLOB DataOut;
    QByteArray res;
    BOOL r = pCryptProtectData(&DataIn, NULL, &Entropy, NULL, NULL, 0, &DataOut);
    if (r == false) {
        return res;
    }

    QByteArray data;
    data.setRawData((const char*)DataOut.pbData, DataOut.cbData);

    res.clear();
    res.append("xxxx");
    res.append(data.toBase64());

    LocalFree(DataOut.pbData);
    return res;
}
Beispiel #3
0
void UTPex::handlePexPacket(const Uint8* packet,Uint32 size)
{
    if (size <= 2 || packet[1] != 1)
        return;

    QByteArray tmp;
    tmp.setRawData((const char*)packet,size);
    BNode* node = 0;
    try
    {
        BDecoder dec(tmp,false,2);
        node = dec.decode();
        if (node && node->getType() == BNode::DICT)
        {
            BDictNode* dict = (BDictNode*)node;

            // ut_pex packet, emit signal to notify PeerManager
            BValueNode* val = dict->getValue("added");
            if (val)
            {
                QByteArray data = val->data().toByteArray();
                peer->emitPex(data);
            }
        }
    }
    catch (...)
    {
        // just ignore invalid packets
        Out(SYS_CON|LOG_DEBUG) << "Invalid extended packet" << endl;
    }
    delete node;
    tmp.resetRawData((const char*)packet,size);
}
Beispiel #4
0
void ClsIqrGUI::createAnimation() {
    QFrame *qframeSpace = new QFrame(qtoolbarToolbar);
    qtoolbarToolbar->setStretchableWidget ( qframeSpace );


    QFrame *qframeAnimation = new QFrame(qtoolbarToolbar);
    QPalette palette;
    palette.setColor(qframeAnimation->backgroundRole(), QColor(255,0,0));
    qframeAnimation->setPalette(palette);
    

    qframeAnimation->setFixedWidth(30);
    qlblStatus = new QLabel(qframeAnimation, "animation");

#ifdef USE_MEMARRAY_LOGO
    QByteArray qbaMoview;
    qbaMoview.setRawData( movie_data, sizeof(movie_data) );
    qlblStatus->setMovie(QMovie(qbaMoview));
#else
    QString filename = "/usr/lib/iqr/iqr-logo.gif";
    if(QFile::exists(filename)){
	qlblStatus->setMovie(QMovie(filename));
    }
#endif

    if(qlblStatus->movie()!=NULL){
	qlblStatus->movie()->pause();
	qlblStatus->movie()->step();
    }
}
void DisplayRenderer::sendDisplayData(QImage im1, QImage im2)
{
	qDebug() << "sending data for displays";
	
	PC2TB_PACKET outPacket;

	// pack tha packet:
	outPacket.magicNumber1 = MAGIC_NUMBER1;
	outPacket.magicNumber2 = MAGIC_NUMBER2;
	outPacket.packetVersion = PACKET_VERSION;
	QTime midnight(0,0);
    int time_ms = midnight.msecsTo(MainWindow::app()->getTimeBaseTime());
	uint32_t time_100us = 10*time_ms;
	outPacket.pcTime_100us = time_100us;
	
	// ALGE text
	memcpy(outPacket.algeText, algeText().toAscii().data(), ALGE_TEXT_LEN);
	
	genMatrixData(im1, 1, outPacket.matrixData1);
	genMatrixData(im2, 2, outPacket.matrixData2);
	
	outPacket.matrixDataValid=1;
	
	outPacket.cmdReceiver=COMMAND_INVALID_RECEIVER;
	outPacket.command=COMMAND_INVALID_CMD;
	
	outPacket.crc = CRC8_run((uint8_t*)(&outPacket), (uint16_t)(sizeof(PC2TB_PACKET)-1));

	QByteArray datagram;
	datagram.setRawData((char*)(&outPacket), sizeof(PC2TB_PACKET));
	
	emit sendDatagram(datagram);
}
Beispiel #6
0
QString datastream_control::m4_getpkt() {
  m4_lock.lock();
  QByteArray t;
  t.setRawData((char *)construct_mode4 +3,12);
  QString out = t.toHex();
  out.toUpper();
  m4_lock.unlock();
  return out;
}
Beispiel #7
0
void Loader::slotRetrieverDone(const QByteArray &data, bool success)
{
   d->lastError = d->retriever->errorCode();

   delete d->retriever;
   d->retriever = NULL;

   Document rssDoc;
   Status status = Success;

   if (success) {
      QDomDocument doc;

      /* Some servers insert whitespace before the <?xml...?> declaration.
       * QDom doesn't tolerate that (and it's right, that's invalid XML),
       * so we strip that.
       */

      const char *charData = data.data();
      int len = data.count();

      while (len && QChar(*charData).isSpace()) {
         --len;
         ++charData;
      }

      if ( len > 3 && QChar(*charData) == QChar(0357) ) { // 0357 0273 0277
			  len -= 3;
			  charData += 3;
	  }
      QByteArray tmpData;
      tmpData.setRawData(charData, len);

      if (doc.setContent(tmpData))
      {
         rssDoc = Document(doc);
         if (!rssDoc.isValid())
         {
            discoverFeeds(tmpData);
            status = ParseError;
         }
      }
      else
      {
         discoverFeeds(tmpData);
         status = ParseError;
      }

      tmpData.resetRawData(charData, len);
   } else
      status = RetrieveError;

   emit loadingComplete(this, rssDoc, status);

   delete this;
}
Beispiel #8
0
void kio_afpProtocol::get(const KURL& url )
{
    kdDebug(7101) << "\n\nget " << url.prettyURL() << endl;
    struct afp_url afp_url;
    int ret;
    unsigned int fileid;
    unsigned long long total=0;
    QString resumeOffset = metaData("resume");
    // bool ok;
    // struct stat stat;
    // KIO::fileoffset_t offset = resumeOffset.toLongLong(&ok);

    QString kafpurl = url.url(0,0);
    afp_default_url(&afp_url);
    afp_parse_url(&afp_url,kafpurl,0);

    if (attachvolume(&afp_url)==false) {
    kdDebug(7101) << "could not attach for get of " << url.prettyURL() << endl;
       finished();
       return;
    }

    ret=afp_sl_open(NULL,NULL,&afp_url, &fileid,0);


#if 0

    char buffer[GET_DATA_SIZE];
    QByteArray array;
    

    while (eof==0) {
       ret = afp_sl_read(&connection,&volid,fileid,0,
               offset, GET_DATA_SIZE,&received,&eof,buffer);

       array.setRawData(buffer,received);
       data(array);
       array.resetRawData(buffer,received);

       total+=received;
       offset=total;
    }


    infoMessage( i18n( "Retrieving %1 from %2...") 
      .arg(KIO::convertSize(retreived)) .arg(afp_url.servername));


#endif

    totalSize(total);

    ret=afp_sl_close(&volumeid,fileid);

}
Beispiel #9
0
bool NoSqlDatabase::fetch(const QString &key, QByteArray &data)
{
    qDebug() << "Fetching data" << key;
    ::std::string value;
    if( ! m_db->Get(leveldb::ReadOptions(), key.toStdString(), &value).ok() ) {
        qDebug() << "Data not found" << key;
        return false;
    }

    data.setRawData(value.c_str(), value.size());
    data.detach();
    return true;
}
bool QPixmap::loadFromData( const uchar *buf, uint len, const char *format,
			    int conversion_flags )
{
    QByteArray a;
    a.setRawData( (char *)buf, len );
    QBuffer b( a );
    b.open( IO_ReadOnly );
    QImageIO io( &b, format );
    bool result = io.read();
    b.close();
    a.resetRawData( (char *)buf, len );
    if ( result ) {
	detach();
	result = convertFromImage( io.image(), conversion_flags );
    }
    return result;
}
Beispiel #11
0
Id::Id(const char *name)
{
    static uint firstUnusedId = 1;

    static QByteArray temp;
    temp.setRawData(name, qstrlen(name));                           // avoid copying data

    StringHash sh(temp);

    int id = idFromString.value(sh, 0);

    if (id == 0) {
        id = firstUnusedId++;
        sh.string = QByteArray(temp.constData(), temp.length());    // copy
        idFromString.insert(sh, id);
        stringFromId.insert(id, sh);
    }

    mId = id;
}
Beispiel #12
0
bool CoverUtils::coverFromXiphComment(TagLib::Ogg::XiphComment *xiphComment, Album *album) {

    if (!xiphComment) return false;

    const TagLib::StringList &stringList = xiphComment->fieldListMap()["COVERART"];
    if (stringList.isEmpty()) return false;
    TagLib::ByteVector byteVector = stringList.front().data(TagLib::String::Latin1);

    QByteArray encodedData;
    encodedData.setRawData(byteVector.data(), byteVector.size());

    QByteArray data = QByteArray::fromBase64(encodedData);

    QImage image;
    image.loadFromData(data);
    if (!isAcceptableImage(image)) return false;

    qDebug() << "Cover from Xiph!";

    return saveImage(image, album);
}
void Client::OnMReceive() {
    const auto byteCount = receiveSocket_->bytesAvailable();

    //new a buffer

    char buf[byteCount];

    const auto readCount = receiveSocket_->readDatagram(buf, byteCount );

    QByteArray ba;
    ba.setRawData( buf, readCount );

    QDataStream so(&ba, QIODevice::ReadOnly);

    int width;
    int height;
    int top;
    QPixmap newMap;

    so >> width >> height >> top >> newMap;
    //update the contents
    pcv_->redrawPixmap( width, height, top, newMap );
}
void DialogTimeStampGenerator2::on_pushButton_clicked()
{
	static TB2PC_PACKET p;
	static ALIVE_PACKET ap;

	p.magicNumber1 = MAGIC_NUMBER1;
	p.magicNumber2 = MAGIC_NUMBER2;

	p.packetVersion = ui->lineEdit_packetVersion->text().toInt();
	p.batteryVoltageTB = ui->lineEdit_batteryVoltageTB->text().toInt();
	p.triggerStationID = ui->comboBox_triggerStationID->itemData(ui->comboBox_triggerStationID->currentIndex()).toInt();
	p.binRssiTS = ui->lineEdit_binRssiTS->text().toInt();

	QTime t0(0,0,0);
	ap.triggerTimeBB = t0.msecsTo(ui->timeEdit_triggerTimeBB->time())*10;
	ap.triggerTimeTS_L = t0.msecsTo(ui->timeEdit_triggerTimeTS_L->time())*10;
	ap.triggerTimeTS_R = t0.msecsTo(ui->timeEdit_triggerTimeTS_R->time())*10;
	ap.batteryVoltageTS = ui->lineEdit_batteryVoltageTS->text().toInt();
	ap.batteryVoltageBB = ui->lineEdit_batteryVoltageBB->text().toInt();
	ap.boatBoxID = ui->comboBox_boatBoxID->itemData(ui->comboBox_boatBoxID->currentIndex()).toInt();
	ap.binRssiBB = ui->lineEdit_binRssiBB->text().toInt();
	ap.stationTriggeredAt = ui->comboBox_stationTriggeredAt->itemData(ui->comboBox_stationTriggeredAt->currentIndex()).toInt();

	p.tsPacket = ap;

	p.baseTime_100us = t0.msecsTo(ui->timeEdit_baseTime->time())*10;

	p.crc = CRC8_run((uint8_t*)(&p), sizeof(p)-1);

	//printPacket(p);

	QByteArray datagram;
	datagram.setRawData((char*)(&p), sizeof(p));

	QUdpSocket* udpSocket = new QUdpSocket(this);
	udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, UDP_LISTEN_PORT);
}
Beispiel #15
0
QByteArray KoStore::read( unsigned long int max )
{
  QByteArray data; // Data is a QArray<char>

  if ( !m_bIsOpen )
  {
    kdWarning(s_area) << "KoStore: You must open before reading" << endl;
    data.resize( 0 );
    return data;
  }
  if ( m_mode != Read )
  {
    kdError(s_area) << "KoStore: Can not read from store that is opened for writing" << endl;
    data.resize( 0 );
    return data;
  }

  if ( m_stream->atEnd() )
  {
    data.resize( 0 );
    return data;
  }

  if ( max > m_iSize - m_stream->at() )
    max = m_iSize - m_stream->at();
  if ( max == 0 )
  {
    data.resize( 0 );
    return data;
  }

  char *p = new char[ max ];
  m_stream->readBlock( p, max );

  data.setRawData( p, max );
  return data;
}
Beispiel #16
0
void QWebcamServer::run()
{    
    qDebug() << tr("Webcam Server Thread started");

    // >>>>> Frame compression parameters
    vector<int> params;
    params.push_back(CV_IMWRITE_JPEG_QUALITY);
    params.push_back(85);
    // <<<<< Frame compression parameters

    quint8 frameCount = 0;

    // >>>>> Thread Initialization
    mUdpSocketSender = new QUdpSocket();
    // Multicast on the subnet
    mUdpSocketSender->setSocketOption( QAbstractSocket::MulticastTtlOption, 1 );

    mUdpSocketReceiver = new QUdpSocket();
    mUdpSocketReceiver->bind( mListenPort, QUdpSocket::ShareAddress );

    connect( mUdpSocketReceiver, SIGNAL(readyRead()),
             this, SLOT(onReadyRead() ) );

    mStopped = false;
    // <<<<< Thread Initialization

    cv::Mat frame;
    vector<uchar> compressed;

    setPriority( QThread::TimeCriticalPriority );

    // >>>>> Thread Loop
    forever
    {
        // Waiting between loops according to FPS
        double sleepMsec = 1000.0/((double)mFps);

        QTime chrono;
        chrono.start();

        mStopMutex.lock();
        {
            if( mStopped )
            {
                mStopMutex.unlock();
                break;
            }
        }
        mStopMutex.unlock();

        if( !mWebcamConnected )
            mWebcamConnected = connectWebcam();

        if(mWebcamConnected)
            mCap >> frame;
        else
        {
            int h = mDefImage.height();
            int w = mDefImage.width();

            cv::Mat img( h, w, CV_8UC3, mDefImage.bits() );
            frame = img.clone();
        }

        frameCount++;

        //qDebug() << tr( "Frame %1").arg( frameCount );

#ifdef WIN32
        if( !frame.empty() )
        {
            cv::imshow( "Frame", frame );
        }
#endif

        //QTime chrono_elab;
        //chrono_elab.start();
        // JPG Compression in memory
        if( !frame.empty() )
        {
            cv::imencode( ".jpg", frame, compressed, params );

            // >>>>> UDP Sending
            QByteArray fullDatagram;
            fullDatagram.setRawData( (char*)compressed.data(), compressed.size() );

            sendFragmentedData( fullDatagram, frameCount );
            // <<<<< UDP Sending
        }
        //qDebug() << tr("Elaboration time: %1 msec").arg(chrono_elab.elapsed());

        QCoreApplication::processEvents( QEventLoop::AllEvents, 1 );

        int elapsed = chrono.elapsed();
        //qDebug() << tr("Elapsed: %1 msec").arg(elapsed);

        int sleep = sleepMsec - elapsed;

       // >>>>> FPS auto-tuning
        // Note FPS are tuned such to give to client at 10msec between
        // two consecutive frames
        double oldFps = mFps;
        if( sleep<0 )
        {
            mFps -= 1.0;

        }
        else if( sleep<1 )
        {
            mFps -= 0.05;
            if( mFps<MIN_FPS )
                mFps = MIN_FPS;
        }
        else if( sleep>3 )
        {
            mFps += 0.05;
            if( mFps>MAX_FPS )
                mFps = MAX_FPS;
        }

        if( mFps!=oldFps )
            qDebug() << PREFIX << tr("New FPS %1 (Sleep: %2)").arg(mFps).arg(sleep);
        // <<<<< FPS auto-tuning

        if( sleep>0 )
            msleep(sleep);


        //qDebug() << QTime::currentTime().toString("hh:mm:ss.zzz") << tr("Wait: %1msec").arg(wait);
    }
Beispiel #17
0
/* ---------------------------------------------------------------------------------- */
void ChmProtocol::get( const KURL& url )
{
    /** When :catalog is appended to the end, a plain-text representation of the catalog
      * is given out where each entry consists of four lines, an integer representing the parent
      * of the node, an integer representing a node's ID, the Title of the Node, and it's hyperlink.
      * When :contents is appended, all contained htm- and html-files will be printed, each in a line.
      */
    kdDebug() << "kio_chm::get(const KURL& url) " << url.path() << endl;

    bool catalog = false;
    bool contents = false;
    QString bigpath = url.path();

    if(bigpath.endsWith(":catalog")) {
        catalog = true;
        int len = QString(":catalog").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    if(bigpath.endsWith(":contents")) {
        contents = true;
        int len = QString(":contents").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    QString path;
    if ( !checkNewFile( bigpath, path ) ) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }


    if (m_dirMap.find(path) == m_dirMap.end()) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }

    QByteArray theData;

    //init..
    //added by lucida [email protected]
    QString fname = QString();
    QString chmpath = QString();
    KTempFile f("",".html");
    fname = f.name();
    QTextStream *t = f.textStream();
    QString firstPage = QString("");
    QString m_strIndex = QString("");
    QString tmpstr = QString("");
    bool m_bIndex = 0;


    if(contents) {
        QString output;
        KURL u = url;

        ChmDirectoryMap::Iterator it;
        for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
            u.setPath(bigpath);
            u.addPath(it.key());
            output += u.prettyURL() + "\n";
        }

        data(output.local8Bit());
        processedSize(output.length());
        finished();
        return;
    }


    //try get some page to display, if the chm missing index
    ChmDirectoryMap::Iterator it;
    for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
        tmpstr.sprintf("%s", it.key().latin1());
        if ((m_strIndex == "") &&
                (tmpstr.endsWith(".htm") || tmpstr.endsWith(".html")))
            m_strIndex = tmpstr;
        if ((tmpstr == "/index.htm") || (tmpstr == "/index.html")) {
            m_strIndex = tmpstr;
            break;
        }
    }
    m_strIndex.remove(0,1);


    if (path == "/" || catalog) {
        bool htmlOutput = !catalog;
        int offset = m_dirMap["/@contents"].offset;
        int length = m_dirMap["/@contents"].length;
        theData.setRawData(&m_contents[offset], length);
        QString s(theData);
        QString output;

        QRegExp object("<OBJECT type=\"text/sitemap\">(.*)</OBJECT>", false);
        object.setMinimal(true);

        QRegExp nameParam("<param name=\"Name\" value=\"(.*)\">", false);
        nameParam.setMinimal(true);

        QRegExp localParam("<param name=\"Local\" value=\"(.*)\">", false);
        localParam.setMinimal(true);

        QRegExp mergeParam("<param name=\"Merge\" value=\"(.*)\">", false);
        mergeParam.setMinimal(true);

        std::stack<int> parents;
        int counter = 1;
        int current = 0;
        int old = 0, pos = 0;
        parents.push(0);
        while ((pos = s.find(object, pos)) != -1) {
            if(htmlOutput) output += s.mid(old, pos - old);
            if(catalog) {
                QRegExp ex("<UL>|</UL>", false);
                ex.setMinimal(true);
                QString ms = s.mid(old, pos - old);
                int pos = 0;
                while( (pos = ms.find(ex, pos)) != -1) {
                    if(ms.mid(pos, 4) == "<UL>") {
                        parents.push(current);
                    } else {
                        if(parents.empty()) {
                        } else {
                            current = parents.top();
                            parents.pop();
                        }
                    }
                    pos++;
                }
            }
            pos += object.matchedLength();
            old = pos;
            QString obj = object.cap(1);
            QString name, local;
            if (obj.find(nameParam) != -1) {
                name = nameParam.cap(1);
                if (obj.find(localParam) != -1) {
                    local = localParam.cap(1);
                    //output += "<a href=\"" + local + "\">" + name + "</a>";
                    //added by lucida [email protected]
                    if (local != "" && local != "/") {
                        if(!catalog) {
                            output += "<a target=\"browse\" href=\"" + url.url() + local + "\">" + name + "</a>";
                        } else {
                            current = counter;
                            ++counter;
                            KURL u = url;
                            u.setPath(bigpath + local);
                            QString str;
                            output += str.sprintf("%i\n%i\n", parents.top(), current);
                            output += name + "\n" + u.prettyURL() + "\n";
                        }
                        m_bIndex = 1;
                        if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
                    }
                    else if(htmlOutput) output += name;
                } else {
                    if(htmlOutput) output += name;
                }
            }
            if (obj.find(mergeParam) != -1 && htmlOutput) {
                QString link = mergeParam.cap(1);
                QString href = link.left(link.find("::"));
                QString path = m_chmFile.left(m_chmFile.findRev("/") + 1);
                //output += " (<a href=\"" + path + href + "\">link</a>)";
                m_bIndex = 1;
                output += " (<a target=\"browse\" href=\"" + url.url() + path + href + "\">link</a>)";
                if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
            }
        }
        if(htmlOutput) output += s.mid(old);

        //set left pane
        //added by lucida, [email protected]
        QString lframe = QString("</HEAD><FRAMESET COLS=\"25%,*\">\n");
        lframe += "<FRAME NAME=\"index\" src=\"file:"+ fname+"\"" + " marginwidth=\"0\"></FRAME>\n";
        if (!m_bIndex) {
            lframe = "</HEAD><FRAMESET>";
            firstPage = url.url() + QString::fromLocal8Bit(m_strIndex.latin1());
        }
        theData.resetRawData(&m_contents[offset], length);
        //KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( output, path );
        //kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        //mimeType( result->mimeType() );
        /*        QCString output1 = (QCString)(output.latin1());
                data(output1);
                processedSize(output1.length());*/

        //construct the frame
        //added by lucida [email protected]
        QString framestr = QString("<HTML><HEAD>\n");
        framestr += lframe;
        framestr += "<FRAME NAME=\"browse\" src=\"" + firstPage + "\">\n";
        framestr += "</FRAME>\n";
        framestr += "</FRAMESET></HTML>";
        //write index file
        //added by lucida [email protected]
        *t << QString::fromLocal8Bit(output.latin1()) << endl;

        if(catalog) {
            data(output.local8Bit());
            processedSize(output.length());
        } else {
            data(framestr.local8Bit());
            processedSize(framestr.length());
        }
    } else {
        int offset = m_dirMap[path].offset;
        int length = m_dirMap[path].length;
        totalSize(length);
        theData.setRawData(&m_contents[offset], length);

        KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( theData, path );
        kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        mimeType( result->mimeType() );
        data(theData);
        theData.resetRawData(&m_contents[offset], length);
        processedSize(length);
    }

    finished();
}
Beispiel #18
0
bool LDIFConverter::LDIFToAddressee( const QString &str, AddresseeList &addrList, QDateTime dt )
{
  if (str.isEmpty())
     return true;

  bool endldif = false, end = false;
  LDIF ldif;
  LDIF::ParseVal ret;
  const char *latinstr = str.latin1();
  int latinstrlen = qstrlen( latinstr );
  QByteArray data;
  Addressee a;
  Address homeAddr, workAddr;

  data.setRawData( latinstr, latinstrlen );
  ldif.setLDIF( data );
  if (!dt.isValid())
    dt = QDateTime::currentDateTime();
  a.setRevision(dt);
  homeAddr = Address( Address::Home );
  workAddr = Address( Address::Work );

  do {
    ret = ldif.nextItem();
    switch ( ret ) {
      case LDIF::Item: {
        QString fieldname = ldif.attr().lower();
        QString value = QString::fromUtf8( ldif.val(), ldif.val().size() );
        evaluatePair( a, homeAddr, workAddr, fieldname, value );
        break;
      }
      case LDIF::EndEntry:
      // if the new address is not empty, append it
        if ( !a.formattedName().isEmpty() || !a.name().isEmpty() ||
          !a.familyName().isEmpty() ) {
          if ( !homeAddr.isEmpty() )
            a.insertAddress( homeAddr );
          if ( !workAddr.isEmpty() )
            a.insertAddress( workAddr );
          addrList.append( a );
        }
        a = Addressee();
        a.setRevision(dt);
        homeAddr = Address( Address::Home );
        workAddr = Address( Address::Work );
        break;
      case LDIF::MoreData: {
        if ( endldif )
          end = true;
        else {
          ldif.endLDIF();
          endldif = true;
          break;
        }
      }
      default:
        break;
    }
  } while ( !end );

  data.resetRawData( latinstr, latinstrlen );

  return true;
}
 virtual void getContactData(QByteArray& contactCardData) const override
 {
   contactCardData.setRawData (Data.body.data(), Data.body.size());
 }
Beispiel #20
0
//----------------------------------------------------------------
QVariant AbifReader::fromDir(const AbifDir &dir)
{
    // Try to unserialize all data ! Not sure if all is working
    // Check specification from http://www6.appliedbiosystems.com/support/software_community/ABIF_File_Format.pdf

    //debugDir(dir);
    QByteArray part;


    if (dir.dataSize<=4){

        int val = dir.dataOffset;
        val = __bswap_32(val);
        char * data = (char*)&val;
        part.setRawData(data,dir.dataSize);

    }
    else {
        mDevice->seek(dir.dataOffset);
        part = mDevice->read(dir.dataSize);

    }

    QDataStream stream(part);
    stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
    stream.setByteOrder(QDataStream::BigEndian);



    //-----------------------------------------------
    if (Type(dir.elementType) == CString ) // 19
    {
        part.chop(1);
        return QString(part);
    }
    //-----------------------------------------------

    if (Type(dir.elementType) == PString ) // 18
    {
        part.remove(0,1);
        return QString(part);
    }

    //-----------------------------------------------

    if (Type(dir.elementType) == Word ) // 3
        return QString(part);
    //-----------------------------------------------

    if (Type(dir.elementType) == Char ) // 2
        return QString(part);
    //-----------------------------------------------

    if (Type(dir.elementType) == Short ) // 4
    {
        QVariantList list;
        qint16 v;

        if (dir.name == "Scal")
        {
            qDebug()<<dir.elementsize;
        }

        while (!stream.atEnd())
        {

            stream >> v;
            list.append(v);
        }

        return reduce(list);
    }
Beispiel #21
0
void HelpProtocol::get_file(const KURL &url)
{
    kdDebug(7119) << "get_file " << url.url() << endl;

    QCString _path(QFile::encodeName(url.path()));
    struct stat buff;
    if(::stat(_path.data(), &buff) == -1)
    {
        if(errno == EACCES)
            error(KIO::ERR_ACCESS_DENIED, url.path());
        else
            error(KIO::ERR_DOES_NOT_EXIST, url.path());
        return;
    }

    if(S_ISDIR(buff.st_mode))
    {
        error(KIO::ERR_IS_DIRECTORY, url.path());
        return;
    }
    if(S_ISFIFO(buff.st_mode) || S_ISSOCK(buff.st_mode))
    {
        error(KIO::ERR_CANNOT_OPEN_FOR_READING, url.path());
        return;
    }

    int fd = open(_path.data(), O_RDONLY);
    if(fd < 0)
    {
        error(KIO::ERR_CANNOT_OPEN_FOR_READING, url.path());
        return;
    }

    totalSize(buff.st_size);
    int processed_size = 0;

    char buffer[MAX_IPC_SIZE];
    QByteArray array;

    while(1)
    {
        int n = ::read(fd, buffer, MAX_IPC_SIZE);
        if(n == -1)
        {
            if(errno == EINTR)
                continue;
            error(KIO::ERR_COULD_NOT_READ, url.path());
            close(fd);
            return;
        }
        if(n == 0)
            break; // Finished

        array.setRawData(buffer, n);
        data(array);
        array.resetRawData(buffer, n);

        processed_size += n;
        processedSize(processed_size);
    }

    data(QByteArray());

    close(fd);

    processedSize(buff.st_size);

    finished();
}
Beispiel #22
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("ptparse");
    QCoreApplication::setApplicationVersion("0.1");
    QCommandLineParser parser;

    parser.setApplicationDescription("Extract Intel PT data from perf.data AUX buffer");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("perf.data", "path to perf.data file");

    parser.process(app);
    const QStringList args = parser.positionalArguments();

    QString perfData = "perf.data";
    QString ptFileName = "extracted.pt";

    /* Custom path, if needed */
    if (args.size() > 0) {
        perfData = args.at(0);  /* Input perf.data file */
        ptFileName = args.at(1);    /* Extracted PT file */
    }

    QFile file(perfData);
    if (file.open(QFile::ReadOnly)) {
        uchar *buf = file.map(0, file.size());
        QString str(QByteArray{(char *)buf, 8});

        struct perf_file_header* perfHead;
        perfHead = (struct perf_file_header*) buf;

        //qDebug() << QString("%1").arg(perfHead->data.offset, 0, 16);
        //qDebug() << QString("%1").arg(perfHead->data.size, 0, 16);

        int pos = perfHead->data.offset;

        fflush(stderr);

        int prev_pos = 0;
        //qDebug() << "file size:" << file.size();

        while (pos < file.size()) {

            struct perf_event_header *h = (struct perf_event_header *) (buf + pos);

            switch(h->type) {

            case PERF_RECORD_AUXTRACE:
            {
                struct auxtrace_event *aux = (struct auxtrace_event *) (buf + pos);

                if (aux->size == 0)
                    break;

                QByteArray baba;

                /* Skip 48 bytes of auxtrace_event struct also */
                char *ptData = (char *) (buf + pos) + sizeof(struct auxtrace_event);

                baba.setRawData(ptData, aux->size);
                QString extn = QString::number(aux->cpu); /* Extension is AUX buf's CPU */

                /* Write per-CPU files */
                QFile ptFile(ptFileName + "." + extn);
                //qDebug() << ptFile.fileName();
                ptFile.open(QIODevice::WriteOnly | QIODevice::Append);
                ptFile.write(baba);
                ptFile.close();

                /* Advance pos by AUX size */
                pos += aux->size;

                /* Advance pos by event size */
                pos += h->size;
            }
                break;

            default:
                /* Advance pos by event size */
                pos += h->size;
                break;
            }

            /* TODO: Investigate further and make sure what the extra bytes are just before header
             * starts. Refer https://twitter.com/tuxology/status/742701706572668928
             *
             * If event size is 0, assume we are not an event and bail out. Usually always happens
             * just after some PERF_RECORD_FINISHED_ROUND events right before the perf header at
             * the end of perf.data
             */

            if (prev_pos == pos)
                return 0;
            prev_pos = pos;

        }
    }
    return 0;
}
Beispiel #23
0
//===========================================================================
void SMBSlave::get( const KURL& kurl )
{
    char        buf[MAX_XFER_BUF_SIZE];
    int         filefd          = 0;
    ssize_t     bytesread       = 0;
    // time_t      curtime         = 0;
    time_t      lasttime        = 0;
    time_t      starttime       = 0;
    KIO::filesize_t totalbytesread  = 0;
    QByteArray  filedata;
    SMBUrl      url;

    kdDebug(KIO_SMB) << "SMBSlave::get on " << kurl << endl;

    // check (correct) URL
    KURL kvurl = checkURL(kurl);
    // if URL is not valid we have to redirect to correct URL
    if (kvurl != kurl) {
        redirection(kvurl);
        finished();
        return;
    }

    if(!auth_initialize_smbc())
        return;


    // Stat
    url = kurl;
    if(cache_stat(url,&st) == -1 )
    {
        if ( errno == EACCES )
           error( KIO::ERR_ACCESS_DENIED, url.prettyURL());
        else
           error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL());
        return;
    }
    if ( S_ISDIR( st.st_mode ) ) {
        error( KIO::ERR_IS_DIRECTORY, url.prettyURL());
        return;
    }

    // Set the total size
    totalSize( st.st_size );

    // Open and read the file
    filefd = smbc_open(url.toSmbcUrl(),O_RDONLY,0);
    if(filefd >= 0)
    {
        if(buf)
        {
	    bool isFirstPacket = true;
            lasttime = starttime = time(NULL);
            while(1)
            {
                bytesread = smbc_read(filefd, buf, MAX_XFER_BUF_SIZE);
                if(bytesread == 0)
                {
                    // All done reading
                    break;
                }
                else if(bytesread < 0)
                {
                    error( KIO::ERR_COULD_NOT_READ, url.prettyURL());
                    return;
                }

                filedata.setRawData(buf,bytesread);
		if (isFirstPacket)
		{
                    // We need a KMimeType::findByNameAndContent(filename,data)
                    // For now we do: find by extension, and if not found (or extension not reliable)
                    // then find by content.
                    bool accurate = false;
                    KMimeType::Ptr mime = KMimeType::findByURL( kurl, st.st_mode, false, true, &accurate );
                    if ( !mime || mime->name() == KMimeType::defaultMimeType()
                         || !accurate )
                    {
                        KMimeType::Ptr p_mimeType = KMimeType::findByContent(filedata);
                        if ( p_mimeType && p_mimeType->name() != KMimeType::defaultMimeType() )
                            mime = p_mimeType;
                    }
		    mimeType(mime->name());
		    isFirstPacket = false;
		}
                data( filedata );
                filedata.resetRawData(buf,bytesread);

                // increment total bytes read
                totalbytesread += bytesread;

		processedSize(totalbytesread);
            }
        }

        smbc_close(filefd);
        data( QByteArray() );
        processedSize(static_cast<KIO::filesize_t>(st.st_size));

    }
    else
    {
          error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL());
	  return;
    }

    finished();
}
void LiveViewConsumer::buildLiveView(){
    //LOG_LIVEVIETHREAD_DEBUG << "\n++++++++++++++++++++++++++++++++++++++";
    //LOG_LIVEVIETHREAD_DEBUG << "buildLiveViewPic";
    //LOG_LIVEVIETHREAD_DEBUG<< "offset" << offset << "starttime: " << starttime << "endtime: " << endtime;
    QByteArray array;

#ifdef  __USE_STANDARD_HEADER
    int commonHeaderLength = 1 + 1 + 2 + 4;
    int payloadHeaderLength = 4 + 3 + 1 + 4 + 1 + 115;
    // Header = 136 Bytes;
    commonHeaderLength =commonHeaderLength;
    payloadHeaderLength = payloadHeaderLength;
    jpegSize = 0;
    offset = 0;

    mutex.lock();
    bufferIsNotEmpty.wait(&mutex);
//#define    _USECHAR //! for Testing only
#ifdef _USECHAR
    char consumerP[gRealLoadSize];
    qint64 loadedBytes = ringBuffer->getData(consumerP,gRealLoadSize);
    LOG_MIN_LIVEVIETHREAD_DEBUG << "";
    LOG_MIN_LIVEVIETHREAD_DEBUG << "Consumer loadedBytes:   " << loadedBytes;
    QByteArray tmpArray;
    tmpArray.resize(loadedBytes);
    tmpArray.setRawData(consumerP,loadedBytes);
    if(loadedBytes >0){
        inputStream.append(tmpArray,loadedBytes);
    }

    if(loadedBytes < gRealLoadSize){
        char consumerP[gRealLoadSize-loadedBytes];
        loadedBytes = ringBuffer->getData(consumerP,gRealLoadSize-loadedBytes);
    LOG_LIVEVIETHREAD_DEBUG << "loadedBytes 2:          " << loadedBytes;
        if(loadedBytes >0){
            tmpArray.resize(loadedBytes);
            tmpArray.setRawData(consumerP,loadedBytes);
            inputStream.append(tmpArray);
        }
    }
#else
    char tmpBuffer[gRealLoadSize];
    qint64 loadedBytes = ringBuffer->getData(tmpBuffer,gRealLoadSize);
    LOG_MIN_LIVEVIETHREAD_DEBUG << "";
    LOG_MIN_LIVEVIETHREAD_DEBUG << "Consumer loadedBytes:   " << loadedBytes;
    if(loadedBytes >0){
        inputStream.append(tmpBuffer,loadedBytes);
    }
    if(loadedBytes < gRealLoadSize){
        char tmpBuffer[gRealLoadSize-loadedBytes];
        loadedBytes = ringBuffer->getData(tmpBuffer,gRealLoadSize-loadedBytes);
    LOG_LIVEVIETHREAD_DEBUG << "loadedBytes 2:          " << loadedBytes;
        if(loadedBytes >0){
            inputStream.append(tmpBuffer,loadedBytes);
        }
    }

#endif


    LOG_LIVEVIETHREAD_DEBUG << "inputStream.size() 1:   " << inputStream.size() << "\n";

    if(!inputStream.isNull()){
         while (offset < inputStream.length() -15) {
             if (inputStream.at(offset) == (char) 0xFF) {
                        //LOG_LIVEVIETHREAD_DEBUG << "Start byte Found at:    " << offset;
                 switch (inputStream.at(offset+1)) {
                    case (char) 0x12:
                        LOG_MIN_LIVEVIETHREAD_DEBUG << "Informati Header at:    " << offset+1;
                        break;
                    case (char) 0x01:
                        LOG_MIN_LIVEVIETHREAD_DEBUG << "Start byte Found at:    " << offset;
                        //offset+=8;
                        break;
                    case (char) 0x11:
                        LOG_MIN_LIVEVIETHREAD_DEBUG << "Payload           at:    " << offset+1;
                        //offset+=8;
                        break;
                    default:
                        break;
                    }
                 if (inputStream.at(offset+8) == (char) 0x24
                         && inputStream.at(offset+9) == (char) 0x35
                         && inputStream.at(offset+10) == (char) 0x68
                         && inputStream.at(offset+11) == (char) 0x79) {
                         hjpegSize = bytesToInt(inputStream, offset+12, 3);
                         paddingSize = bytesToInt(inputStream, offset+15, 1);
                         LOG_MIN_LIVEVIETHREAD_DEBUG << "Payloadheader Found at: " << offset+8;

                         offset+=8;
                         offset+=128;
                 }
             }
             offset++;
             //LOG_LIVEVIETHREAD_DEBUG << "offset:                 " << offset;
             if(hjpegSize > 0 && hjpegSize < (inputStream.size() - offset)//){
                     && inputStream.at(offset-1) == (char) 0xff
                     && inputStream.at(offset) == (char)0xd8){
                 LOG_MIN_LIVEVIETHREAD_DEBUG << "hjpegSize:              " << hjpegSize;
                 LOG_MIN_LIVEVIETHREAD_DEBUG << "paddingSize:            " << paddingSize;
                 int arraysize = 0;
                 array.resize(hjpegSize);
                 for (; arraysize < hjpegSize; arraysize++,offset++){
                     array[arraysize] = inputStream.at(offset-1);
                     /*
                     if(array[arraysize] == (char)0xd9
                             && array[arraysize-1] == (char)0xff){
                         LOG_MIN_LIVEVIETHREAD_DEBUG << "publishLiveViewBytes:   " << arraysize;

                         offset+= hjpegSize-arraysize-1;
                        arraysize = hjpegSize;
                     }*/

                 }
                 emit publishLiveViewBytes(array);
                 inputStream.remove(0,offset-1);
                 LOG_MIN_LIVEVIETHREAD_DEBUG << "publishLiveViewBytes:   " << arraysize;
                 LOG_MIN_LIVEVIETHREAD_DEBUG << "inputStream.size()  :   " << inputStream.size();
                 hjpegSize = 0;
                 paddingSize = 0;
                 offset = 0;
             }
         }//while
    }// if not empty
    mutex.unlock();

#else

    //bool foundstart = false;
    //bool foundend = false;

    //starttime=0;
    //endtime=0;
    //foundstartOffset =0;


    //LOG_LIVEVIETHREAD_DEBUG << "consumerBufferLen: " << consumerBufferLen;
    //LOG_LIVEVIETHREAD_DEBUG << "ringBuffer->Free_Space():     " << ringBuffer->Free_Space();
    //LOG_LIVEVIETHREAD_DEBUG << "ringBuffer->Buffered_Bytes(): " <<ringBuffer->Buffered_Bytes();


    mutex.lock();
    bufferIsNotEmpty.wait(&mutex);
    char consumerP[gRealLoadSize];
    qint64 loadedBytes = ringBuffer->getData(consumerP,gRealLoadSize);
    LOG_LIVEVIETHREAD_DEBUG << "Consumer loadedBytes: " << loadedBytes;
    QByteArray tmpArray;
    tmpArray.resize(loadedBytes);
    tmpArray.setRawData(consumerP,loadedBytes);
    if(loadedBytes >0){
        inputStream.append(tmpArray,loadedBytes);
    }

    if(loadedBytes < gRealLoadSize){
        char consumerP[gRealLoadSize-loadedBytes];
       loadedBytes = ringBuffer->getData(consumerP,gRealLoadSize-loadedBytes);
        LOG_LIVEVIETHREAD_DEBUG << "loadedBytes 2: " << loadedBytes;
        if(loadedBytes >0){
            tmpArray.resize(loadedBytes);
            tmpArray.setRawData(consumerP,loadedBytes);
            inputStream.append(tmpArray);
        }
    }
    LOG_LIVEVIETHREAD_DEBUG     << "inputStream.size() 1:   " << inputStream.size() << "\n";
    if(!inputStream.isEmpty()){
        //LOG_LIVEVIETHREAD_DEBUG << "!inputStream.isEmpty()" << inputStream.size();
        //! search in Buffer, perhaps we have more than one image
        while (offset < (inputStream.length() -1)) {
            //! suche nach Bildanfang ab Stelle offset
            while(!foundstart && offset < (inputStream.length() -1) ){
                if (inputStream.at(offset) == (char) 0xFF) {
                    LOG_LIVEVIETHREAD_DEBUG << "Start byte Found at:    " << offset;
                    switch (inputStream.at(offset+1)) {
                    case (char) 0x12:
                        LOG_LIVEVIETHREAD_DEBUG << "Information Header at:    " << offset+1;
                        break;
                    case (char) 0x01:
                        LOG_LIVEVIETHREAD_DEBUG << "Nothing            at:    " << offset+1;
                        break;
                    case (char) 0x11:
                        LOG_LIVEVIETHREAD_DEBUG << "Payload             at:    " << offset+1;
                        break;
                    default:
                        break;
                    }

                    if (inputStream.at(offset+8) == (char) 0x24
                            && inputStream.at(offset+9) == (char) 0x35
                            && inputStream.at(offset+10) == (char) 0x68
                            && inputStream.at(offset+11) == (char) 0x79) {
                            //char calculatejpeg[3];

                            hjpegSize = bytesToInt(inputStream, offset+12, 3);
                            paddingSize = bytesToInt(inputStream, offset+15, 1);
                            LOG_LIVEVIETHREAD_DEBUG << "Payloadheader Found at: " << offset+8;
                    }
                }

                // osx: -1,40 Android: 255,216
                if(inputStream.at(offset) == (char) 0xff  && inputStream.at(offset+1) == (char)0xd8){
                    starttime = offset;
                    foundstart = true;
                    LOG_LIVEVIETHREAD_DEBUG << "start Found at:         " << starttime << "\n";
                    foundstartOffset = offset;
                }

                offset++;

            }//while


            LOG_LIVEVIETHREAD_DEBUG << "actual arrayiter:       " << arrayiter;
            //! suche nach Bildende ab Stelle offset
            while(foundstart && !foundend && offset<(inputStream.length()-1)){
                // osx: -1,39 Android: 255,217
                if(inputStream.at(offset) == (char)0xff && inputStream.at(offset+1) == (char)0xd9){
                    endtime = offset;
                    foundend = true;
                    LOG_LIVEVIETHREAD_DEBUG << "end Found at:           " << endtime;
                }
                array[arrayiter] = inputStream.at(offset-1);
                arrayiter++;
                offset++;
            }//while
            /*
            for (int i = 0; i< hjpegSize;i++){
                array[i] = inputStream.at(foundstartOffset);
                foundstartOffset++;
            }*/

            //! Bild gefunden
            if(foundstart && foundend){
                if(carry){
                    jpegSize = endtime-starttime;
                }
                else
                    jpegSize = endtime-starttime;
                LOG_LIVEVIETHREAD_DEBUG << "Picture Found           " <<"\n"
                         << "arrayiter:              " << arrayiter << "\n"
                         << "Starttime:              " << starttime << "\n"
                         << "endtime:                " << endtime << "\n"
                         << "offset:                 " << offset << "\n"
                         << "inputStream.size():     " << inputStream.size() << "\n"
                         << "jpegSize calculated:    " << jpegSize << "\n"
                         << "jpegSize from Header:   " << hjpegSize << "\n"
                         << "paddingSize:            " << paddingSize << "\n"
                         << "jpegSize full size:     " << endtime << "\n"
                         << "inputStream.size():     " << inputStream.size() << "\n";
                emit publishLiveViewBytes(array);

                inputStream.remove(0,endtime);
                offset = 0;
                arrayiter = 0;
                foundend = false;
                foundstart = false;
                starttime = 0;
                endtime = 0;
                carry = false;
                LOG_LIVEVIETHREAD_DEBUG << "inputStream new size:   " << inputStream.size() << "\n";
                //LOG_LIVEVIETHREAD_DEBUG << "publishLiveViewBytes";
            }
            else if (foundstart && !foundend){
                carry = true;
                //arrayiter = foundstartOffset;
                //offset = 0;
                LOG_LIVEVIETHREAD_DEBUG << "arrayiter               " << arrayiter <<"\n";
            }
        } // while search in tmp buffer;
    }// !inputStream.isEmpty()
    mutex.unlock();
   #endif

}