Exemple #1
0
void MocParser::loadStringData(char *&stringdata)
{
    stringdata = 0;
    QVarLengthArray<char, 1024> array;

    while (!input->atEnd()) {
        QByteArray line = readLine();
        if (line == "};\n") {
            // end of data
            stringdata = new char[array.count()];
            memcpy(stringdata, array.data(), array.count() * sizeof(*stringdata));
            return;
        }

        int start = line.indexOf('"');
        if (start == -1)
            parseError();

        int len = line.length() - 1;
        line.truncate(len);     // drop ending \n
        if (line.at(len - 1) != '"')
            parseError();

        --len;
        ++start;
        for ( ; start < len; ++start)
            if (line.at(start) == '\\') {
                // parse escaped sequence
                ++start;
                if (start == len)
                    parseError();

                QChar c(QLatin1Char(line.at(start)));
                if (!c.isDigit()) {
                    switch (c.toLatin1()) {
                    case 'a':
                        array.append('\a');
                        break;
                    case 'b':
                        array.append('\b');
                        break;
                    case 'f':
                        array.append('\f');
                        break;
                    case 'n':
                        array.append('\n');
                        break;
                    case 'r':
                        array.append('\r');
                        break;
                    case 't':
                        array.append('\t');
                        break;
                    case 'v':
                        array.append('\v');
                        break;
                    case '\\':
                    case '?':
                    case '\'':
                    case '"':
                        array.append(c.toLatin1());
                        break;

                    case 'x':
                        if (start + 2 <= len)
                            parseError();
                        array.append(char(line.mid(start + 1, 2).toInt(0, 16)));
                        break;

                    default:
                        array.append(c.toLatin1());
                        fprintf(stderr, PROGRAMNAME ": warning: invalid escape sequence '\\%c' found in input",
                                c.toLatin1());
                    }
                } else {
                    // octal
                    QRegExp octal(QLatin1String("([0-7]+)"));
                    if (octal.indexIn(QLatin1String(line), start) == -1)
                        parseError();
                    array.append(char(octal.cap(1).toInt(0, 8)));
                }
            } else {
                array.append(line.at(start));
            }
    }

    parseError();
}
Exemple #2
0
voidpf ZCALLBACK qiodevice_open_file_func (
   voidpf opaque,
   voidpf file,
   int mode)
{
    QIODevice_descriptor *d = reinterpret_cast<QIODevice_descriptor*>(opaque);
    QIODevice *iodevice = reinterpret_cast<QIODevice*>(file);
    QIODevice::OpenMode desiredMode;
    if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
        desiredMode = QIODevice::ReadOnly;
    else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
        desiredMode = QIODevice::ReadWrite;
    else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
        desiredMode = QIODevice::WriteOnly;
    if (iodevice->isOpen()) {
        if ((iodevice->openMode() & desiredMode) == desiredMode) {
            if (desiredMode != QIODevice::WriteOnly
                    && iodevice->isSequential()) {
                // We can use sequential devices only for writing.
                delete d;
                return NULL;
            } else {
                if ((desiredMode & QIODevice::WriteOnly) != 0) {
                    // open for writing, need to seek existing device
                    if (!iodevice->isSequential()) {
                        iodevice->seek(0);
                    } else {
                        d->pos = iodevice->pos();
                    }
                }
            }
            return iodevice;
        } else {
            delete d;
            return NULL;
        }
    }
    iodevice->open(desiredMode);
    if (iodevice->isOpen()) {
        if (desiredMode != QIODevice::WriteOnly && iodevice->isSequential()) {
            // We can use sequential devices only for writing.
            iodevice->close();
            delete d;
            return NULL;
        } else {
            return iodevice;
        }
    } else {
        delete d;
        return NULL;
    }
}
Exemple #3
0
//***************************************************************************
bool Kwave::AudiofileDecoder::open(QWidget *widget, QIODevice &src)
{
    metaData().clear();
    Q_ASSERT(!m_source);
    if (m_source) qWarning("AudiofileDecoder::open(), already open !");

    // try to open the source
    if (!src.open(QIODevice::ReadOnly)) {
	qWarning("AudiofileDecoder::open(), failed to open source !");
	return false;
    }

    // source successfully opened
    m_source = &src;
    m_src_adapter = new Kwave::VirtualAudioFile(*m_source);

    Q_ASSERT(m_src_adapter);
    if (!m_src_adapter) return false;

    m_src_adapter->open(m_src_adapter, 0);

    AFfilehandle fh = m_src_adapter->handle();
    if (!fh || (m_src_adapter->lastError() >= 0)) {
	QString reason;

	switch (m_src_adapter->lastError()) {
	    case AF_BAD_NOT_IMPLEMENTED:
	        reason = i18n("Format or function is not implemented");
	        break;
	    case AF_BAD_MALLOC:
	        reason = i18n("Out of memory");
	        break;
	    case AF_BAD_HEADER:
	        reason = i18n("File header is damaged");
	        break;
	    case AF_BAD_CODEC_TYPE:
	        reason = i18n("Invalid codec type");
	        break;
	    case AF_BAD_OPEN:
	        reason = i18n("Opening the file failed");
	        break;
	    case AF_BAD_READ:
	        reason = i18n("Read access failed");
	        break;
	    case AF_BAD_SAMPFMT:
	        reason = i18n("Invalid sample format");
	        break;
	    default:
		reason = reason.number(m_src_adapter->lastError());
	}

	QString text= i18n("An error occurred while opening the "\
	    "file:\n'%1'", reason);
	Kwave::MessageBox::error(widget, text);

	return false;
    }

    AFframecount length = afGetFrameCount(fh, AF_DEFAULT_TRACK);
    unsigned int tracks = qMax(afGetVirtualChannels(fh, AF_DEFAULT_TRACK), 0);
    unsigned int bits = 0;
    double       rate = 0.0;
    int af_sample_format;
    afGetVirtualSampleFormat(fh, AF_DEFAULT_TRACK, &af_sample_format,
	reinterpret_cast<int *>(&bits));
    Kwave::SampleFormat::Format fmt;
    switch (af_sample_format)
    {
	case AF_SAMPFMT_TWOSCOMP:
	    fmt = Kwave::SampleFormat::Signed;
	    break;
	case AF_SAMPFMT_UNSIGNED:
	    fmt = Kwave::SampleFormat::Unsigned;
	    break;
	case AF_SAMPFMT_FLOAT:
	    fmt = Kwave::SampleFormat::Float;
	    break;
	case AF_SAMPFMT_DOUBLE:
	    fmt = Kwave::SampleFormat::Double;
	    break;
	default:
	    fmt = Kwave::SampleFormat::Unknown;
	    break;
    }

    // get sample rate, with fallback to 8kHz
    rate = afGetRate(fh, AF_DEFAULT_TRACK);
    if (rate < 1.0) {
	qWarning("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"\
	         "WARNING: file has no sample rate!\n"\
	         "         => using 8000 samples/sec as fallback\n"\
	         "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
	rate = 8000.0;
    }

    Kwave::SampleFormat::Map sf;
    QString sample_format_name = sf.description(Kwave::SampleFormat(fmt), true);

    if (static_cast<signed int>(bits) < 0) bits = 0;

    int af_compression = afGetCompression(fh, AF_DEFAULT_TRACK);
    const Kwave::Compression compression(
	Kwave::Compression::fromAudiofile(af_compression)
    );

    Kwave::FileInfo info(metaData());
    info.setRate(rate);
    info.setBits(bits);
    info.setTracks(tracks);
    info.setLength(length);
    info.set(INF_SAMPLE_FORMAT, Kwave::SampleFormat(fmt).toInt());
    info.set(Kwave::INF_COMPRESSION, compression.toInt());
    metaData().replace(Kwave::MetaDataList(info));
    qDebug("-------------------------");
    qDebug("info:");
    qDebug("compression = %d", af_compression);
    qDebug("channels    = %d", info.tracks());
    qDebug("rate        = %0.0f", info.rate());
    qDebug("bits/sample = %d", info.bits());
    qDebug("length      = %lu samples",
	   static_cast<unsigned long int>(info.length()));
    qDebug("format      = %d (%s)", af_sample_format,
                                    DBG(sample_format_name));
    qDebug("-------------------------");

    // set up libaudiofile to produce Kwave's internal sample format
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
    afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
#else
    afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
#endif
    afSetVirtualSampleFormat(fh, AF_DEFAULT_TRACK,
	AF_SAMPFMT_TWOSCOMP, SAMPLE_STORAGE_BITS);

    return true;
}
Exemple #4
0
int main(int argc, char* argv[])
      {
      int c;
      while ((c = getopt(argc, argv, "vdD:r")) != EOF) {
            switch (c) {
                  case 'v':
                        printVersion();
                        return 0;
                  case 'd':
                        debugMode = true;
                        break;
                  default:
                        usage();
                        return -1;
                  }
            }
      QIODevice* in = 0;
      QIODevice* out = 0;

      switch (argc - optind) {
            case 2:
                  out = new QFile(argv[1 + optind]);
                  if (!out->open(QIODevice::WriteOnly)) {
                        printf("cannot open output file <%s>: %s\n", argv[optind+1], strerror(errno));
                        return -3;
                        }
            case 1:
                  in = new QFile(argv[optind]);
                  if (!in->open(QIODevice::ReadOnly)) {
                        printf("cannot open input file <%s>: %s\n", argv[optind], strerror(errno));
                        return -4;
                        }
                  break;
            case 0:
                  break;
            default:
                  usage();
                  return -2;
                  break;
            }
      if (in == 0) {
            in = new QFile;
            ((QFile*)in)->open(stdin, QIODevice::ReadOnly);
            }
      if (out == 0) {
            out = new QFile;
            ((QFile*)out)->open(stdout, QIODevice::WriteOnly);
            }

      MidiFile mf;
      mf.setFormat(1);

      XmlReader e(in);
      while (e.readNextStartElement()) {
            const QStringRef& tag(e.name());
            if (tag == "SMF") {
                  while (e.readNextStartElement()) {
                        const QStringRef& tag(e.name());
                        if (tag == "Track") {
                              MidiTrack* track = new MidiTrack(&mf);
                              while (e.readNextStartElement()) {
                                    const QStringRef& tag(e.name());
                                    if (tag == "NoteOff") {
                                          MidiEventType t = MidiEventType::NOTEOFF;
                                          int tick        = e.intAttribute("tick");
                                          uchar c         = e.intAttribute("c");
                                          uchar a         = e.intAttribute("a", 0, 16);
                                          uchar b         = e.intAttribute("b", 0, 16);
                                          track->events().insert(std::pair<int,MidiEvent>(tick, MidiEvent(t, c, a, b)));
                                          e.skipCurrentElement();
                                          }
                                    else if (tag == "NoteOn") {
                                          MidiEventType t = MidiEventType::NOTEON;
                                          int tick        = e.intAttribute("tick");
                                          uchar c         = e.intAttribute("c");
                                          uchar a         = e.intAttribute("a", 0, 16);
                                          uchar b         = e.intAttribute("b", 0, 16);
                                          track->events().insert(std::pair<int,MidiEvent>(tick, MidiEvent(t, c, a, b)));
                                          e.skipCurrentElement();
                                          }
                                    else if (tag == "Ctrl") {
                                          MidiEventType t = MidiEventType::CONTROLLER;
                                          int tick        = e.intAttribute("tick");
                                          uchar c         = e.intAttribute("c");
                                          uchar a         = e.intAttribute("a", 0, 16);
                                          uchar b         = e.intAttribute("b", 0, 16);
                                          track->events().insert(std::pair<int,MidiEvent>(tick, MidiEvent(t, c, a, b)));
                                          e.skipCurrentElement();
                                          }
                                    else if (tag == "Program") {
                                          MidiEventType t = MidiEventType::PROGRAM;
                                          int tick        = e.intAttribute("tick");
                                          uchar c         = e.intAttribute("c");
                                          uchar a         = e.intAttribute("a", 0, 16);
                                          track->events().insert(std::pair<int,MidiEvent>(tick, MidiEvent(t, c, a, 0)));
                                          e.skipCurrentElement();
                                          }
                                    else if (tag == "Event") {
                                          uchar t         = e.intAttribute("t");
                                          int tick        = e.intAttribute("tick");
                                          uchar c         = e.intAttribute("c");
                                          uchar a         = e.intAttribute("a", 0, 16);
                                          uchar b         = e.intAttribute("b", 0, 16);
                                          track->events().insert(std::pair<int,MidiEvent>(tick,
                                             MidiEvent(MidiEventType(t), c, a, b)));
                                          e.skipCurrentElement();
                                          }
                                    else
                                          e.unknown();
                                    }
                              mf.tracks().push_back(track);
                              }
                        else if (tag == "division")
                              mf.setDivision(e.readInt());
                        else if (tag == "format")
                              mf.setFormat(e.readInt());
                        else
                              e.unknown();
                        }
                  }
            else
                  e.unknown();
            }

      mf.write(out);

      delete out;
      delete in;
      return 0;
      }
Exemple #5
0
void WriteIconData::writeImage(QIODevice &output, DomImage *image)
{
    QByteArray array = transformImageData(image->elementData()->text());
    output.write(array, array.size());
}
Exemple #6
0
// Read pre atlas header from file, return NULL if invalid
//
boost::shared_ptr< tChPreAtlasHdr > tAt5PreAtlas::ExtPreAtlasHdr(QIODevice& Qd) 
{
    // Since we don't know the version number at this time,
    //  we need to get tChPreAtlasHdr using version 1.
    //  From there, we'll read the version and then re-read the entire
    //  header again using the proper version number.


    // First get as version 1 then get as defined in PreAtlasHdr
    //
    tChPreAtlasHdr preAtlasV1( tAt5AtlasVersion( 1, 0 ) );           

    // 1st test to see if enough data in i/o to read header, return NULL if not
    //
    if ( Qd.size() < preAtlasV1.DataSize() )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Insufficient amount of data in I/O" ) );
        throw except; 
    }

    // Now open stream and read pre_atlas1
    //
    tAt5Stream strm; 
    try
    {
        strm.InsStrm( Qd, 0, 0, 0, preAtlasV1.DataSize() );
        strm >> preAtlasV1;
    }
    catch( tAt5Exception Excpt )
    {
        Excpt.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO ) );
        throw Excpt;
    }

    // Verify preamble for correct signiture, return NULL if not
    //
    if ( ( preAtlasV1.SigChar0 != 0x55 ) || ( preAtlasV1.SigChar1 != 0xaa ) )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Invalid preamble" ) );
        throw except; 
    }

    // Now read header again to get proper version

    boost::shared_ptr< tChPreAtlasHdr > xPreAtlas( new tChPreAtlasHdr( tAt5AtlasVersion( preAtlasV1.MajorAtlasVer, preAtlasV1.MinorAtlasVer ) ) ); 

    // see if enough data in i/o to read header, return NULL if not
    //
    if ( Qd.size() < xPreAtlas->DataSize() )
    {
        tAt5Exception except;
        except.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO, "Insufficient amount of data in I/O" ) );
        throw except; 
    }

    strm.Reset();    

    try
    {
        strm.InsStrm( Qd, 0, 0, 0, xPreAtlas->DataSize() );
        strm >> *xPreAtlas;
    }
    catch( tAt5Exception Excpt )
    {
        Excpt.m_CatchTrail.push_back( tAt5ExceptionDescription( AT5_EXCEPTION_WHERE_INFO ) );
        throw Excpt;
    }

    // TODO: Insert checksum test here if version 6 or above.    

    return xPreAtlas;
}
Exemple #7
0
bool TextBuffer::save (const QString &filename)
{
  // codec must be set!
  Q_ASSERT (m_textCodec);

  /**
   * construct correct filter device and try to open
   */
  QIODevice *file = KFilterDev::deviceForFile (filename, m_mimeTypeForFilterDev, false);
  if (!file->open (QIODevice::WriteOnly)) {
    delete file;
    return false;
  }

  /**
   * construct stream + disable Unicode headers
   */
  QTextStream stream (file);
  stream.setCodec (QTextCodec::codecForName("UTF-16"));

  // set the correct codec
  stream.setCodec (m_textCodec);

  // generate byte order mark?
  stream.setGenerateByteOrderMark (generateByteOrderMark());

  // our loved eol string ;)
  QString eol = "\n"; //m_doc->config()->eolString ();
  if (endOfLineMode() == eolDos)
    eol = QString ("\r\n");
  else if (endOfLineMode() == eolMac)
    eol = QString ("\r");

  // just dump the lines out ;)
  for (int i = 0; i < m_lines; ++i)
  {
    // get line to save
    Kate::TextLine textline = line (i);

    // strip trailing spaces
    if (m_removeTrailingSpaces)
    {
      int lastChar = textline->lastChar();
      if (lastChar > -1)
      {
        stream << textline->text().left (lastChar+1);
      }
    }
    else // simple, dump the line
      stream << textline->text();

    // append correct end of line string
    if ((i+1) < m_lines)
      stream << eol;
  }

  // flush stream
  stream.flush ();

  // close and delete file
  file->close ();
  delete file;

#ifndef Q_OS_WIN
  // ensure that the file is written to disk
  // we crete new qfile, as the above might be wrapper around compression
  QFile syncFile (filename);
  syncFile.open (QIODevice::ReadOnly);

#ifdef HAVE_FDATASYNC
  fdatasync (syncFile.handle());
#else
  fsync (syncFile.handle());
#endif
#endif

  // did save work?
  bool ok = stream.status() == QTextStream::Ok;

  // remember this revision as last saved if we had success!
  if (ok)
    m_history.setLastSavedRevision ();

  // report CODEC + ERRORS
  kDebug (13020) << "Saved file " << filename << "with codec" << m_textCodec->name()
    << (ok ? "without" : "with") << "errors";

  // emit signal on success
  if (ok)
    emit saved (filename);

  // return success or not
  return ok;
}
QByteArray FlushedProcess::readAll() {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?QByteArray():dev->readAll();
}
qint64 FlushedProcess::readLine(char * data, qint64 maxSize) {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?-1:dev->readLine(data,maxSize);
}
Exemple #10
0
int khopper::ffmpeg::write_packet( void * opaque, uint8_t * buf, int buf_size ) {
	QIODevice * device = static_cast< QIODevice * >( opaque );
	return device->write( static_cast< char * >( static_cast< void * >( buf ) ), buf_size );
}
/*!
    reads the content of the file \c fileName to the data source \c dataSource or return as string for preview.
    Uses the settings defined in the data source.
*/
QString AsciiFilterPrivate::readData(const QString & fileName, AbstractDataSource* dataSource, AbstractFileFilter::ImportMode mode, int lines){
	QStringList dataString;

	QIODevice *device = KFilterDev::deviceForFile(fileName);
	if (!device->open(QIODevice::ReadOnly))
		return QString();

	QTextStream in(device);

	//TODO implement
	// if (transposed)
	//...

	//skip rows, if required
	for (int i=0; i<startRow-1; i++){
        //if the number of rows to skip is bigger then the actual number
		//of the rows in the file, then quit the function.
		if( in.atEnd() ) {
			if (mode==AbstractFileFilter::Replace) {
				//file with no data to be imported. In replace-mode clear the data source
				if(dataSource != NULL)
					dataSource->clear();
			}
			return QString();
		}

		in.readLine();
	}

	//parse the first row:
	//use the first row to determine the number of columns,
	//create the columns and use (optionaly) the first row to name them
	if( in.atEnd() ) {
		if (mode==AbstractFileFilter::Replace) {
			//file with no data to be imported. In replace-mode clear the data source
			if(dataSource != NULL)
				dataSource->clear();
		}
		return QString();
	}

	QString line = in.readLine();
	if( simplifyWhitespacesEnabled)
		line = line.simplified();

	// determine separator
	QString separator;
	QStringList lineStringList;
	if( separatingCharacter == "auto" ){
		QRegExp regExp("(\\s+)|(,\\s+)|(;\\s+)|(:\\s+)");
		lineStringList = line.split( regExp, QString::SplitBehavior(skipEmptyParts) );

		//determine the separator
		if (lineStringList.size()){
			int length1 = lineStringList.at(0).length();
			if (lineStringList.size()>1){
				int pos2 = line.indexOf(lineStringList.at(1),length1);
				separator = line.mid(length1, pos2-length1);
			}else {
				separator = line.right(line.length()-length1);
			}
		}
	}else {
		separator = separatingCharacter.replace(QLatin1String("TAB"), QLatin1String("\t"), Qt::CaseInsensitive);
		separator = separatingCharacter.replace(QLatin1String("SPACE"), QLatin1String(" "), Qt::CaseInsensitive);
		lineStringList = line.split( separator, QString::SplitBehavior(skipEmptyParts) );
	}
#ifdef QT_DEBUG
 	qDebug() << "separator '"<<separator << "'";
#endif

	if (endColumn == -1)
		endColumn = lineStringList.size(); //use the last available column index

	QStringList vectorNameList;
	if ( headerEnabled ){
		vectorNameList = lineStringList;
	}else{
		//create vector names out of the space separated vectorNames-string, if not empty
		if (!vectorNames.isEmpty()){
			vectorNameList = vectorNames.split(' ');
		}
	}

	//qDebug()<<"	vector names ="<<vectorNameList;

	int actualRows = AsciiFilter::lineNumber(fileName);	// data rows
	int actualEndRow;
	if (endRow == -1)
		actualEndRow = actualRows;
	else if (endRow > actualRows-1)
		actualEndRow = actualRows-1;
	else
		actualEndRow = endRow;
	int actualCols=endColumn-startColumn+1;

	if (headerEnabled)
		actualRows = actualEndRow-startRow;
	else
		actualRows = actualEndRow-startRow+1;
	if (lines == -1)
		lines=actualRows;

#ifdef QT_DEBUG
	qDebug()<<"	start column ="<<startColumn;
	qDebug()<<"	end column ="<<endColumn;
	qDebug()<<"	actual cols ="<<actualCols;
	qDebug()<<"	start row ="<<startRow;
	qDebug()<<"	end row ="<<actualEndRow;
	qDebug()<<"	actual rows ="<<actualRows;
	qDebug()<<"	lines ="<<lines;
#endif

	int currentRow=0; //indexes the position in the vector(column)
	int columnOffset=0; //indexes the "start column" in the spreadsheet. Starting from this column the data will be imported.
	//pointers to the actual data containers
	QVector<QVector<double>*> dataPointers;

	if(dataSource != NULL)
		columnOffset = dataSource->create(dataPointers, mode, actualRows, actualCols, vectorNameList);

	//header: import the values in the first line, if they were not used as the header (as the names for the columns)
	bool isNumber;
	if (!headerEnabled){
		for ( int n=0; n<actualCols; n++ ){
			if (n<lineStringList.size()) {
				const double value = lineStringList.at(n).toDouble(&isNumber);
				if (dataSource != NULL)
					isNumber ? dataPointers[n]->operator[](0) = value : dataPointers[n]->operator[](0) = NAN;
				else
					isNumber ? dataString<<QString::number(value)<<" " : dataString<<QLatin1String("NAN ");
			} else {
				if (dataSource != NULL)
					dataPointers[n]->operator[](0) = NAN;
				else
					dataString<<QLatin1String("NAN ");
			}
		}
		dataString<<"\n";
		currentRow++;
	}

	//Read the remainder of the file.
	for (int i=currentRow; i<qMin(lines,actualRows); i++){
		line = in.readLine();

		if(simplifyWhitespacesEnabled)
			line = line.simplified();

		//skip empty lines
		if (line.isEmpty())
			continue;

		if( line.startsWith(commentCharacter) == true ){
			currentRow++;
			continue;
		}

		lineStringList = line.split( separator, QString::SplitBehavior(skipEmptyParts) );

		// TODO : read strings (comments) or datetime too
		for ( int n=0; n<actualCols; n++ ){
			if (n<lineStringList.size()) {
				const double value = lineStringList.at(n).toDouble(&isNumber);
				if (dataSource != NULL)
					isNumber ? dataPointers[n]->operator[](currentRow) = value : dataPointers[n]->operator[](currentRow) = NAN;
				else
					isNumber ? dataString<<QString::number(value)<<" " : dataString<<QString("NAN ");
			} else {
				if (dataSource != NULL)
					dataPointers[n]->operator[](currentRow) = NAN;
				else
					dataString<<QLatin1String("NAN ");
			}
		}

		dataString<<"\n";
		currentRow++;
		emit q->completed(100*currentRow/actualRows);
	}

	if (!dataSource)
		return dataString.join("");

	//make everything undo/redo-able again
	//set the comments for each of the columns
	Spreadsheet* spreadsheet = dynamic_cast<Spreadsheet*>(dataSource);
	if (spreadsheet) {
		//TODO: generalize to different data types
		QString comment = i18np("numerical data, %1 element", "numerical data, %1 elements", headerEnabled ? currentRow : currentRow+1);
		for ( int n=startColumn; n<=endColumn; n++ ){
			Column* column = spreadsheet->column(columnOffset+n-startColumn);
			column->setComment(comment);
			column->setUndoAware(true);
			if (mode==AbstractFileFilter::Replace) {
				column->setSuppressDataChangedSignal(false);
				column->setChanged();
			}
		}
		spreadsheet->setUndoAware(true);
		return dataString.join("");
	}


	Matrix* matrix = dynamic_cast<Matrix*>(dataSource);
	if (matrix) {
		matrix->setSuppressDataChangedSignal(false);
		matrix->setChanged();
		matrix->setUndoAware(true);
	}

	return dataString.join("");
}
sf_count_t nSndfileStream_vio_read(void * ptr, sf_count_t count, void * userData)
{
    QIODevice * device = ((QIODevice*)userData);
    return device->read((char*)ptr, count);
}
sf_count_t nSndfileStream_vio_filelen(void * userData)
{
    QIODevice * device = ((QIODevice*)userData);
    sf_count_t size = device->size();
    return size;
}
int TAbstractWebSocket::parse(QByteArray &recvData)
{
    tSystemDebug("parse enter  data len:%d  sid:%d", recvData.length(), socketId());
    if (websocketFrames().isEmpty()) {
        websocketFrames().append(TWebSocketFrame());
    } else {
        const TWebSocketFrame &f = websocketFrames().last();
        if (f.state() == TWebSocketFrame::Completed) {
            websocketFrames().append(TWebSocketFrame());
        }
    }

    TWebSocketFrame *pfrm = &websocketFrames().last();
    quint8  b;
    quint16 w;
    quint32 n;
    quint64 d;

    QDataStream ds(recvData);
    ds.setByteOrder(QDataStream::BigEndian);
    QIODevice *dev = ds.device();
    QByteArray hdr;

    while (!ds.atEnd()) {
        switch (pfrm->state()) {
        case TWebSocketFrame::Empty: {
            hdr = dev->peek(14);
            QDataStream dshdr(hdr);
            dshdr.setByteOrder(QDataStream::BigEndian);
            QIODevice *devhdr = dshdr.device();

            if (Q_UNLIKELY(devhdr->bytesAvailable() < 2)) {
                goto parse_end;
            }

            dshdr >> b;
            pfrm->setFirstByte(b);
            dshdr >> b;
            bool maskFlag = b & 0x80;
            quint8 len = b & 0x7f;

            // payload length
            switch (len) {
            case 126:
                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(w))) {
                    goto parse_end;
                }
                dshdr >> w;
                if (Q_UNLIKELY(w < 126)) {
                    tSystemError("WebSocket protocol error  [%s:%d]", __FILE__, __LINE__);
                    return -1;
                }
                pfrm->setPayloadLength( w );
                break;

            case 127:
                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(d))) {
                    goto parse_end;
                }
                dshdr >> d;
                if (Q_UNLIKELY(d <= 0xFFFF)) {
                    tSystemError("WebSocket protocol error  [%s:%d]", __FILE__, __LINE__);
                    return -1;
                }
                pfrm->setPayloadLength( d );
                break;

            default:
                pfrm->setPayloadLength( len );
                break;
            }

            // Mask key
            if (maskFlag) {
                if (Q_UNLIKELY(devhdr->bytesAvailable() < (int)sizeof(n))) {
                    goto parse_end;
                }
                dshdr >> n;
                pfrm->setMaskKey( n );
            }

            if (pfrm->payloadLength() == 0) {
                pfrm->setState(TWebSocketFrame::Completed);
            } else {
                pfrm->setState(TWebSocketFrame::HeaderParsed);
                if (pfrm->payloadLength() >= 2 * 1024 * 1024 * 1024ULL) {
                    tSystemError("Too big frame  [%s:%d]", __FILE__, __LINE__);
                    pfrm->clear();
                } else {
                    pfrm->payload().reserve(pfrm->payloadLength());
                }
            }

            tSystemDebug("WebSocket parse header pos: %lld", devhdr->pos());
            tSystemDebug("WebSocket payload length:%lld", pfrm->payloadLength());

            int hdrlen = hdr.length() - devhdr->bytesAvailable();
            ds.skipRawData(hdrlen);  // Forwards the pos
            break; }

        case TWebSocketFrame::HeaderParsed:  // fall through
        case TWebSocketFrame::MoreData: {
            tSystemDebug("WebSocket reading payload:  available length:%lld", dev->bytesAvailable());
            tSystemDebug("WebSocket parsing  length to read:%llu  current buf len:%d", pfrm->payloadLength(), pfrm->payload().size());
            quint64 size = qMin((pfrm->payloadLength() - pfrm->payload().size()), (quint64)dev->bytesAvailable());
            if (Q_UNLIKELY(size == 0)) {
                Q_ASSERT(0);
                break;
            }

            char *p = pfrm->payload().data() + pfrm->payload().size();
            size = ds.readRawData(p, size);

            if (pfrm->maskKey()) {
                // Unmask
                const quint8 mask[4] = { quint8((pfrm->maskKey() & 0xFF000000) >> 24),
                                         quint8((pfrm->maskKey() & 0x00FF0000) >> 16),
                                         quint8((pfrm->maskKey() & 0x0000FF00) >> 8),
                                         quint8((pfrm->maskKey() & 0x000000FF)) };

                int i = pfrm->payload().size();
                const char *end = p + size;
                while (p < end) {
                    *p++ ^= mask[i++ % 4];
                }
            }
            pfrm->payload().resize( pfrm->payload().size() + size );
            tSystemDebug("WebSocket payload curent buf len: %d", pfrm->payload().length());

            if ((quint64)pfrm->payload().size() == pfrm->payloadLength()) {
                pfrm->setState(TWebSocketFrame::Completed);
                tSystemDebug("Parse Completed   payload len: %d", pfrm->payload().size());
            } else {
                pfrm->setState(TWebSocketFrame::MoreData);
                tSystemDebug("Parse MoreData   payload len: %d", pfrm->payload().size());
            }
            break; }

        case TWebSocketFrame::Completed:  // fall through
        default:
            Q_ASSERT(0);
            break;
        }

        if (pfrm->state() == TWebSocketFrame::Completed) {
            if (Q_UNLIKELY(!pfrm->validate())) {
                pfrm->clear();
                continue;
            }

            // Fragmented message validation
            if (pfrm->opCode() == TWebSocketFrame::Continuation) {
                if (websocketFrames().count() >= 2) {
                    const TWebSocketFrame &before = websocketFrames()[websocketFrames().count() - 2];
                    if (before.isFinalFrame() || before.isControlFrame()) {
                        pfrm->clear();
                        tSystemWarn("Invalid continuation frame detected  [%s:%d]", __FILE__, __LINE__);
                        continue;
                    }
                }
            }

            // In case of control frame, moves forward after previous control frames
            if (pfrm->isControlFrame()) {
                if (websocketFrames().count() >= 2) {
                    TWebSocketFrame frm = websocketFrames().takeLast();
                    QMutableListIterator<TWebSocketFrame> it(websocketFrames());
                    while (it.hasNext()) {
                        TWebSocketFrame &f = it.next();
                        if (!f.isControlFrame()) {
                            break;
                        }
                    }

                    it.insert(frm);
                }
            }

            if (!ds.atEnd()) {
                // Prepare next frame
                websocketFrames().append(TWebSocketFrame());
                pfrm = &websocketFrames().last();
            } else {
                break;
            }
        }
    }

