Пример #1
0
QByteArray Scanner::hashFile(QFile &f)
{
    uchar *map;

    QCryptographicHash hasher(QCryptographicHash::Sha1);
    hasher.reset();

    /* Try map first */
    map = f.map( 0, f.size() );
    if (NULL==map) {
        /* no mmap, read in chunks */
        uchar buffer[512];
        qint64 r;
        do {
            r = f.read((char*)buffer,sizeof(buffer));
            if (r<0){
                throw 1;
            }
            if (r<=0)
                break;
            hasher.addData( (const char*)buffer, r);
        } while (r>0);

    } else {
        hasher.addData((const char*)map,f.size());
        f.unmap(map);
    }

    return hasher.result();
}
Пример #2
0
TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString *error) noexcept
{
    if (error)
        error->clear();

    QFile file {path};
    if (!file.open(QIODevice::ReadOnly)) {
        if (error)
            *error = file.errorString();
        return TorrentInfo();
    }

    const qint64 fileSizeLimit = 100 * 1024 * 1024;  // 100 MB
    if (file.size() > fileSizeLimit) {
        if (error)
            *error = tr("File size exceeds max limit %1").arg(fileSizeLimit);
        return TorrentInfo();
    }

    const QByteArray data = file.read(fileSizeLimit);
    if (data.size() != file.size()) {
        if (error)
            *error = tr("Torrent file read error");
        return TorrentInfo();
    }

    file.close();

    // 2-step construction to overcome default limits of `depth_limit` & `token_limit` which are
    // used in `torrent_info()` constructor
    const int depthLimit = 100;
    const int tokenLimit = 10000000;
    libt::error_code ec;

#if LIBTORRENT_VERSION_NUM < 10100
    libt::lazy_entry node;
    libt::lazy_bdecode(data.constData(), (data.constData() + data.size()), node, ec
        , nullptr, depthLimit, tokenLimit);
#else
    libt::bdecode_node node;
    bdecode(data.constData(), (data.constData() + data.size()), node, ec
        , nullptr, depthLimit, tokenLimit);
#endif
    if (ec) {
        if (error)
            *error = QString::fromStdString(ec.message());
        return TorrentInfo();
    }

    TorrentInfo info {NativePtr(new libt::torrent_info(node, ec))};
    if (ec) {
        if (error)
            *error = QString::fromStdString(ec.message());
        return TorrentInfo();
    }

    return info;
}
Пример #3
0
Hash DialogBase::publishBinaryAttachment(const MetadataQueryDialog::MetadataResultSet& aFileMetadata,
        bool aForceNoEncryption,
        const QList<Hash>* aBinaryRecipientList) {
    Hash retval ( KNullHash ) ;
    bool isCompressed (false ) ;

    QFile f ( aFileMetadata.iFileName ) ;
    if ( f.open(QIODevice::ReadOnly) ) {
        if ( f.size() > ( KMaxProtocolItemSize * 10 ) ) {
            emit error ( MController::FileOperationError, tr("File way too big")) ;
        } else {
            QByteArray content ( f.read(f.size() ) ) ;
            QByteArray compressedContent ( qCompress(content) ) ;
            LOG_STR2("Size of content = %d", (int) (content.size())) ;
            LOG_STR2("Size of compressed = %d", (int) (compressedContent.size())) ;
            if (content.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) &&
                    compressedContent.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) ) {
                emit error ( MController::FileOperationError, tr("File too big")) ;
            } else {
                if ( compressedContent.size() < content.size () ) {
                    content.clear() ;
                    content.append(compressedContent) ;
                    compressedContent.clear() ;
                    isCompressed = true ;
                } else {
                    compressedContent.clear() ;
                }
                // ok, here we have content in content and it is
                // either compressed or not. size is checked.
                iController->model().lock() ;
                retval=
                    iController->model().
                    binaryFileModel().publishBinaryFile(iSelectedProfile,
                                                        QFileInfo(f).fileName(),
                                                        aFileMetadata.iDescription,
                                                        aFileMetadata.iMimeType,
                                                        aFileMetadata.iOwner,
                                                        aFileMetadata.iLicense,
                                                        content,
                                                        isCompressed,
                                                        aForceNoEncryption,
                                                        aBinaryRecipientList)  ;

                iController->model().unlock() ;
            }
        }
    } else {
        emit error ( MController::FileOperationError, tr("File open error")) ;
    }
    return retval ;
}
Пример #4
0
uint JsonEngine::findEnd(QFile &file)
{
	int len = file.size();
	QByteArray data;
	uchar *fmap = file.map(0, file.size());
	if(!fmap)
	{
		data = file.readAll();
		fmap = (uchar *)data.constData();
	}
	uint end = file.size();
	const uchar *s = K8JSON::skipBlanks(fmap, &len);
	uchar qch = *s;
	if(!s || (qch != '[' && qch != '{'))
	{
		if(data.isEmpty())
			file.unmap(fmap);
		return end;
	}
	qch = (qch == '{' ? '}' : ']');
	s++;
	len--;
	bool first = true;
	while(s)
	{
		s = K8JSON::skipBlanks(s, &len);
		if(len < 2 || (s && *s == qch))
		{
			if(*(s-1) == '\n')
				s--;
			end = (uint)(s - fmap);
			break;
		}
		if(!s)
			break;
		if((!first && *s != ',') || (first && *s == ','))
			break;
		first = false;
		if(*s == ',')
		{
			s++;
			len--;
		}
		if(!(s = K8JSON::skipRec(s, &len)))
			break;
	}
	if(data.isEmpty())
		file.unmap(fmap);
	return end;
}
Пример #5
0
unsigned int FileTrans::readTransPos(QFile &file)
{
    unsigned int postemp = file.pos();  //push file pos
    file.seek(file.size()-4);
    QDataStream str(&file);
    str.setByteOrder(QDataStream::LittleEndian);
    unsigned int pos ;
    str>>pos;
    file.seek(postemp);    //pop file pos
    if(pos<file.size())
        return pos;
    else
        return 0;
}
Пример #6
0
void FilePersistThread::rollFileIfNecessary(QFile& file, bool notifyListenersIfRolled) {
    uint64_t now = usecTimestampNow();
    if ((file.size() > MAX_LOG_SIZE) || (now - _lastRollTime) > MAX_LOG_AGE_USECS) {
        QString newFileName = getLogRollerFilename();
        if (file.copy(newFileName)) {
            file.open(QIODevice::WriteOnly | QIODevice::Truncate);
            file.close();
            qDebug() << "Rolled log file:" << newFileName;

            if (notifyListenersIfRolled) {
                emit rollingLogFile(newFileName);
            }

            _lastRollTime = now;
        }
        QStringList nameFilters;
        nameFilters << FILENAME_WILDCARD;

        QDir logQDir(FileUtils::standardPath(LOGS_DIRECTORY));
        logQDir.setNameFilters(nameFilters);
        logQDir.setSorting(QDir::Time);
        QFileInfoList filesInDir = logQDir.entryInfoList();
        qint64 totalSizeOfDir = 0;
        foreach(QFileInfo dirItm, filesInDir){
            if (totalSizeOfDir < MAX_LOG_DIR_SIZE){
                totalSizeOfDir += dirItm.size();
            } else {
                QFile file(dirItm.filePath());
                file.remove();
            }
        }
    }
Пример #7
0
void XmlConfigFile::read()
{
	kdebugf();
	QFile file;
	QDir backups(ggPath(), "kadu.conf.xml.backup.*", QDir::Name, QDir::Files);
	QStringList files("kadu.conf.xml");
	files += backups.entryList();
	bool fileOpened(false);

	foreach(const QString &fileName, files)
	{
		file.setFileName(ggPath(fileName));
		fileOpened = file.open(QIODevice::ReadOnly);
		if (fileOpened && file.size() > 0)
		{
			kdebugm(KDEBUG_INFO, "configuration file %s opened!\n", qPrintable(file.fileName()));
			break;
		}
		if (fileOpened) // && file.size() == 0
		{
			kdebugm(KDEBUG_INFO, "config file (%s) is empty, looking for backup\n", qPrintable(file.fileName()));
			file.close();
			fileOpened = false;
		}
		else
			kdebugm(KDEBUG_INFO, "config file (%s) not opened, looking for backup\n", qPrintable(file.fileName()));
	}
Пример #8
0
void janelaPrincipal::copiarAquivos(QFile &origem, QFile &destino)
{

    qint64 nCopySize = origem.size();
    ui->progressBarGeral->setMaximum(nCopySize);
    if(!(origem.open(QFile::ReadOnly) && destino.open(QFile::ReadWrite))){
        return;
    }


  qDebug() << QString::number(nCopySize)+" o tamanho do arquivo";
  //dialog->show();

     for (qint64 i = 0; i < nCopySize; i += 1024*1024) {
         if(iscopy){
         destino.write(origem.read(i)); // write a byte
         destino.seek(i);  // move to next byte to read
         origem.seek(i); // move to next byte to write
         ui->progressBarGeral->setValue(i);
    }else {
             destino.remove();
             break;
         }

         // ui->progressBarGeral->;
     }
     ui->progressBarGeral->setVisible(false);
     ui->progressBarGeral->setValue(0);
      modeldir->refresh();
}
Пример #9
0
qint64 StateImport::loadCTM(State *state, QFile& file)
{
    struct CTMHeader5 header;
    auto size = file.size();
    if ((std::size_t)size<sizeof(header))
    {
        state->setErrorMessage(QObject::tr("Error: CTM file too small"));
        qDebug() << "Error. File size too small to be CTM (" << size << ").";
        return -1;
    }

    size = file.read((char*)&header, sizeof(header));
    if ((std::size_t)size<sizeof(header))
        return -1;

    // check header
    if (header.id[0] != 'C' || header.id[1] != 'T' || header.id[2] != 'M')
    {
        state->setErrorMessage(QObject::tr("Error: invalid CTM file"));
        qDebug() << "Not a valid CTM file";
        return -1;
    }

    // check version
    if (header.version == 4) {
        return loadCTM4(state, file, (struct CTMHeader4*)&header);
    } else if (header.version == 5) {
        return loadCTM5(state, file, &header);
    }

    state->setErrorMessage(QObject::tr("Error: CTM version not supported"));
    qDebug() << "Invalid CTM version: " << header.version;
    return -1;
}
Пример #10
0
void WavSound::play() {
    QFile *file = new QFile(fileName);
    file->open(QIODevice::ReadOnly);
    QAudioFormat f;
    readHeader(&f, file);

    QAudioFormat format = f;

    QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
    if (!info.isFormatSupported(format)) {
        qWarning() << "Raw audio format not supported by backend, cannot play audio.";
        return;
    }

    //seek(0x4e*4); //...avoiding clicks from the wav files

    file->seek(0x4e);

    QAudioOutput *audio = new QAudioOutput(format, NULL);
    if(file->size()<30000)
        audio->setBufferSize(10000);

    audio->setVolume(0.5);
    connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
    audio->start(file);
}
Пример #11
0
std::string DataBlockFile::getData()
{
    if (!exists())
        return std::string();

    prepareToRead();

    QDataStream stream(&m_file);
 //   std::cerr << "DataBlockFile::getData() : file size = " << m_file.size() << std::endl;
    char* tmp = new char[m_file.size()];
    stream.readRawData(tmp, m_file.size());
    std::string res(tmp, m_file.size());
    delete[] tmp;

    return res;
}
Пример #12
0
void SlimServerInfo::WriteDataFile( void )
{
    DEBUGF("");
    QString dataPath = QDir::homePath()+DATAPATH;
    QDir d(dataPath);
    if(!d.exists())
        d.mkpath(dataPath);
    QDir::setCurrent(dataPath);

    QFile file;
    file.setFileName(DATAFILE);

    //update the information
    if(!file.open(QIODevice::WriteOnly)) {
        DEBUGF("Error opening file for writing");
        return;
    }
    QDataStream out(&file);   // read the data serialized from the file
    out << (qint16)DATAVERSION; // set data verion number

    out << lastServerRefresh;
    out << m_Artist2AlbumIds;
    out << m_AlbumArtist2AlbumID;
    out << (qint16)m_AlbumID2AlbumInfo.count();
    out << m_albumList;
    out << m_AlbumID2AlbumInfo;
    out << m_artistList;

    DEBUGF( "Writing file of size: " << file.size() );
    file.close();
    return;
}
Пример #13
0
QString ZString::getFileCoding(const QString &filePath)
{
    QFile *file = new QFile(filePath);
    if (!file->open(QFile::ReadOnly)) {
        return "";
    }

    qint64 size = file->size();
    char *buf = new char[size];
    file->read(buf, size);
    file->close();

    // 读取文件头
    ///
    /// ANSI: 没有文件头(2字节/汉字,1字节/英文)
    /// UTF-8: 文件头[0xEF,0xBB,0xBF](3字节/汉字,1字节/英文)
    /// Unicode: 文件头[0xFF,0xFE](2字节/汉字,2字节/英文)
    /// Unicode big endian: 文件头[0xFE,0xFF](同Unicode,字节序相反)
    ///
    uchar *p = (uchar*)buf;
    if (0xEF == p[0] && 0xBB == p[1] && 0xBF == p[2]) {
        qDebug() << QString::fromUtf8(buf + 3, size -3);
        return "UFT-8";
    } else if (0xFF == p[0] && 0xFE == p[1]) {
        qDebug() << QString::fromWCharArray((wchar_t*)(buf + 2), (size - 2) / 2);
        return "Unicode";
    } else if (0xFE == p[0] && 0xFF == p[1]) {
        qDebug() << QString::fromWCharArray((wchar_t*)(buf + 2), (size - 2) / 2);
        return "Unicode big endian";
    } else {
        qDebug() << QString::fromLocal8Bit(buf, size);
        return "ANSI";
    }
}
Пример #14
0
void NetworkManager::handleVideo(QSharedPointer<MediaFile> mediaEntry, QHttpRequest *req, QHttpResponse *resp)
{
    QFile *file = new QFile(mediaEntry->path(), resp);
    if(!file->open(QFile::OpenModeFlag::ReadOnly))
    {
        sendError(QHttpResponse::STATUS_NOT_FOUND, resp);
        return;
    }

    resp->setHeader("Accept-Ranges", "bytes");

    qint64 size = file->size();
    qint64 offset = 0;

    if(req->headers().contains("range"))
    {
        QString range = req->headers()["range"];
        offset = QStringRef(&range, 6, (range.indexOf('-') - 6)).toLongLong();
        resp->setHeader("Content-Range", QString("bytes " + QString::number(offset) + "-" + QString::number(size) + "/" + QString::number(size)).toLatin1());
        resp->setHeader("Content-Length", QString::number(size - offset).toLatin1());
        resp->writeHead(QHttpResponse::STATUS_PARTIAL_CONTENT);
    }
    else
    {
        resp->setHeader("Content-Length", QString::number(file->size()).toLatin1());
        resp->writeHead(QHttpResponse::STATUS_OK);
    }

    file->seek(offset);

    QObject::connect(resp, &QHttpResponse::allBytesWritten,
                     [file,resp](){
                        QByteArray data = file->read(0x40000);
                        if(data.size() > 0)
                        {
                            resp->write(data);
                        }
                        else
                        {
                            file->close();
                            resp->end();
                            delete file;
                        }
                    });

    resp->write(file->read(0x40000));
}
Пример #15
0
void MainWindow::on_streamButton_clicked()
{
    if (QFile::exists(ui->fileEdit->text()) != true)
    {
        QMessageBox::critical(this, "Critical", QString(FILE_NOT_FOUND).arg(ui->fileEdit->text()));
        return;
    }

    QFile *file = new QFile(ui->fileEdit->text());
    if (!file->open(QIODevice::ReadOnly))
    {
        delete file;
        QMessageBox::critical(this, "Critical", QString(CANT_OPEN_TO_READ).arg(ui->fileEdit->text()));
        return;
    }

    if (file->size() == 0)
    {
        file->close();
        delete file;
        QMessageBox::critical(this, "Critical", QString(FILE_IS_EMPTY).arg(ui->fileEdit->text()));
    }

    QByteArray *data = new QByteArray();
    *data = file->readAll();
    file->close();
    delete file;

    QByteArray *data_compressed = new QByteArray();
    *data_compressed = qCompress(*data).remove(0, 4);

    int size = data->size();
    int size_compressed = data_compressed->size();
    if(size_compressed < size) {
        delete data;
        data = data_compressed;
    }
    else {
        delete data_compressed;
        size_compressed = size;
    }

    QByteArray *args = new QByteArray();
    //*args = ui->argEdit->text().toAscii(); //toAscii() has been depreciated in qt5
    *args = ui->argEdit->text().toLatin1(); //toAscii() has been replaced by toLatin1()
    int args_len = 0;
    if(!args->isEmpty())
        args_len = args->size() + 1;

    ui->progressBar->setMaximum(size_compressed);
    ui->progressBar->setEnabled(true);

    wiiStreamThread = new QWiiStreamThread(ui->hostEdit->text(), data, size, size_compressed, args, args_len);
    connect(wiiStreamThread, SIGNAL(transferFail(QString)), this, SLOT(transferFail(QString)));
    connect(wiiStreamThread, SIGNAL(transferDone()), this, SLOT(transferDone()));
    connect(wiiStreamThread, SIGNAL(progressBarPosition(int)), this, SLOT(progressBarPosition(int)));
    wiiStreamThread->start();
    ui->streamButton->setEnabled(false);
}
Пример #16
0
bool SlimServerInfo::ReadDataFile( void )
{
    DEBUGF("");
    QString dataPath = QDir::homePath()+DATAPATH;
    QDir d(dataPath);
    if(!d.exists())
        d.mkpath(dataPath);
    QDir::setCurrent(dataPath);

    QFile file;
    if( file.exists(DATAFILE) ) // there is a file, so read from it
        file.setFileName(DATAFILE);
    else {
        DEBUGF("no file to read at " << dataPath+DATAFILE);
        return false;
    }

    quint16 albumCount;

    //update the images
    file.open(QIODevice::ReadOnly);
    QDataStream in(&file);   // read the data serialized from the file

    // check version of data
    qint16 versionNo;
    in >> versionNo;
    qDebug() << versionNo << DATAVERSION;
    if(versionNo != (qint16)DATAVERSION)
        return false;


    in >> freshnessDate;
    in >> m_Artist2AlbumIds;
    in >> m_AlbumArtist2AlbumID;
    in >> albumCount;
    in >> m_albumList;
    in >> m_AlbumID2AlbumInfo;
    in >> m_artistList;

    DEBUGF("reading in info on " << albumCount << " files");

#ifdef SLIMSERVERINFO_DEBUG
    QListIterator<Artist> art(m_artistList);
    while(art.hasNext()) {
        Artist a = art.next();
        qDebug() << a.id << a.name << a.textKey;
    }

    QListIterator<Album> al(m_albumList);
    while(al.hasNext()) {
        Album a = al.next();
        qDebug() << a.albumTextKey << a.albumtitle << a.artist;
    }
#endif

    DEBUGF( "Reading file of size: " << file.size() );
    file.close();
    return true;
}
Пример #17
0
//static
uint32_t SoundSourceWV::GetlengthCallback(void* id)
{
    QFile* pFile = static_cast<QFile*>(id);
    if (!pFile) {
        return 0;
    }
    return pFile->size();
}
Пример #18
0
void ImageManager::getCDImages(void){
	qint64 size = 0;
	QList<QStringList> result = db_image.getFields();

	int numRows = tableImage->rowCount();
	int curRows = 0;

	for (int i = 0; i < result.size(); ++i) {
		curRows++;

		if (curRows>numRows){
			tableImage->insertRow (numRows);
			numRows = tableImage->rowCount();
		}

		QFile file (result.at(i).at(1));
		if (file.exists ()){
			size = file.size() / 1024 / 1024;
		} else {
			size = 0;
		}

		if (tableImage->item(curRows - 1, 0)){
			tableImage->item(curRows - 1, 0)->setText(result.at(i).at(0));
			tableImage->item(curRows - 1, 1)->setText(tr("%1 Mb").arg(size));
			if (!file.exists ()){
				tableImage->item(curRows - 1, 0)->setIcon (QIcon(":/data/important.png"));
			} else {
				tableImage->item(curRows - 1, 0)->setIcon (QIcon());
			}
		} else {
			std::auto_ptr<QTableWidgetItem> newItem (new QTableWidgetItem(result.at(i).at(0)));
			if (!file.exists ()){
				newItem->setIcon ( QIcon(":/data/important.png") );
			} else {
				newItem->setIcon ( QIcon() );
			}
			newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
			tableImage->setItem(curRows - 1, 0, newItem.release());
			newItem.reset(new QTableWidgetItem(tr("%1 Mb").arg(size)));
			newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
			tableImage->setItem(curRows - 1, 1, newItem.release());
		}
	}

	numRows = tableImage->rowCount();

	if (numRows > curRows)
		for (int i=curRows; i <= numRows; i++)
			tableImage->removeRow(curRows);

	tableImage->resizeRowsToContents();
	tableImage->resizeColumnsToContents();
	tableImage->horizontalHeader()->setStretchLastSection(TRUE);

	return;
}
Пример #19
0
static void initLogFile(const QString &p_file)
{
    g_logFile.setFileName(p_file);
    if (g_logFile.size() >= MAX_LOG_SIZE) {
        g_logFile.open(QIODevice::WriteOnly | QIODevice::Text);
    } else {
        g_logFile.open(QIODevice::Append | QIODevice::Text);
    }
}
Пример #20
0
void DialogBase::attachButtonClicked() {
    LOG_STR("DialogBase::attachButtonClicked\n") ;

    QString fileName = QFileDialog::getOpenFileName(this, tr("Select file to be published"),
                       "",
                       tr("Files (*.*)"));
    if ( fileName.length() > 0 ) {
        QFile f ( fileName ) ;
        if ( f.open(QIODevice::ReadOnly) ) {
            if ( f.size() > ( KMaxProtocolItemSize * 10 ) ) {
                emit error ( MController::FileOperationError, tr("File way too big")) ;
            } else {
                QByteArray content ( f.read(f.size() ) ) ;
                QByteArray compressedContent ( qCompress(content) ) ;
                LOG_STR2("Size of content = %d", (int) (content.size())) ;
                LOG_STR2("Size of compressed = %d", (int) (compressedContent.size())) ;
                if (content.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) &&
                        compressedContent.size() > (qint64)(( KMaxProtocolItemSize - ( 50*1024 ) )) ) {
                    emit error ( MController::FileOperationError, tr("File too big")) ;
                } else {
                    // file was not too big. here now just mark the filename
                    // for later use.
                    if ( iFilesAboutToBeAttached.count() != 0 ) {
                        iFilesAboutToBeAttached.clear() ;
                    }
                    MetadataQueryDialog::MetadataResultSet metadata ;
                    metadata.iFileName = fileName ;
                    MetadataQueryDialog metadataDialog(this,
                                                       *iController,
                                                       metadata ) ;
                    if ( metadataDialog.exec() == QDialog::Accepted ) {
                        iFilesAboutToBeAttached.append(metadata) ;

                        iAttachmentListLabel->setText(metadata.iFileName) ;
                    } else {
                        iAttachmentListLabel->setText(QString()) ;
                    }
                }
            }
        } else {
            emit error ( MController::FileOperationError, tr("File open error")) ;
        }
    }
}
Пример #21
0
bufsize_t AbstractFileBuffer::getReadableSize(QFile &fIn)
{
    qint64 fileSize = fIn.size();
    bufsize_t size = static_cast<bufsize_t> (fileSize);

    if (size > FILE_MAXSIZE) {
        size = FILE_MAXSIZE;
    }
    return size;
}
Пример #22
0
static QFile* map(QString path, raw_buffer &fData)
{
	const char *message;

	QFile *f = new QFile(path);

	if (!f->open(QIODevice::ReadOnly)) {
		message = "is not readable";
		goto map_failed;
	}

	if (f->size() > std::numeric_limits<typeof(fData.m_len)>::max()) {
		message = "is too big";
		goto map_failed;
	}

	if (f->size() != 0) {
		fData.m_len = f->size();
		fData.m_str = (const char *)f->map(0, f->size());
		if (fData.m_str == NULL) {
			message = "failed to memory map";
			goto map_failed;
		}
	} else {
		qDebug() << "File" << path << "is empty";
		fData.m_len = 0;
		fData.m_str = "";
	}

	return f;

map_failed:

	f->close();
	delete f;
	f = NULL;

	const char *fileNameStr = qPrintable(path);

	fprintf(stderr, "%s %s\n", fileNameStr, message);
	return f;
}
Пример #23
0
QTreeWidgetItem* dragTarget::ramifica ( QString path, QTreeWidget *parent ) //overloaded function to work with toplevels
{
  puts("ramifico");
  /*se il cursore si trova sopra un elemento esistente appendiamo sotto...*/
  KIcon icon;
  //e' necessario gestire la stringa di controllo per il mime che arriva dal mime di tipo aku/newarchive
  //rimuovo la stringa di controllo dalla stringa che servir� per ricostruire il path e il nome file, e scrivo il mimeType nella colonna appropriata
  QString toPath = "/"; //su windows impostare C:\/
  int target = path.indexOf ( "!*mimetosend:" );
  mimeCheck = path;
  mimeCheck.remove ( 0,target );
  mimeCheck.remove ( "!*mimetosend:" );
  icon = KIcon(KMimeType::mimeType(mimeCheck) -> iconName());///KIcon(mimeCheck);
  path.remove ( target, path.length() );
  //************************************************************************************************************************************//
  if ( path.indexOf ( tr ( "*User created Folder*" ) ) == -1 )  //distinguo le cartelle normali da quelle create dall'utente (* iniziale)
  {
    QStringList folders = path.split ( QDir().separator(), QString::SkipEmptyParts );
    lastItemAdded = new QTreeWidgetItem ( parent );
    lastItemAdded -> setText ( 0, folders[folders.size()-1] );
    for ( int i=0; i<folders.size() - 1; i++ )
    {
      toPath.append ( folders[i]+QDir().separator() );
    }
  }
  else
  {
    //imposto gli attributi della cartella creata dall'utente
    toPath = tr ( "*User created Folder*" ); //questo va nel path
    path.remove ( target, path.length() );
    path.remove ( tr ( "*User created Folder*" ) );
    lastItemAdded = new QTreeWidgetItem ( parent );
    lastItemAdded -> setText ( 0, path ); //nome cartella
    mimeCheck =  "inode/directory" ; //mimetype
    icon = KIcon("inode-directory");
  }
  lastItemAdded -> setText ( 1, toPath );

  //scrivo le informazioni sul mime
  lastItemAdded -> setText ( 2, mimeCheck );
  lastItemAdded -> setIcon ( 0,icon );

  //scriviamo le informazioni sulla dimensione
  if ( lastItemAdded -> text ( 2 ) != "inode/directory" )   //se non è una cartella
  {
    QFile sizeInfo ( lastItemAdded -> text ( 1 ) + lastItemAdded -> text ( 0 ) );
    lastItemAdded -> setText ( 3, KLocale("").formatByteSize(sizeInfo.size()) ); //usiamo la funzione della classe rar per la conversione della dimensione
    lastItemAdded -> setTextAlignment ( 3, Qt::AlignRight | Qt::AlignVCenter );
  }

  header() -> setResizeMode ( QHeaderView::ResizeToContents );
  return lastItemAdded;
  
}
Пример #24
0
void UIImageViewer::loadImage(int i) {
    QFile f;
    QPixmap p;
    QString filename;

    if (!this->isVisible()) {
        ui->image->clear();
        show();
    }

    QLOG_TRACE() << "ImageViewer :: Loading image " << currentImage << "from" << imagesToDisplay.count();
    rotation = 0;

    if (imagesToDisplay.count() > i) {
        filename = imagesToDisplay.value(i);

        if (f.exists(filename)) {
            f.setFileName(filename);
            ui->statusbar->showMessage("Working...");
            if (ui->image->movie() != 0) ui->image->movie()->stop();

            if (filename.endsWith(".gif")) {
                // Always assume gifs are animated -> therefore use QMovie for playback
                QMovie *movie = new QMovie(filename);
                ui->image->setMovie(movie);
                movie->start();
                ui->statusbar->showMessage("Loaded image " + filename, 2000);
                ui->lCurrentImage->setText(QString("%1/%2").arg(currentImage+1).arg(imagesToDisplay.count()));
                ui->lImageInfo->setText("");
            }
            else {
                if (p.load(filename)) {
                    originalPixmap = p;
                    transformPixmap();
                    fitImage();
                    ui->statusbar->showMessage("Loaded image " + filename, 2000);
                    ui->lCurrentImage->setText(QString("%1/%2").arg(currentImage+1).arg(imagesToDisplay.count()));
                    ui->lImageInfo->setText(QString("Resolution: %1x%2, Size: %3kB")
                                            .arg(originalPixmap.width())
                                            .arg(originalPixmap.height())
                                            .arg(f.size()/1024)
                                            );
                }
                else {
                    QLOG_ERROR() << "ImageViewer :: Error loading image" << filename;
                }
            }
        }

        if (runSlideshow)
            slideshowTimer->start();

    }
}
Пример #25
0
 void rollFileIfNecessary(QFile& file) {
     uint64_t now = usecTimestampNow();
     if ((file.size() > MAX_LOG_SIZE) || (now - _lastRollTime) > MAX_LOG_AGE_USECS) {
         QString newFileName = getLogRollerFilename();
         if (file.copy(newFileName)) {
             _lastRollTime = now;
             file.open(QIODevice::WriteOnly | QIODevice::Truncate);
             file.close();
             qDebug() << "Rolled log file: " << newFileName;
         }
     }
 }
bool QBluetoothTransferReplyBluez::start()
{
    QFile *file = qobject_cast<QFile *>(m_source);

    if(!file){
        m_tempfile = new QTemporaryFile(this );
        m_tempfile->open();
        qCDebug(QT_BT_BLUEZ) << "Not a QFile, making a copy" << m_tempfile->fileName();
        if (!m_source->isReadable()) {
            m_errorStr = QBluetoothTransferReply::tr("QIODevice cannot be read. "
                                                     "Make sure it is open for reading.");
            m_error = QBluetoothTransferReply::IODeviceNotReadableError;
            m_finished = true;
            m_running = false;

            emit QBluetoothTransferReply::error(m_error);
            emit finished(this);
            return false;
        }

        QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
        QObject::connect(watcher, SIGNAL(finished()), this, SLOT(copyDone()));

        QFuture<bool> results = QtConcurrent::run(QBluetoothTransferReplyBluez::copyToTempFile, m_tempfile, m_source);
        watcher->setFuture(results);
    }
    else {
        if (!file->exists()) {
            m_errorStr = QBluetoothTransferReply::tr("Source file does not exist");
            m_error = QBluetoothTransferReply::FileNotFoundError;
            m_finished = true;
            m_running = false;

            emit QBluetoothTransferReply::error(m_error);
            emit finished(this);
            return false;
        }
        if (request().address().isNull()) {
            m_errorStr = QBluetoothTransferReply::tr("Invalid target address");
            m_error = QBluetoothTransferReply::HostNotFoundError;
            m_finished = true;
            m_running = false;

            emit QBluetoothTransferReply::error(m_error);
            emit finished(this);
            return false;
        }
        m_size = file->size();
        startOPP(file->fileName());
    }
    return true;
}
Пример #27
0
void MainWindow::fileSent(){
    ip = ui->lineEditIp->text();
    port = ui->spinBoxPort->value();
    soc.connectToHost(ip,port);
    if(soc.waitForConnected(1)){
        /*
          ARTHUR 27/11 :
          Modifié afin d'intégré : - La taille du nom du fichier
                                   - Le nom du fichier
                                   - La taille du fichier
                                   - Le fichier
         */
        qDebug() << "[CLI] - NETWORK SUCCESS";
        QFile * myFile = new QFile(QFileInfo(fileName).absoluteFilePath());
        QByteArray ba = QFileInfo(fileName).baseName().toLocal8Bit();
        const char *c_str2 = ba.data();
        int cpt=0,myFileSize=myFile->size();
        qDebug() << "[CLI] FileName" << QFileInfo(fileName).baseName();
        while(c_str2[cpt]!='\0'){
            cpt++;
        }
        cpt++;
        qDebug() << "[CLI] - TOTAL SIZE TO SENT " << myFile->size() + 2*sizeof(int)+cpt*sizeof(char);
        qDebug() << "[CLI] - SIZE OF FILE " << myFile->size();
        ui->progressBarFile->setMaximum(myFile->size() + 2*sizeof(int)+cpt*sizeof(char));
        myFile->open(QIODevice::ReadOnly);
        this->soc.write((const char*) &cpt, sizeof(int));
        this->soc.write((const char*) c_str2, cpt);
        this->soc.write((const char*) &myFileSize,sizeof(int));
        soc.setReadBufferSize(myFileSize);
        //  this->soc.flush();
        qDebug() << this->soc.write(myFile->readAll());
        soc.flush();
    }else{
        qDebug() << "[CLI] - NETWORK ISSUE";
        QMessageBox::critical(this,"Error","Network Issue");
        return;
    }
}
Пример #28
0
QByteArray QCOMM::md5(QFile &file)
{
    unsigned char *buf;
    bool isopen;
    if(!file.exists())
        return QByteArray();
    if(file.size()==0)
        return QByteArray();
    if(file.isOpen())
        isopen = TRUE;
    if(isopen&&(!file.open(QIODevice::ReadOnly)))
        return QByteArray();
    buf = file.map(0,file.size());
    if(isopen)
        file.close();
    if(0==buf)
        return QByteArray();
    QByteArray data = QByteArray::fromRawData((char*)buf,file.size());
    QByteArray md5 =  QCryptographicHash::hash (data, QCryptographicHash::Md5);
    file.unmap(buf);
    return md5;
}
Пример #29
0
bool Packer::Pack_Directory(QFile &file, const QString &sourceFolderLocation) {
    QDir dir(sourceFolderLocation);
    assert(dir.count() > 0); //empty folders should never enter this function

    //Allocate space for the length of the directory names
    qint64 startingOffset = file.size();
    if (!this->Write_Buffer_To_File(file, QByteArray(8, 0x00))) return false;

    //Create a table entry for each directory
    QFileInfoList directories = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    QHash<QString, qint64> directoryTable;
    foreach (QFileInfo sourceDirectory, directories) {
        if (sourceDirectory.dir().count() == 0) continue; //we won't pack empty folders

        //Write the length of the directory name and the directory name itself
        if (!this->Write_Buffer_To_File(file, this->Get_Byte_Array_From_int(sourceDirectory.fileName().size()))) return false;
        if (!this->Write_Buffer_To_File(file, sourceDirectory.fileName().toUtf8())) return false;

        //Insert the directory into the hash to update it later
        directoryTable.insert(sourceDirectory.fileName(), file.size());

        //Allocate 8 bytes for the start pointer and size value
        if (!this->Write_Buffer_To_File(file, QByteArray(8, 0x00))) return false;
    }
    if (!this->Write_Buffer_To_File(file, this->Get_Byte_Array_From_qint64(file.size()-startingOffset), startingOffset)) return false;

    //Allocate space for the length of the file names
    startingOffset = file.size();
    if (!this->Write_Buffer_To_File(file, QByteArray(8, 0x00))) return false;

    //Create a table entry for each file
    QFileInfoList files = dir.entryInfoList(QDir::Files);
    QHash<QString, qint64> fileTable;
    foreach (QFileInfo sourceFile, files) {
        //Write the length of the filename and the filename itself
        if (!this->Write_Buffer_To_File(file, this->Get_Byte_Array_From_int(sourceFile.fileName().size()))) return false;
        if (!this->Write_Buffer_To_File(file, sourceFile.fileName().toUtf8())) return false;

        //Insert the file into the hash to update it later
        fileTable.insert(sourceFile.fileName(), file.size());

        //Allocate 16 bytes for the start pointer and size value
        if (!this->Write_Buffer_To_File(file, QByteArray(16, 0x00))) return false;
    }
    if (!this->Write_Buffer_To_File(file, this->Get_Byte_Array_From_qint64(file.size()-startingOffset), startingOffset)) return false;

    //Pack each file. Update the table entry for each file along the way
    foreach (QFileInfo sourceFile, files) {
        qint64 startByte = file.size();
        if (!this->Pack_File(file, sourceFile.filePath())) return false;

        //Update the table entry with the new pointers
        if (!this->Write_Buffer_To_File(file, this->Get_Byte_Array_From_qint64(startByte)+this->Get_Byte_Array_From_qint64(sourceFile.size()), fileTable.value(sourceFile.fileName()))) return false;
    }
Пример #30
0
void ZGui::load ( const QString fileName, bool AutoCodec )
{
	toLog("load ("+fileName+")");
	QFile file ( fileName );
	if (  file.open ( IO_ReadWrite ) )//IO_ReadOnly ) )
	{
		//Block update
	    edit->blockSignals(true);
		edit->setAutoUpdate(false);	
			
		//Set def editor
		edit->clear();
		edit->setText("");
	
		//Detect codec
		if ( AutoCodec )
		{
			//Reset all checked
			for (int i=0; i<CODEC_COUNT;i++)
				CodeMenu->setItemChecked(i,false);
			//Read data for detect
			char data[10000];
			int size = file.readBlock(data, sizeof(data));
			file.reset();
			textCode = detectCodec(data, size);
			//Check codec
			CodeMenu->setItemChecked(textCode, true);
		}
		
		toLog("\tload text");
		//Load file
		char data[ file.size() ];
		file.readBlock(data, sizeof(data));
		QTextCodec* codec = codecByLocalId(textCode);
		toLog("\tset text");
		edit->setText( codec->toUnicode( data ) );
		toLog("\tclose file");
		file.close();
		
		//Unblock update
	    edit->blockSignals(false);
		edit->setAutoUpdate(true);
		
		#ifdef MDI
		setMainWidgetTitle(sFileName);
		buildDlgMenu();
		#endif
		
		toLog("end load");
	}
}