예제 #1
0
void FileWatchUnitTest::filewatchTest()
{
    QWARN("Unittest will take about 1 minute. Please wait.");

    QCA::FileWatch watcher;
    QCOMPARE( watcher.fileName(), QString() );

    QSignalSpy spy( &watcher, SIGNAL(changed()) );
    QVERIFY( spy.isValid() );
    QCOMPARE( spy.count(), 0 );

    QTemporaryFile *tempFile = new QTemporaryFile;

    tempFile->open();

    watcher.setFileName( tempFile->fileName() );
    QCOMPARE( watcher.fileName(), tempFile->fileName() );
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 0 );
    tempFile->close();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 0 );

    tempFile->open();
    tempFile->write("foo");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 1 );

    tempFile->close();
    QTest::qWait(7000);

    QCOMPARE( spy.count(), 1 );

    tempFile->open();
    tempFile->write("foo");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 2 );

    tempFile->write("bar");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 3 );

    tempFile->close();
    QTest::qWait(7000);

    QCOMPARE( spy.count(), 3 );

    delete tempFile;
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 4 );
    
}
예제 #2
0
        void ExiftoolImageWritingWorker::process() {
            Helpers::AsyncCoordinatorUnlocker unlocker(m_AsyncCoordinator);
            Q_UNUSED(unlocker);

            bool success = false;

            initWorker();

            QTemporaryFile jsonFile;
            if (jsonFile.open()) {
                LOG_INFO << "Serializing artworks to json" << jsonFile.fileName();
                QJsonArray objectsToSave;
                artworksToJsonArray(m_ItemsToWriteSnapshot, objectsToSave);
                QJsonDocument document(objectsToSave);
                jsonFile.write(document.toJson());
                jsonFile.flush();
                jsonFile.close();

                int numberOfItems = (int)m_ItemsToWriteSnapshot.size();

                QTemporaryFile argumentsFile;
                if (argumentsFile.open()) {
                    QStringList exiftoolArguments = createArgumentsList(jsonFile.fileName());

                    foreach (const QString &line, exiftoolArguments) {
                        argumentsFile.write(line.toUtf8());
#ifdef Q_OS_WIN
                        argumentsFile.write("\r\n");
#else
                        argumentsFile.write("\n");
#endif
                    }
QgsRasterLayer* QgsRemoteDataSourceBuilder::rasterLayerFromRemoteRDS( const QDomElement& remoteRDSElem, const QString& layerName, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  QgsMSDebugMsg( "entering." );
  //load file with QgsHttpTransaction or QgsFtpTransaction
  QByteArray fileContents;
  QString uri = remoteRDSElem.text();

  QgsRasterLayer* rl = 0;
  if ( loadData( uri, fileContents ) != 0 )
  {
    return 0;
  }

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( tmpFile->open() )
  {
    tmpFile->write( fileContents );
    tmpFile->flush();
  }
  else
  {
    QgsMSDebugMsg( "Error, creation of temp file failed" );
    delete tmpFile;
    return 0;
  }

  //create rasterlayer
  rl = new QgsRasterLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ) );
  layersToRemove.push_back( rl );
  filesToRemove.push_back( tmpFile );
  clearRasterSymbology( rl );
  return rl;
}
예제 #4
0
static bool removeUserChoice(const QString & extension)
{
    QSettings RegCU("HKEY_CURRENT_USER", QSettings::NativeFormat);
    QString FileExtsKey = QString("Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/.") + extension;

    if(QSysInfo::WindowsVersion < QSysInfo::WV_VISTA){ //XP
        RegCU.remove(FileExtsKey + "/Progid");
        return true;
    }

    QTemporaryFile file;
    if (file.open()) {
        QTextStream out(&file);
        // Unlock Registry, make user 'everyone' can access 'UserChoice' completely.
        out << "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\." + extension + "\\UserChoice [7]";
        out.flush();
        file.flush();

        // win7 build-in tool, for user access changing. Require path argument encoded by Unicode. Chinese may cause problem.
        // Only return after execute completely.
        QProcess::execute(QString("regini.exe %1").arg(file.fileName()));

        /// Windows 7, only can remove "/UserChoice" if we own it. remove "/UserChoice/Progid" is forbidden.
        RegCU.remove(FileExtsKey + "/UserChoice");

        return true;
    }

    return false;

    // The QTemporaryFile destructor removes the temporary file
    // as it goes out of scope.
}
예제 #5
0
void TestImport::csvImport()
{
    // Fetch data
    QFETCH(QString, csv);
    QFETCH(char, separator);
    QFETCH(char, quote);
    QFETCH(QString, encoding);
    QFETCH(int, numfields);
    QFETCH(QVector<QStringList>, result);

    // Create temporary CSV file
    QTemporaryFile file;
    QVERIFY(file.open());
    {
    QTextStream out(&file);
    out.setCodec(encoding.toUtf8());
    out << csv;
    }
    file.flush();

    CSVParser csvparser(true, separator, quote);
    file.seek(0);
    QTextStream tstream(&file);
    tstream.setCodec(encoding.toUtf8());
    csvparser.parse(tstream);

    // Check return values
    QCOMPARE(csvparser.csv(), result);
    QCOMPARE((int)csvparser.columns(), numfields);
}
QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem, const QString& layerName, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  QString providerString;
  QString formatString = remoteVDSElem.attribute( "format" );
  if ( formatString.compare( "gml", Qt::CaseInsensitive ) == 0 )
  {
    providerString = "WFS";
  }
  else
  {
    providerString = formatString;
  }

  //load file with QgsHttpTransaction
  QByteArray fileContents;
  QString uri = remoteVDSElem.text();

  QgsVectorLayer* vl = 0;

  if ( loadData( uri, fileContents ) != 0 )
  {
    return 0;
  }

  //store content into temporary file
  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( tmpFile->open() )
  {
    tmpFile->write( fileContents );
    tmpFile->flush();
  }
  else
  {
    delete tmpFile;
    return 0;
  }

  //create vector layer

  //SOS has a special datasource key...
  if ( formatString.compare( "SOS", Qt::CaseInsensitive ) == 0 )
  {
    QString url = "url=" + tmpFile->fileName() + " method=FILE xml=";
    vl =  new QgsVectorLayer( url, layerNameFromUri( tmpFile->fileName() ), providerString );
  }
  else
  {
    vl =  new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), providerString );
  }

  if ( !( vl->isValid() ) )
  {
    QgsMapServerLogger::instance()->printMessage( "vl is not valid" );
  }

  layersToRemove.push_back( vl );
  filesToRemove.push_back( tmpFile );
  return vl;
}
예제 #7
0
void KoVersionDialog::slotOpen()
{
    if (!list->currentItem())
        return;

    KoVersionInfo *version = 0;
    for (int i = 0; i < m_doc->versionList().size(); ++i) {
        if (m_doc->versionList().at(i).date.toString() == list->currentItem()->text(0)) {
            version = &m_doc->versionList()[i];
            break;
        }
    }
    if (!version)
        return;

    QTemporaryFile tmp;
    tmp.setAutoRemove(false);
    tmp.open();
    tmp.write(version->data);
    tmp.flush();
    tmp.setPermissions(QFile::ReadUser);
    tmp.flush();

    if (!m_doc->documentPart()->mainWindows().isEmpty()) { //open the version in a new window if possible
        KoDocumentEntry entry = KoDocumentEntry::queryByMimeType(m_doc->nativeOasisMimeType());
        if (entry.isEmpty()) {
            entry = KoDocumentEntry::queryByMimeType(m_doc->nativeFormatMimeType());
        }
        Q_ASSERT(!entry.isEmpty());
        QString errorMsg;
        KoPart *part= entry.createKoPart(&errorMsg);
        if (!part) {
            if (!errorMsg.isEmpty())
                KMessageBox::error(0, errorMsg);
            return;
        }
        KoMainWindow *mainWindow = part->createMainWindow();
        mainWindow ->openDocument(QUrl::fromLocalFile(tmp.fileName()));
        mainWindow ->show();
    } else {
        m_doc->openUrl(QUrl::fromUserInput(tmp.fileName()));
    }

    tmp.setAutoRemove(true);
    slotButtonClicked(Close);
}
예제 #8
0
파일: epubdocument.cpp 프로젝트: KDE/okular
QVariant EpubDocument::loadResource(int type, const QUrl &name)
{
  int size;
  char *data;

  QString fileInPath = mCurrentSubDocument.resolved(name).path();

  // Get the data from the epub file
  size = epub_get_data(mEpub, fileInPath.toUtf8().constData(), &data);

  QVariant resource;

  if (data) {
    switch(type) {
    case QTextDocument::ImageResource:{
      QImage img = QImage::fromData((unsigned char *)data, size);
      const int maxHeight = maxContentHeight();
      const int maxWidth = maxContentWidth();
      if(img.height() > maxHeight)
        img = img.scaledToHeight(maxHeight);
      if(img.width() > maxWidth)
        img = img.scaledToWidth(maxWidth);
      resource.setValue(img);
      break;
    }
    case QTextDocument::StyleSheetResource: {
      QString css = QString::fromUtf8(data);
      checkCSS(css);
      resource.setValue(css);
      break;
    }
    case EpubDocument::MovieResource: {
      QTemporaryFile *tmp = new QTemporaryFile(QStringLiteral("%1/okrXXXXXX").arg(QDir::tempPath()),this);
      if(!tmp->open()) qCWarning(OkularEpuDebug) << "EPUB : error creating temporary video file";
      if(tmp->write(data,size) == -1) qCWarning(OkularEpuDebug) << "EPUB : error writing data" << tmp->errorString();
      tmp->flush();
      resource.setValue(tmp->fileName());
      break;
    }
    case EpubDocument::AudioResource: {
      QByteArray ba(data,size);
      resource.setValue(ba);
      break;
    }
    default:
      resource.setValue(QString::fromUtf8(data));
      break;
    }

    free(data);
  }

  // add to cache
  addResource(type, name, resource); 

  return resource;
}
예제 #9
0
bool UltMtgReader::proceed(QList<MtgEntity>& entityList, QList<QPair<int,int> >& edgeList)
{
    //qDebug("UltMtgReader::proceed()");
    QFile file(QString::fromStdString(_in));
    if (!file.open(QIODevice::ReadOnly))
        return false;
    QDataStream in(&file);
    _unserializer = new JavaUnserializer(in);
    if(checkMtgMagic())
        qDebug("[+] file is a .mtg");
    else
    {
        qCritical("[X] file is not a .mtg");
        qCritical("[X] fail");
        file.close();
        return false;
    }
    delete _unserializer;

//Uncompress
    QByteArray inArray = in.device()->readAll();
    file.close();

    QTemporaryFile gzfileTmp;
    //QFile gzfileTmp("gzfileTemp.tmp");
    //if (!gzfileTmp.open(QIODevice::ReadWrite))
    if (!gzfileTmp.open())
        return false;
    QDataStream gzstream(&gzfileTmp);
    gzstream.writeRawData(inArray.data(),inArray.size());

    gzfileTmp.flush();

    QTemporaryFile ungzfileTmp;
    //QFile ungzfileTmp("ungzfileTemp.tmp");
    //if (!ungzfileTmp.open(QIODevice::ReadWrite))
    if (!ungzfileTmp.open())
        return false;

    unGZip(gzfileTmp.fileName().toStdString(),ungzfileTmp.fileName().toStdString());

    gzfileTmp.close();    
//End Uncompress

    QDataStream stream(&ungzfileTmp);

    _unserializer = new JavaUnserializer(stream);
    if(!readData(entityList,edgeList))
    {
        qCritical("\n[X] fail");
        delete _unserializer;
        return false;
    }
    return true;
}
예제 #10
0
void ConfigTabAppearance::onThemeModified(const QByteArray &bytes)
{
    QTemporaryFile tmpfile;
    if ( !openTemporaryFile(&tmpfile, ".ini") )
        return;

    tmpfile.write(bytes);
    tmpfile.flush();

    QSettings settings(tmpfile.fileName(), QSettings::IniFormat);
    loadTheme(settings);
}
예제 #11
0
void IosDeployStep::checkProvisioningProfile()
{
    IosDevice::ConstPtr device = iosdevice();
    if (device.isNull())
        return;

    Utils::FileName provisioningFilePath = Utils::FileName::fromString(appBundle());
    provisioningFilePath.appendPath(QLatin1String("embedded.mobileprovision"));

    // the file is a signed plist stored in DER format
    // we simply search for start and end of the plist instead of decoding the DER payload
    if (!provisioningFilePath.exists())
        return;
    QFile provisionFile(provisioningFilePath.toString());
    if (!provisionFile.open(QIODevice::ReadOnly))
        return;
    QByteArray provisionData = provisionFile.readAll();
    int start = provisionData.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    int end = provisionData.indexOf("</plist>");
    if (start == -1 || end == -1)
        return;
    end += 8;

    QTemporaryFile f;
    if (!f.open())
        return;
    f.write(provisionData.mid(start, end - start));
    f.flush();
    QSettings provisionPlist(f.fileName(), QSettings::NativeFormat);

    if (!provisionPlist.contains(QLatin1String("ProvisionedDevices")))
        return;
    QStringList deviceIds = provisionPlist.value(QLatin1String("ProvisionedDevices")).toStringList();
    QString targetId = device->uniqueDeviceID();
    foreach (const QString &deviceId, deviceIds) {
        if (deviceId == targetId)
            return;
    }

    m_expectFail = true;
    QString provisioningProfile = provisionPlist.value(QLatin1String("Name")).toString();
    QString provisioningUid = provisionPlist.value(QLatin1String("UUID")).toString();
    Task task(Task::Warning,
              tr("The provisioning profile \"%1\" (%2) used to sign the application "
                 "does not cover the device %3 (%4). Deployment to it will fail.")
              .arg(provisioningProfile, provisioningUid, device->displayName(),
                   targetId),
              Utils::FileName(), /* filename */
              -1, /* line */
              ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
    emit addTask(task);
}
예제 #12
0
파일: rules.cpp 프로젝트: 8l/kwin
Rules::Rules(const QString& str, bool temporary)
    : temporary_state(temporary ? 2 : 0)
{
    QTemporaryFile file;
    if (file.open()) {
        QByteArray s = str.toUtf8();
        file.write(s.data(), s.length());
    }
    file.flush();
    KConfig cfg(file.fileName(), KConfig::SimpleConfig);
    readFromCfg(cfg.group(QString()));
    if (description.isEmpty())
        description = QStringLiteral("temporary");
}
예제 #13
0
파일: csv_xxport.cpp 프로젝트: KDE/kdepim
bool CsvXXPort::exportContacts(const ContactList &contacts, VCardExportSelectionWidget::ExportFields) const
{
    QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QStringLiteral("addressbook.csv")));
    if (url.isEmpty()) {
        return true;
    }

    if (QFileInfo(url.isLocalFile() ? url.toLocalFile() : url.path()).exists()) {
        if (url.isLocalFile() && QFileInfo(url.toLocalFile()).exists()) {
            PimCommon::RenameFileDialog::RenameFileDialogResult result = PimCommon::RenameFileDialog::RENAMEFILE_IGNORE;
            PimCommon::RenameFileDialog *dialog = new PimCommon::RenameFileDialog(url, false, parentWidget());
            result = static_cast<PimCommon::RenameFileDialog::RenameFileDialogResult>(dialog->exec());
            if (result == PimCommon::RenameFileDialog::RENAMEFILE_RENAME) {
                url = dialog->newName();
            } else if (result == PimCommon::RenameFileDialog::RENAMEFILE_IGNORE) {
                delete dialog;
                return true;
            }
            delete dialog;
        }
    }

    if (!url.isLocalFile()) {
        QTemporaryFile tmpFile;
        if (!tmpFile.open()) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b></qt>", url.url());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&tmpFile, contacts.addressList());
        tmpFile.flush();
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite);
        KJobWidgets::setWindow(job, parentWidget());
        return job->exec();
    } else {
        QFile file(url.toLocalFile());
        if (!file.open(QIODevice::WriteOnly)) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b>.</qt>", url.toLocalFile());
            KMessageBox::error(parentWidget(), msg);
            return false;
        }

        exportToFile(&file, contacts.addressList());
        file.close();

        return true;
    }
}
예제 #14
0
PRL_RESULT Stunnel::prepare(QTemporaryFile& dst_, const QByteArray data_)
{
	if (!dst_.open())
	{
		WRITE_TRACE(DBG_FATAL, "Error: cannot open a temporary file");
		return PRL_ERR_OPEN_FAILED;
	}
	dst_.setAutoRemove(true);
	if (-1 == dst_.write(data_) || !dst_.flush())
	{
		WRITE_TRACE(DBG_FATAL, "Error: cannot write to a temporary file");
		return PRL_ERR_WRITE_FAILED;
	}
	return PRL_ERR_SUCCESS;
}
예제 #15
0
void TestImport::csvImport()
{
    // Fetch data
    QFETCH(QString, csv);
    QFETCH(char, separator);
    QFETCH(char, quote);
    QFETCH(QString, encoding);
    QFETCH(int, numfields);
    QFETCH(QVector<QVector<QByteArray>>, result);

    // Create temporary CSV file
    QTemporaryFile file;
    QVERIFY(file.open());
    {
        QTextStream out(&file);
        out.setCodec(encoding.toUtf8());
        out << csv;
    }
    file.flush();

    CSVParser csvparser(true, separator, quote);
    file.seek(0);
    QTextStream tstream(&file);
    tstream.setCodec(encoding.toUtf8());

    QVector<QVector<QByteArray>> parsedCsv;
    int parsedCsvColumns = 0;
    csvparser.parse([&parsedCsv, &parsedCsvColumns](size_t /*rowNum*/, const CSVRow& data) -> bool {
        QVector<QByteArray> row;
        for(size_t i=0;i<data.num_fields;i++)
            row.push_back(QByteArray(data.fields[i].data, data.fields[i].data_length));
        parsedCsv.push_back(row);
        if(row.size() > parsedCsvColumns)
            parsedCsvColumns = row.size();
        return true;
    }, tstream);

    // Check return values
    QCOMPARE(parsedCsvColumns, numfields);
    QCOMPARE(parsedCsv.size(), result.size());
    for(int i=0;i<parsedCsv.size();i++)
    {
        QCOMPARE(parsedCsv.at(i).size(), result.at(i).size());
        for(int j=0;j<parsedCsv.at(i).size();j++)
            QCOMPARE(parsedCsv.at(i).at(j), result.at(i).at(j));
    }
    QCOMPARE(parsedCsv, result);
}
예제 #16
0
bool ItemEditor::start()
{
    // create temp file
    const QString tmpFileName = QString("CopyQ.XXXXXX") + getFileSuffixFromMime(m_mime);
    QString tmpPath = QDir( QDir::tempPath() ).absoluteFilePath(tmpFileName);

    QTemporaryFile tmpfile;
    tmpfile.setFileTemplate(tmpPath);
    tmpfile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);

    if ( !tmpfile.open() ) {
        printError( tr("Failed to open temporary file (%1) for editing item in external editor!")
             .arg(tmpfile.fileName()) );
        return false;
    }

    // write text to temp file
    tmpfile.write(m_data);
    tmpfile.flush();

    // monitor file
    m_info.setFile( tmpfile.fileName() );
    m_lastmodified = m_info.lastModified();
    m_lastSize = m_info.size();
    m_timer->start(500);
    connect( m_timer, SIGNAL(timeout()),
             this, SLOT(onTimer()) );

    // create editor process
    m_editor = new QProcess(this);
    connect( m_editor, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(close()) );
    connect( m_editor, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(onError()) );

    // use native path for filename to edit and escape all backslashes
    const QString nativeFilePath = QDir::toNativeSeparators(m_info.filePath());
    QString cmd = m_editorcmd.arg('"' + nativeFilePath + '"');
    cmd.replace("\\", "\\\\");

    // execute editor
    m_editor->start(cmd);

    tmpfile.setAutoRemove(false);
    tmpfile.close();

    return true;
}
예제 #17
0
void ExportEPUB::CreateEncryptionXML(const QString &fullfolderpath)
{
    QTemporaryFile file;

    if (!file.open()) {
        boost_throw(CannotOpenFile()
                    << errinfo_file_fullpath(file.fileName().toStdString())
                    << errinfo_file_errorstring(file.errorString().toStdString())
                   );
    }

    EncryptionXmlWriter enc(*m_Book, file);
    enc.WriteXML();
    // Write to disk immediately
    file.flush();
    QFile::copy(file.fileName(), fullfolderpath + "/" + ENCRYPTION_XML_FILE_NAME);
}
예제 #18
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::loadChunk( const QByteArray & _chunk )
{
	QTemporaryFile tf;
	if( tf.open() )
	{
		tf.write( _chunk );
		tf.flush();

		lock();
		sendMessage( message( IdLoadSettingsFromFile ).
				addString(
					QSTR_TO_STDSTR(
						QDir::toNativeSeparators( tf.fileName() ) ) ).
				addInt( _chunk.size() ) );
		waitForMessage( IdLoadSettingsFromFile, true );
		unlock();
	}
}
예제 #19
0
파일: AurBackend.cpp 프로젝트: drf/aqpm
void Backend::Private::__k__replyFinished(QNetworkReply* reply)
{
    if (reply->property("aqpm_AUR_is_archive_Download").toBool()) {
        // We got an archive. Let's save and extract it where requested
        QTemporaryFile file;
        file.setAutoRemove(false);
        file.open();
        file.write(reply->readAll());
        file.flush();

        QProcess process;
        process.setWorkingDirectory(reply->property("aqpm_AUR_extract_path").toString());
        process.start(QString("tar -zxf %1").arg(file.fileName()));
        process.waitForFinished();
        file.close();

        // Stream the success
        emit q->buildEnvironmentReady(reply->property("aqpm_AUR_ID").toInt(), reply->property("aqpm_AUR_pkg_name").toString());
        return;
    }

    // Parse it!
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(reply, &ok).toMap();

    if (!ok || result["type"].toString() != reply->property("aqpm_AUR_Request_Type").toString()) {
        // Shit.
        return;
    }

    if (reply->property("aqpm_AUR_Request_Type").toString() == "search") {
        Package::List retlist;

        foreach(const QVariant &ent, result["results"].toList()) {
            QVariantMap valuesMap = ent.toMap();
            retlist.append(packageFromMap(valuesMap));
        }

        emit q->searchCompleted(reply->property("aqpm_AUR_Subject").toString(), retlist);
    } else if (reply->property("aqpm_AUR_Request_Type").toString() == "info") {
예제 #20
0
    QString makeFile(const QString &resource)
    {
        QFile memory(resource);
        if (!memory.open(QIODevice::ReadOnly)) {
            qDebug() << "error reading resource" << resource;
            return QString();
        }
        QTemporaryFile *file = new QTemporaryFile;
        file->open();
        file->write(memory.readAll());
        tempFiles.append(file);
        file->flush();
#ifdef Q_OS_WINCE
        // flush does not flush to disk on Windows CE. It flushes it into its application
        // cache. Thus we need to close the file to be able that other processes(lackey) can read it
        QString fileName = file->fileName();
        file->close();
        return fileName;
#endif
        return file->fileName();
    }
예제 #21
0
파일: ssproxy.cpp 프로젝트: karoyqiu/sslink
void SSProxy::start()
{
    QTemporaryFile *config = new QTemporaryFile(QDir::tempPath() + "/ssconfig-XXXXXX.json", this);

    if (Q_UNLIKELY(!config->open()))
    {
        qCritical() << "Failed to open temporary file.";
        return;
    }

    QSettings settings;
    settings.beginGroup("sslocal");

    QJsonObject json;
    json.insert("server", server_.ip);
    json.insert("server_port", server_.port);
    json.insert("local_address", "127.0.0.1");
    json.insert("local_port", settings.value("localPort", 1080).toInt());
    json.insert("password", server_.password);
    json.insert("method", server_.method);
    json.insert("timeout", settings.value("timeout", 60).toInt());

    QJsonDocument doc(json);
    config->write(doc.toJson());
    config->flush();
    qDebug() << "sslocal config file:" << config->fileName();

    QProcess *sslocal = new QProcess(this);
    connect(sslocal, &QProcess::stateChanged, this, [this, sslocal](QProcess::ProcessState state)
    {
        if (state == QProcess::Running)
        {
            QTimer::singleShot(3000, this, SIGNAL(ready()));
        }
    });

    QStringList args;
    args << "-c" << QDir::toNativeSeparators(config->fileName());
    sslocal->start(settings.value("sslocal", "sslocal").toString(), args);
}
예제 #22
0
파일: Downloader.cpp 프로젝트: drf/aqpm
void Downloader::downloadFinished(QNetworkReply *reply)
{
    if (reply->property("is_Header_Check").toBool()) {
        // First of all notify that the head check has taken place
        emit headCheckFinished(reply);

        return;
    }
    qDebug() << "Download finished";
    QTemporaryFile file;
    file.setAutoRemove(false);

    file.open();
    file.write(reply->readAll());
    file.flush();
    file.close();

    emit finished(reply->url().toString(), file.fileName());

    // Remove the reply from the list and delete it
    d->replies.removeOne(reply);
    reply->deleteLater();
}
예제 #23
0
void EditEntryWidget::openAttachment(const QModelIndex& index)
{
    if (!index.isValid()) {
        Q_ASSERT(false);
        return;
    }

    QString filename = m_attachmentsModel->keyByIndex(index);
    QByteArray attachmentData = m_entryAttachments->value(filename);

    // tmp file will be removed once the database (or the application) has been closed
    QString tmpFileTemplate = QDir::temp().absoluteFilePath(QString("XXXXXX.").append(filename));
    QTemporaryFile* file = new QTemporaryFile(tmpFileTemplate, this);

    if (!file->open()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (file->write(attachmentData) != attachmentData.size()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    if (!file->flush()) {
        MessageBox::warning(this, tr("Error"),
                tr("Unable to save the attachment:\n").append(file->errorString()));
        return;
    }

    file->close();

    QDesktopServices::openUrl(QUrl::fromLocalFile(file->fileName()));
}
예제 #24
0
void ZynAddSubFxInstrument::loadSettings( const QDomElement & _this )
{
	if( !_this.hasChildNodes() )
	{
		return;
	}

	m_portamentoModel.loadSettings( _this, "portamento" );
	m_filterFreqModel.loadSettings( _this, "filterfreq" );
	m_filterQModel.loadSettings( _this, "filterq" );
	m_bandwidthModel.loadSettings( _this, "bandwidth" );
	m_fmGainModel.loadSettings( _this, "fmgain" );
	m_resCenterFreqModel.loadSettings( _this, "rescenterfreq" );
	m_resBandwidthModel.loadSettings( _this, "resbandwidth" );
	m_forwardMidiCcModel.loadSettings( _this, "forwardmidicc" );

	QDomDocument doc;
	QDomElement data = _this.firstChildElement( "ZynAddSubFX-data" );
	if( data.isNull() )
	{
		data = _this.firstChildElement();
	}
	doc.appendChild( doc.importNode( data, true ) );

	QTemporaryFile tf;
	tf.setAutoRemove( false );
	if( tf.open() )
	{
		QByteArray a = doc.toString( 0 ).toUtf8();
		tf.write( a );
		tf.flush();

		const std::string fn = QSTR_TO_STDSTR( QDir::toNativeSeparators( tf.fileName() ) );
		m_pluginMutex.lock();
		if( m_remotePlugin )
		{
			m_remotePlugin->lock();
			m_remotePlugin->sendMessage( RemotePlugin::message( IdLoadSettingsFromFile ).addString( fn ) );
			m_remotePlugin->waitForMessage( IdLoadSettingsFromFile );
			m_remotePlugin->unlock();
		}
		else
		{
			m_plugin->loadXML( fn );
		}
		m_pluginMutex.unlock();

		m_modifiedControllers.clear();
		foreach( const QString & c, _this.attribute( "modifiedcontrollers" ).split( ',' ) )
		{
			if( !c.isEmpty() )
			{
				switch( c.toInt() )
				{
					case C_portamento: updatePortamento(); break;
					case C_filtercutoff: updateFilterFreq(); break;
					case C_filterq: updateFilterQ(); break;
					case C_bandwidth: updateBandwidth(); break;
					case C_fmamp: updateFmGain(); break;
					case C_resonance_center: updateResCenterFreq(); break;
					case C_resonance_bandwidth: updateResBandwidth(); break;
					default:
						break;
				}
			}
		}

		emit settingsChanged();
	}
void runRdb( uint flags )
{
  // Obtain the application palette that is about to be set.
  bool exportColors      = flags & KRdbExportColors;
  bool exportQtColors    = flags & KRdbExportQtColors;
  bool exportQtSettings  = flags & KRdbExportQtSettings;
  bool exportXftSettings = flags & KRdbExportXftSettings;
  bool exportGtkTheme    = flags & KRdbExportGtkTheme;

  KSharedConfigPtr kglobalcfg = KSharedConfig::openConfig( QStringLiteral("kdeglobals") );
  KConfigGroup kglobals(kglobalcfg, "KDE");
  QPalette newPal = KColorScheme::createApplicationPalette(kglobalcfg);

  QTemporaryFile tmpFile;
  if (!tmpFile.open())
  {
    qDebug() << "Couldn't open temp file";
    exit(0);
  }


  KConfigGroup generalCfgGroup(kglobalcfg, "General");

  QString gtkTheme;
  if (kglobals.hasKey("widgetStyle"))
    gtkTheme = kglobals.readEntry("widgetStyle");
  else
    gtkTheme = QStringLiteral("oxygen");

  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 1 );
  createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 2 );

  // Export colors to non-(KDE/Qt) apps (e.g. Motif, GTK+ apps)
  if (exportColors)
  {
    KConfigGroup g(KSharedConfig::openConfig(), "WM");
    QString preproc;
    QColor backCol = newPal.color( QPalette::Active, QPalette::Background );
    addColorDef(preproc, "FOREGROUND"         , newPal.color( QPalette::Active, QPalette::Foreground ) );
    addColorDef(preproc, "BACKGROUND"         , backCol);
    addColorDef(preproc, "HIGHLIGHT"          , backCol.light(100+(2*KColorScheme::contrast()+4)*16/1));
    addColorDef(preproc, "LOWLIGHT"           , backCol.dark(100+(2*KColorScheme::contrast()+4)*10));
    addColorDef(preproc, "SELECT_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Highlight));
    addColorDef(preproc, "SELECT_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::HighlightedText));
    addColorDef(preproc, "WINDOW_BACKGROUND"  , newPal.color( QPalette::Active, QPalette::Base ) );
    addColorDef(preproc, "WINDOW_FOREGROUND"  , newPal.color( QPalette::Active, QPalette::Text ) );
    addColorDef(preproc, "INACTIVE_BACKGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
    addColorDef(preproc, "INACTIVE_FOREGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
    addColorDef(preproc, "ACTIVE_BACKGROUND"  , g.readEntry("activeBackground", QColor(48, 174, 232)));
    addColorDef(preproc, "ACTIVE_FOREGROUND"  , g.readEntry("activeBackground", QColor(48, 174, 232)));
    //---------------------------------------------------------------

    tmpFile.write( preproc.toLatin1(), preproc.length() );

    QStringList list;

    const QStringList adPaths = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
        QStringLiteral("kdisplay/app-defaults/"), QStandardPaths::LocateDirectory);
    for (QStringList::ConstIterator it = adPaths.constBegin(); it != adPaths.constEnd(); ++it) {
      QDir dSys( *it );

      if ( dSys.exists() ) {
        dSys.setFilter( QDir::Files );
        dSys.setSorting( QDir::Name );
        dSys.setNameFilters(QStringList(QStringLiteral("*.ad")));
        list += dSys.entryList();
      }
    }

    for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
      copyFile(tmpFile, QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kdisplay/app-defaults/"+(*it)), true);
  }

  // Merge ~/.Xresources or fallback to ~/.Xdefaults
  QString homeDir = QDir::homePath();
  QString xResources = homeDir + "/.Xresources";

  // very primitive support for ~/.Xresources by appending it
  if ( QFile::exists( xResources ) )
    copyFile(tmpFile, xResources, true);
  else
    copyFile(tmpFile, homeDir + "/.Xdefaults", true);

  // Export the Xcursor theme & size settings
  KConfigGroup mousecfg(KSharedConfig::openConfig( QStringLiteral("kcminputrc") ), "Mouse" );
  QString theme = mousecfg.readEntry("cursorTheme", QString());
  QString size  = mousecfg.readEntry("cursorSize", QString());
  QString contents;

  if (!theme.isNull())
    contents = "Xcursor.theme: " + theme + '\n';

  if (!size.isNull())
    contents += "Xcursor.size: " + size + '\n';

  if (exportXftSettings)
  {
    if (generalCfgGroup.hasKey("XftAntialias"))
    {
      contents += QLatin1String("Xft.antialias: ");
      if(generalCfgGroup.readEntry("XftAntialias", true))
        contents += QLatin1String("1\n");
      else
        contents += QLatin1String("0\n");
    }

    if (generalCfgGroup.hasKey("XftHintStyle"))
    {
      QString hintStyle = generalCfgGroup.readEntry("XftHintStyle", "hintmedium");
      contents += QLatin1String("Xft.hinting: ");
      if(hintStyle.isEmpty())
        contents += QLatin1String("-1\n");
      else
      {
        if(hintStyle!=QLatin1String("hintnone"))
          contents += QLatin1String("1\n");
        else
          contents += QLatin1String("0\n");
        contents += "Xft.hintstyle: " + hintStyle + '\n';
      }
    }

    if (generalCfgGroup.hasKey("XftSubPixel"))
    {
      QString subPixel = generalCfgGroup.readEntry("XftSubPixel");
      if(!subPixel.isEmpty())
        contents += "Xft.rgba: " + subPixel + '\n';
    }

    KConfig _cfgfonts( QStringLiteral("kcmfonts") );
    KConfigGroup cfgfonts(&_cfgfonts, "General");

    if( cfgfonts.readEntry( "forceFontDPI", 0 ) != 0 )
      contents += "Xft.dpi: " + cfgfonts.readEntry( "forceFontDPI" ) + '\n';
    else
    {
      KProcess proc;
      proc << QStringLiteral("xrdb") << QStringLiteral("-quiet") << QStringLiteral("-remove") << QStringLiteral("-nocpp");
      proc.start();
      if (proc.waitForStarted())
      {
        proc.write( QByteArray( "Xft.dpi\n" ) );
        proc.closeWriteChannel();
        proc.waitForFinished();
      }
    }
  }

  if (contents.length() > 0)
    tmpFile.write( contents.toLatin1(), contents.length() );

  tmpFile.flush();

  KProcess proc;
#ifndef NDEBUG
  proc << QStringLiteral("xrdb") << QStringLiteral("-merge") << tmpFile.fileName();
#else
  proc << "xrdb" << "-quiet" << "-merge" << tmpFile.fileName();
#endif
  proc.execute();

  applyGtkStyles(exportColors, 1);
  applyGtkStyles(exportColors, 2);

  /* Qt exports */
  if ( exportQtColors || exportQtSettings )
  {
    QSettings* settings = new QSettings(QStringLiteral("Trolltech"));

    if ( exportQtColors )
      applyQtColors( kglobalcfg, *settings, newPal );    // For kcmcolors

    if ( exportQtSettings )
      applyQtSettings( kglobalcfg, *settings );          // For kcmstyle

    delete settings;
    QApplication::flush();
#if HAVE_X11
    if (qApp->platformName() == QStringLiteral("xcb")) {
        // We let KIPC take care of ourselves, as we are in a KDE app with
        // QApp::setDesktopSettingsAware(false);
        // Instead of calling QApp::x11_apply_settings() directly, we instead
        // modify the timestamp which propagates the settings changes onto
        // Qt-only apps without adversely affecting ourselves.

        // Cheat and use the current timestamp, since we just saved to qtrc.
        QDateTime settingsstamp = QDateTime::currentDateTime();

        static Atom qt_settings_timestamp = 0;
        if (!qt_settings_timestamp) {
            QString atomname(QStringLiteral("_QT_SETTINGS_TIMESTAMP_"));
            atomname += XDisplayName( 0 ); // Use the $DISPLAY envvar.
            qt_settings_timestamp = XInternAtom( QX11Info::display(), atomname.toLatin1(), False);
        }

        QBuffer stamp;
        QDataStream s(&stamp.buffer(), QIODevice::WriteOnly);
        s << settingsstamp;
        XChangeProperty( QX11Info::display(), QX11Info::appRootWindow(), qt_settings_timestamp,
                        qt_settings_timestamp, 8, PropModeReplace,
                        (unsigned char*) stamp.buffer().data(),
                        stamp.buffer().size() );
        QApplication::flush();
    }
#endif
  }

  //Legacy support:
  //Try to sync kde4 settings with ours

  Kdelibs4Migration migration;
  //kf5 congig groups for general and icons
  KConfigGroup generalGroup(kglobalcfg, "General");
  KConfigGroup iconsGroup(kglobalcfg, "Icons");

  const QString colorSchemeName = generalGroup.readEntry("ColorScheme", QString());
  //if no valid color scheme saved, something weird is going on, abort
  if (colorSchemeName.isEmpty()) {
      return;
  }
  //fix filename, copied from ColorsCM::saveScheme()
  QString colorSchemeFilename = colorSchemeName;
  colorSchemeFilename.remove('\''); // So Foo's does not become FooS
  QRegExp fixer(QStringLiteral("[\\W,.-]+(.?)"));
  int offset;
  while ((offset = fixer.indexIn(colorSchemeFilename)) >= 0)
      colorSchemeFilename.replace(offset, fixer.matchedLength(), fixer.cap(1).toUpper());
  colorSchemeFilename.replace(0, 1, colorSchemeFilename.at(0).toUpper());

  //clone the color scheme
  QString src = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "color-schemes/" +  colorSchemeFilename + ".colors");
  QString dest = migration.saveLocation("data", QStringLiteral("color-schemes")) + colorSchemeName + ".colors";

  QFile::remove(dest);
  QFile::copy(src, dest);

  //Apply the color scheme
  QString configFilePath = migration.saveLocation("config") + "kdeglobals";

  if (configFilePath.isEmpty()) {
      return;
  }

  KConfig kde4config(configFilePath, KConfig::SimpleConfig);

  KConfigGroup kde4generalGroup(&kde4config, "General");
  kde4generalGroup.writeEntry("ColorScheme", colorSchemeName);

  //fonts
  QString font = generalGroup.readEntry("font", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("font", font);
  }
  font = generalGroup.readEntry("desktopFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("desktopFont", font);
  }
  font = generalGroup.readEntry("menuFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("menuFont", font);
  }
  font = generalGroup.readEntry("smallestReadableFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("smallestReadableFont", font);
  }
  font = generalGroup.readEntry("taskbarFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("taskbarFont", font);
  }
  font = generalGroup.readEntry("toolBarFont", QString());
  if (!font.isEmpty()) {
      kde4generalGroup.writeEntry("toolBarFont", font);
  }

  //TODO: does exist any way to check if a qt4 widget style is present from a qt5 app?
  //kde4generalGroup.writeEntry("widgetStyle", "qtcurve");
  kde4generalGroup.sync();

  KConfigGroup kde4IconGroup(&kde4config, "Icons");
  QString iconTheme = iconsGroup.readEntry("Theme", QString());
  if (!iconTheme.isEmpty()) {
      kde4IconGroup.writeEntry("Theme", iconTheme);
  }
  kde4IconGroup.sync();

  //copy all the groups in the color scheme in kdeglobals
  KSharedConfigPtr kde4ColorConfig = KSharedConfig::openConfig(src, KConfig::SimpleConfig);

  foreach (const QString &grp, kde4ColorConfig->groupList()) {
      KConfigGroup cg(kde4ColorConfig, grp);
      KConfigGroup cg2(&kde4config, grp);
      cg.copyTo(&cg2);
  }

  //widgets settings
  KConfigGroup kglobals4(&kde4config, "KDE");
  kglobals4.writeEntry("ShowIconsInMenuItems", kglobals.readEntry("ShowIconsInMenuItems", true));
  kglobals4.writeEntry("ShowIconsOnPushButtons", kglobals.readEntry("ShowIconsOnPushButtons", true));
  kglobals4.writeEntry("contrast", kglobals.readEntry("contrast", 4));
  //FIXME: this should somehow check if the kde4 version of the style is installed
  kde4generalGroup.writeEntry("widgetStyle", kglobals.readEntry("widgetStyle", "breeze"));

  //toolbar style
  KConfigGroup toolbars4(&kde4config, "Toolbar style");
  KConfigGroup toolbars5(kglobalcfg, "Toolbar style");
  toolbars4.writeEntry("ToolButtonStyle", toolbars5.readEntry("ToolButtonStyle", "TextBesideIcon"));
  toolbars4.writeEntry("ToolButtonStyleOtherToolbars", toolbars5.readEntry("ToolButtonStyleOtherToolbars", "TextBesideIcon"));
}
예제 #26
0
bool MapnikRenderer::Preprocess( IImporter* importer, QString dir )
{
	QString filename = fileInDirectory( dir, "Mapnik Renderer" );

	try {
		IImporter::BoundingBox box;
		if ( !importer->GetBoundingBox( &box ) )
			return false;
		std::vector< IImporter::RoutingEdge > inputEdges;
		std::vector< IImporter::RoutingNode > inputNodes;
		std::vector< IImporter::RoutingNode > inputPaths;
		if ( m_settings.deleteTiles ) {
			if ( !importer->GetRoutingEdges( &inputEdges ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing edges";
				return false;
			}
			if ( !importer->GetRoutingNodes( &inputNodes ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing nodes";
				return false;
			}
			if ( !importer->GetRoutingEdgePaths( &inputPaths ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing paths";
			}
		}

		Timer time;

		mapnik::datasource_cache::instance().register_datasources( m_settings.plugins.toLatin1().constData() );
		QDir fonts( m_settings.fonts );
		mapnik::projection projection( "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Bold.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Oblique.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-BoldOblique.ttf" ).toLatin1().constData() );

		qDebug() << "Mapnik Renderer: initialized mapnik connection:" << time.restart() << "ms";

		int numThreads = omp_get_max_threads();
		qDebug() << "Mapnik Renderer: using" << numThreads << "threads";

		qDebug() << "Mapnik Renderer: x: " << box.min.x << "-" << box.max.x;
		qDebug() << "Mapnik Renderer: y: " << box.min.y << "-" << box.max.y;

		FileStream configData( filename );
		if ( !configData.open( QIODevice::WriteOnly ) )
			return false;

		configData << quint32( m_settings.tileSize ) << quint32( m_settings.zoomLevels.size() );

		long long tilesSkipped = 0;
		long long tiles = 0;
		long long metaTilesRendered = 0;
		long long pngcrushSaved = 0;

		std::vector< ZoomInfo > zoomInfo( m_settings.zoomLevels.size() );
		std::vector< MetaTile > tasks;

		for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) {
			ZoomInfo& info = zoomInfo[zoomLevel];
			int zoom = m_settings.zoomLevels[zoomLevel];

			info.minX = box.min.GetTileX( zoom );
			info.maxX = box.max.GetTileX( zoom ) + 1;
			info.minY = box.min.GetTileY( zoom );
			info.maxY = box.max.GetTileY( zoom ) + 1;

			if ( zoom <= m_settings.fullZoom ) {
				info.minX = info.minY = 0;
				info.maxX = info.maxY = 1 << zoom;
			} else {
				info.minX = std::max( 0 , info.minX - m_settings.tileMargin );
				info.maxX = std::min ( 1 << zoom, info.maxX + m_settings.tileMargin );
				info.minY = std::max( 0, info.minY - m_settings.tileMargin );
				info.maxY = std::min ( 1 << zoom, info.maxY + m_settings.tileMargin );
			}

			tiles += ( info.maxX - info.minX ) * ( info.maxY - info.minY );
			qDebug() << "Mapnik Renderer: [" << zoom << "] x:" << info.minX << "-" << info.maxX << "; y:" << info.minY << "-" << info.maxY;
			configData << quint32( zoom ) << quint32( info.minX ) << quint32( info.maxX ) << quint32( info.minY ) << quint32( info.maxY );

			int numberOfTiles = ( info.maxX - info.minX ) * ( info.maxY - info.minY );
			IndexElement dummyIndex;
			dummyIndex.start = dummyIndex.size = 0;
			info.index.resize( numberOfTiles, dummyIndex );

			std::vector< UnsignedCoordinate > path;
			for ( std::vector< IImporter::RoutingEdge >::const_iterator i = inputEdges.begin(), e = inputEdges.end(); i != e; ++i ) {
				path.push_back( inputNodes[i->source].coordinate );
				for ( int pathID = 0; pathID < i->pathLength; pathID++ )
					path.push_back( inputPaths[pathID + i->pathID].coordinate );
				path.push_back( inputNodes[i->target].coordinate );

				for ( unsigned edge = 0; edge < path.size(); edge++ ) {
					int sourceX = path[edge].GetTileX( zoom );
					int sourceY = path[edge].GetTileY( zoom );
					int targetX = path[edge].GetTileX( zoom );
					int targetY = path[edge].GetTileY( zoom );
					if ( sourceX > targetX )
						std::swap( sourceX, targetX );
					if ( sourceY > targetY )
						std::swap( sourceY, targetY );
					sourceX = std::max( sourceX, info.minX );
					sourceX = std::min( sourceX, info.maxX - 1 );
					sourceY = std::max( sourceY, info.minY );
					sourceY = std::min( sourceY, info.maxY - 1 );
					targetX = std::max( targetX, info.minX );
					targetX = std::min( targetX, info.maxX - 1 );
					targetY = std::max( targetY, info.minY );
					targetY = std::min( targetY, info.maxY - 1 );
					for ( int x = sourceX; x <= targetX; ++x )
						for ( int y = sourceY; y <= targetY; ++y )
							info.index[( x - info.minX ) + ( y - info.minY ) * ( info.maxX - info.minX )].size = 1;
				}

				path.clear();
			}

			info.tilesFile = new QFile( filename + QString( "_%1_tiles" ).arg( zoom ) );
			if ( !openQFile( info.tilesFile, QIODevice::WriteOnly ) )
				return false;

			for ( int x = info.minX; x < info.maxX; x+= m_settings.metaTileSize ) {
				int metaTileSizeX = std::min( m_settings.metaTileSize, info.maxX - x );
				for ( int y = info.minY; y < info.maxY; y+= m_settings.metaTileSize ) {
					int metaTileSizeY = std::min( m_settings.metaTileSize, info.maxY - y );
					MetaTile tile;
					tile.zoom = zoomLevel;
					tile.x = x;
					tile.y = y;
					tile.metaTileSizeX = metaTileSizeX;
					tile.metaTileSizeY = metaTileSizeY;
					tasks.push_back( tile );
				}
			}
		}


#pragma omp parallel
		{
			int threadID = omp_get_thread_num();
			const int metaTileSize = m_settings.metaTileSize * m_settings.tileSize + 2 * m_settings.margin;

			mapnik::Map map;
			mapnik::image_32 image( metaTileSize, metaTileSize );
			QTemporaryFile tempOut;
			QTemporaryFile tempIn;
			mapnik::load_map( map, m_settings.theme.toLocal8Bit().constData() );

#pragma omp for schedule( dynamic )
			for ( int i = 0; i < ( int ) tasks.size(); i++ ) {

				int metaTileSizeX = tasks[i].metaTileSizeX;
				int metaTileSizeY = tasks[i].metaTileSizeY;
				int x = tasks[i].x;
				int y = tasks[i].y;
				int zoomLevel = tasks[i].zoom;
				int zoom = m_settings.zoomLevels[zoomLevel];
				ZoomInfo& info = zoomInfo[zoomLevel];

				map.resize( metaTileSizeX * m_settings.tileSize + 2 * m_settings.margin, metaTileSizeY * m_settings.tileSize + 2 * m_settings.margin );

				ProjectedCoordinate drawTopLeft( x - 1.0 * m_settings.margin / m_settings.tileSize, y - 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				ProjectedCoordinate drawBottomRight( x + metaTileSizeX + 1.0 * m_settings.margin / m_settings.tileSize, y + metaTileSizeY + 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				GPSCoordinate drawTopLeftGPS = drawTopLeft.ToGPSCoordinate();
				GPSCoordinate drawBottomRightGPS = drawBottomRight.ToGPSCoordinate();
				projection.forward( drawTopLeftGPS.longitude, drawBottomRightGPS.latitude );
				projection.forward( drawBottomRightGPS.longitude, drawTopLeftGPS.latitude );
				mapnik::box2d<double> boundingBox( drawTopLeftGPS.longitude, drawTopLeftGPS.latitude, drawBottomRightGPS.longitude, drawBottomRightGPS.latitude );
				map.zoom_to_box( boundingBox );
				mapnik::agg_renderer<mapnik::image_32> renderer( map, image );
				renderer.apply();

				std::string data;
				int skipped = 0;
				int saved = 0;
				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						mapnik::image_view<mapnik::image_data_32> view = image.get_view( subX * m_settings.tileSize + m_settings.margin, subY * m_settings.tileSize + m_settings.margin, m_settings.tileSize, m_settings.tileSize );
						std::string result;
						if ( !m_settings.deleteTiles || info.index[( x + subX - info.minX ) + ( y + subY - info.minY ) * ( info.maxX - info.minX )].size == 1 ) {
							if ( m_settings.reduceColors )
								result = mapnik::save_to_string( view, "png256" );
							else
								result = mapnik::save_to_string( view, "png" );

							if ( m_settings.pngcrush ) {
								tempOut.open();
								tempOut.write( result.data(), result.size() );
								tempOut.flush();
								tempIn.open();
								pclose( popen( ( "pngcrush " + tempOut.fileName() + " " + tempIn.fileName() ).toUtf8().constData(), "r" ) );
								QByteArray buffer = tempIn.readAll();
								tempIn.close();
								tempOut.close();
								if ( buffer.size() != 0 && buffer.size() < ( int ) result.size() ) {
									saved += result.size() - buffer.size();
									result.assign( buffer.constData(), buffer.size() );
								}
							}
						}

						info.index[indexNumber].start = data.size();
						info.index[indexNumber].size = result.size();
						data += result;
					}
				}

				qint64 position;
#pragma omp critical
				{
					position = info.tilesFile->pos();
					info.tilesFile->write( data.data(), data.size() );

					metaTilesRendered++;
					tilesSkipped += skipped;
					pngcrushSaved += saved;
					qDebug() << "Mapnik Renderer: [" << zoom << "], thread" << threadID << ", metatiles:" << metaTilesRendered << "/" << tasks.size();
				}

				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						info.index[indexNumber].start += position;
					}
				}
			}
		}

		for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) {
			const ZoomInfo& info = zoomInfo[zoomLevel];
			int zoom = m_settings.zoomLevels[zoomLevel];
			QFile indexFile( filename + QString( "_%1_index" ).arg( zoom ) );
			if ( !openQFile( &indexFile, QIODevice::WriteOnly ) )
				return false;
			for ( int i = 0; i < ( int ) info.index.size(); i++ ) {
				indexFile.write( ( const char* ) &info.index[i].start, sizeof( info.index[i].start ) );
				indexFile.write( ( const char* ) &info.index[i].size, sizeof( info.index[i].size ) );
			}
			delete info.tilesFile;
		}

		if ( m_settings.deleteTiles )
			qDebug() << "Mapnik Renderer: removed" << tilesSkipped << "tiles";
		if ( m_settings.pngcrush )
			qDebug() << "Mapnik Renderer: PNGcrush saved" << pngcrushSaved / 1024 / 1024 << "MB";

		qDebug() << "Mapnik Renderer: finished:" << time.restart() << "ms";

	} catch ( const mapnik::config_error & ex ) {
		qCritical( "Mapnik Renderer: ### Configuration error: %s", ex.what() );
		return false;
	} catch ( const std::exception & ex ) {
		qCritical( "Mapnik Renderer: ### STD error: %s", ex.what() );
		return false;
	} catch ( ... ) {
		qCritical( "Mapnik Renderer: ### Unknown error" );
		return false;
	}
	return true;
}
void CSVImportExportPluginInterface::exportCSV()
{
    QPointer<KAddressBookImportExport::KAddressBookContactSelectionDialog> dlg =
        new KAddressBookImportExport::KAddressBookContactSelectionDialog(itemSelectionModel(), false, parentWidget());
    dlg->setMessageText(i18n("Which contact do you want to export?"));
    dlg->setDefaultAddressBook(defaultCollection());
    if (!dlg->exec() || !dlg) {
        delete dlg;
        return;
    }
    const KContacts::AddresseeList contacts = dlg->selectedContacts().addressList();
    delete dlg;

    if (contacts.isEmpty()) {
        KMessageBox::sorry(Q_NULLPTR, i18n("You have not selected any contacts to export."));
        return;
    }

    KAddressBookImportExport::KAddressBookImportExportContactList contactLists;
    contactLists.setAddressList(contacts);
    QFileDialog::Options options = QFileDialog::DontConfirmOverwrite;
    QUrl url = QFileDialog::getSaveFileUrl(parentWidget(), QString(), QUrl::fromLocalFile(QStringLiteral("addressbook.csv")), QString(), Q_NULLPTR, options);
    if (url.isEmpty()) {
        return;
    }

    if (QFileInfo(url.isLocalFile() ? url.toLocalFile() : url.path()).exists()) {
        if (url.isLocalFile() && QFileInfo(url.toLocalFile()).exists()) {
            PimCommon::RenameFileDialog::RenameFileDialogResult result = PimCommon::RenameFileDialog::RENAMEFILE_IGNORE;
            PimCommon::RenameFileDialog *dialog = new PimCommon::RenameFileDialog(url, false, parentWidget());
            result = static_cast<PimCommon::RenameFileDialog::RenameFileDialogResult>(dialog->exec());
            if (result == PimCommon::RenameFileDialog::RENAMEFILE_RENAME) {
                url = dialog->newName();
            } else if (result == PimCommon::RenameFileDialog::RENAMEFILE_IGNORE) {
                delete dialog;
                return;
            }
            delete dialog;
        }
    }

    if (!url.isLocalFile()) {
        QTemporaryFile tmpFile;
        if (!tmpFile.open()) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b></qt>", url.url());
            KMessageBox::error(parentWidget(), msg);
            return;
        }
        exportToFile(&tmpFile, contactLists.addressList());
        tmpFile.flush();
        auto job = KIO::file_copy(QUrl::fromLocalFile(tmpFile.fileName()), url, -1, KIO::Overwrite);
        KJobWidgets::setWindow(job, parentWidget());
        job->exec();
    } else {
        QFile file(url.toLocalFile());
        if (!file.open(QIODevice::WriteOnly)) {
            const QString msg = i18n("<qt>Unable to open file <b>%1</b>.</qt>", url.toLocalFile());
            KMessageBox::error(parentWidget(), msg);
            return;
        }

        exportToFile(&file, contactLists.addressList());
        file.close();
    }
}
예제 #28
0
Variant TestLocalSocket::randomData(uchar *type, uchar dataAmnt, uchar pkgAmnt, uchar fdAmnt, QFile **targetFile) const
{
	///@todo Get actual user file number limit and use it here
	const int		maxFiles	=	512;	// Limit number of files to send
	
	if(m_openFiles.count() >= maxFiles)
		fdAmnt	=	0;
		
	ushort	maxAmnt	=	dataAmnt + pkgAmnt + fdAmnt;
	
	if(maxAmnt == 0)
		return Variant();
	
	ushort	actVal	=	(qrand()/(double(RAND_MAX)))*maxAmnt;
	*type	=	(actVal < dataAmnt ? 0 : (actVal < dataAmnt+pkgAmnt ? 1 : 2));
	
// 	*type	=	qMin(uchar((qrand()/(double(RAND_MAX)))*3), uchar(2));	// 0..2
// 	*type	=	qMin(uchar((qrand()/(double(RAND_MAX)))*2), uchar(1));	// 0..1 => no file descriptors yet
// 	*type	=	2;	// Only file descriptors
	Variant			ret;
	
	#define SIZE_MAX		1048576		// 1 M
// 	#define SIZE_MAX		262144		// 256 K
	
	switch(*type)
	{
		// Random data
		case 0:
		case 1:
		{
			quint32	size	=	qMax(quint32((qrand()/double(RAND_MAX))*SIZE_MAX), quint32(1));	// At least one byte
			
			QByteArray	data;
			data.reserve(size);
			
			for(qint64 j = 0; j < size; j += sizeof(int))
			{
				int	r	=	qrand();
				data.append((char*)&r, qMin(int(size - data.size()), (int)sizeof(int)));
			}
			
			ret	=	data;
		}break;
		
		// File descriptor
		case 2:
		{
			QTemporaryFile	*	file	=	new QTemporaryFile(QDir::tempPath() + QDir::separator() +  "testlocalsocket");
			
			if(!file->open())
			{
				delete file;
				qDebug("Could not create temporary file!");
				return Variant();
			}
			
			// Write filename to temp file
			QFileInfo	info(*file);
			file->write(QString("%1").arg(info.absoluteFilePath()).toUtf8());
			file->flush();
			file->seek(0);
			
			ret		=	Variant::fromSocketDescriptor(file->handle());
			*targetFile	=	file;
		}break;
	}
	
	return ret;
}