void MocParser::parse(const char *fname, QIODevice *io, int lineNum) { filename = fname; input = io; lineNumber = lineNum; while (!input->atEnd()) { QByteArray line = readLine(); if (line.startsWith("static const uint qt_meta_data_")) { // start of new class data uint *data; loadIntData(data); // find the start of the string data do { line = readLine(); if (input->atEnd()) parseError(); } while (!line.startsWith("static const char qt_meta_stringdata_")); char *stringdata; loadStringData(stringdata); QMetaObject mo; mo.d.superdata = &QObject::staticMetaObject; mo.d.stringdata = stringdata; mo.d.data = data; mo.d.extradata = 0; objects.append(mo); } } fname = 0; input = 0; }
ColorScheme* KDE3ColorSchemeReader::read() { Q_ASSERT(_device->openMode() == QIODevice::ReadOnly || _device->openMode() == QIODevice::ReadWrite); ColorScheme* scheme = new ColorScheme(); QRegExp comment("#.*$"); while (!_device->atEnd()) { QString line(_device->readLine()); line.remove(comment); line = line.simplified(); if (line.isEmpty()) continue; if (line.startsWith(QLatin1String("color"))) { if (!readColorLine(line, scheme)) kWarning() << "Failed to read KDE 3 color scheme line" << line; } else if (line.startsWith(QLatin1String("title"))) { if (!readTitleLine(line, scheme)) kWarning() << "Failed to read KDE 3 color scheme title line" << line; } else { kWarning() << "KDE 3 color scheme contains an unsupported feature, '" << line << "'"; } } return scheme; }
const QByteArray& QxtMailAttachment::rawData() const { if (qxt_d->content == 0) { qWarning("QxtMailAttachment::rawData(): Content not set!"); static QByteArray defaultRv; return defaultRv; } if (qobject_cast<QBuffer *>(qxt_d->content.data()) == 0) { // content isn't hold in a buffer but in another kind of QIODevice // (probably a QFile...). Read the data and cache it into a buffer static QByteArray empty; QIODevice* c = content(); if (!c->isOpen() && !c->open(QIODevice::ReadOnly)) { qWarning() << "QxtMailAttachment::rawData(): Cannot open content for reading"; return empty; } QBuffer* cache = new QBuffer(); cache->open(QIODevice::WriteOnly); char buf[1024]; while (!c->atEnd()) { cache->write(buf, c->read(buf, 1024)); } if (qxt_d->deleteContent && qxt_d->content) qxt_d->content->deleteLater(); qxt_d->content = cache; qxt_d->deleteContent = true; } return qobject_cast<QBuffer *>(qxt_d->content.data())->data(); }
bool QIODeviceProto::atEnd() const { QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject()); if (item) return item->atEnd(); return false; }
/*! \reimp */ void QNetworkDiskCache::updateMetaData(const QNetworkCacheMetaData &metaData) { #if defined(QNETWORKDISKCACHE_DEBUG) qDebug() << "QNetworkDiskCache::updateMetaData()" << metaData.url(); #endif QUrl url = metaData.url(); QIODevice *oldDevice = data(url); if (!oldDevice) { #if defined(QNETWORKDISKCACHE_DEBUG) qDebug() << "QNetworkDiskCache::updateMetaData(), no device!"; #endif return; } QIODevice *newDevice = prepare(metaData); if (!newDevice) { #if defined(QNETWORKDISKCACHE_DEBUG) qDebug() << "QNetworkDiskCache::updateMetaData(), no new device!" << url; #endif return; } char data[1024]; while (!oldDevice->atEnd()) { qint64 s = oldDevice->read(data, 1024); newDevice->write(data, s); } delete oldDevice; insert(newDevice); }
int QIOInputFunction(void* data, uint8_t* buf, size_t count) { QIODevice* io = static_cast<QIODevice*>(data); if (io->atEnd()) return 0; return io->read(reinterpret_cast<char*>(buf),count); }
/*! \internal Reads the configuration out from a io device. */ void dtkLoggingPrivate::readSettings(QIODevice &device) { QMutexLocker locker(&_mutexRegisteredCategory); { _logConfigItemList.clear(); if (device.open(QIODevice::ReadOnly)) { QByteArray truearray("true"); QByteArray line; while (!device.atEnd()) { line = device.readLine().replace(" ", ""); line = line.simplified(); const QList<QByteArray> pair = line.split('='); if (pair.count() == 2) _logConfigItemList.append(dtkLogConfigFilterItem(QString::fromLatin1(pair.at(0)) , (pair.at(1).toLower() == truearray))); } } foreach (dtkLoggingCategory *category, _registeredCategories) { updateCategory(category); } _registerCategories = true; }
/** * This tests the decompression using kfilterdev, basically. * To debug KTarPrivate::fillTempFile(). * * @dataProvider setupData */ void KArchiveTest::testUncompress() { QFETCH(QString, fileName); QFETCH(QString, mimeType); // testCreateTar must have been run first. QVERIFY(QFile::exists(fileName)); QIODevice *filterDev = KFilterDev::deviceForFile(fileName, mimeType, true); QVERIFY(filterDev); QByteArray buffer; buffer.resize(8*1024); kDebug() << "buffer.size()=" << buffer.size(); QVERIFY(filterDev->open(QIODevice::ReadOnly)); qint64 totalSize = 0; qint64 len = -1; while (!filterDev->atEnd() && len != 0) { len = filterDev->read(buffer.data(), buffer.size()); QVERIFY(len >= 0); totalSize += len; // kDebug() << "read len=" << len << " totalSize=" << totalSize; } filterDev->close(); delete filterDev; // kDebug() << "totalSize=" << totalSize; QVERIFY(totalSize > 26000); // 27648 here when using gunzip }
void MocParser::loadIntData(uint *&data) { data = 0; // initialise QVarLengthArray<uint> array; QRegExp rx(QLatin1String("(\\d+|0x[0-9abcdef]+)"), Qt::CaseInsensitive); while (!input->atEnd()) { QString line = QLatin1String(readLine()); int pos = line.indexOf(QLatin1String("//")); if (pos != -1) line.truncate(pos); // drop comments if (line == QLatin1String("};\n")) { // end of data data = new uint[array.count()]; memcpy(data, array.data(), array.count() * sizeof(*data)); return; } pos = 0; while ((pos = rx.indexIn(line, pos)) != -1) { QString num = rx.cap(1); if (num.startsWith(QLatin1String("0x"))) array.append(num.mid(2).toUInt(0, 16)); else array.append(num.toUInt()); pos += rx.matchedLength(); } } parseError(); }
Replayer::Replayer(QObject *parent, const QString &filename) : QThread(parent), m_commandSeriesCounter(1), filename(filename), speed(1.0), playing(true) { QIODevice *device = NULL; if (filename.endsWith(".png")) { QByteArray *data = new QByteArray(PNG2TXT(filename)); device = new QBuffer(data); } else if (filename.endsWith(".qsgs")) { QFile *file = new QFile(filename); if (file->open(QFile::ReadOnly)) { char header; file->getChar(&header); if (header == '\0') { QByteArray content = file->readAll(); delete file; QByteArray *data = new QByteArray(qUncompress(content)); device = new QBuffer(data); } else { file->close(); device = file; } } else { return; } } if (device == NULL) return; if (!device->open(QIODevice::ReadOnly | QIODevice::Text)) return; while (!device->atEnd()) { QByteArray line = device->readLine(); int split = line.indexOf(' '); Pair pair; pair.elapsed = line.left(split).toInt(); pair.cmd = line.mid(split + 1); pairs << pair; } delete device; int time_offset = 0; pair_offset = 0; foreach (const Pair &pair, pairs) { Packet packet; if (packet.parse(pair.cmd)) { if (packet.getCommandType() == S_COMMAND_START_IN_X_SECONDS) { time_offset = pair.elapsed; break; } } pair_offset++; }
Replayer::Replayer(QObject *parent, const QString &filename) :QThread(parent), m_isOldVersion(false), m_commandSeriesCounter(1), filename(filename), speed(1.0), playing(true) { QIODevice *device = NULL; if(filename.endsWith(".png")){ QByteArray *data = new QByteArray(PNG2TXT(filename)); QBuffer *buffer = new QBuffer(data); device = buffer; }else if(filename.endsWith(".txt")){ QFile *file = new QFile(filename); device = file; } if(device == NULL) return; if(!device->open(QIODevice::ReadOnly | QIODevice::Text)) return; typedef char buffer_t[1024]; initCommandPair(); while(!device->atEnd()){ buffer_t line; memset(line, 0, sizeof(buffer_t)); device->readLine(line, sizeof(buffer_t)); char *space = strchr(line, ' '); if(space == NULL) continue; *space = '\0'; QString cmd = space + 1; int elapsed = atoi(line); //@todo: There is a serious problem that the old protocol didn't has //any tag or type definition for the sent messages, and if the old protocol // wants to be translated to the new protocol, there is no information for the package type //and client will be confused of showing dialog or not. commandTranslation(cmd); Pair pair; pair.elapsed = elapsed; pair.cmd = cmd; pairs << pair; } if(m_isOldVersion){ QMessageBox::warning(NULL, tr("Warning"), tr("The replay use old protocol")); } delete device; }
static bool copyData(QIODevice &inFile, QIODevice &outFile) { while (!inFile.atEnd()) { char buf[4096]; qint64 readLen = inFile.read(buf, 4096); if (readLen <= 0) return false; if (outFile.write(buf, readLen) != readLen) return false; } return true; }
// Helper for xmlBufferCompare static bool textBufferCompare( const QByteArray& source, const QByteArray& dest, // for the qDebug only QIODevice& sourceFile, QIODevice& destFile) { int lineNumber = 1; while (!sourceFile.atEnd()) { if (destFile.atEnd()) return false; QByteArray sourceLine = sourceFile.readLine(); QByteArray destLine = destFile.readLine(); if (sourceLine != destLine) { sourceLine.chop(1); // remove '\n' destLine.chop(1); // remove '\n' qDebug() << source << "and" << dest << "differ at line" << lineNumber; qDebug("got : %s", sourceLine.constData()); qDebug("expected: %s", destLine.constData()); return false; } ++lineNumber; } return true; }
Tellico::Data::CollPtr AMCImporter::collection() { if(m_coll) { return m_coll; } if(!fileRef().open()) { return Data::CollPtr(); } QIODevice* f = fileRef().file(); m_ds.setDevice(f); // AMC is always little-endian? can't confirm m_ds.setByteOrder(QDataStream::LittleEndian); emit signalTotalSteps(this, f->size()); const uint l = AMC_FILE_ID.length(); QVector<char> buffer(l+1); m_ds.readRawData(buffer.data(), l); QString version = QString::fromLocal8Bit(buffer.data(), l); QRegExp versionRx(QLatin1String(".+AMC_(\\d+)\\.(\\d+).+")); if(versionRx.indexIn(version) == -1) { myDebug() << "no file id match"; return Data::CollPtr(); } m_coll = new Data::VideoCollection(true); m_majVersion = versionRx.cap(1).toInt(); m_minVersion = versionRx.cap(2).toInt(); // myDebug() << m_majVersion << "-" << m_minVersion; readString(); // name readString(); // email if(m_majVersion <= 3 && m_minVersion < 5) { readString(); // icq } readString(); // webpage readString(); // description const bool showProgress = options() & ImportProgress; while(!m_cancelled && !m_failed && !f->atEnd()) { readEntry(); if(showProgress) { emit signalProgress(this, f->pos()); qApp->processEvents(); } } return m_coll; }
bool ExternalFile::readItem( QDataStream& in, ItemData& itemData, DatFormat *datFormat, TibiaModule *tibiaModule, qint32 index, quint32& address, QString& error ) { QIODevice *device = in.device(); if( !device ) return false; quint8 type = 0; in >> type; if( type != ITEM_TYPE_ITEM && type != ITEM_TYPE_OUTFIT && type != ITEM_TYPE_EFFECT && type != ITEM_TYPE_PROJECTILE ) { error = QObject::tr( "Unknown Item type" ); return false; } ItemData d_itemData; if( datFormat ) { if( !ItemFile::loadItem( datFormat, in, d_itemData, error ) ) return false; } d_itemData.parent = ITEM_PARENT_EXTERNAL; d_itemData.type = type; address = 0; if( !device->atEnd() ) { quint32 spriteCount = 0, now = 0, offset = 0; in >> spriteCount; address = device->pos(); now = device->pos(); for( quint32 i = 0; i < spriteCount; i++ ) { device->seek( now ); in >> offset; if ( offset == 0x00000000 || offset > device->size() ) { // Direct to an image that doesnt exist or out of boundaries now += sizeof( quint32 ); continue; } QMutex mutex; mutex.lock(); SharedResource *resource = &g_resourceHandler.addResource(RESOURCE_TYPE_SPRITE, index, i, tibiaModule); d_itemData.setSpriteResource(i, *resource); mutex.unlock(); now += sizeof( quint32 ); } }
bool KDSoapServerSocket::handleFileDownload(KDSoapServerObjectInterface *serverObjectInterface, const QString &path) { QByteArray contentType; QIODevice* device = serverObjectInterface->processFileRequest(path, contentType); if (!device) { const QByteArray notFound = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"; write(notFound); return true; } if (!device->open(QIODevice::ReadOnly)) { const QByteArray forbidden = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"; write(forbidden); delete device; return true; // handled! } const QByteArray response = httpResponseHeaders(false, contentType, device->size()); if (m_doDebug) { qDebug() << "KDSoapServerSocket: file download response" << response; } qint64 written = write(response); Q_ASSERT(written == response.size()); // Please report a bug if you hit this. Q_UNUSED(written); char block[4096]; qint64 totalRead = 0; while (!device->atEnd()) { const qint64 in = device->read(block, sizeof(block)); if (in <= 0) break; totalRead += in; if(in != write(block, in)) { //error = true; break; } } //if (totalRead != device->size()) { // // Unable to read from the source. // error = true; //} delete device; // TODO log the file request, if logging is enabled? return true; }
Replayer::Replayer(QObject *parent, const QString &filename) : QThread(parent), m_commandSeriesCounter(1), filename(filename), speed(1.0), playing(true) { QIODevice *device = NULL; if (filename.endsWith(".png")) { QByteArray *data = new QByteArray(Recorder::PNG2TXT(filename)); QBuffer *buffer = new QBuffer(data); device = buffer; } else if (filename.endsWith(".txt")) { QFile *file = new QFile(filename); device = file; } if (device == NULL) return; if (!device->open(QIODevice::ReadOnly | QIODevice::Text)) return; typedef char buffer_t[65535]; while (!device->atEnd()) { buffer_t line; memset(line, 0, sizeof(buffer_t)); device->readLine(line, sizeof(buffer_t)); char *space = strchr(line, ' '); if (space == NULL) continue; *space = '\0'; QString cmd = space + 1; int elapsed = atoi(line); Pair pair; pair.elapsed = elapsed; pair.cmd = cmd; pairs << pair; } delete device; }
QVariantMap Message::parse(QIODevice &data, const QString &tagPathPrefix) const { QVariantMap parsedFields; while (!data.atEnd()) { // Fetch the next field's tag index and wire type. QPair<quint32, quint8> tagAndType = parseTagAndType(data); if (tagAndType.first == 0) { qWarning() << "invalid tag:" << tagAndType.first; return QVariantMap(); } // If this is a (deprecated) "end group", return the parsed group. if (tagAndType.second == Types::EndGroup) { return parsedFields; } // Get the (optional) field name and type hint for this field. const QString tagPath = QString::fromLatin1("%1%2").arg(tagPathPrefix).arg(tagAndType.first); FieldInfo fieldInfo = this->fieldInfo.value(tagPath); // Note intentional fallback to default-constructed. if (fieldInfo.fieldName.isEmpty()) { fieldInfo.fieldName = QString::fromLatin1("%1").arg(tagAndType.first); } // Parse the field value. const QVariant value = parseValue(data, tagAndType.second, fieldInfo.scalarType, tagPath); if (!value.isValid()) { return QVariantMap(); } // Add the parsed value(s) to the parsed fields map. QVariantList list = parsedFields[fieldInfo.fieldName].toList(); if (static_cast<QMetaType::Type>(value.type()) == QMetaType::QVariantList) { list << value.toList(); } else { list << value; } parsedFields[fieldInfo.fieldName] = list; } return parsedFields; }
bool Nicookie::safariFindFile(QIODevice &device) { // Signature QByteArray headr_signature("cook", 4); if (headr_signature != device.read(4)) { setError(Nicookie::InvalidDataFormtaError); return false; } // No. of pages quint32 page_num = readUint32BE(device); if (page_num == 0) { setError(Nicookie::NotFoundDataError); return false; } // Page N Size QList<quint32> page_size_list; for (quint32 i = 0; i < page_num; ++i) { page_size_list.append(readUint32BE(device)); } if (device.atEnd()) { setError(Nicookie::InvalidDataFormtaError); return false; } // Page N for (auto &page_size: page_size_list) { qint64 pos = device.pos(); if (safariFindPage(device)) return true; device.seek(pos + page_size); } if (!hasError()) { setError(Nicookie::NotFoundDataError); } return false; }
void QMQTT::SslNetwork::onSocketReadReady() { QIODevice *ioDevice = _socket->ioDevice(); while(!ioDevice->atEnd()) { if(_bytesRemaining == 0) { if (!ioDevice->getChar(reinterpret_cast<char *>(&_header))) { // malformed packet emit error(QAbstractSocket::OperationError); ioDevice->close(); return; } _bytesRemaining = readRemainingLength(); if (_bytesRemaining < 0) { // malformed remaining length emit error(QAbstractSocket::OperationError); ioDevice->close(); return; } } QByteArray data = ioDevice->read(_bytesRemaining); _buffer.append(data); _bytesRemaining -= data.size(); if(_bytesRemaining == 0) { Frame frame(_header, _buffer); _buffer.clear(); emit received(frame); } } }
Replayer::Replayer(QObject *parent, const QString &filename) : QThread(parent), m_commandSeriesCounter(1), filename(filename), speed(1.0), playing(true) { QIODevice *device = NULL; if (filename.endsWith(".png")) { QByteArray *data = new QByteArray(PNG2TXT(filename)); QBuffer *buffer = new QBuffer(data); device = buffer; } else if (filename.endsWith(".qsgs")) { QFile *file = new QFile(filename); device = file; } if (device == NULL) return; if (!device->open(QIODevice::ReadOnly | QIODevice::Text)) return; while (!device->atEnd()) { QString line = QString::fromUtf8(device->readLine()); QStringList splited_line = line.split(" "); QString elapsed_str = splited_line.takeFirst(); QString cmd = splited_line.join(" "); int elapsed = elapsed_str.toInt(); Pair pair; pair.elapsed = elapsed; pair.cmd = cmd; pairs << pair; } delete device; }
bool Record::open() { QIODevice *device = new QFile(m_fileName); if (!device->open(QFile::ReadOnly)) return false; char header; device->getChar(&header); if (header == '\0') { m_format = CompressedText; QByteArray content = device->readAll(); delete device; QByteArray *data = new QByteArray(qUncompress(content)); device = new QBuffer(data); device->open(QFile::ReadOnly); } else { m_format = PlainText; device->ungetChar(header); device->seek(0); } m_commands.clear(); while (!device->atEnd()) { QByteArray line = device->readLine(); int split = line.indexOf(' '); Command command; command.elapsed = line.left(split).toInt(); command.data = line.mid(split + 1); m_commands << command; } return true; }
void tst_QIODevice::peekAndRead() { QByteArray originalData; for (int i=0; i<1000; i++) originalData += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; QBuffer buffer; QFile::remove("peektestfile"); QFile file("peektestfile"); for (int i = 0; i < 2; ++i) { QByteArray readData; QIODevice *device = i ? (QIODevice *)&file : (QIODevice *)&buffer; device->open(QBuffer::ReadWrite); device->write(originalData); device->seek(0); while (!device->atEnd()) { char peekIn[26]; device->peek(peekIn, 26); readData += device->read(26); } QCOMPARE(readData, originalData); } QFile::remove("peektestfile"); }
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 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 FlushedProcess::atEnd() const { QIODevice * dev = readingIODevice(); return (dev == NULL)?true:dev->atEnd(); }
bool PSCommentLexer::parse(QIODevice& fin) { char c; m_buffer.clear(); m_curState = State_Start; parsingStarted(); while (!fin.atEnd()) { fin.getChar(&c); // qDebug ("got %c", c); State newState; Action action; nextStep(c, &newState, &action); switch (action) { case Action_Copy : m_buffer.append(c); break; case Action_CopyOutput : m_buffer.append(c); doOutput(); break; case Action_Output : doOutput(); break; case Action_OutputUnget : doOutput(); fin.ungetChar(c); break; case Action_Ignore : /* ignore */ break; case Action_Abort : qWarning("state %s / %s char %c (%d)" , statetoa(m_curState), statetoa(newState), c, c); parsingAborted(); return false; break; case Action_InitTemp : m_temp.clear(); break; case Action_CopyTemp : m_temp.append(c); break; case Action_DecodeUnget : m_buffer.append(decode()); fin.ungetChar(c); break; default : qWarning("unknown action: %d ", action); } m_curState = newState; } parsingFinished(); return true; }
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(); }
void PakProtocol::get(const KURL &url) { kdDebug(PAK_DEBUG_ID) << "ArchiveProtocol::get " << url << endl; QString path; KIO::Error errorNum; if ( !checkNewFile( url, path, errorNum ) ) { if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING ) { // If we cannot open, it might be a problem with the archive header (e.g. unsupported format) // Therefore give a more specific error message error( KIO::ERR_SLAVE_DEFINED, i18n( "Could not open the file, probably due to an unsupported file format.\n%1") .arg( url.prettyURL() ) ); return; } else { // We have any other error error( errorNum, url.prettyURL() ); return; } } kdDebug(PAK_DEBUG_ID) << "Continue getting" << endl; path = QString::fromLocal8Bit(remoteEncoding()->encode(path)); kdDebug(PAK_DEBUG_ID) << "Path > " << path << endl; const KArchiveDirectory* root = _pakFile->directory(); const KArchiveEntry* archiveEntry = root->entry( path ); kdDebug(PAK_DEBUG_ID) << "Check if no archiveEntry > " << archiveEntry << endl; if ( !archiveEntry ) { error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() ); return; } kdDebug(PAK_DEBUG_ID) << "archiveEntry::name > " << archiveEntry->name() << endl; if ( archiveEntry->isDirectory() ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL() ); return; } const KArchiveFile* archiveFileEntry = static_cast<const KArchiveFile *>(archiveEntry); if ( !archiveEntry->symlink().isEmpty() ) { kdDebug(7109) << "Redirection to " << archiveEntry->symlink() << endl; KURL realURL; if (archiveEntry->symlink().startsWith("/")) { // absolute path realURL.setPath(archiveEntry->symlink() ); // goes out of tar:/, back into file: } else { realURL = KURL( url, archiveEntry->symlink() ); } kdDebug(7109) << "realURL= " << realURL << endl; redirection( realURL ); finished(); return; } //kdDebug(7109) << "Preparing to get the archive data" << endl; /* * The easy way would be to get the data by calling archiveFileEntry->data() * However this has drawbacks: * - the complete file must be read into the memory * - errors are skipped, resulting in an empty file */ QIODevice* io = 0; // Getting the device is hard, as archiveFileEntry->device() is not virtual! if ( url.protocol() == "pak" ) { io = archiveFileEntry->device(); } else { // Wrong protocol? Why was this not catched by checkNewFile? kdWarning(7109) << "Protocol " << url.protocol() << " not supported by this IOSlave; " << k_funcinfo << endl; error( KIO::ERR_UNSUPPORTED_PROTOCOL, url.protocol() ); return; } if (!io) { error( KIO::ERR_SLAVE_DEFINED, i18n( "The archive file could not be opened, perhaps because the format is unsupported.\n%1" ) .arg( url.prettyURL() ) ); return; } if ( !io->open( IO_ReadOnly ) ) { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL() ); return; } totalSize( archiveFileEntry->size() ); // Size of a QIODevice read. It must be large enough so that the mime type check will not fail const int maxSize = 0x100000; // 1MB int bufferSize = kMin( maxSize, archiveFileEntry->size() ); QByteArray buffer ( bufferSize ); if ( buffer.isEmpty() && bufferSize > 0 ) { // Something went wrong error( KIO::ERR_OUT_OF_MEMORY, url.prettyURL() ); return; } bool firstRead = true; // How much file do we still have to process? int fileSize = archiveFileEntry->size(); KIO::filesize_t processed = 0; while ( !io->atEnd() && fileSize > 0 ) { if ( !firstRead ) { bufferSize = kMin( maxSize, fileSize ); buffer.resize( bufferSize, QGArray::SpeedOptim ); } const Q_LONG read = io->readBlock( buffer.data(), buffer.size() ); // Avoid to use bufferSize here, in case something went wrong. if ( read != bufferSize ) { kdWarning(7109) << "Read " << read << " bytes but expected " << bufferSize << endl; error( KIO::ERR_COULD_NOT_READ, url.prettyURL() ); return; } if ( firstRead ) { // We use the magic one the first data read // (As magic detection is about fixed positions, we can be sure that it is enough data.) KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( buffer, path ); kdDebug(7109) << "Emitting mimetype " << result->mimeType() << endl; mimeType( result->mimeType() ); firstRead = false; } data( buffer ); processed += read; processedSize( processed ); fileSize -= bufferSize; } io->close(); delete io; data( QByteArray() ); finished(); /*kdDebug(PAK_DEBUG_ID) << "Entering get()" << endl; mimetype("text/plain"); QCString str("Hello Pak World!!"); data(str); finished(); kdDebug(PAK_DEBUG_ID) << "Exiting get()" << endl;*/ }
void ArchiveProtocol::get( const KUrl & url ) { kDebug( 7109 ) << "ArchiveProtocol::get" << url.url(); QString path; KIO::Error errorNum; if ( !checkNewFile( url, path, errorNum ) ) { if ( errorNum == KIO::ERR_CANNOT_OPEN_FOR_READING ) { // If we cannot open, it might be a problem with the archive header (e.g. unsupported format) // Therefore give a more specific error message error( KIO::ERR_SLAVE_DEFINED, i18n( "Could not open the file, probably due to an unsupported file format.\n%1", url.prettyUrl() ) ); return; } else { // We have any other error error( errorNum, url.prettyUrl() ); return; } } const KArchiveDirectory* root = m_archiveFile->directory(); const KArchiveEntry* archiveEntry = root->entry( path ); if ( !archiveEntry ) { error( KIO::ERR_DOES_NOT_EXIST, url.prettyUrl() ); return; } if ( archiveEntry->isDirectory() ) { error( KIO::ERR_IS_DIRECTORY, url.prettyUrl() ); return; } const KArchiveFile* archiveFileEntry = static_cast<const KArchiveFile *>(archiveEntry); if ( !archiveEntry->symLinkTarget().isEmpty() ) { kDebug(7109) << "Redirection to" << archiveEntry->symLinkTarget(); KUrl realURL( url, archiveEntry->symLinkTarget() ); kDebug(7109).nospace() << "realURL=" << realURL.url(); redirection( realURL ); finished(); return; } //kDebug(7109) << "Preparing to get the archive data"; /* * The easy way would be to get the data by calling archiveFileEntry->data() * However this has drawbacks: * - the complete file must be read into the memory * - errors are skipped, resulting in an empty file */ QIODevice* io = archiveFileEntry->createDevice(); if (!io) { error( KIO::ERR_SLAVE_DEFINED, i18n( "The archive file could not be opened, perhaps because the format is unsupported.\n%1" , url.prettyUrl() ) ); return; } if ( !io->open( QIODevice::ReadOnly ) ) { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyUrl() ); delete io; return; } totalSize( archiveFileEntry->size() ); // Size of a QIODevice read. It must be large enough so that the mime type check will not fail const qint64 maxSize = 0x100000; // 1MB qint64 bufferSize = qMin( maxSize, archiveFileEntry->size() ); QByteArray buffer; buffer.resize( bufferSize ); if ( buffer.isEmpty() && bufferSize > 0 ) { // Something went wrong error( KIO::ERR_OUT_OF_MEMORY, url.prettyUrl() ); delete io; return; } bool firstRead = true; // How much file do we still have to process? qint64 fileSize = archiveFileEntry->size(); KIO::filesize_t processed = 0; while ( !io->atEnd() && fileSize > 0 ) { if ( !firstRead ) { bufferSize = qMin( maxSize, fileSize ); buffer.resize( bufferSize ); } const qint64 read = io->read( buffer.data(), buffer.size() ); // Avoid to use bufferSize here, in case something went wrong. if ( read != bufferSize ) { kWarning(7109) << "Read" << read << "bytes but expected" << bufferSize ; error( KIO::ERR_COULD_NOT_READ, url.prettyUrl() ); delete io; return; } if ( firstRead ) { // We use the magic one the first data read // (As magic detection is about fixed positions, we can be sure that it is enough data.) KMimeType::Ptr mime = KMimeType::findByNameAndContent( path, buffer ); kDebug(7109) << "Emitting mimetype" << mime->name(); mimeType( mime->name() ); firstRead = false; } data( buffer ); processed += read; processedSize( processed ); fileSize -= bufferSize; } io->close(); delete io; data( QByteArray() ); finished(); }