static void raiseError(QXmlStreamReader &reader, const QString &error, Settings::ParseMode parseMode)
{
    if (parseMode == Settings::StrictParseMode) {
        reader.raiseError(error);
    } else {
        QFile *xmlFile = qobject_cast<QFile*>(reader.device());
        if (xmlFile) {
            qWarning().noquote().nospace()
                    << "Ignoring following settings reader error in " << xmlFile->fileName()
                                 << ", line " << reader.lineNumber() << ", column " << reader.columnNumber()
                                 << ": " << error;
        } else {
            qWarning("Ignoring following settings reader error: %s", qPrintable(error));
        }
    }
}
예제 #2
0
파일: utils.cpp 프로젝트: axecute/phantomjs
static QString findScript(const QString& jsFilePath, const QString& libraryPath)
{
    if (!jsFilePath.isEmpty()) {
        QFile jsFile;

        // Is file in the PWD?
        jsFile.setFileName(QDir::fromNativeSeparators(jsFilePath)); //< Normalise User-provided path
        if (!jsFile.exists()) {
            // File is not in the PWD. Is it in the lookup directory?
            jsFile.setFileName(libraryPath + '/' + QDir::fromNativeSeparators(jsFilePath));
        }

        return jsFile.fileName();
    }
    return QString();
}
예제 #3
0
void ThumbnailPicker::slotUnsetImage() {
    QFile file;
    if ( KSUtils::openDataFile( file, "noimage.png" ) ) {
        file.close();
        Image->load( file.fileName(), "PNG" );
    } else {
        *Image = Image->scaled( dd->thumbnail()->width(), dd->thumbnail()->height() );
        Image->fill( dd->palette().color( QPalette::Window ) );
    }

    ui->EditButton->setEnabled( false );
    ui->CurrentImage->setPixmap( *Image );
    ui->CurrentImage->update();

    bImageFound = false;
}
예제 #4
0
bool PNGAImageWriter::Export(QFile& file) {
    QImage pixmap = buildImage();
    assert(pixmap.isGrayscale());
    png::image<png::gray_pixel> image(pixmap.width(), pixmap.height());
    for (size_t y = 0; y < image.get_height(); ++y)
    {
        for (size_t x = 0; x < image.get_width(); ++x)
        {
            QRgb pix = pixmap.pixel(x, y);
            assert(qIsGray(pix));
            image[y][x] = png::gray_pixel(qAlpha(pix));
        }
    }
    image.write(file.fileName().toStdString());
    return true;
}
예제 #5
0
파일: ftp.cpp 프로젝트: castrouk/LinDrm
bool ftpInterface::downloadFile(QString sourceFileName,QString destinationFilename)
{
    delSrc=FALSE;
    aborting=FALSE;
    addToLog("FTP downloadFile",LOGFTP);
    QFile *destFn;
    destFn=new QFile(destinationFilename);
    if(!destFn->open(QIODevice::WriteOnly))
      {
        addToLog(QString("FTP unable to open destinationFilename %1").arg(destinationFilename),LOGFTP);
        return FALSE;
      }


    if (sourceFileName.isNull() )  return FALSE;
    ftpDone=TRUE;
    if(isUnconnected())
      {
        ftpDone=FALSE;
        connectToHost();
      }

    while(!ftpDone)
     {
       if(aborting) return FALSE;
       qApp->processEvents();
     }
    if(isUnconnected())
      {
        addToLog("FTP connection failed",LOGFTP);
        return FALSE;
      }

    ftpDone=FALSE;
    ftpCommandSuccess=FALSE;
    ftp->get( sourceFileName, destFn,QFtp::Binary);
    addToLog(QString("FTP get sourcefile %1 destination %2").arg(sourceFileName).arg(destFn->fileName()),LOGFTP);
    while(!ftpDone)
     {
       if(aborting) return FALSE;
       qApp->processEvents();
     }
    if(!ftpCommandSuccess) return FALSE;
     addToLog(QString("FTP file: %1 bytes: %2").arg(destinationFilename).arg(QFile(destinationFilename).size()),LOGFTP);

     return TRUE;
}
예제 #6
0
static qint64 open_file(QFile & fp, BooL & ro)
{
    QString filename = fp.fileName();

    while (! fp.open(QIODevice::ReadOnly)) {
        if (QMessageBox::critical(0, "Uml",
                                  filename + "\ncannot be opened for read, retry ?\n",
                                  "yes", "no", 0, 0, 0) != 0)
            return -1;
    }

    QFileInfo fi(fp);

    ro = !fi.isWritable();

    return fi.size();
}
예제 #7
0
/**
 * Updates the widget from a xml document (of a test)
 * @param root
 */