parse_end:
    int parsedlen = recvData.size() - dev->bytesAvailable();
    recvData.remove(0, parsedlen);
    return parsedlen;
}
void QIODeviceProto::close()
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    item->close();
}
QByteArray FlushedProcess::readLine(qint64 maxSize) {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?QByteArray():dev->readLine(maxSize);
}
Exemple #17
0
//---------------------------------------------------------------------------
void FileInformation::readStats(QIODevice& StatsFromExternalData_File, bool StatsFromExternalData_FileName_IsCompressed)
{
    m_hasStats = true;

    streamsStats = new StreamsStats();
    formatStats = new FormatStats();

    //Stats init
    VideoStats* Video=new VideoStats();
    Stats.push_back(Video);
    AudioStats* Audio=new AudioStats();
    Stats.push_back(Audio);

    //XML init
    const char*  Xml_HeaderFooter="</frames></ffprobe:ffprobe><ffprobe:ffprobe><frames>";
    const size_t Xml_HeaderSize=25;
    const size_t Xml_FooterSize=27;
    const size_t Xml_MaxSize=0x1000000; //Blocks of 16 MiB, arbitrary chosen
    char* Xml=new char[Xml_MaxSize+Xml_HeaderSize+Xml_FooterSize];

    //Read init
    const size_t Compressed_MaxSize=0x100000; //Blocks of 1 MiB, arbitrary chosen
    char* Compressed=new char[Compressed_MaxSize];

    //Uncompress init
    z_stream strm;
    if (StatsFromExternalData_FileName_IsCompressed)
    {
        strm.next_in = NULL;
        strm.avail_in = 0;
        strm.next_out = NULL;
        strm.avail_out = 0;
        strm.total_out = 0;
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        inflateInit2(&strm, 15 + 16); // 15 + 16 are magic values for gzip
    }

    //Load and parse compressed data chunk by chunk
    char* Xml_Pointer=Xml;
    int inflate_Result;
    int TEMP = 0;

    for (;;)
    {
        //Load
        qint64 ReadSize;
        size_t avail_out=Xml_MaxSize-(Xml_Pointer-Xml);
        if (StatsFromExternalData_FileName_IsCompressed)
            ReadSize=StatsFromExternalData_File.read(Compressed, Compressed_MaxSize); //Load in an intermediate buffer for decompression
        else
            ReadSize=StatsFromExternalData_File.read(Xml_Pointer, avail_out); //Load directly in the XML buffer
        if (!ReadSize)
            break;
        TEMP += ReadSize;

        //Parse compressed data, with handling of the case the output buffer is not big enough
        strm.next_in=(Bytef*)Compressed;
        strm.avail_in=ReadSize;
        for (;;)
        {
            size_t Xml_Size=Xml_Pointer-Xml;
            if (StatsFromExternalData_FileName_IsCompressed)
            {
                //inflate
                strm.next_out=(Bytef*)Xml_Pointer;
                strm.avail_out= (avail_out - Xml_Size);
                if ((inflate_Result=inflate(&strm, Z_NO_FLUSH))<0)
                    break;
                Xml_Size+=(avail_out - Xml_Size) -strm.avail_out;
            }
            else
                Xml_Size+=ReadSize;

            //Cut the XML after the last XML frame footer, and keep the remaining data for the next turn
            size_t Xml_SizeForParsing=Xml_Size;
            //Look for XML frame footer
            while (Xml_SizeForParsing>Xml_HeaderSize &&
                    ( Xml[Xml_SizeForParsing-1]!='>' //"</frame>"
                || Xml[Xml_SizeForParsing-2]!='e'
                || Xml[Xml_SizeForParsing-3]!='m'
                || Xml[Xml_SizeForParsing-4]!='a'
                || Xml[Xml_SizeForParsing-5]!='r'
                || Xml[Xml_SizeForParsing-6]!='f'
                || Xml[Xml_SizeForParsing-7]!='/'
                || Xml[Xml_SizeForParsing-8]!='<'))
                Xml_SizeForParsing--;
            if (Xml_SizeForParsing<=Xml_HeaderSize)
            {
                //The block does not contain any complete frame, looping in order to get more data from the file
                Xml_Pointer=Xml+Xml_Size;
                break;
            }

            //Insert Xml_HeaderFooter inside the XML content
            memmove(Xml+Xml_SizeForParsing+Xml_HeaderSize+Xml_FooterSize, Xml+Xml_SizeForParsing, Xml_Size-Xml_SizeForParsing);
            memcpy(Xml+Xml_SizeForParsing, Xml_HeaderFooter, Xml_HeaderSize+Xml_FooterSize);
            Xml_Size+=Xml_HeaderSize+Xml_FooterSize;
            Xml_SizeForParsing+=Xml_FooterSize;

            Video->StatsFromExternalData(Xml, Xml_SizeForParsing);
            Audio->StatsFromExternalData(Xml, Xml_SizeForParsing);

            //Cut the parsed content
            memmove(Xml, Xml+Xml_SizeForParsing, Xml_Size-Xml_SizeForParsing);
            Xml_Pointer=Xml+Xml_Size-Xml_SizeForParsing;

            //Check if we need to stop
            if (!StatsFromExternalData_FileName_IsCompressed || strm.avail_out || inflate_Result == Z_STREAM_END)
                break;
        }

        //Coherency checks
        if (Xml_Pointer>=Xml+Xml_MaxSize+Xml_HeaderSize)
            break;
    }

    //Inform the parser that parsing is finished
    Video->StatsFromExternalData_Finish();
    Audio->StatsFromExternalData_Finish();

    //Parse formats
    formatStats->readFromXML(Xml, Xml_Pointer - Xml);

    //Parse streams
    streamsStats->readFromXML(Xml, Xml_Pointer - Xml);

    //Cleanup
    if (StatsFromExternalData_FileName_IsCompressed)
        inflateEnd(&strm);
    delete[] Compressed;
    delete[] Xml;
}
bool FlushedProcess::atEnd() const {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?true:dev->atEnd();
}
Exemple #19
0
//--------------------------------------------------------------------
void tst_QIODevice::peek()
{
    QBuffer buffer;
    QFile::remove("peektestfile");
    QFile file("peektestfile");

    for (int i = 0; i < 2; ++i) {
	QIODevice *device = i ? (QIODevice *)&file : (QIODevice *)&buffer;

	device->open(QBuffer::ReadWrite);
	device->write("ZXCV");

	device->seek(0);
	QCOMPARE(device->peek(4), QByteArray("ZXCV"));
	QCOMPARE(device->pos(), qint64(0));
	device->write("ABCDE");
	device->seek(3);
	QCOMPARE(device->peek(1), QByteArray("D"));
	QCOMPARE(device->peek(5), QByteArray("DE"));
	device->seek(0);
	QCOMPARE(device->read(4), QByteArray("ABCD"));
	QCOMPARE(device->pos(), qint64(4));

	device->seek(0);
	device->write("ZXCV");
	device->seek(0);
	char buf[5];
	buf[4] = 0;
	device->peek(buf, 4);
	QCOMPARE(static_cast<const char *>(buf), "ZXCV");
	QCOMPARE(device->pos(), qint64(0));
	device->read(buf, 4);
	QCOMPARE(static_cast<const char *>(buf), "ZXCV");
	QCOMPARE(device->pos(), qint64(4));
    }
    QFile::remove("peektestfile");
}
qint64 FlushedProcess::bytesAvailable() const {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?0:dev->bytesAvailable();
}
Exemple #21
0
int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    QCoreApplication::setOrganizationDomain(QLatin1String("sites.google.com/site/zeromusparadoxe01"));
    QCoreApplication::setApplicationName(QLatin1String("zBrowser"));

    QStringList args = application.arguments();
    args.takeFirst();
    if (args.isEmpty()) {
        QTextStream stream(stdout);
        stream << "zbrowser-cacheinfo is a tool for viewing and extracting information out of zBrowser cache files." << endl;
        stream << "zbrowser-cacheinfo [-o cachefile] [file | url]" << endl;
        return 0;
    }

    NetworkDiskCache diskCache;
    QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation)
            + QLatin1String("/browser/");
    diskCache.setCacheDirectory(location);

    QNetworkCacheMetaData metaData;
    QString last = args.takeLast();
    if (QFile::exists(last)) {
        qDebug() << "Reading in from a file and not a URL.";
        metaData = diskCache._fileMetaData(last);
    } else {
        qDebug() << "Reading in from a URL and not a file.";
        metaData = diskCache.metaData(last);
    }

    if (!args.isEmpty()
        && args.count() >= 1
        && args.first() == QLatin1String("-o")) {
        QUrl url = metaData.url();
        QIODevice *device = diskCache.data(url);
        if (!device) {
            qDebug() << "Error: data for URL is 0!";
            return 1;
        }
        QString fileName;
        if (args.count() == 2) {
            fileName = args.last();
        } else {
            QFileInfo info(url.path());
            fileName = info.fileName();
            if (fileName.isEmpty()) {
                qDebug() << "URL file name is empty, please specify an output file, I wont guess.";
                return 1;
            }
            if (QFile::exists(fileName)) {
                qDebug() << "File already exists, not overwriting, please specify an output file.";
                return 1;
            }
        }
        qDebug() << "Saved cache file to:" << fileName;
        QFile file(fileName);
        if (!file.open(QFile::ReadWrite))
            qDebug() << "Unable to open the output file for writing.";
        else
            file.write(device->readAll());
        delete device;
    }

    QTextStream stream(stdout);
    stream << "URL: " << metaData.url().toString() << endl;
    stream << "Expiration Date: " << metaData.expirationDate().toString() << endl;
    stream << "Last Modified Date: " << metaData.lastModified().toString() << endl;
    stream << "Save to disk: " << metaData.saveToDisk() << endl;
    stream << "Headers:" << endl;
    foreach (const QNetworkCacheMetaData::RawHeader &header, metaData.rawHeaders())
        stream << "\t" << header.first << ": " << header.second << endl;
    QIODevice *device = diskCache.data(metaData.url());
    if (device) {
        stream << "Data Size: " << device->size() << endl;
        stream << "First line: " << device->readLine(100);
    } else {
        stream << "No data? Either the file is corrupt or there is an error." << endl;
    }

    delete device;
    return 0;
}
bool FlushedProcess::canReadLine() const {
    QIODevice * dev = readingIODevice();
    return (dev == NULL)?false:dev->canReadLine();
}
Exemple #23
0
/**
 * Verifies contents of specified archive against test fileset
 * @param archive archive
 */
