/*! \reimp */ void QxtXmlFileLoggerEngine::initLoggerEngine() { QxtAbstractFileLoggerEngine::initLoggerEngine(); // Mkay, we have an open file. We need to check that it's all valid. // at the end of this block of code, we either can't log, or the carat is ready for writing. /* <?xml version="1.0" encoding="UTF-8"?> <log> <entry type="Error" time="sometime"> <message>What's going on?</message> <message?Hi there</message> </entry> </log> */ QIODevice* file = device(); Q_ASSERT(file); if (file->size() == 0) { file->write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); file->write("<log>\n"); file->write("</log>"); } else { QByteArray data = file->read(64); if (!data.startsWith(QByteArray("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<log>"))) { QFile* ptr_fileTarget = static_cast<QFile*>(file); qxtLog->warning(QString(" is not a valid XML log file.").prepend(ptr_fileTarget->fileName())); killLoggerEngine(); return; } } }
// FIXME move to frame? bool writeFrame(QIODevice& output, const Frame& frame, bool compressed = true) { if (frame.type == Frame::TYPE_INVALID) { qWarning() << "Attempting to write invalid frame"; return true; } auto written = output.write((char*)&(frame.type), sizeof(FrameType)); if (written != sizeof(FrameType)) { return false; } //qDebug(recordingLog) << "Writing frame with time offset " << frame.timeOffset; written = output.write((char*)&(frame.timeOffset), sizeof(Frame::Time)); if (written != sizeof(Frame::Time)) { return false; } QByteArray frameData = frame.data; if (compressed) { frameData = qCompress(frameData); } uint16_t dataSize = frameData.size(); written = output.write((char*)&dataSize, sizeof(FrameSize)); if (written != sizeof(uint16_t)) { return false; } if (dataSize != 0) { written = output.write(frameData); if (written != dataSize) { return false; } } return true; }
bool VideoData::saveData(QIODevice &device) { if (d->dataStoreState == StateSpooled) { Q_ASSERT(d->temporaryFile); // otherwise the collection should not have called this if (d->temporaryFile) { if (!d->temporaryFile->open()) { kWarning(30006) << "Read file from temporary store failed"; return false; } char buf[8192]; while (true) { d->temporaryFile->waitForReadyRead(-1); qint64 bytes = d->temporaryFile->read(buf, sizeof(buf)); if (bytes <= 0) break; // done! do { qint64 nWritten = device.write(buf, bytes); if (nWritten == -1) { d->temporaryFile->close(); return false; } bytes -= nWritten; } while (bytes > 0); } d->temporaryFile->close(); } return true; } else if (!d->videoLocation.isEmpty()) { if (d->saveVideoInZip) { // An external video have been specified QFile file(d->videoLocation.toLocalFile()); if (!file.open(QIODevice::ReadOnly)) { kWarning(30006) << "Read file failed"; return false; } char buf[8192]; while (true) { file.waitForReadyRead(-1); qint64 bytes = file.read(buf, sizeof(buf)); if (bytes <= 0) break; // done! do { qint64 nWritten = device.write(buf, bytes); if (nWritten == -1) { file.close(); return false; } bytes -= nWritten; } while (bytes > 0); } file.close(); } } return false; }
bool BString::writeToDevice(QIODevice &device) { const QByteArray lengthStr(QByteArray::number(m_data.length())); if(lengthStr.size() != device.write(lengthStr.data(), lengthStr.size())) return false; if(!device.putChar(':')) return false; if(m_data.size() != device.write(m_data.constData(), m_data.size())) return false; return true; }
// called from the collection bool KoImageDataPrivate::saveData(QIODevice &device) { // if we have a temp file save that to the store. This is needed as to not loose data when // saving lossy formats. Also wrinting out gif is not supported by qt so saving temp file // also fixes the problem that gif images are empty after saving- if (temporaryFile) { if (!temporaryFile->open()) { kWarning(30006) << "Read file from temporary store failed"; return false; } char buf[4096]; while (true) { temporaryFile->waitForReadyRead(-1); qint64 bytes = temporaryFile->read(buf, sizeof(buf)); if (bytes <= 0) break; // done! do { qint64 nWritten = device.write(buf, bytes); if (nWritten == -1) { temporaryFile->close(); return false; } bytes -= nWritten; } while (bytes > 0); } temporaryFile->close(); return true; } switch (dataStoreState) { case KoImageDataPrivate::StateEmpty: return false; case KoImageDataPrivate::StateNotLoaded: // we should not reach this state as above this will already be saved. Q_ASSERT(temporaryFile); return true; case KoImageDataPrivate::StateImageLoaded: case KoImageDataPrivate::StateImageOnly: { // save image QBuffer buffer; QImageWriter writer(&buffer, suffix.toLatin1()); bool result = writer.write(image); device.write(buffer.data(), buffer.size()); return result; } } return false; }
void outputStringList(QIODevice& output, const QStringList& sl){ QListIterator<QString> itr (sl); while (itr.hasNext()) { output.write(QString(itr.next()).toUtf8()); } }
// Javascript does not support pass by reference String parameters. Don't use a pointer. //qint64 QIODeviceProto::write(const char *data) qint64 QIODeviceProto::write(char data) { QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject()); if (item) return item->write(&data); return 0; }
bool KoStorePrivate::extractFile(const QString &srcName, QIODevice &buffer) { if (!q->open(srcName)) return false; if (!buffer.open(QIODevice::WriteOnly)) { q->close(); return false; } // ### This could use KArchive::copy or something, no? QByteArray data; data.resize(8 * 1024); uint total = 0; for (int block = 0; (block = q->read(data.data(), data.size())) > 0; total += block) { buffer.write(data.data(), block); } if (q->size() != static_cast<qint64>(-1)) Q_ASSERT(total == q->size()); buffer.close(); q->close(); return true; }
/*! \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); }
qint64 QIODeviceProto::write(const char *data, qint64 maxSize) { QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject()); if (item) return item->write(data, maxSize); return 0; }
void push(double *left, double *right, int length, int offset) { if (!device) { device = out->start(); } int remain = length; int finished = 0; while (0 < remain) { int amount = kUnitBufferLength / 4 <= remain ? kUnitBufferLength / 4 : remain; int index = 0; for (int i = 0; i < amount; i++) { int16_t leftData = (int16_t)(left[i + finished + offset] * 32767); int16_t rightData = (int16_t)(right[i + finished + offset] * 32767); buffer[index++] = static_cast<uint8_t *>(&leftData)[0]; buffer[index++] = static_cast<uint8_t *>(&leftData)[1]; buffer[index++] = static_cast<uint8_t *>(&rightData)[0]; buffer[index++] = static_cast<uint8_t *>(&rightData)[1]; } int bytesToWrite = amount * 4; int bytesWritten = 0; while (bytesWritten < bytesToWrite) { int actualWrittenBytes = device->write( (const char *)(buffer + bytesWritten), (qint64)(bytesToWrite - bytesWritten)); bytesWritten += actualWrittenBytes; } remain -= amount; finished += amount; } }
void GameState::Serialize(QIODevice& f) { QString serialization; QXmlStreamWriter stream(&serialization); stream.setAutoFormatting(true); stream.writeStartDocument(); stream.writeStartElement("SaveGame"); stream.writeStartElement("Board"); stream.writeAttribute("Width", QString::number(this->width)); stream.writeAttribute("Height", QString::number(this->height)); stream.writeAttribute("StepsPerformed", QString::number((this->stepNum))); for (uint i = 0; i < height; i++) { stream.writeCharacters("\n "); for (uint j = 0; j < width; j++) { stream.writeCharacters(QString::number(this->board[i][j]) + " "); } } stream.writeCharacters("\n "); stream.writeEndElement(); stream.writeEndElement(); stream.writeEndDocument(); f.open(QIODevice::WriteOnly); f.write(serialization.toUtf8()); f.close(); }
// This function simulates a partially or fully occupied disk cache // like a normal user of a cache might encounter is real-life browsing. // The point of this is to trigger degradation in file-system and media performance // that occur due to the quantity and layout of data. void tst_qnetworkdiskcache::injectFakeData() { QNetworkCacheMetaData::RawHeaderList headers; headers.append(qMakePair(QByteArray("X-TestHeader"),QByteArray("HeaderValue"))); //Prep cache dir with fake data using QNetworkDiskCache APIs for (quint32 i = 0; i < NumFakeCacheObjects; i++) { //prepare metata for url QNetworkCacheMetaData meta; QString fakeURL; QTextStream stream(&fakeURL); stream << fakeURLbase << i; QUrl url(fakeURL); meta.setUrl(url); meta.setRawHeaders(headers); meta.setSaveToDisk(true); //commit payload and metadata to disk QIODevice *device = cache->prepare(meta); device->write(payload); cache->insert(device); } }
bool SaveToJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion) { // marker that this data is valid data[magicIdentifier] = magicVersion; QJsonDocument doc = QJsonDocument::fromVariant(data); if(doc.isEmpty() || doc.isNull()) { qCritical() << "Failed to convert data to JSON document"; return false; } QByteArray jsontext = doc.toJson(QJsonDocument::Indented); qint64 ret = f.write(jsontext); if(ret != jsontext.size()) { qCritical() << "Failed to write JSON data: " << ret << " " << f.errorString(); return false; } return true; }
bool UdpDecorator::execute(Request &req, QIODevice &io) { form(req); io.readAll(); io.write(req.getBody()); QByteArray rxData; int cnt = 0; while(1) { int wait = 15; if(req.getWaitTime()!=0) wait = req.getWaitTime(); int length=0; for(int i=0; i<wait; i++) { QThread::currentThread()->msleep(1); rxData+=io.readAll(); if(rxData.count()) { if(length==rxData.count()) break; length = rxData.count(); } } if(rxData.count()) { req.updateRdData(rxData); req.setAnswerData(rxData); if(checkAnAnswer(req)) { getAnAnswer(req); return true; } } else cnt++; if(cnt>=20) { req.setAnswerData(QByteArray()); break; } } return false; }
bool writeConfFile(QIODevice &device, const QSettings::SettingsMap &map) { int maxKeyWidth = 20; QRegExp reKeyXt("^(.+)/(.+)$"); // for extracting keys/values // first go over map and find longest key length for(int i=0; i<map.keys().size(); i++) { QString k = map.keys().at(i); QString key = k; if (reKeyXt.exactMatch(k)) key = reKeyXt.cap(2); if (key.size() > maxKeyWidth) maxKeyWidth = key.size(); } // OK, this time actually write to the file - first non-section values QString outputLine; for(int i=0; i<map.keys().size(); i++) { QString k = map.keys().at(i); if (!reKeyXt.exactMatch(k)) { // this is for those keys without a section outputLine = QString("%1=%2\n").arg(k,map[k].toString()); device.write(outputLine.toUtf8()); } } return true; }
/*! Writes the contents of \a document to the text document \a content. It is left up to the calling code to \l {QContent::commit()}{commit} the changes in \a content to the document system. Returns true if the write was successful and false otherwise. */ bool NotesDemo::writeContent( QTextDocument *document, QContent *content ) { // Attempt to open the content in write-only mode. If the open succeeds QContent // will construct a new I/O device and return a pointer to it, the caller takes // ownership of the I/O device and is responsible for deleting it. QIODevice *ioDevice = content->open( QIODevice::WriteOnly ); if ( !ioDevice ) { qWarning() << "Could not open the new content object to write to!!"; return false; } // Gets the plain text content of the text document and converts it to an 8-bit // ASCII byte array before writing it to the I/O device. // (This assumes that the notes are short enough to fit into memory. For longer // documents, use QTextDocument::begin(), QTextDocument::end() and QTextDocument::findBlock(int).) int bytesWritten = ioDevice->write( document->toPlainText().toAscii() ); // Close the I/O device and delete it. ioDevice->close(); delete ioDevice; if ( bytesWritten < 0 ) { qWarning() << "Error while trying to create a new notes object!!"; return false; } else { return true; } }
qint64 QIODeviceProto::write(const QByteArray &byteArray) { QIODevice *item = qscriptvalue_cast<QIODevice*>(thisObject()); if (item) return item->write(byteArray); return 0; }
void Entity::handleTag( const Comment* openingTag, const Comment* closingTag, QTextStream& file, QIODevice& output) { file.seek(openingTag->getCommentEnd()+1); while (!file.atEnd()) { qint64 pos=file.pos(); if (pos>=closingTag->getCommentStart()){ file.seek(closingTag->getCommentEnd()+1); break; } QChar c1; file >> c1; const Comment* p= isSpecial(pos); if (p!=nullptr){ if (p->isAutoClosing()){ // output.write(p->comment); // output.write("<!--REMOVESTART-->"); p->output(this,output); // output.write("<!--REMOVEEND-->"); } else { const Comment* closingTag=findClosingTag(p,file); if (closingTag != nullptr){ QBuffer buf; buf.open(QBuffer::WriteOnly|QBuffer::Text); handleTag(p,closingTag,file,buf); buf.close(); if (false /*p->getTag()==STYLE_START*/){ //embedded_styles.append(buf.buffer()); } else { output.write(buf.buffer()); } } } } else if (isInOuput(pos)){ if (openingTag->isHTML() && c1=='\n'){ output.write(QString("<BR/>").toUtf8()); } else { if (!c1.isNonCharacter()) output.write(QString(c1).toUtf8()); } } } return ; }
int qiodevice_iostream_write_bytes(void *context, const void *ptr, size_t size, size_t nmemb) { QIODevice* io = (QIODevice*) context; return (io->write((const char*) ptr, size * nmemb) >= 0 ? 0 : 1); }
void KHTMLPageCacheEntry::endData() { m_complete = true; m_file->write(m_buffer); m_buffer.clear(); m_file->close(); }
void CompiledMaterial::save(QIODevice &dev) { const uint NodeData = NmtReader::Reserved + 1; QByteArray sh = getShader().toLatin1(); if(!(dev.openMode() & QIODevice::WriteOnly || dev.openMode() & QIODevice::Append)) { dev.open(QIODevice::WriteOnly); } NmtReader::Version2Header header; header.version = 2; header.numData = 2 + samplers.size(); dev.write((const char *)&header, sizeof(header)); NmtReader::DataHeader h; h.id = NmtReader::FragShader; h.offset = sizeof(header) + header.numData * sizeof(h); dev.write((const char *)&h, sizeof(h)); h.id = NodeData; h.offset += sh.size() + sizeof(uint); dev.write((const char *)&h, sizeof(h)); h.offset += data.size() + sizeof(uint); for(int i = 0; i != samplers.size(); i++) { h.id = NmtReader::TextureName; h.offset += sizeof(uint) + samplers[i].file.toLatin1().size(); dev.write((const char *)&h, sizeof(h)); } uint len = sh.size(); dev.write((const char *)&len, sizeof(uint)); dev.write(sh); len = data.size(); dev.write((const char *)&len, sizeof(uint)); dev.write(data); for(int i = 0; i != samplers.size(); i++) { QByteArray name = samplers[i].file.toLatin1(); uint len = name.size(); dev.write((const char *)&len, sizeof(uint)); dev.write(name); } }
bool KoImageDataPrivate::saveToFile(QIODevice & device) { if (!rawData.isEmpty()) { return device.write(rawData) == rawData.size(); } else { return image.save(&device, "PNG"); // if we only have a image save it as png } }
void QWebdav::replyReadyRead() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); if (reply->bytesAvailable() < 256000) return; QIODevice* dataIO = m_inDataDevices.value(reply, 0); if(dataIO == 0) return; dataIO->write(reply->readAll()); }
void kp_png_write_fn(png_structp png_ptr, png_bytep data, png_size_t length) { QIODevice* out = (QIODevice*)png_get_io_ptr(png_ptr); uint nr = out->write((char*)data, length); if (nr != length) { png_error(png_ptr, "Write Error"); return; } }
bool WavHeader::writeDataLength(QIODevice &device, qint64 dataLength) { bool result = false; if (!device.isSequential()) { device.seek(40); unsigned char dataLengthLE[4]; qToLittleEndian<quint32>(quint32(dataLength), dataLengthLE); result = (device.write(reinterpret_cast<const char *>(dataLengthLE), 4) == 4); } return result; }
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; }
void tst_qnetworkdiskcache::timeExpiration() { QFETCH(QString, cacheRootDirectory); cacheDir = QString( cacheRootDirectory + QDir::separator() + "man_qndc"); QDir d; qDebug() << "Setting cache directory to = " << d.absoluteFilePath(cacheDir); //Housekeeping initCacheObject(); cleanRecursive(cacheDir); // slow op. cache->setCacheDirectory(cacheDir); // Make max cache size HUGE, so that evictions don't happen below cache->setMaximumCacheSize(qint64(HugeCacheLimit)); cache->clear(); //populate some fake data to simulate partially full cache injectFakeData(); //Sanity-check that the URL is already in there somewhere QVERIFY(isUrlCached(NumRemovals-1) == true); //Entries in the cache should be > what we try to remove QVERIFY(NumFakeCacheObjects > NumRemovals); //Set cache limit lower, so this force 1 round of eviction cache->setMaximumCacheSize(qint64(TinyCacheLimit)); //time insertions of additional content, which is likely to internally cause evictions QBENCHMARK_ONCE { for (quint32 i = NumFakeCacheObjects; i < (NumFakeCacheObjects + NumInsertions); i++) { //prepare metata for url QNetworkCacheMetaData meta; QString fakeURL; QTextStream stream(&fakeURL); stream << fakeURLbase << i;//codescanner::leave QUrl url(fakeURL); meta.setUrl(url); meta.setSaveToDisk(true); //commit payload and metadata to disk QIODevice *device = cache->prepare(meta); device->write(payload); cache->insert(device); // this should trigger evictions, if TinyCacheLimit is small enough } } //Cleanup (slow) cleanupCacheObject(); cleanRecursive(cacheDir); }
static void CALLBACK_CALL_TYPE qpiw_write_fn(png_structp png_ptr, png_bytep data, png_size_t length) { QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr(png_ptr); QIODevice* out = qpiw->device(); uint nr = out->write((char*)data, length); if (nr != length) { png_error(png_ptr, "Write Error"); return; } }
static qint64 blockingWrite( QIODevice& dev, const QByteArray& data ) { qint64 written = 0; while( written < data.size() ) { const qint64 n = dev.write( data.data() + written, data.size() - written ); if( n < 0 ) return -1; written += n; } return data.size(); }