void NMGNetperfXMLInterpret::updateWidgetFromXMLDocument ( const QString & fileName )
{
	widget->txtTestName->setText ( "" );
	widget->txtTestId->setText ( "" );

	QString testType = "";
	NMGMetaData * metadata = new NMGMetaData();

	QFile file ( fileName );
	if ( !file.open ( QFile::ReadOnly | QFile::Text ) )
		cerr << "File " << qPrintable( fileName ) << " couldn't be read";
	else
	{
		NMGMetaDataParser metaParser ( *metadata );
		if ( !metaParser.read ( &file ) )
			cerr << "Parse error reading metadata in file " << qPrintable ( file.fileName() ) << ":\n" << qPrintable( metaParser.errorString() );
		else
		{
			testType = metadata->getTypeOfTest().toLower();

			//Backward compatibility with older test files that doesn't have <type> tag
			if ( testType.isEmpty() )
			{
				if ( metadata->isSetUncommonElement ( TAG_CONF_NETPERF ) ) metadata->setTypeOfTest ( TYPE_TPUT );
				testType = metadata->getTypeOfTest().toLower();
			}
		}
	}

	if ( testType == TYPE_TPUT )
	{
		widget->txtTestName->setText ( metadata->getTestName() );
		widget->txtTestId->setText ( metadata->getTestIdentifier() );
		//TODO result Path?
		//updateWidgetFromXMLNodeSource ( elem );
		NMGHostInformationComboWidget * combo = widget->hostSourceCombo;
		combo->setAddressOfStation ( metadata->getSourceAddress() );
	
		//updateWidgetFromXMLNodeDestination ( elem );
		combo = widget->hostDestinationCombo;
		combo->setAddressOfStation ( metadata->getDestinationAddress() );
	
		updateWidgetFromXMLNodeConfNetperf ( metadata->getUncommonElement ( TAG_CONF_NETPERF ) );
		delete metadata;
	}
}
예제 #8
0
void MainWindow::on_openIncoming_clicked()
{
    if (ClientReceiveSetup() == 0)
    {
        QFile *file = new QFile(QFileDialog::getSaveFileName(this, tr("Save song as"), 0, tr("Music (*.wav)")));
        if (file->fileName() != NULL)
        {
            ui->openIncoming->setEnabled(false);
            ui->disconnectIncoming->setEnabled(true);
            file->open(QIODevice::WriteOnly);
            ClientListen((HANDLE) _get_osfhandle(file->handle()));
        } else
        {
            ClientCleanup();
        }
    }
}
예제 #9
0
bool UBImportCFF::addFileToDocument(UBDocumentProxy* pDocument, const QFile& pFile)
{
    QFileInfo fi(pFile);
    UBApplication::showMessage(tr("Importing file %1...").arg(fi.baseName()), true);

    // first unzip the file to the correct place
    //TODO create temporary path for iwb file content
    QString path = QDir::tempPath();

    QString documentRootFolder = expandFileToDir(pFile, path);
        QString contentFile;
    if (documentRootFolder.isEmpty()) //if file has failed to unzip it is probably just xml file
        contentFile = pFile.fileName();
    else //get path to content xml (according to iwbcff specification)
        contentFile = documentRootFolder.append("/content.xml");

    if(!contentFile.length()){
            UBApplication::showMessage(tr("Import of file %1 failed.").arg(fi.baseName()));
            return false;
    }
    else{
        //TODO convert expanded CFF file content to the destination document
        //create destination document proxy
        //fill metadata and save
        UBDocumentProxy* destDocument = new UBDocumentProxy(UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath());
        QDir dir;
        dir.mkdir(destDocument->persistencePath());

        //try to import cff to document
        if (UBCFFSubsetAdaptor::ConvertCFFFileToUbz(contentFile, destDocument))
        {
            UBPersistenceManager::persistenceManager()->addDirectoryContentToDocument(destDocument->persistencePath(), pDocument);
            UBFileSystemUtils::deleteDir(destDocument->persistencePath());
            delete destDocument;
            UBApplication::showMessage(tr("Import successful."));
            return true;
        }
        else
        {
            UBFileSystemUtils::deleteDir(destDocument->persistencePath());
            delete destDocument;
            UBApplication::showMessage(tr("Import failed."));
            return false;
        }
    }
}
예제 #10
0
void PhoneInfoWidget::saveScreenshot()
{
    QFile plik;
    plik.setFileName(QFileDialog::getSaveFileName(this, tr("Save File..."), "./screenshot.png", tr("Png file")+" (*.png)"));
    if (plik.fileName().isEmpty())
        return;
    if (plik.open(QFile::WriteOnly))
    {
        QMatrix matrix;
        matrix.rotate(this->rotation);
        QImage image;
        image = this->screenshot.toImage();
        image = image.transformed(matrix);
        image.save(&plik, "PNG");
        plik.close();
    }
}
	/** The clients are free to not call this function if they know the avatar is
	 * already stored. That means that we should be beware of this when implementing
	 * caching, if we'd ever do.
	 *
	 * See EntryBase::SetVCard() for example.
	 */
	void AvatarsStorage::StoreAvatar (const QImage& image, const QByteArray& hash)
	{
		QFile file (AvatarsDir_.absoluteFilePath (hash));
		if (file.exists () && file.size ())
			return;

		if (!file.open (QIODevice::WriteOnly | QIODevice::Truncate))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to open file"
					<< file.fileName ()
					<< "for writing";
			return;
		}

		image.save (&file, "PNG", 100);
	}