static void testFileData( KArchive* archive )
{
    const KArchiveDirectory* dir = archive->directory();

    const KArchiveEntry* e = dir->entry( "z/test3" );
    QVERIFY( e );
    QVERIFY( e->isFile() );
    const KArchiveFile* f = static_cast<const KArchiveFile*>( e );
    QByteArray arr( f->data() );
    QCOMPARE( arr.size(), 13 );
    QCOMPARE( arr, QByteArray( "Noch so einer" ) );

    // Now test using createDevice()
    QIODevice *dev = f->createDevice();
    QByteArray contents = dev->readAll();
    QCOMPARE( contents, arr );
    delete dev;

    dev = f->createDevice();
    contents = dev->read(5); // test reading in two chunks
    QCOMPARE(contents.size(), 5);
    contents += dev->read(50);
    QCOMPARE(contents.size(), 13);
    QCOMPARE( QString::fromLatin1(contents), QString::fromLatin1(arr) );
    delete dev;

    e = dir->entry( "mediumfile" );
    QVERIFY( e && e->isFile() );
    f = (KArchiveFile*)e;
    QCOMPARE( f->data().size(), SIZE1 );

    e = dir->entry( "hugefile" );
    QVERIFY( e && e->isFile() );
    f = (KArchiveFile*)e;
    QCOMPARE( f->data().size(), 20000   );

    e = dir->entry( "aaaemptydir" );
    QVERIFY( e && e->isDirectory() );

    e = dir->entry( "my/dir/test3" );
    QVERIFY( e && e->isFile() );
    f = (KArchiveFile*)e;
    dev = f->createDevice();
    QByteArray firstLine = dev->readLine();
    QCOMPARE(QString::fromLatin1(firstLine), QString::fromLatin1("I do not speak German\n"));
    QByteArray secondLine = dev->read(100);
    QCOMPARE(QString::fromLatin1(secondLine), QString::fromLatin1("David."));
    delete dev;
#ifndef Q_OS_WIN
    e = dir->entry( "z/test3_symlink" );
    QVERIFY(e);
    QVERIFY(e->isFile());
    QCOMPARE(e->symLinkTarget(), QString("test3"));
#endif

    // Test "./" prefix for KOffice (xlink:href="./ObjectReplacements/Object 1")
    e = dir->entry( "./hugefile" );
    QVERIFY( e && e->isFile() );
    e = dir->entry( "./my/dir/test3" );
    QVERIFY( e && e->isFile() );

    // Test directory entries
    e = dir->entry( "my" );
    QVERIFY(e && e->isDirectory());
    e = dir->entry( "my/" );
    QVERIFY(e && e->isDirectory());
    e = dir->entry( "./my/" );
    QVERIFY(e && e->isDirectory());
}
Exemple #24
0
void MemoryMap::diffWith(MemoryMap* other)
{
    _pmemDiff.clear();

    QIODevice* dev = _vmem->physMem();
    QIODevice* otherDev = other->vmem()->physMem();
    if (!otherDev || !dev)
        return;

    assert(dev != otherDev);

    // Open devices for reading, if required
    if (!dev->isReadable()) {
        if (dev->isOpen())
            dev->close();
        assert(dev->open(QIODevice::ReadOnly));
    }
    else
        assert(dev->reset());

    if (!otherDev->isReadable()) {
        if (otherDev->isOpen())
            otherDev->close();
        assert(otherDev->open(QIODevice::ReadOnly));
    }
    else
        assert(otherDev->reset());

    QTime timer;
    timer.start();
    bool wasEqual = true, equal = true;
    quint64 addr = 0, startAddr = 0, length = 0;
    const int bufsize = 1024;
    const int granularity = 16;
    char buf1[bufsize], buf2[bufsize];
    qint64 readSize1, readSize2;
    qint64 done, prevDone = -1;
    qint64 totalSize = qMin(dev->size(), otherDev->size());
    if (totalSize < 0)
        totalSize = qMax(dev->size(), otherDev->size());

    // Compare the complete physical address space
    while (!Console::interrupted() && !dev->atEnd() && !otherDev->atEnd()) {
        readSize1 = dev->read(buf1, bufsize);
        readSize2 = otherDev->read(buf2, bufsize);

        if (readSize1 <= 0 || readSize2 <= 0)
            break;

        qint64 size = qMin(readSize1, readSize2);
        for (int i = 0; i < size; ++i) {
            if (buf1[i] != buf2[i])
                equal = false;
            // We only consider memory chunks of size "granularity"
            if (addr % granularity == granularity - 1) {
                // Memory is equal
                if (equal) {
                    // Add difference to tree
                    if (!wasEqual)
                        _pmemDiff.insert(Difference(startAddr, length));
                }
                // Memory differs
                else {
                    // Start new difference
                    if (wasEqual) {
                        startAddr = addr - (addr % granularity);
                        length = granularity;
                    }
                    // Enlarge difference
                    else
                        length += granularity;
                }
                wasEqual = equal;
            }
            ++addr;
            equal = true;
        }

        done = (int) (addr / (float) totalSize * 100);
        if (prevDone < 0 || (done != prevDone && timer.elapsed() > 500)) {
            Console::out() << "\rComparing memory dumps: " << done << "%" << flush;
            prevDone = done;
            timer.restart();
        }
    }

    // Add last difference, if any
    if (!wasEqual)
        _pmemDiff.insert(Difference(startAddr, length));

    Console::out() << "\rComparing memory dumps finished." << endl;

//    debugmsg("No. of differences: " << _pmemDiff.objectCount());
}
bool LimitedSocket::readCycle()
{
	QByteArray buffer;
	bool bProblem = false;
	
	QIODevice* pRemote = getRemote();

	if(m_timer.isNull())
	{
		m_prevBytes = 0;
		m_timer.start();
	}
	
	int limit = m_nSpeedLimit;

	do
	{
		QByteArray buf;
		qint64 available;
		
		available = pRemote->bytesAvailable();
		if(!available && !pRemote->waitForReadyRead(10000))
		{
			bProblem = true;
			break;
		}
		
		qint64 toread = (limit) ? limit/2 : available;
		
		if(m_nToTransfer && m_nToTransfer-m_nTransfered < toread)
			toread = m_nToTransfer-m_nTransfered;
		
		buf = pRemote->read(toread);
		buffer += buf;
		m_nTransfered += buf.size();
		
		if(m_nTransfered >= m_nToTransfer && m_nToTransfer)
			break;
	}
	while(buffer.size() < 1024);

	m_file.write(buffer);

	if(bProblem)
	{
		/*if(m_pSocket->state() == QAbstractSocket::ConnectedState) // timeout
			m_strError = tr ( "Timeout" );
		else if(m_pSocket->error() == QAbstractSocket::RemoteHostClosedError)
		{
			if(m_nToTransfer > m_nTransfered && m_nToTransfer)
			{
				qDebug() << "Remote host closed the connection";
				m_strError = tr ( "Connection lost" );
			}
		}
		else
		{
			m_strError = m_pSocket->errorString();
			if ( m_strError.isEmpty() )
			{
				qDebug() << "Connection lost!";
				m_strError = tr ( "Connection lost" );
			}
		}*/
	}
	else if(!m_bAbort)
	{
//		QTime now = QTime::currentTime();
		qulonglong bnow = m_nTransfered;

		int msecs;
		qulonglong bytes = bnow - m_prevBytes;

		if((msecs = m_timer.elapsed()) > 1000)
		{
			m_statsLock.lockForWrite();
			m_stats << QPair<int,qulonglong> ( m_timer.restart(), bytes );
			if(m_stats.size() > SPEED_SAMPLES)
				m_stats.removeFirst();
			m_statsLock.unlock();

			m_prevBytes = bnow;
		}

		if(limit > 0 && bytes)
		{
			int sleeptime = bytes/ ( limit/1000 ) - msecs;
			if(sleeptime > 0)
				msleep(sleeptime*2);
		}
	}

	return !bProblem;
}
void QIODeviceProto::setTextModeEnabled(bool enabled)
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    item->setTextModeEnabled(enabled);
}
Exemple #27
0
void RpcConnection::sendRpcReply(PbRpcController *controller)
{
    google::protobuf::Message *response = controller->response();
    QIODevice *blob;
    char msgBuf[PB_HDR_SIZE];
    char* const msg = &msgBuf[0];
    int len;

    if (controller->Failed())
    {
        QByteArray err = controller->ErrorString().toUtf8();

        qWarning("rpc failed (%s)", qPrintable(controller->ErrorString()));
        len = err.size();
        writeHeader(msg, PB_MSG_TYPE_ERROR, pendingMethodId, len);
        clientSock->write(msg, PB_HDR_SIZE);
        clientSock->write(err.constData(), len);

        goto _exit;
    }

    blob = controller->binaryBlob();
    if (blob)
    {
        len = blob->size();
        qDebug("is binary blob of len %d", len);

        writeHeader(msg, PB_MSG_TYPE_BINBLOB, pendingMethodId, len);
        clientSock->write(msg, PB_HDR_SIZE);

        blob->seek(0);
        while (!blob->atEnd())
        {    
            int l;

            len = blob->read(msg, sizeof(msgBuf));
            l = clientSock->write(msg, len);
            Q_ASSERT(l == len);
            Q_UNUSED(l);
        }

        goto _exit;
    }

    if (!response->IsInitialized())
    {
        qWarning("response missing required fields!! <----");
        qDebug("response = \n%s"
               "missing = \n%s---->",
                response->DebugString().c_str(),
                response->InitializationErrorString().c_str());
        qFatal("exiting");
        goto _exit;
    }

    len = response->ByteSize();
    writeHeader(msg, PB_MSG_TYPE_RESPONSE, pendingMethodId, len);

    // Avoid printing stats since it happens once every couple of seconds
    if (pendingMethodId != 13)
    {
        qDebug("Server(%s): sending %d bytes to client <----",
            __FUNCTION__, len + PB_HDR_SIZE);
        BUFDUMP(msg, 8);
        qDebug("method = %d\nreq = \n%s---->", 
            pendingMethodId, response->DebugString().c_str());
    }

    clientSock->write(msg, PB_HDR_SIZE);
    response->SerializeToZeroCopyStream(outStream);
    outStream->Flush();

    if (pendingMethodId == 15) {
        isCompatCheckDone = true;
        isNotifEnabled = controller->NotifEnabled();
    }

_exit:
    if (controller->Disconnect())
        clientSock->disconnectFromHost();

    delete controller;
    isPending = false;
}
void QIODeviceProto::ungetChar(char c)
{
  QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject());
  if (item)
    item->ungetChar(c);
}
Exemple #29
0
//--------------------------------------------------------------------
void tst_QIODevice::unget()
{
#if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST)
    QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll);