예제 #12
0
void MetaInfoParser::errorHandling(QXmlStreamReader &reader, QFile &file)
{
    if (!reader.hasError())
        return;

    qDebug() << QString("Error at %1, %2:%3: %4")
            .arg(file.fileName())
            .arg(reader.lineNumber())
            .arg(reader.columnNumber())
            .arg(reader.errorString());

    file.reset();

    QString fileString = file.readAll();
    QString snippetString;
    int lineCount = 0;
    int position = reader.characterOffset();
    while (position >= 0)
    {
        if (fileString[position] == '\n') {
            if (lineCount > 3)
                break;
            lineCount++;
        }

        snippetString.prepend(fileString[position]);
        position--;
    }

    lineCount = 0;
    position = reader.characterOffset();
    while (position >= 0)
    {
        position++;
        if (fileString[position] == '\n') {
            if (lineCount > 1)
                break;
            lineCount++;
        }

        snippetString.append(fileString[position]);
    }

    qDebug() << snippetString;

}
예제 #13
0
파일: qimagereader.cpp 프로젝트: cedrus/qt
/*!
    \internal
*/
bool QImageReaderPrivate::initHandler()
{
    // check some preconditions
    if (!device || (!deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly))) {
        imageReaderError = QImageReader::DeviceError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Invalid device"));
        return false;
    }

    // probe the file extension
    if (deleteDevice && !device->isOpen() && !device->open(QIODevice::ReadOnly) && autoDetectImageFormat) {
        QList<QByteArray> extensions = QImageReader::supportedImageFormats();
        if (!format.isEmpty()) {
            // Try the most probable extension first
            int currentFormatIndex = extensions.indexOf(format.toLower());
            if (currentFormatIndex > 0)
                extensions.swap(0, currentFormatIndex);
        }

        int currentExtension = 0;

        QFile *file = static_cast<QFile *>(device);
        QString fileName = file->fileName();

        do {
            file->setFileName(fileName + QLatin1Char('.')
                    + QString::fromLatin1(extensions.at(currentExtension++).constData()));
            file->open(QIODevice::ReadOnly);
        } while (!file->isOpen() && currentExtension < extensions.size());

        if (!device->isOpen()) {
            imageReaderError = QImageReader::FileNotFoundError;
            errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "File not found"));
            file->setFileName(fileName); // restore the old file name
            return false;
        }
    }

    // assign a handler
    if (!handler && (handler = createReadHandlerHelper(device, format, autoDetectImageFormat, ignoresFormatAndExtension)) == 0) {
        imageReaderError = QImageReader::UnsupportedFormatError;
        errorString = QLatin1String(QT_TRANSLATE_NOOP(QImageReader, "Unsupported image format"));
        return false;
    }
    return true;
}
예제 #14
0
TrackList::TrackList(QFile &input)
{
    if (!input.exists()) {
        throw new Exception(QString("File not found: <%1>").arg(input.fileName()));
    }

    QDomDocument d;
    d.setContent(&input);

    QDomElement root = d.documentElement();
    QDomElement pointNode, segmentNode, trackNode;

    Track t;

    // <gpx
    // <trk><name>АВГ-30-09 14:15:47</name>
    // <trkseg>
    // <trkpt lat="54.11111" lon="37.11111"><ele>112.13</ele><time>2009-08-29T15:36:42Z</time></trkpt>

    tracks.clear();
    trackNode = root.firstChildElement("trk");
    for (; !trackNode.isNull(); trackNode = trackNode.nextSiblingElement("trk")) {
        t.name = trackNode.firstChildElement("name").text();

        segmentNode = trackNode.firstChildElement("trkseg");
        for (; !segmentNode.isNull(); segmentNode = segmentNode.nextSiblingElement("trkseg")) {
            t.points.clear();

            pointNode = segmentNode.firstChildElement("trkpt");
            for (; !pointNode.isNull(); pointNode = pointNode.nextSiblingElement("trkpt")) {
                t.points.append(TrackPoint(
                    pointNode.attribute("lat").toFloat(),
                    pointNode.attribute("lon").toFloat(),
                    QDateTime::fromString(pointNode.firstChildElement("time").text(), Qt::ISODate)
                ));
            }

            qSort(t.points);

            if (t.points.length()) {
                tracks.append(t);
            }
        }
    }
}
예제 #15
0
void MainWindow::saveData(DecodeChannel *decode, const char *err)
{
    QByteArray &buf = decode->buf;
    QFile *file = decode->file;

    if (buf.size() > 0) {
            QDate date = QDate::currentDate();
            QTime time = QTime::currentTime();
            if (file->isOpen()) {
                if (file->size() > (64 * 1024 * 1024))
                    file->close();
                QStringList gzipArgs;
                gzipArgs << "-1";
                gzipArgs << file->fileName();
                QProcess::startDetached("gzip", gzipArgs);
            }

            if (!file->isOpen()) {
                QString suffix("-");
                suffix += date.toString("MMdd");
                suffix += time.toString("-hhmmss");
                QString filename = QString(decode->basename).arg(suffix);
                file->setFileName(filename);
                file->open(QIODevice::WriteOnly | QIODevice::Truncate);
            }

            QString prefix;
            prefix += date.toString("MM/dd-");
            prefix += time.toString("hh:mm:ss (");
            if (err)
                    prefix += err;
            prefix += ") >>> ";

            QByteArray stream;
            stream.reserve(4096);
            stream.append(prefix);
            char str[4];
            for (int i = 0; i < buf.size(); i++) {
                qsnprintf(str, 4, "%02x ", (unsigned char)buf.at(i));
                stream.append(str, 3);
            }
            stream.append('\n');
            file->write(stream);
    }
}
bool KTPackageHandler::compress(QuaZip *zip, const QString &path)
{
	QFile inFile;
	QuaZipFile outFile(zip);
	char c;
	
	QFileInfoList files= QDir(path).entryInfoList();
	
	foreach(QFileInfo file, files)
	{
		QString filePath = path+"/"+file.fileName();
		
		
		if ( file.fileName().startsWith(".") ) continue;
		
		if ( file.isDir() )
		{
			compress(zip, file.path()+"/"+file.fileName());
			continue;
		}
		
		inFile.setFileName(filePath);
		if(!inFile.open(QIODevice::ReadOnly)) 
		{
			dError() << "Error opening file " << inFile.fileName() << " : " << inFile.errorString();
			return false;
		}
		
		if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(stripRepositoryFromPath(filePath), stripRepositoryFromPath(filePath) ))) 
		{
			return false;
		}
		while(inFile.getChar(&c) && outFile.putChar(c));
		
		if(outFile.getZipError()!=UNZ_OK)
		{
			return false;
		}
		outFile.close();
		if(outFile.getZipError()!=UNZ_OK)
		{
			return false;
		}
		inFile.close();
	}