#endif
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    buffer.write("ZXCV");
    buffer.seek(0);
    QCOMPARE(buffer.read(4), QByteArray("ZXCV"));
    QCOMPARE(buffer.pos(), qint64(4));

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    char buf[6];
    QCOMPARE(buffer.readLine(buf, 5), qint64(4));
    QCOMPARE(buffer.pos(), qint64(4));
    QCOMPARE(static_cast<const char*>(buf), "dcba");

    buffer.ungetChar('a');
    buffer.ungetChar('b');
    buffer.ungetChar('c');
    buffer.ungetChar('d');

    QCOMPARE(buffer.pos(), qint64(0));

    for (int i = 0; i < 5; ++i) {
        buf[0] = '@';
        buf[1] = '@';
        QTest::ignoreMessage(QtWarningMsg,
                             "QIODevice::readLine: Called with maxSize < 2");
        QCOMPARE(buffer.readLine(buf, 1), qint64(-1));
        QCOMPARE(buffer.readLine(buf, 2), qint64(i < 4 ? 1 : -1));
        switch (i) {
        case 0:
            QCOMPARE(buf[0], 'd');
            break;
        case 1:
            QCOMPARE(buf[0], 'c');
            break;
        case 2:
            QCOMPARE(buf[0], 'b');
            break;
        case 3:
            QCOMPARE(buf[0], 'a');
            break;
        case 4:
            QCOMPARE(buf[0], '\0');
            break;
        }
        QCOMPARE(buf[1], i < 4 ? '\0' : '@');
    }

    buffer.ungetChar('\n');
    QCOMPARE(buffer.readLine(), QByteArray("\n"));

    buffer.seek(1);
    buffer.readLine(buf, 3);
    QCOMPARE(static_cast<const char*>(buf), "XC");

    buffer.seek(4);
    buffer.ungetChar('Q');
    QCOMPARE(buffer.readLine(buf, 3), qint64(1));

    for (int i = 0; i < 2; ++i) {
        QTcpSocket socket;
        QIODevice *dev;
        QByteArray result;
        const char *lineResult;
        if (i == 0) {
            dev = &buffer;
            result = QByteArray("ZXCV");
            lineResult = "ZXCV";
        } else {
            socket.connectToHost(QtNetworkSettings::serverName(), 80);
            socket.write("GET / HTTP/1.0\r\n\r\n");
            QVERIFY(socket.waitForReadyRead());
            dev = &socket;
            result = QByteArray("HTTP");
            lineResult = "Date";
        }
        char ch, ch2;
        dev->seek(0);
        dev->getChar(&ch);
        dev->ungetChar(ch);
        QCOMPARE(dev->peek(4), result);
        dev->getChar(&ch);
        dev->getChar(&ch2);
        dev->ungetChar(ch2);
        dev->ungetChar(ch);
        QCOMPARE(dev->read(1), result.left(1));
        QCOMPARE(dev->read(3), result.right(3));

        if (i == 0)
            dev->seek(0);
        else
            dev->readLine();
        dev->getChar(&ch);
        dev->ungetChar(ch);
        dev->readLine(buf, 5);
        QCOMPARE(static_cast<const char*>(buf), lineResult);

        if (i == 1)
            socket.close();
    }
}
Exemple #30
0
QByteArray MocParser::readLine()
{
    ++lineNumber;
    return input->readLine();
}