예제 #17
0
			void KinotifyWidget::LoadTheme (const QString& themePath)
			{
				Theme_.clear ();
				QFile content (themePath + "/tmp.html");
				if (!content.open (QIODevice::ReadOnly))
				{
					qWarning () << Q_FUNC_INFO
							<< "could not open theme file at"
							<< content.fileName ()
							<< content.errorString ();
					return;
				}

				Theme_ = content.readAll ();

				const QPalette& palette = QApplication::palette ();

#define REPLACE1(a) { const QColor& c = palette.color (QPalette::a); \
					  Theme_.replace ("{Color"#a "}", QString ("%1, %2, %3").arg (c.red ()).arg (c.green ()).arg (c.blue ())); }
				REPLACE1 (Window);
				REPLACE1 (WindowText);
				REPLACE1 (Base);
				REPLACE1 (AlternateBase);
				REPLACE1 (ToolTipBase);
				REPLACE1 (ToolTipText);
				REPLACE1 (Text);
				REPLACE1 (Button);
				REPLACE1 (ButtonText);
				REPLACE1 (BrightText);
				REPLACE1 (Light);
				REPLACE1 (Midlight);
				REPLACE1 (Dark);
				REPLACE1 (Mid);
				REPLACE1 (Shadow);
				REPLACE1 (Link);
				REPLACE1 (LinkVisited);
				REPLACE1 (Highlight);
				REPLACE1 (HighlightedText);
#undef REPLACE1

				QDir imgDir (themePath + "/img");
				Q_FOREACH (QString elem, imgDir.entryList (QStringList ("*.png")))
					Theme_.replace (QString ("{%1}").arg (elem.left (elem.size () - 4)),
							MakeImage (themePath + "/img/" + elem));
			}
예제 #18
0
bool ImageThread::getNextImage(QString* s) {
    int i;
    bool ret;
    _IMAGE tmp;
    QFile f;
    QRegExp rx(__IMAGEFILE_REGEXP__, Qt::CaseInsensitive, QRegExp::RegExp2);
    QStringList res;
    int pos;

    ret = false;

    if (_downloading) {
        for (i=0; i<images.length(); i++) {
            if (!images.at(i).downloaded && !images.at(i).requested) {
                tmp = images.at(i);
                tmp.requested = true;
                images.replace(i,tmp);

                // Check if file already exists in destination dir
                pos = 0;

                pos = rx.indexIn(tmp.largeURI);
                res = rx.capturedTexts();

                if (pos != -1) {
                    f.setFileName(getSavepath() + res.at(0));
                }

                if (f.exists()) {
                    tmp.downloaded = true;
                    images.replace(i, tmp);

                    setCompleted(tmp.largeURI, f.fileName());
                }
                else {
                    *s = tmp.largeURI;
                    ret = true;
                    break;
                }
            }
        }
    }

    return ret;
}
예제 #19
0
// Constructor with QFile
GLC_Texture::GLC_Texture(const QFile &file)
: m_pQGLContext(NULL)
, m_FileName(file.fileName())
, m_GlTextureID(0)
, m_textureImage()
, m_TextureSize()
, m_HasAlphaChannel(m_textureImage.hasAlphaChannel())
{
	m_textureImage.load(const_cast<QFile*>(&file), QFileInfo(m_FileName).suffix().toLocal8Bit());
	if (m_textureImage.isNull())
	{
		QString ErrorMess("GLC_Texture::GLC_Texture open image : ");
		ErrorMess.append(m_FileName).append(" Failed");
		qDebug() << ErrorMess;
		GLC_Exception e(ErrorMess);
		throw(e);
	}
}
예제 #20
0
파일: FstReader.cpp 프로젝트: Chris7/hifi
bool FstReader::addPart(const QString &path, const QString& name) {
    QFile* file = new QFile(path);
    if (!file->open(QIODevice::ReadOnly)) {
        qDebug() << "[ERROR] Couldn't open " << file->fileName();
        return false;
    }
    
    QHttpPart part;
    part.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;"
                   " name=\"" + name.toUtf8() +  "\";"
                   " filename=\"" + QFileInfo(*file).fileName().toUtf8() +  "\"");
    part.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    part.setBodyDevice(file);
    _dataMultiPart->append(part);
    file->setParent(_dataMultiPart);
    
    return true;
}
예제 #21
0
파일: tzipper.cpp 프로젝트: brillywu/tea-qt
bool CZipper::pack_prepared()
{
  if (archive_fullpath.isEmpty())
     return false;
  
  QString zipname (archive_fullpath);
  QuaZip zip (zipname, settings->value ("zip_charset_out", "UTF-8").toString().trimmed());

  if (! zip.open (QuaZip::mdCreate))
      return false;

  QFile inFile;
  QuaZipFile outFile (&zip);

  foreach (QString fi, files_list)
          {
           QFileInfo file (fi);
           
           if (! file.isFile())
              continue;

           inFile.setFileName (file.absoluteFilePath());

           if (! inFile.open (QIODevice::ReadOnly))
               return false;

           QString outfname (archive_name);
           outfname.append ("/").append (file.fileName());

           if (! outFile.open (QIODevice::WriteOnly, QuaZipNewInfo (outfname, inFile.fileName())))
               return false;

           QByteArray ba = inFile.readAll();
           outFile.write (ba);

           outFile.close();
           
           if (outFile.getZipError() != UNZ_OK)
               return false;

           inFile.close();

           emit new_iteration (file);
         }
예제 #22
0
파일: Snapshot.cpp 프로젝트: gcalero/hifi
void Snapshot::uploadSnapshot(const QString& filename, const QUrl& href) {

    const QString SNAPSHOT_UPLOAD_URL = "/api/v1/snapshots";
    QUrl url = href;
    if (url.isEmpty()) {
        SnapshotMetaData* snapshotData = Snapshot::parseSnapshotData(filename);
        if (snapshotData) {
            url = snapshotData->getURL();
        }
        delete snapshotData;
    }
    if (url.isEmpty()) {
        url = QUrl(DependencyManager::get<AddressManager>()->currentShareableAddress());
    }
    SnapshotUploader* uploader = new SnapshotUploader(url, filename);
    
    QFile* file = new QFile(filename);
    Q_ASSERT(file->exists());
    file->open(QIODevice::ReadOnly);

    QHttpPart imagePart;
    if (filename.right(3) == "gif") {
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/gif"));
    } else {
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
    }
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                        QVariant("form-data; name=\"image\"; filename=\"" + file->fileName() + "\""));
    imagePart.setBodyDevice(file);
    
    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
    multiPart->append(imagePart);
    
    auto accountManager = DependencyManager::get<AccountManager>();
    JSONCallbackParameters callbackParams(uploader, "uploadSuccess", uploader, "uploadFailure");

    accountManager->sendRequest(SNAPSHOT_UPLOAD_URL,
                                AccountManagerAuth::Required,
                                QNetworkAccessManager::PostOperation,
                                callbackParams,
                                nullptr,
                                multiPart);
}
예제 #23
0
    LocalFileStream(const QUrl& _url)
    {
        QString fileName = _url.toString();

        if (fileName.startsWith("qrc:/"))
            fileName.remove(0, 3);
        else if (fileName.startsWith("file://"))
            fileName.remove(0, 7);

        m_file.setFileName(fileName);

        m_data.resize(PAGE_SIZE);
        m_file.open(QIODevice::ReadOnly);

        if (m_file.error() != QFile::NoError)
        {
            throw m_file.fileName() + ": " + m_file.errorString();
        }
    }
예제 #24
0
Template::Template(QFile& file, QTextCodec* textCodec)
{
	this->warnings=false;
	sourceName=QFileInfo(file.fileName()).baseName();
	if (file.open(QFile::ReadOnly | QFile::Text))
	{
		QByteArray data=file.readAll();
		file.close();

		if(textCodec)
			append(textCodec->toUnicode(data));
		else
			append(fromUtf8(data));
	}
	else
	{
		qCritical("Template: cannot read from %s, %s",qPrintable(sourceName),qPrintable(file.errorString()));
	}
}
예제 #25
0
// #########################################################################
// Loads the XML settings file and stores the settings.
bool loadXmlSettings (void)
{
  bool result = true;

  QFile file (QDir::homeDirPath()+QDir::convertSeparators ("/.qucs/filterrc"));
  if (!file.open(QIODevice::ReadOnly))
    result = false; // settings file doesn't exist
  else {
    QDomDocument doc;
    QString errmsg;
    int line, col;
    if (!doc.setContent(&file, true, &errmsg, &line, &col)) {
		
      cerr << (const char*)file.fileName().toUtf8() << ":" << line << ":" << col
	   << ": " << (const char*)errmsg.toUtf8() << endl;
      cerr << (const char*)doc.toString ().toUtf8();
      file.close();
      return false;
    }

    QucsSettings.x = getInteger (&doc, "Window", "x");
    QucsSettings.y = getInteger (&doc, "Window", "y");

    QucsSettings.type = getInteger (&doc, "Type", "Type", "LC");
    QucsSettings.form = getInteger (&doc, "Type", "Class", "LC");
    QucsSettings.specify = getInteger (&doc, "Type", "SpecifyOrder", "LC");
    QucsSettings.ord = getInteger (&doc, "Type", "Order", "LC");
    QucsSettings.subord = getInteger (&doc, "Type", "SubOrder", "LC");

    QucsSettings.cutoff = getDouble (&doc, "Cutoff", "Value", "LC");
    QucsSettings.cutoff_unit = getInteger (&doc, "Cutoff", "Unit", "LC");
    QucsSettings.zin = getDouble (&doc, "Impedance", "Zin", "LC");
    QucsSettings.zout = getDouble (&doc, "Impedance", "Zout", "LC");
    QucsSettings.bw = getDouble (&doc, "Bandwidth", "Value", "LC");
    QucsSettings.bw_unit = getInteger (&doc, "Bandwidth", "Unit", "LC");
    QucsSettings.sb = getDouble (&doc, "Stopband", "Value", "LC");
    QucsSettings.sb_unit = getInteger (&doc, "Stopband", "Unit", "LC");
    QucsSettings.ripple = getDouble (&doc, "Ripple", "Value", "LC");
    QucsSettings.angle = getDouble (&doc, "Angle", "Value", "LC");
    QucsSettings.atten = getDouble (&doc, "Attenuation", "Value", "LC");
  }
  return result;
}
예제 #26
0
void SnapshotShareDialog::uploadSnapshot() {

    if (AccountManager::getInstance().getAccountInfo().getDiscourseApiKey().isEmpty()) {
        QMessageBox::warning(this, "",
                             "Your Discourse API key is missing, you cannot share snapshots. Please try to relog.");
        return;
    }

    if (!_networkAccessManager) {
        _networkAccessManager = new QNetworkAccessManager(this);
    }

    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart apiKeyPart;
    apiKeyPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"api_key\""));
    apiKeyPart.setBody(AccountManager::getInstance().getAccountInfo().getDiscourseApiKey().toLatin1());

    QFile* file = new QFile(_fileName);
    file->open(QIODevice::ReadOnly);

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                        QVariant("form-data; name=\"file\"; filename=\"" + file->fileName() +"\""));
    imagePart.setBodyDevice(file);
    file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

    multiPart->append(apiKeyPart);
    multiPart->append(imagePart);

    QUrl url(FORUM_UPLOADS_URL);
    QNetworkRequest request(url);

    QNetworkReply* reply = _networkAccessManager->post(request, multiPart);


    connect(reply, &QNetworkReply::finished, this, &SnapshotShareDialog::uploadRequestFinished);

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
}
예제 #27
0
파일: mainwindow.cpp 프로젝트: KDE/rocs
QString MainWindow::uniqueFilename(const QString &basePrefix, const QString &suffix) {
    QFile targetFile;
    QString basePath = m_currentProject->projectUrl().path();
    QString fullSuffix = '.' + suffix;
    QString fullPrefix = basePrefix;

    if (fullPrefix.isNull()) {
        fullPrefix = m_currentProject->projectUrl().fileName().remove(QRegExp(".rocs*$"));
    } else if (fullPrefix.endsWith(fullSuffix)) {
        fullPrefix.remove(QRegExp(fullSuffix + '$'));
    }

    targetFile.setFileName(basePath + fullPrefix + fullSuffix);
    for(int i = 1; targetFile.exists(); i++) {
        targetFile.setFileName(basePath + fullPrefix + QString::number(i) + fullSuffix);
    }

    return targetFile.fileName();
}
예제 #28
0
bool EventModel::loadEventData(QFile& qFile)
{
    beginResetModel();
    clearModel();

    // Read events
    MatrixXi events;

    if(!MNE::read_events(qFile, events)) {
        qDebug() << "Error while reading events.";
        return false;
    }

    //std::cout << events << endl;

    qDebug() << QString("Events read from %1").arg(qFile.fileName());

    //set loaded fiff event data
    for(int i = 0; i < events.rows(); i++) {
        m_dataSamples.append(events(i,0));
        m_dataTypes.append(events(i,2));
        m_dataIsUserEvent.append(0);
    }

    //Set filtered events to original
    m_dataSamples_Filtered = m_dataSamples;
    m_dataTypes_Filtered = m_dataTypes;
    m_dataIsUserEvent_Filtered = m_dataIsUserEvent;

    //Create type string list
    m_eventTypeList.clear();
    for(int i = 0; i<m_dataTypes.size(); i++)
        if(!m_eventTypeList.contains(QString().number(m_dataTypes[i])))
            m_eventTypeList<<QString().number(m_dataTypes[i]);

    emit updateEventTypes("All");

    endResetModel();

    m_bFileloaded = true;

    return true;
}
RatpPrivate::RatpPrivate(Ratp *q):
    q_ptr(q)
{
    QFile file (":/data/backward/stations.txt");
    if (!file.open(QIODevice::ReadOnly)) {
        debug("ratp-plugin") << "Failed to read" << file.fileName().constData();
        return;
    }
    QTextStream fileStream (&file);
    while (!fileStream.atEnd()) {
        QString line = fileStream.readLine().trimmed();
        if (!line.isEmpty()) {
            stations.append(line);
        }
    }

    file.close();

}
예제 #30
0
/**
  This method should load the specified image file as a texture in video memory
  and return its texture id.

  @TODO: Finish filling this in!
  **/
GLuint GLWidget::loadTexture(const QFile &file) {
    QImage image, texture;
    if(!file.exists()) return -1;
    image.load(file.fileName());
    texture = QGLWidget::convertToGLFormat(image);
    GLuint textureID;
    //Put your code here

    glEnable(GL_TEXTURE_2D);

    glGenTextures(1, &textureID);

    glBindTexture(GL_TEXTURE_2D, textureID);

    glTexImage2D(GL_TEXTURE_2D, 0, 3, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits());
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    return textureID; /* return something meaningful */
}