/* Purpose: calls external static code test tool and display it's results
   TODO: call only selected part of code (if something is selected)
*/
void toPLSQLEditor::checkCode(void)
{
    if (currentEditor()->editor()->text().isEmpty())
    {
        // do nothing if code text is empty
        return;
    }

    QTemporaryFile tf;
    if (tf.open())
    {
        if (!toWriteFile(tf.fileName(), currentEditor()->editor()->text()))
        {
#ifdef DEBUG
            qDebug() << "Unable to write file (" + tf.fileName() + ")";
#endif
            return;
        }
        else
        {
#ifdef DEBUG
            qDebug() << "Success!!! Temporary file " + tf.fileName();
#endif
        }
    }

    QString program = toConfigurationSingle::Instance().staticChecker().arg(tf.fileName());
#ifdef DEBUG
    qDebug() << "program to be executed: " + program;
#endif
    QProcess staticCheck(qApp);

    staticCheck.setProcessChannelMode(QProcess::MergedChannels);
    staticCheck.start(program);
    staticCheck.waitForFinished(); // default timeout - 30000 miliseconds

    int exit_code = staticCheck.exitStatus();
    if (exit_code != 0)
    {
#ifdef DEBUG
        qDebug() << "Error executing static check. Exit code = " << exit_code;
        int run_error = staticCheck.error();
        // error values taken from Qt4.6 documentation for QProcess
        switch (run_error)
        {
        case 0:
            qDebug() << "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.";
            break;
        case 1:
            qDebug() << "The process crashed some time after starting successfully.";
            break;
        case 5:
            qDebug() << "An unknown error occurred.";
            break;
        default:
            qDebug() << "Error code: " << run_error << "--" << staticCheck.errorString();
        } // switch
#endif
        return;
    }
    QString qq = staticCheck.readAllStandardOutput();
#ifdef DEBUG
    qDebug() << "stdout" << qq;
#endif

    QMultiMap<int, QString> Observations;
    parseResults(qq, Observations);
    currentEditor()->editor()->setErrors(Observations, false);
    currentEditor()->applyResult("STATIC", Observations);
    currentEditor()->resizeResults();
} // checkCode
NS_IMETHODIMP nsDeviceContextSpecQt::GetSurfaceForPrinter(
        gfxASurface** aSurface)
{
    NS_ENSURE_ARG_POINTER(aSurface);
    *aSurface = nullptr;

    double width, height;
    mPrintSettings->GetEffectivePageSize(&width, &height);

    // If we're in landscape mode, we'll be rotating the output --
    // need to swap width & height.
    int32_t orientation;
    mPrintSettings->GetOrientation(&orientation);
    if (nsIPrintSettings::kLandscapeOrientation == orientation) {
        double tmp = width;
        width = height;
        height = tmp;
    }

    // convert twips to points
    width  /= TWIPS_PER_POINT_FLOAT;
    height /= TWIPS_PER_POINT_FLOAT;

    DO_PR_DEBUG_LOG(("\"%s\", %f, %f\n", mPath, width, height));

    QTemporaryFile file;
    if(!file.open()) {
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }
    file.setAutoRemove(false);

    nsresult rv = NS_NewNativeLocalFile(
            nsDependentCString(file.fileName().toUtf8().constData()),
            false,
            getter_AddRefs(mSpoolFile));
    if (NS_FAILED(rv)) {
        file.remove();
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }

    mSpoolName = file.fileName().toUtf8().constData();

    mSpoolFile->SetPermissions(0600);

    nsCOMPtr<nsIFileOutputStream> stream =
        do_CreateInstance("@mozilla.org/network/file-output-stream;1");

    rv = stream->Init(mSpoolFile, -1, -1, 0);
    if (NS_FAILED(rv))
        return rv;

    int16_t format;
    mPrintSettings->GetOutputFormat(&format);

    nsRefPtr<gfxASurface> surface;
    gfxSize surfaceSize(width, height);

    if (format == nsIPrintSettings::kOutputFormatNative) {
        if (mIsPPreview) {
            // There is nothing to detect on Print Preview, use PS.
            // TODO: implement for Qt?
            //format = nsIPrintSettings::kOutputFormatPS;
            return NS_ERROR_NOT_IMPLEMENTED;
        }
        format = nsIPrintSettings::kOutputFormatPDF;
    }
    if (format == nsIPrintSettings::kOutputFormatPDF) {
        surface = new gfxPDFSurface(stream, surfaceSize);
    } else {
        return NS_ERROR_NOT_IMPLEMENTED;
    }

    NS_ABORT_IF_FALSE(surface, "valid address expected");

    surface.swap(*aSurface);
    return NS_OK;
}
Beispiel #3
0
void HistoryManager::save()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("history"));
    settings.setValue(QLatin1String("historyLimit"), m_historyLimit);

    bool saveAll = m_lastSavedUrl.isEmpty();
    int first = m_history.count() - 1;
    if (!saveAll) {
        // find the first one to save
        for (int i = 0; i < m_history.count(); ++i) {
            if (m_history.at(i).url == m_lastSavedUrl) {
                first = i - 1;
                break;
            }
        }
    }
    if (first == m_history.count() - 1)
        saveAll = true;

    QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    if (!QFile::exists(directory)) {
        QDir dir;
        dir.mkpath(directory);
    }

    QFile historyFile(directory + QLatin1String("/history"));
    // When saving everything use a temporary file to prevent possible data loss.
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    bool open = false;
    if (saveAll) {
        open = tempFile.open();
    } else {
        open = historyFile.open(QFile::Append);
    }

    if (!open) {
        qWarning() << "Unable to open history file for saving"
                   << (saveAll ? tempFile.fileName() : historyFile.fileName());
        return;
    }

    QDataStream out(saveAll ? &tempFile : &historyFile);
    for (int i = first; i >= 0; --i) {
        QByteArray data;
        QDataStream stream(&data, QIODevice::WriteOnly);
        HistoryItem item = m_history.at(i);
        stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
        out << data;
    }
    tempFile.close();

    if (saveAll) {
        if (historyFile.exists() && !historyFile.remove())
            qWarning() << "History: error removing old history." << historyFile.errorString();
        if (!tempFile.rename(historyFile.fileName()))
            qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
    }
    m_lastSavedUrl = m_history.value(0).url;
}
Beispiel #4
0
bool Packaging::ExtractTar(QTemporaryFile& tarFile, PackageData *packageData)
{
	TarHeader tarHeader;

	if (!tarFile.open())
	{
		Alerts::DisplayError(QString("Error opening temporary TAR archive:\n%1").arg(tarFile.fileName()));
		return (false);
	}

	bool previousEmpty = false;

	QProgressDialog progressDialog("Extracting files...", "Cancel", 0, tarFile.size());
	progressDialog.setWindowModality(Qt::ApplicationModal);
	progressDialog.setWindowTitle("Heimdall Frontend");

	while (!tarFile.atEnd())
	{
		qint64 dataRead = tarFile.read(tarHeader.buffer, TarHeader::kBlockLength);

		if (dataRead != TarHeader::kBlockLength)
		{
			progressDialog.close();
			Alerts::DisplayError("Package's TAR archive is malformed.");

			tarFile.close();

			return (false);
		}

		progressDialog.setValue(tarFile.pos());

		if (progressDialog.wasCanceled())
		{
			tarFile.close();
			progressDialog.close();

			return (false);
		}

		//bool ustarFormat = strcmp(tarHeader.fields.magic, ustarMagic) == 0;
		bool empty = true;

		for (int i = 0; i < TarHeader::kBlockLength; i++)
		{
			if (tarHeader.buffer[i] != 0)
			{
				empty = false;
				break;
			}
		}

		if (empty)
		{
			if (previousEmpty)
			{
				// Two empty blocks in a row means we've reached the end of the archive.
				break;
			}
		}
		else
		{
			int checksum = 0;

			for (char *bufferIndex = tarHeader.buffer; bufferIndex < tarHeader.fields.checksum; bufferIndex++)
				checksum += static_cast<unsigned char>(*bufferIndex);

			checksum += 8 * ' ';
			checksum += static_cast<unsigned char>(tarHeader.fields.typeFlag);

			// Both the TAR and USTAR formats have terrible documentation, it's not clear if the following code is required.
			/*if (ustarFormat)
			{
				for (char *bufferIndex = tarHeader.fields.linkName; bufferIndex < tarHeader.fields.prefix + 155; bufferIndex++)
					checksum += static_cast<unsigned char>(*bufferIndex);
			}*/

			bool parsed = false;
		
			// The size field is not always null terminated, so we must create a copy and null terminate it for parsing.
			char fileSizeString[13];
			memcpy(fileSizeString, tarHeader.fields.size, 12);
			fileSizeString[12] = '\0';

			qulonglong fileSize = QString(fileSizeString).toULongLong(&parsed, 8);

			if (!parsed)
			{
				progressDialog.close();
				Alerts::DisplayError("Tar header contained an invalid file size.");

				tarFile.close();

				return (false);
			}

			if (fileSize > 0 && tarHeader.fields.typeFlag == '0')
			{
				// We're working with a file.
				QString filename = QString::fromUtf8(tarHeader.fields.name);

				QTemporaryFile *outputFile = new QTemporaryFile("XXXXXX-" + filename);
				packageData->GetFiles().append(outputFile);

				if (!outputFile->open())
				{
					progressDialog.close();
					Alerts::DisplayError(QString("Failed to open output file: \n%1").arg(outputFile->fileName()));

					tarFile.close();

					return (false);
				}

				qulonglong dataRemaining = fileSize;
				char readBuffer[TarHeader::kBlockReadCount * TarHeader::kBlockLength];

				// Copy the file contents from tarFile to outputFile
				while (dataRemaining > 0)
				{
					qint64 fileDataToRead = (dataRemaining < TarHeader::kBlockReadCount * TarHeader::kBlockLength)
						? dataRemaining : TarHeader::kBlockReadCount * TarHeader::kBlockLength;

					qint64 dataRead = tarFile.read(readBuffer, fileDataToRead + (TarHeader::kBlockLength - fileDataToRead % TarHeader::kBlockLength) % TarHeader::kBlockLength);

					if (dataRead < fileDataToRead || dataRead % TarHeader::kBlockLength != 0)
					{
						progressDialog.close();
						Alerts::DisplayError("Unexpected read error whilst extracting package files.");

						tarFile.close();
						outputFile->close();

						remove(outputFile->fileName().toStdString().c_str());

						return (false);
					}

					outputFile->write(readBuffer, fileDataToRead);

					dataRemaining -= fileDataToRead;

					progressDialog.setValue(tarFile.pos());

					if (progressDialog.wasCanceled())
					{
						tarFile.close();
						outputFile->close();

						remove(outputFile->fileName().toStdString().c_str());

						progressDialog.close();

						return (false);
					}
				}

				outputFile->close();
			}
			else
			{
				progressDialog.close();
				Alerts::DisplayError("Heimdall packages shouldn't contain links or directories.");

				tarFile.close();

				return (false);
			}
		}

		previousEmpty = empty;
	}

	progressDialog.close();
	tarFile.close();

	return (true);
}
Beispiel #5
0
			int TorrentPlugin::AddJob (Entity e)
			{
				QString suggestedFname;

				if (e.Entity_.canConvert<QUrl> ())
				{
					QUrl resource = e.Entity_.toUrl ();
					if (resource.scheme () == "magnet")
					{
						QString at = XmlSettingsManager::Instance ()->
							property ("AutomaticTags").toString ();
						QStringList tags = e.Additional_ [" Tags"].toStringList ();
						Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
								GetTagsManager ()->Split (at))
							tags << Core::Instance ()->GetProxy ()->
								GetTagsManager ()->GetID (tag);

						QList<QPair<QString, QString> > queryItems = resource.queryItems ();
						for (QList<QPair<QString, QString> >::const_iterator i = queryItems.begin (),
								end = queryItems.end (); i != end; ++i)
							if (i->first == "kt")
							{
								QStringList humanReadable = i->second
									.split ('+', QString::SkipEmptyParts);
								Q_FOREACH (QString hr, humanReadable)
									tags += Core::Instance ()->GetProxy ()->
										GetTagsManager ()->GetID (hr);
							}

						return Core::Instance ()->AddMagnet (resource.toString (),
								e.Location_,
								tags,
								e.Parameters_);
					}
					else if (resource.scheme () == "file")
						suggestedFname = resource.toLocalFile ();
				}

				QByteArray entity = e.Entity_.toByteArray ();

				QFile file (suggestedFname);
				if ((!file.exists () ||
						!file.open (QIODevice::ReadOnly)) &&
						Core::Instance ()->IsValidTorrent (entity))
				{
					QTemporaryFile file ("lctemporarybittorrentfile.XXXXXX");
					if (!file.open  ())
						return -1;
					file.write (entity);
					suggestedFname = file.fileName ().toUtf8 ();
					file.setAutoRemove (false);
				}

				AddTorrentDialog_->Reinit ();
				AddTorrentDialog_->SetFilename (suggestedFname);
				if (!e.Location_.isEmpty ())
					AddTorrentDialog_->SetSavePath (e.Location_);

				QString path;
				QStringList tags = e.Additional_ [" Tags"].toStringList ();
				QVector<bool> files;
				QString fname;
				bool tryLive = e.Additional_ ["TryToStreamLive"].toBool ();
				if (e.Parameters_ & FromUserInitiated)
				{
					if (!tags.isEmpty ())
						AddTorrentDialog_->SetTags (tags);

					if (AddTorrentDialog_->exec () == QDialog::Rejected)
						return -1;

					fname = AddTorrentDialog_->GetFilename (),
					path = AddTorrentDialog_->GetSavePath ();
					tryLive = AddTorrentDialog_->GetTryLive ();
					files = AddTorrentDialog_->GetSelectedFiles ();
					tags = AddTorrentDialog_->GetTags ();
					if (AddTorrentDialog_->GetAddType () == Core::Started)
						e.Parameters_ &= ~NoAutostart;
					else
						e.Parameters_ |= NoAutostart;
				}
				else
				{
					fname = suggestedFname;
					path = e.Location_;
					QString at = XmlSettingsManager::Instance ()->
						property ("AutomaticTags").toString ();
					Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
							GetTagsManager ()->Split (at))
						tags << Core::Instance ()->GetProxy ()->
							GetTagsManager ()->GetID (tag);
				}
				int result = Core::Instance ()->AddFile (fname,
						path,
						tags,
						tryLive,
						files,
						e.Parameters_);
				setActionsEnabled ();
				file.remove ();
				return result;
			}
void BootloaderInstallHex::installStage2(void)
{
    emit logItem(tr("Adding bootloader to firmware file"), LOGINFO);
    QCoreApplication::processEvents();

    // local temp file
    QTemporaryFile tempbin;
    tempbin.open();
    QString tempbinName = tempbin.fileName();
    tempbin.close();
    // get temporary files filenames -- external tools need this.
    m_descrambled.open();
    QString descrambledName = m_descrambled.fileName();
    m_descrambled.close();
    m_tempfile.open();
    QString tempfileName = m_tempfile.fileName();
    m_tempfile.close();

    int origin = 0;
    switch(m_model) {
        case 3:
            origin = 0x3f0000;
            break;
        case 2:
        case 1:
            origin = 0x1f0000;
            break;
        default:
            origin = 0;
            break;
    }

    // iriver decode already done in stage 1
    int result;
    if((result = mkboot(descrambledName.toLocal8Bit().constData(),
                    tempfileName.toLocal8Bit().constData(),
                    tempbinName.toLocal8Bit().constData(), origin)) < 0)
    {
        QString error;
        switch(result) {
            case -1: error = tr("could not open input file"); break;
            case -2: error = tr("reading header failed"); break;
            case -3: error = tr("reading firmware failed"); break;
            case -4: error = tr("can't open bootloader file"); break;
            case -5: error = tr("reading bootloader file failed"); break;
            case -6: error = tr("can't open output file"); break;
            case -7: error = tr("writing output file failed"); break;
        }
        emit logItem(tr("Error in patching: %1").arg(error), LOGERROR);

        emit done(true);
        return;
    }
    QTemporaryFile targethex;
    targethex.open();
    QString targethexName = targethex.fileName();
    if((result = iriver_encode(tempbinName.toLocal8Bit().constData(),
                    targethexName.toLocal8Bit().constData(), FALSE)) < 0)
    {
        emit logItem(tr("Error in scramble: %1").arg(scrambleError(result)), LOGERROR);
        targethex.close();

        emit done(true);
        return;
    }

    // finally check the md5sum of the created file
    QByteArray filedata;
    filedata = targethex.readAll();
    targethex.close();
    QString hash = QCryptographicHash::hash(filedata,
            QCryptographicHash::Md5).toHex();
    qDebug() << "[BootloaderInstallHex] created hexfile hash:" << hash;

    emit logItem(tr("Checking modified firmware file"), LOGINFO);
    if(hash != QString(md5sums[m_hashindex].patched)) {
        emit logItem(tr("Error: modified file checksum wrong"), LOGERROR);
        targethex.remove();
        emit done(true);
        return;
    }
    // finally copy file to player
    targethex.copy(m_blfile);

    emit logItem(tr("Success: modified firmware file created"), LOGINFO);
    logInstall(LogAdd);
    emit done(false);

    return;
}
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"));
}
Beispiel #8
0
void autofix(QString originalFileName, int numFiles, QSize size)
{
    std::cout << "Autofixing " << numFiles << size.width() << "x" << size.height()
              << " thumbnails of " << originalFileName.toLocal8Bit().constData() << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], Strings::jpegMimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int prepareTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    time.restart();

    for (int i=0; i<numFiles; i++) {
        QuillImageFilter *filter =
            QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_AutoLevels);
        quillFile[i]->runFilter(filter);
    }

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are edited!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms" << "\n";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Total prepare " << numFiles << " QuillFiles: "
             << prepareTime << "ms" << "\n";

    std::cout << "Use case edit response for " << numFiles << " QuillFiles: "
             << finalTime << "ms" << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
Beispiel #9
0
void ut_file::testRevertRestore()
{
   QTemporaryFile testFile;
   testFile.open();

   QuillImage image = Unittests::generatePaletteImage();
   image.save(testFile.fileName(), "png");

   QuillImageFilter *filter =
       QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_BrightnessContrast);
   QVERIFY(filter);
   filter->setOption(QuillImageFilter::Brightness, QVariant(20));
   QuillImage imageAfter = filter->apply(image);

   QuillFile *file = new QuillFile(testFile.fileName(), Strings::png);
   QVERIFY(file->setDisplayLevel(0));
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),false);
   file->runFilter(filter);
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),true);
   QuillImageFilter *filter1 =
       QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Rotate);

   filter1->setOption(QuillImageFilter::Angle, QVariant(-90));
   QuillImage imageAfter1 = filter1->apply(imageAfter);
   file->runFilter(filter1);
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),true);

   //Test revert
   file->revert();
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),true);
   QCOMPARE(file->canRevert(),false);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),3);
   QVERIFY(Unittests::compareImage(file->image(), image));
   file->save();
   Quill::releaseAndWait();
   Quill::releaseAndWait();

   //Test restore
   file->restore();
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),true);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);
   QVERIFY(Unittests::compareImage(file->image(), imageAfter1));

   //Test redo with revert and restore
   file->revert();
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),true);
   QCOMPARE(file->canRevert(),false);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),3);
   file->redo();
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),true);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);

   //Test one additional operation after revert
   file->revert();
   Quill::releaseAndWait();
   Quill::releaseAndWait();
   QCOMPARE(file->canRestore(),true);
   QCOMPARE(file->canRevert(),false);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),2);
   QuillImageFilter *filter2 =
       QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Rotate);

   filter2->setOption(QuillImageFilter::Angle, QVariant(-90));
   file->runFilter(filter2);
   QCOMPARE(file->canRestore(),false);
   QCOMPARE(file->canRevert(),true);
   QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);

   delete file;
}
Beispiel #10
0
void PaymentServerTests::paymentServerTests()
{
    SelectParams(CBaseChainParams::MAIN);
    OptionsModel optionsModel;
    PaymentServer* server = new PaymentServer(nullptr, false);
    X509_STORE* caStore = X509_STORE_new();
    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));
    PaymentServer::LoadRootCAs(caStore);
    server->setOptionsModel(&optionsModel);
    server->uiReady();

    std::vector<unsigned char> data;
    SendCoinsRecipient r;
    QString merchant;

    // Now feed PaymentRequests to server, and observe signals it produces

    // This payment request validates directly against the
    // caCert1 certificate authority:
    data = DecodeBase64(paymentrequest1_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant.org"));

    // Signed, but expired, merchant cert in the request:
    data = DecodeBase64(paymentrequest2_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // 10-long certificate chain, all intermediates valid:
    data = DecodeBase64(paymentrequest3_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString("testmerchant8.org"));

    // Long certificate chain, with an expired certificate in the middle:
    data = DecodeBase64(paymentrequest4_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Validly signed, but by a CA not in our root CA list:
    data = DecodeBase64(paymentrequest5_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Try again with no root CA's, verifiedMerchant should be empty:
    caStore = X509_STORE_new();
    PaymentServer::LoadRootCAs(caStore);
    data = DecodeBase64(paymentrequest1_cert1_BASE64);
    r = handleRequest(server, data);
    r.paymentRequest.getMerchant(caStore, merchant);
    QCOMPARE(merchant, QString(""));

    // Load second root certificate
    caStore = X509_STORE_new();
    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));
    PaymentServer::LoadRootCAs(caStore);

    QByteArray byteArray;

    // For the tests below we just need the payment request data from
    // paymentrequestdata.h parsed + stored in r.paymentRequest.
    //
    // These tests require us to bypass the following normal client execution flow
    // shown below to be able to explicitly just trigger a certain condition!
    //
    // handleRequest()
    // -> PaymentServer::eventFilter()
    //   -> PaymentServer::handleURIOrFile()
    //     -> PaymentServer::readPaymentRequestFromFile()
    //       -> PaymentServer::processPaymentRequest()

    // Contains a testnet paytoaddress, so payment request network doesn't match client network:
    data = DecodeBase64(paymentrequest1_cert2_BASE64);
    byteArray = QByteArray((const char*)&data[0], data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized, because network "main" is default, even for
    // uninitialized payment requests and that will fail our test here.
    QVERIFY(r.paymentRequest.IsInitialized());
    QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);

    // Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
    data = DecodeBase64(paymentrequest2_cert2_BASE64);
    byteArray = QByteArray((const char*)&data[0], data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares 1 < GetTime() == false (treated as expired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);

    // Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):
    // 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
    // -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
    data = DecodeBase64(paymentrequest3_cert2_BASE64);
    byteArray = QByteArray((const char*)&data[0], data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);

    // Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):
    // 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
    // 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
    data = DecodeBase64(paymentrequest4_cert2_BASE64);
    byteArray = QByteArray((const char*)&data[0], data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // compares -9223372036854775808 < GetTime() == true (treated as expired payment request)
    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);

    // Test BIP70 DoS protection:
    unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];
    GetRandBytes(randData, sizeof(randData));
    // Write data to a temp file:
    QTemporaryFile tempFile;
    tempFile.open();
    tempFile.write((const char*)randData, sizeof(randData));
    tempFile.close();
    // compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false
    QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);

    // Payment request with amount overflow (amount is set to 21000001 BTC):
    data = DecodeBase64(paymentrequest5_cert2_BASE64);
    byteArray = QByteArray((const char*)&data[0], data.size());
    r.paymentRequest.parse(byteArray);
    // Ensure the request is initialized
    QVERIFY(r.paymentRequest.IsInitialized());
    // Extract address and amount from the request
    QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
    for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
        CTxDestination dest;
        if (ExtractDestination(sendingTo.first, dest))
            QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
    }

    delete server;
}
void doTests() {

  KstVectorPtr vp = new KstVector(KstObjectTag::fromString("tempVector"), 10);
  for (int i = 0; i < 10; i++){
    vp->value()[i] = i;
  }

  KstPSDPtr psd = new KstPSD(QString("psdTest"), vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDUndefined);
  doTest(!psd->apodize());
  doTest(!psd->removeMean());
  doTest(!psd->average());
  doTest(psd->freq() == 0.0);
  doTest(psd->apodizeFxn() == WindowUndefined);
  doTest(psd->gaussianSigma() == 0);
  KstVectorPtr vpVX = psd->vX();
  KstVectorPtr vpVY = psd->vY();

  doTest(vpVX->length() == 1);
  doTest(vpVX->value()[0] != vpVX->value()[0]);
  doTest(vpVY->length() == 1);
  doTest(vpVY->value()[0] != vpVY->value()[0]);

  psd->writeLock();
  doTest(psd->update(0) == KstObject::UPDATE);
  psd->unlock();
 
  for(int j = 0; j < vpVX->length(); j++){
      doTest(vpVX->value()[j] == 0);
  }

  psd->setOutput(PSDAmplitudeSpectralDensity);
  psd->setApodize(true);
  psd->setRemoveMean(true);
  psd->setAverage(true);
  psd->setFreq(0.1);
  psd->setApodizeFxn(WindowOriginal);
  psd->setGaussianSigma(0.2);

  doTest(psd->tagName() == "psdTest");
  doTest(psd->vTag() == "tempVector");
  doTest(psd->output() == PSDAmplitudeSpectralDensity);
  doTest(psd->apodize());
  doTest(psd->removeMean());
  doTest(psd->average());
  doTest(psd->freq() == 0.1);
  doTest(psd->apodizeFxn() == WindowOriginal);
  doTest(psd->gaussianSigma() == 0.2);
  
//   doTest(psd->update(0) == KstObject::UPDATE);
//   QString ps = "PSD: " + psd->vTag();
//   doTest(psd->propertyString() == ps);
//    doTest(!psd->curveHints().curveName() == "");
//   printf("Curve name [%s]", kstCHL[0].curveName());
//   printf("X Vector name [%s]", kstCHL[0].xVectorName());
//   printf("Y Vector name [%s]", kstCHL[0].yVectorName());

  QTemporaryFile tf;
  tf.open();
  QTextStream ts(&tf);
  psd->save(ts, "");
  QFile::remove(tf.fileName());

  QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
  QDomElement e = n.toElement();
  KstPSDPtr psdDOM = new KstPSD(e);

  doTest(psdDOM->tagName() == "psdDOMPsd");
  doTest(psdDOM->output() == PSDAmplitudeSpectralDensity);
  doTest(psdDOM->apodize());
  doTest(psdDOM->removeMean());
  doTest(psdDOM->average());
  doTest(psdDOM->freq() == 128);
  doTest(psdDOM->apodizeFxn() == WindowOriginal);
  doTest(psdDOM->gaussianSigma() == 0.01);

//   KstVectorPtr vpVX = psdDOM->vX();
//   for(int j = 0; j < vpVX->length(); j++){
//       printf("[%d][%lf]", j, vpVX->value()[j]);
//   }
//   KstVectorPtr vpVY = psdDOM->vY();
}
Beispiel #12
0
QFile* Snapshot::savedFileForSnapshot(bool isTemporary) {
    auto glCanvas = DependencyManager::get<GLCanvas>();
    QImage shot = glCanvas->grabFrameBuffer();
    
    Avatar* avatar = Application::getInstance()->getAvatar();
    
    glm::vec3 location = avatar->getPosition();
    glm::quat orientation = avatar->getHead()->getOrientation();
    
    // add metadata
    shot.setText(LOCATION_X, QString::number(location.x));
    shot.setText(LOCATION_Y, QString::number(location.y));
    shot.setText(LOCATION_Z, QString::number(location.z));
    
    shot.setText(ORIENTATION_X, QString::number(orientation.x));
    shot.setText(ORIENTATION_Y, QString::number(orientation.y));
    shot.setText(ORIENTATION_Z, QString::number(orientation.z));
    shot.setText(ORIENTATION_W, QString::number(orientation.w));
    
    shot.setText(DOMAIN_KEY, DependencyManager::get<NodeList>()->getDomainHandler().getHostname());

    QString formattedLocation = QString("%1_%2_%3").arg(location.x).arg(location.y).arg(location.z);
    // replace decimal . with '-'
    formattedLocation.replace('.', '-');
    
    QString username = AccountManager::getInstance().getAccountInfo().getUsername();
    // normalize username, replace all non alphanumeric with '-'
    username.replace(QRegExp("[^A-Za-z0-9_]"), "-");
    
    QDateTime now = QDateTime::currentDateTime();
    
    QString filename = FILENAME_PATH_FORMAT.arg(username, now.toString(DATETIME_FORMAT), formattedLocation);
    
    const int IMAGE_QUALITY = 100;
    
    if (!isTemporary) {
        QString snapshotFullPath = Menu::getInstance()->getSnapshotsLocation();
        
        if (!snapshotFullPath.endsWith(QDir::separator())) {
            snapshotFullPath.append(QDir::separator());
        }
        
        snapshotFullPath.append(filename);
        
        QFile* imageFile = new QFile(snapshotFullPath);
        imageFile->open(QIODevice::WriteOnly);
        
        shot.save(imageFile, 0, IMAGE_QUALITY);
        imageFile->close();
        
        return imageFile;
    } else {
        QTemporaryFile* imageTempFile = new QTemporaryFile(QDir::tempPath() + "/XXXXXX-" + filename);
        
        if (!imageTempFile->open()) {
            qDebug() << "Unable to open QTemporaryFile for temp snapshot. Will not save.";
            return NULL;
        }
        
        shot.save(imageTempFile, 0, IMAGE_QUALITY);
        imageTempFile->close();
        
        return imageTempFile;
    }
}
Beispiel #13
0
int process( const QDir &input, const QDir &output, const QString &xml )
{
    QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE" );
    database.setDatabaseName( input.filePath( "speakers.db" ) );
    if ( !database.open() ) {
        qDebug() << "Failed to connect to database " << input.filePath( "speakers.db" );
        return 3;
    }

    output.mkdir( "files.kde.org" );
    QSqlQuery query( "SELECT * FROM speakers ORDER BY Id" );

    QFile xmlFile( xml );
    if ( !xmlFile.open( QFile::WriteOnly | QFile::Truncate ) ) {
        qDebug() << "Failed to write to " << xmlFile.fileName();
        return 3;
    }

    QTextStream xmlOut( &xmlFile );
    xmlOut << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    xmlOut << "<!DOCTYPE knewstuff SYSTEM \"knewstuff.dtd\">\n";
    xmlOut << "<?xml-stylesheet type=\"text/xsl\" href=\"speakers.xsl\" ?>\n";
    xmlOut << "<knewstuff>\n";

    int index = 71;
    while (query.next()) {
        QString const name = query.value(1).toString();
        QString const email = query.value(2).toString();
        QString const nick = query.value(3).toString();
        QString const gender = query.value(4).toString();
        QString const language = query.value(5).toString();
        QString const lang = language.mid(0, language.indexOf(QLatin1Char('(')) - 1).replace(QLatin1Char(' '), QLatin1Char('-'));
        QString const description = query.value(6).toString();
        QString const token = query.value(7).toString();
        QString const date = query.value(8).toString();
        QString const zip = input.filePath( token );
        QTemporaryFile tmpFile;
        tmpFile.open();
        QString const extracted = tmpFile.fileName();
        tmpFile.remove();
        QDir::root().mkdir( extracted );
        qDebug() << "Name: " << name;

        QString const simpleNick = QString( nick ).replace( QLatin1Char(' '), QLatin1Char('-') );
        QString const nickDir = output.filePath("files.kde.org") + QLatin1Char('/') + simpleNick;
        QDir::root().mkdir( nickDir );
        extract( zip, extracted );
        normalize( extracted );
        createLegalFiles( extracted, name, email );
        QFile::copy(extracted + QLatin1String("/Marble.ogg"), nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".ogg"));
        convertToMarbleFormat(extracted, nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".zip"));
        convertToTomTomFormat(extracted, nickDir, nick, simpleNick, index, gender == QLatin1String("male"), lang);
        convertToNewStuffFormat(extracted, nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".tar.gz"));

        xmlOut << "  <stuff category=\"marble/data/audio\">\n";
        xmlOut << "    <name lang=\"en\">" << language << " - " << nick << " (" <<  gender << ")" << "</name>\n";
        xmlOut << "    <author>" << name << "</author>\n";
        xmlOut << "    <licence>CC-By-SA 3.0</licence>\n";
        xmlOut << "    <summary lang=\"en\">" << description << "</summary>\n";
        xmlOut << "    <version>0.1</version>\n";
        xmlOut << "    <releasedate>" << date << "</releasedate>\n";
        xmlOut << "    <preview lang=\"en\">http://edu.kde.org/marble/speaker-" << gender << ".png</preview>\n";
        xmlOut << "    <payload lang=\"en\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".tar.gz</payload>\n";
        xmlOut << "    <payload lang=\"ogg\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".ogg</payload>\n";
        xmlOut << "    <payload lang=\"zip\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".zip</payload>\n";
        xmlOut << "    <payload lang=\"tomtom\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << "-TomTom.zip</payload>\n";
        xmlOut << "  </stuff>\n";

        ++index;
    }

    xmlOut << "</knewstuff>\n";
    xmlFile.close();
    return 0;
}
Beispiel #14
0
bool SharePlugin::receivePackage(const NetworkPackage& np)
{
/*
    //TODO: Write a test like this
    if (np.type() == PACKAGE_TYPE_PING) {

        qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc");

        NetworkPackage out(PACKAGE_TYPE_SHARE_REQUEST);
        out.set("filename", mDestinationDir + "itworks.txt");
        AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer

        out.setPayload(file, file->size());

        device()->sendPackage(out);

        return true;

    }
*/

    qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer";

    if (np.hasPayload()) {
        //qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file";
        const QString filename = np.get<QString>(QStringLiteral("filename"), QString::number(QDateTime::currentMSecsSinceEpoch()));
        const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash);
        QUrl destination(dir.toString() + '/' + filename);
        if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) {
            destination = QUrl(dir.toString() + '/' + KIO::suggestName(dir, filename));
        }

        FileTransferJob* job = np.createPayloadTransferJob(destination);
        job->setOriginName(device()->name() + ": " + filename);
        connect(job, &KJob::result, this, &SharePlugin::finished);
        KIO::getJobTracker()->registerJob(job);
        job->start();
    } else if (np.has(QStringLiteral("text"))) {
        QString text = np.get<QString>(QStringLiteral("text"));
        if (!QStandardPaths::findExecutable(QStringLiteral("kate")).isEmpty()) {
            QProcess* proc = new QProcess();
            connect(proc, SIGNAL(finished(int)), proc, SLOT(deleteLater()));
            proc->start(QStringLiteral("kate"), QStringList(QStringLiteral("--stdin")));
            proc->write(text.toUtf8());
            proc->closeWriteChannel();
        } else {
            QTemporaryFile tmpFile;
            tmpFile.setAutoRemove(false);
            tmpFile.open();
            tmpFile.write(text.toUtf8());
            tmpFile.close();

            const QUrl url = QUrl::fromLocalFile(tmpFile.fileName());
            Q_EMIT shareReceived(url);
            QDesktopServices::openUrl(url);
        }
    } else if (np.has(QStringLiteral("url"))) {
        QUrl url = QUrl::fromEncoded(np.get<QByteArray>(QStringLiteral("url")));
        QDesktopServices::openUrl(url);
        Q_EMIT shareReceived(url);
    } else {
        qCDebug(KDECONNECT_PLUGIN_SHARE) << "Error: Nothing attached!";
    }

    return true;

}
/**
 * generate layout and apply it to the given diagram.
 *
 * @return true if generating succeeded
*/
bool LayoutGenerator::generate(UMLScene *scene, const QString &variant)
{
    QTemporaryFile in;
    QTemporaryFile out;
    QTemporaryFile xdotOut;
    if (!isEnabled()) {
        uWarning() << "Could not apply autolayout because graphviz installation has not been found.";
        return false;
    }

#ifdef LAYOUTGENERATOR_DEBUG
    in.setAutoRemove(false);
    out.setAutoRemove(false);
    xdotOut.setAutoRemove(false);
#endif

    // generate filenames
    in.open();
    in.close();
    out.open();
    out.close();
    xdotOut.open();
    xdotOut.close();

#ifdef LAYOUTGENERATOR_DEBUG
    qDebug() << textViewer() << in.fileName();
    qDebug() << textViewer() << out.fileName();
    qDebug() << textViewer() << xdotOut.fileName();
#endif

    if (!createDotFile(scene, in.fileName(), variant))
        return false;

    QString executable = m_dotPath + QLatin1Char('/') + m_generator;

    QProcess p;
    QStringList args;
    args << QLatin1String("-o") << out.fileName() << QLatin1String("-Tplain-ext") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();

    args.clear();
    args << QLatin1String("-o") << xdotOut.fileName() << QLatin1String("-Txdot") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();

#ifdef LAYOUTGENERATOR_DEBUG
    QTemporaryFile pngFile;
    pngFile.setAutoRemove(false);
    pngFile.setFileTemplate(QDir::tempPath() + QLatin1String("/umbrello-layoutgenerator-XXXXXX.png"));
    pngFile.open();
    pngFile.close();
    qDebug() << pngViewer() << pngFile.fileName();
    args.clear();
    args << QLatin1String("-o") << pngFile.fileName() << QLatin1String("-Tpng") << in.fileName();
    p.start(executable, args);
    p.waitForFinished();
#endif
#ifndef USE_XDOT
    if (!readGeneratedDotFile(out.fileName()))
#else
    if (!readGeneratedDotFile(xdotOut.fileName()))
#endif
        return false;

    return true;
}
Beispiel #16
0
tristate SqliteVacuum::run()
{
    const QString dump_app = QString::fromLatin1(KDB_SQLITE_DUMP_TOOL);
    //sqliteDebug() << dump_app;
    if (dump_app.isEmpty()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find tool \"%1\".")
                             .arg(dump_app));
        sqliteWarning() << m_result;
        return false;
    }
    const QString sqlite_app(KDb::sqlite3ProgramPath());
    //sqliteDebug() << sqlite_app;
    if (sqlite_app.isEmpty()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find application \"%1\".")
                             .arg(sqlite_app));
        sqliteWarning() << m_result;
        return false;
    }

    QFileInfo fi(m_filePath);
    if (!fi.isReadable()) {
        m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not read file \"%1\".")
                             .arg(m_filePath));
        sqliteWarning() << m_result;
        return false;
    }

    //sqliteDebug() << fi.absoluteFilePath() << fi.absoluteDir().path();

    delete m_dumpProcess;
    m_dumpProcess = new QProcess(this);
    m_dumpProcess->setWorkingDirectory(fi.absoluteDir().path());
    m_dumpProcess->setReadChannel(QProcess::StandardError);
    connect(m_dumpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStdErr()));
    connect(m_dumpProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(dumpProcessFinished(int,QProcess::ExitStatus)));

    delete m_sqliteProcess;
    m_sqliteProcess = new QProcess(this);
    m_sqliteProcess->setWorkingDirectory(fi.absoluteDir().path());
    connect(m_sqliteProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(sqliteProcessFinished(int,QProcess::ExitStatus)));

    m_dumpProcess->setStandardOutputProcess(m_sqliteProcess);
    m_dumpProcess->start(dump_app, QStringList() << fi.absoluteFilePath());
    if (!m_dumpProcess->waitForStarted()) {
        delete m_dumpProcess;
        m_dumpProcess = 0;
        m_result.setCode(ERR_OTHER);
        return false;
    }

    QTemporaryFile *tempFile = new QTemporaryFile(fi.absoluteFilePath());
    tempFile->open();
    m_tmpFilePath = tempFile->fileName();
    delete tempFile;
    //sqliteDebug() << m_tmpFilePath;
    m_sqliteProcess->start(sqlite_app, QStringList() << m_tmpFilePath);
    if (!m_sqliteProcess->waitForStarted()) {
        delete m_dumpProcess;
        m_dumpProcess = 0;
        delete m_sqliteProcess;
        m_sqliteProcess = 0;
        m_result.setCode(ERR_OTHER);
        return false;
    }

    delete m_dlg;
    m_dlg = new QProgressDialog(0); // krazy:exclude=qclasses
    m_dlg->setWindowTitle(tr("Compacting database"));
    m_dlg->setLabelText(
        QLatin1String("<qt>") + tr("Compacting database \"%1\"...")
            .arg(QLatin1String("<nobr>")
                 + QDir::fromNativeSeparators(fi.fileName())
                 + QLatin1String("</nobr>"))
    );
    m_dlg->adjustSize();
    m_dlg->resize(300, m_dlg->height());
    m_dlg->setMinimumDuration(1000);
    m_dlg->setAutoClose(true);
    m_dlg->setRange(0, 100);
    m_dlg->exec();
    if (m_dlg->wasCanceled()) {
        cancelClicked();
    }
    delete m_dlg;
    m_dlg = 0;
    while (m_dumpProcess->state() == QProcess::Running
           && m_sqliteProcess->state()  == QProcess::Running)
    {
        readFromStdErr();
        qApp->processEvents(QEventLoop::AllEvents, 50000);
    }

    readFromStdErr();
    return true;
}
void OscapScannerLocal::evaluate()
{
    if (mDryRun)
    {
        signalCompletion(mCancelRequested);
        return;
    }

    emit infoMessage(QObject::tr("Querying capabilities..."));

    {
        SyncProcess proc(this);
        proc.setCommand(SCAP_WORKBENCH_LOCAL_OSCAP_PATH);
        proc.setArguments(QStringList("--v"));
        proc.run();

        if (proc.getExitCode() != 0)
        {
            emit errorMessage(
                QObject::tr("Failed to query capabilities of oscap on local machine.\n"
                    "Diagnostic info:\n%1").arg(proc.getDiagnosticInfo())
            );

            mCancelRequested = true;
            signalCompletion(mCancelRequested);
            return;
        }

        mCapabilities.parse(proc.getStdOutContents());
    }

    if (!checkPrerequisites())
    {
        mCancelRequested = true;
        signalCompletion(mCancelRequested);
        return;
    }

    // TODO: Error handling!
    emit infoMessage(QObject::tr("Creating temporary files..."));

    QTemporaryFile resultFile;
    resultFile.setAutoRemove(true);
    // the following forces Qt to give us the filename
    resultFile.open(); resultFile.close();

    QTemporaryFile reportFile;
    reportFile.setAutoRemove(true);
    reportFile.open(); reportFile.close();

    QTemporaryFile arfFile;
    arfFile.setAutoRemove(true);
    arfFile.open(); arfFile.close();

    // This is mainly for check-engine-results and oval-results, to ensure
    // we get a full report, including info from these files. openscap's XSLT
    // uses info in the check engine results if it can find them.
    TemporaryDir workingDir;

    emit infoMessage(QObject::tr("Starting the oscap process..."));
    QProcess process(this);
    process.setWorkingDirectory(workingDir.getPath());

    QStringList args;

    QTemporaryFile inputARFFile;
    inputARFFile.setAutoRemove(true);

    if (mScannerMode == SM_OFFLINE_REMEDIATION)
    {
        inputARFFile.open();
        inputARFFile.write(getARFForRemediation());
        inputARFFile.close();

        args = buildOfflineRemediationArgs(inputARFFile.fileName(),
                resultFile.fileName(),
                reportFile.fileName(),
                arfFile.fileName());
    }
    else
    {
        args = buildEvaluationArgs(mSession->getOpenedFilePath(),
                mSession->hasTailoring() ? mSession->getTailoringFilePath() : QString(),
                resultFile.fileName(),
                reportFile.fileName(),
                arfFile.fileName(),
                mScannerMode == SM_SCAN_ONLINE_REMEDIATION);
    }

    QString program = "";
#ifdef SCAP_WORKBENCH_LOCAL_NICE_FOUND
    args.prepend(getPkexecOscapPath());
    args.prepend(QString::number(SCAP_WORKBENCH_LOCAL_OSCAP_NICENESS));
    args.prepend("-n");

    program = SCAP_WORKBENCH_LOCAL_NICE_PATH;
#else
    program = getPkexecOscapPath();
#endif

    process.start(program, args);
    process.waitForStarted();

    if (process.state() != QProcess::Running)
    {
        emit errorMessage(QObject::tr("Failed to start local scanning process '%1'. Perhaps the executable was not found?").arg(program));
        mCancelRequested = true;
    }

    const unsigned int pollInterval = 100;

    emit infoMessage(QObject::tr("Processing..."));
    while (!process.waitForFinished(pollInterval))
    {
        // read everything new
        readStdOut(process);
        watchStdErr(process);

        // pump the event queue, mainly because the user might want to cancel
        QAbstractEventDispatcher::instance(mScanThread)->processEvents(QEventLoop::AllEvents);

        if (mCancelRequested)
        {
            emit infoMessage(QObject::tr("Cancellation was requested! Terminating scanning..."));
            process.kill();
            process.waitForFinished(1000);
            break;
        }
    }

    if (!mCancelRequested)
    {
        if (process.exitCode() == 1) // error happened
        {
            watchStdErr(process);
            // TODO: pass the diagnostics over
            emit errorMessage(QObject::tr("There was an error during evaluation! Exit code of the 'oscap' process was 1."));
            // mark this run as canceled
            mCancelRequested = true;
        }
        else
        {
            // read everything left over
            readStdOut(process);
            watchStdErr(process);

            emit infoMessage(QObject::tr("The oscap tool has finished. Reading results..."));

            resultFile.open();
            mResults = resultFile.readAll();
            resultFile.close();

            reportFile.open();
            mReport = reportFile.readAll();
            reportFile.close();

            arfFile.open();
            mARF = arfFile.readAll();
            arfFile.close();

            emit infoMessage(QObject::tr("Processing has been finished!"));
        }
    }

    signalCompletion(mCancelRequested);
}
Beispiel #18
0
int DNGWriter::convert()
{
    d->cancel = false;

    try
    {
        if (inputFile().isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl;
            return -1;
        }

        QFileInfo inputInfo(inputFile());
        QString   dngFilePath = outputFile();

        if (dngFilePath.isEmpty())
        {
            dngFilePath = QString(inputInfo.baseName() + QString(".dng"));
        }

        QFileInfo          outputInfo(dngFilePath);
        QByteArray         rawData;
        DcrawInfoContainer identify;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl;

        KDcraw rawProcessor;
        if (!rawProcessor.extractRAWData(inputFile(), rawData, identify))
        {
            kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl;
            return -1;
        }

        if (d->cancel) return -2;

        int width      = identify.imageSize.width();
        int height     = identify.imageSize.height();
        int pixelRange = 16;

        kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl;
        kDebug( 51000 ) << "--- Data Size:     " << rawData.size() << " bytes" << endl;
        kDebug( 51000 ) << "--- Date:          " << identify.dateTime.toString(Qt::ISODate) << endl;
        kDebug( 51000 ) << "--- Make:          " << identify.make << endl;
        kDebug( 51000 ) << "--- Model:         " << identify.model << endl;
        kDebug( 51000 ) << "--- Size:          " << width << "x" << height << endl;
        kDebug( 51000 ) << "--- Orientation:   " << identify.orientation << endl;
        kDebug( 51000 ) << "--- Top margin:    " << identify.topMargin << endl;
        kDebug( 51000 ) << "--- Left margin:   " << identify.leftMargin << endl;
        kDebug( 51000 ) << "--- Filter:        " << identify.filterPattern << endl;
        kDebug( 51000 ) << "--- Colors:        " << identify.rawColors << endl;
        kDebug( 51000 ) << "--- Black:         " << identify.blackPoint << endl;
        kDebug( 51000 ) << "--- White:         " << identify.whitePoint << endl;
        kDebug( 51000 ) << "--- CAM->XYZ:" << endl;

        QString matrixVal;
        for(int i=0; i<12; i+=3)
        {
            kDebug( 51000 ) << "                   "
                     << QString().sprintf("%03.4f  %03.4f  %03.4f", identify.cameraXYZMatrix[0][ i ],
                                                                    identify.cameraXYZMatrix[0][i+1],
                                                                    identify.cameraXYZMatrix[0][i+2])
                     << endl;
        }

        // Check if CFA layout is supported by DNG SDK.
        int bayerMosaic;

        if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG"))
        {
            bayerMosaic = 0;
        }
        else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB"))
        {
            bayerMosaic = 1;
        }
        else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR"))
        {
            bayerMosaic = 2;
        }
        else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG"))
        {
            bayerMosaic = 3;
        }
        else
        {
            kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl;
            return -1;
        }

        // Check if number of Raw Color components is supported.
        if (identify.rawColors != 3)
        {
            kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl;
            return -1;
        }

/*      // NOTE: code to hack RAW data extraction

        QString   rawdataFilePath(inputInfo.baseName() + QString(".dat"));
        QFileInfo rawdataInfo(rawdataFilePath);

        QFile rawdataFile(rawdataFilePath);
        if (!rawdataFile.open(QIODevice::WriteOnly))
        {
            kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl;
            return -1;
        }
        QDataStream rawdataStream(&rawdataFile);
        rawdataStream.writeRawData(rawData.data(), rawData.size());
        rawdataFile.close();
*/
        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl;

        std::vector<unsigned short> raw_data;
        raw_data.resize(rawData.size());
        const unsigned short* dp = (const unsigned short*)rawData.data();
        for (uint i = 0; i < raw_data.size()/2; i++)
        {
            raw_data[i] = *dp;
            *dp++;
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl;

        dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
        dng_memory_stream stream(memalloc);
        stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short));

        dng_rect rect(height, width);
        DNGWriterHost host(d, &memalloc);

        // Unprocessed raw data.
        host.SetKeepStage1(true);

        // Linearized, tone curve processed data.
        host.SetKeepStage2(true);

        AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl;

        dng_ifd ifd;

        ifd.fUsesNewSubFileType        = true;
        ifd.fNewSubFileType            = 0;
        ifd.fImageWidth                = width;
        ifd.fImageLength               = height;
        ifd.fBitsPerSample[0]          = pixelRange;
        ifd.fBitsPerSample[1]          = 0;
        ifd.fBitsPerSample[2]          = 0;
        ifd.fBitsPerSample[3]          = 0;
        ifd.fCompression               = ccUncompressed;
        ifd.fPredictor                 = 1;
        ifd.fCFALayout                 = 1;                 // Rectangular (or square) layout.
        ifd.fPhotometricInterpretation = piCFA;
        ifd.fFillOrder                 = 1;
        ifd.fOrientation               = identify.orientation;
        ifd.fSamplesPerPixel           = 1;
        ifd.fPlanarConfiguration       = 1;
        ifd.fXResolution               = 0.0;
        ifd.fYResolution               = 0.0;
        ifd.fResolutionUnit            = 0;

        ifd.fUsesStrips                = true;
        ifd.fUsesTiles                 = false;

        ifd.fTileWidth                 = width;
        ifd.fTileLength                = height;
        ifd.fTileOffsetsType           = 4;
        ifd.fTileOffsetsCount          = 0;

        ifd.fSubIFDsCount              = 0;
        ifd.fSubIFDsOffset             = 0;
        ifd.fExtraSamplesCount         = 0;
        ifd.fSampleFormat[0]           = 1;
        ifd.fSampleFormat[1]           = 1;
        ifd.fSampleFormat[2]           = 1;
        ifd.fSampleFormat[3]           = 1;

        ifd.fLinearizationTableType    = 0;
        ifd.fLinearizationTableCount   = 0;
        ifd.fLinearizationTableOffset  = 0;

        ifd.fBlackLevelRepeatRows      = 1;
        ifd.fBlackLevelRepeatCols      = 1;
        ifd.fBlackLevel[0][0][0]       = identify.blackPoint;
        ifd.fBlackLevelDeltaHType      = 0;
        ifd.fBlackLevelDeltaHCount     = 0;
        ifd.fBlackLevelDeltaHOffset    = 0;
        ifd.fBlackLevelDeltaVType      = 0;
        ifd.fBlackLevelDeltaVCount     = 0;
        ifd.fBlackLevelDeltaVOffset    = 0;
        ifd.fWhiteLevel[0]             = identify.whitePoint;
        ifd.fWhiteLevel[1]             = identify.whitePoint;
        ifd.fWhiteLevel[2]             = identify.whitePoint;
        ifd.fWhiteLevel[3]             = identify.whitePoint;

        ifd.fDefaultScaleH             = dng_urational(1, 1);
        ifd.fDefaultScaleV             = dng_urational(1, 1);
        ifd.fBestQualityScale          = dng_urational(1, 1);

        ifd.fCFARepeatPatternRows      = 0;
        ifd.fCFARepeatPatternCols      = 0;

        ifd.fBayerGreenSplit           = 0;
        ifd.fChromaBlurRadius          = dng_urational(0, 0);
        ifd.fAntiAliasStrength         = dng_urational(100, 100);

        ifd.fActiveArea                = rect;
        ifd.fDefaultCropOriginH        = dng_urational(0, 1);
        ifd.fDefaultCropOriginV        = dng_urational(0, 1);
        ifd.fDefaultCropSizeH          = dng_urational(width, 1);
        ifd.fDefaultCropSizeV          = dng_urational(height, 1);

        ifd.fMaskedAreaCount           = 0;
        ifd.fLosslessJPEGBug16         = false;
        ifd.fSampleBitShift            = 0;

        ifd.ReadImage(host, stream, *image.Get());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl;

        AutoPtr<dng_negative> negative(host.Make_dng_negative());

        negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV);
        negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV);
        negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV);
        negative->SetActiveArea(ifd.fActiveArea);

        negative->SetModelName(identify.model.toAscii());
        negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());
        negative->SetOriginalRawFileName(inputInfo.fileName().toAscii());

        negative->SetColorChannels(3);
        negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue);
        negative->SetBayerMosaic(bayerMosaic);

        negative->SetWhiteLevel(identify.whitePoint, 0);
        negative->SetWhiteLevel(identify.whitePoint, 1);
        negative->SetWhiteLevel(identify.whitePoint, 2);
        negative->SetBlackLevel(identify.blackPoint, 0);
        negative->SetBlackLevel(identify.blackPoint, 1);
        negative->SetBlackLevel(identify.blackPoint, 2);

        negative->SetBaselineExposure(0.0);
        negative->SetBaselineNoise(1.0);
        negative->SetBaselineSharpness(1.0);

        dng_orientation orientation;
        switch (identify.orientation)
        {
            case DcrawInfoContainer::ORIENTATION_180:
                orientation = dng_orientation::Rotate180();
                break;

            case DcrawInfoContainer::ORIENTATION_90CCW:
                orientation = dng_orientation::Rotate90CCW();
                break;

            case DcrawInfoContainer::ORIENTATION_90CW:
                orientation = dng_orientation::Rotate90CW();
                break;

            default:   // ORIENTATION_NONE
                orientation = dng_orientation::Normal();
                break;
        }
        negative->SetBaseOrientation(orientation);

        negative->SetAntiAliasStrength(dng_urational(100, 100));
        negative->SetLinearResponseLimit(1.0);
        negative->SetShadowScale( dng_urational(1, 1) );

        negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0));

        // -------------------------------------------------------------------------------

        // Set Camera->XYZ Color matrix as profile.
        dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
        dng_matrix_3by3 camXYZ;

        AutoPtr<dng_camera_profile> prof(new dng_camera_profile);
        prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());

        camXYZ[0][0] = identify.cameraXYZMatrix[0][0];
        camXYZ[0][1] = identify.cameraXYZMatrix[0][1];
        camXYZ[0][2] = identify.cameraXYZMatrix[0][2];
        camXYZ[1][0] = identify.cameraXYZMatrix[0][3];
        camXYZ[1][1] = identify.cameraXYZMatrix[1][0];
        camXYZ[1][2] = identify.cameraXYZMatrix[1][1];
        camXYZ[2][0] = identify.cameraXYZMatrix[1][2];
        camXYZ[2][1] = identify.cameraXYZMatrix[1][3];
        camXYZ[2][2] = identify.cameraXYZMatrix[2][0];

        if (camXYZ.MaxEntry() == 0.0)
            kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl;
        else 
            matrix = camXYZ;

        prof->SetColorMatrix1((dng_matrix) matrix);
        prof->SetCalibrationIlluminant1(lsD65);
        negative->AddProfile(prof);

        // -------------------------------------------------------------------------------

        // Clear "Camera WhiteXY"
        negative->SetCameraWhiteXY(dng_xy_coord());

        // This settings break color on preview and thumbnail
        //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl;

        dng_exif *exif = negative->GetExif();
        exif->fModel.Set_ASCII(identify.model.toAscii());
        exif->fMake.Set_ASCII(identify.make.toAscii());

        // Time from original shot
        dng_date_time dt;
        dt.fYear   = identify.dateTime.date().year();
        dt.fMonth  = identify.dateTime.date().month();
        dt.fDay    = identify.dateTime.date().day();
        dt.fHour   = identify.dateTime.time().hour();
        dt.fMinute = identify.dateTime.time().minute();
        dt.fSecond = identify.dateTime.time().second();

        dng_date_time_info dti;
        dti.SetDateTime(dt);
        exif->fDateTimeOriginal  = dti;
        exif->fDateTimeDigitized = dti;
        negative->UpdateDateTime(dti);

        long int num, den;
        long     val;
        QString  str;
        KExiv2   meta;
        if (meta.load(inputFile()))
        {
            // String Tags

            str = meta.getExifTagString("Exif.Image.Software");
            if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.ImageDescription");
            if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Artist");
            if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Copyright");
            if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Photo.UserComment");
            if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.CameraSerialNumber");
            if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef");
            if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef");
            if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites");
            if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSStatus");
            if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode");
            if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef");
            if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum");
            if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef");
            if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef");
            if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod");
            if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation");
            if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp");
            if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii());

            // Rational Tags

            if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den))          exif->fExposureTime          = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FNumber", num, den))               exif->fFNumber               = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den))     exif->fShutterSpeedValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den))         exif->fApertureValue         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den))       exif->fBrightnessValue       = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den))     exif->fExposureBiasValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den))      exif->fMaxApertureValue      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den))           exif->fFocalLength           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den))      exif->fDigitalZoomRatio      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den))       exif->fSubjectDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den))          exif->fBatteryLevelR         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den))         exif->fGPSAltitude           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den))              exif->fGPSDOP                = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den))            exif->fGPSSpeed              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den))            exif->fGPSTrack              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den))     exif->fGPSImgDirection       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den))      exif->fGPSDestBearing        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den))     exif->fGPSDestDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den))         exif->fGPSLatitude[0]        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den))        exif->fGPSLongitude[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den))        exif->fGPSTimeStamp[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den))     exif->fGPSDestLatitude[0]    = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den))    exif->fGPSDestLongitude[0]   = dng_urational(num, den);

            // Integer Tags

            if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val))          exif->fExposureProgram          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.MeteringMode", val))             exif->fMeteringMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.LightSource", val))              exif->fLightSource              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Flash", val))                    exif->fFlash                    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SensingMethod", val))            exif->fSensingMethod            = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FileSource", val))               exif->fFileSource               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneType", val))                exif->fSceneType                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.CustomRendered", val))           exif->fCustomRendered           = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ExposureMode", val))             exif->fExposureMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val))             exif->fWhiteBalance             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val))         exif->fSceneCaptureType         = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.GainControl", val))              exif->fGainControl              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Contrast", val))                 exif->fContrast                 = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Saturation", val))               exif->fSaturation               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Sharpness", val))                exif->fSharpness                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val))     exif->fSubjectDistanceRange     = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val))    exif->fFocalLengthIn35mmFilm    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val))  exif->fComponentsConfiguration  = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val))          exif->fPixelXDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val))          exif->fPixelYDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val))           exif->fGPSVersionID             = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val))         exif->fGPSAltitudeRef           = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val))        exif->fGPSDifferential          = (uint32)val;
        }

        // Markernote backup.

        QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote");
        if (!mkrnts.isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl;

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(mkrnts.data(), mkrnts.size());
            AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), mkrnts.size());
            negative->SetMakerNote(block);
            negative->SetMakerNoteSafety(true);
        }

        if (d->backupOriginalRawFile)
        {
            kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl;

            // Compress Raw file data to Zip archive.

            QTemporaryFile zipFile;
            if (!zipFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl;
                return -1;
            }
            KZip zipArchive(zipFile.fileName());
            zipArchive.open(QIODevice::WriteOnly);
            zipArchive.setCompression(KZip::DeflateCompression);
            zipArchive.addLocalFile(inputFile(), inputFile());
            zipArchive.close();

            // Load Zip Archive in a byte array

            QFileInfo zipFileInfo(zipFile.fileName());
            QByteArray zipRawFileData;
            zipRawFileData.resize(zipFileInfo.size());
            QDataStream dataStream(&zipFile);
            dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size());
            kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl;

            // Pass byte array to DNG sdk and compute MD5 fingerprint.

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(zipRawFileData.data(), zipRawFileData.size());
            AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), zipRawFileData.size());

            dng_md5_printer md5;
            md5.Process(block->Buffer(), block->LogicalSize());
            negative->SetOriginalRawFileData(block);
            negative->SetOriginalRawFileDigest(md5.Result());
            negative->ValidateOriginalRawFileDigest();

            zipFile.remove();
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl;

        // Assign Raw image data.
        negative->SetStage1Image(image);

        // Compute linearized and range mapped image
        negative->BuildStage2Image(host);

        // Compute demosaiced image (used by preview and thumbnail)
        negative->BuildStage3Image(host);

        negative->SynchronizeMetadata();
        negative->RebuildIPTC();

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        dng_preview_list previewList;

// NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage.
#if QT_VERSION >= 0x40400

        if (d->previewMode != DNGWriter::NONE)
        {
            kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl;

            // Construct a preview image as TIFF format.
            AutoPtr<dng_image> tiffImage;
            dng_render tiff_render(host, *negative);
            tiff_render.SetFinalSpace(dng_space_sRGB::Get());
            tiff_render.SetFinalPixelType(ttByte);
            tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width);
            tiffImage.Reset(tiff_render.Render());

            dng_image_writer tiff_writer;
            AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator));

            tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB,
                                  ccUncompressed, negative.Get(), &tiff_render.FinalSpace());

            // Write TIFF preview image data to a temp JPEG file
            std::vector<char> tiff_mem_buffer(dms->Length());
            dms->SetReadPosition(0);
            dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size());
            dms.Reset();

            QImage pre_image;
            if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF"))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl;
                return -1;
            }

            QTemporaryFile previewFile;
            if (!previewFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            if (!pre_image.save(previewFile.fileName(), "JPEG", 90))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            // Load JPEG preview file data in DNG preview container.
            AutoPtr<dng_jpeg_preview> jpeg_preview;
            jpeg_preview.Reset(new dng_jpeg_preview);
            jpeg_preview->fPhotometricInterpretation = piYCbCr;
            jpeg_preview->fPreviewSize.v             = pre_image.height();
            jpeg_preview->fPreviewSize.h             = pre_image.width();
            jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size()));

            QDataStream previewStream( &previewFile );
            previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size());

            AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) );
            previewList.Append(pp);

            previewFile.remove();
        }

#endif /* QT_VERSION >= 0x40400 */

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl;

        dng_image_preview thumbnail;
        dng_render thumbnail_render(host, *negative);
        thumbnail_render.SetFinalSpace(dng_space_sRGB::Get());
        thumbnail_render.SetFinalPixelType(ttByte);
        thumbnail_render.SetMaximumSize(256);
        thumbnail.fImage.Reset(thumbnail_render.Render());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl;

        dng_image_writer writer;
        dng_file_stream filestream(QFile::encodeName(dngFilePath), true);

        writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, 
                        d->jpegLossLessCompression ? ccJPEG : ccUncompressed,
                        &previewList);
    }

    catch (const dng_exception &exception)
    {
        int ret = exception.ErrorCode();
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl;
        return ret;
    }

    catch (...)
    {
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl;
        return dng_error_unknown;
    }

    kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl;

    return dng_error_none;
}
QgsRasterLayer* QgsRemoteOWSBuilder::wcsLayerFromUrl( const QString &url,
    const QString &layerName,
    QList<QTemporaryFile*> &filesToRemove,
    QList<QgsMapLayer*> &layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );

#if QT_VERSION < 0x050000
  QgsDebugMsg( "Entering" );

  //write server url and coverage name to a temporary file
  QString fileName = createTempFile();
  if ( fileName.isEmpty() )
  {
    return nullptr;
  }

  QFile tempFile( fileName );

  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( !tmpFile->open() )
  {
    delete tmpFile;
    return nullptr;
  }

  filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request

  QgsDebugMsg( "opening successful" );
  QgsDebugMsg( "url: " + url );
  //extract server url and coverage name from string
  QStringList serverSplit = url.split( "?" );
  if ( serverSplit.size() < 2 )
  {
    QgsDebugMsg( "error, no '?' contained in url" );
    return nullptr;
  }
  QString serverUrl = serverSplit.at( 0 );
  QString request = serverSplit.at( 1 );
  QStringList parameterSplit = request.split( "&" );
  QString coverageName;
  QString format;
  for ( int i = 0; i < parameterSplit.size(); ++i )
  {
    if ( parameterSplit.at( i ).startsWith( "COVERAGE", Qt::CaseInsensitive ) )
    {
      coverageName = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
    else if ( parameterSplit.at( i ).startsWith( "FORMAT", Qt::CaseInsensitive ) )
    {
      format = parameterSplit.at( i ).split( "=" ).at( 1 );
    }
  }

  if ( coverageName.isEmpty() )
  {
    QgsDebugMsg( "coverage name is empty" );
    return nullptr;
  }

  if ( format.isEmpty() )
  {
    format = "GeoTIFF"; //use geotiff as default
  }

  QgsDebugMsg( "wcs server url: " + serverUrl );
  QgsDebugMsg( "coverage name: " + coverageName );

  //fetch WCS layer in the current resolution as geotiff
  QString wcsRequest = serverUrl + "?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=" + coverageName + "&FORMAT=" + format;

  //CRS (or SRS)
  QString crs = mParameterMap.value( "CRS", mParameterMap.value( "SRS" ) );
  if ( crs.isEmpty() )
  {
    QgsDebugMsg( "No CRS or SRS parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&CRS=" + crs;

  //width
  QString width = mParameterMap.value( "WIDTH" );
  if ( width.isEmpty() )
  {
    QgsDebugMsg( "No WIDTH parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&WIDTH=" + width;

  //height
  QString height = mParameterMap.value( "HEIGHT" );
  if ( height.isEmpty() )
  {
    QgsDebugMsg( "No HEIGHT parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&HEIGHT=" + height;

  //bbox
  QString bbox = mParameterMap.value( "BBOX" );
  if ( bbox.isEmpty() )
  {
    QgsDebugMsg( "No BBOX parameter found for wcs layer, returning 0" );
    return nullptr;
  }
  wcsRequest += "&BBOX=" + bbox;

  QgsDebugMsg( "WCS request is: " + wcsRequest );
  //make request and store byte array into temporary file
  QgsHttpTransaction httpTransaction( wcsRequest );
  QByteArray result;
  if ( !httpTransaction.getSynchronously( result ) )
  {
    return nullptr;
  }

  QDataStream tempFileStream( &tempFile );
  tempFileStream.writeRawData( result.data(), result.size() );
  tempFile.close();

  QgsRasterLayer* rl = new QgsRasterLayer( fileName, layerNameFromUri( fileName ) );
  layersToRemove.push_back( rl ); //make sure the layer gets deleted after each request
  return rl;
#else
  Q_UNUSED( url )
  Q_UNUSED( filesToRemove )
  Q_UNUSED( layersToRemove )
  QgsDebugMsg( "remote http not supported with Qt5" );
  return nullptr;
#endif

}
Beispiel #20
0
QByteArray* QgsWCSServer::getCoverage()
{
  QStringList wcsLayersId = mConfigParser->wcsLayers();

  QList<QgsMapLayer*> layerList;

  QStringList mErrors = QStringList();

  //defining coverage name
  QString coveName = QLatin1String( "" );
  //read COVERAGE
  QMap<QString, QString>::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "COVERAGE" ) );
  if ( cove_name_it != mParameters.constEnd() )
  {
    coveName = cove_name_it.value();
  }
  if ( coveName == QLatin1String( "" ) )
  {
    QMap<QString, QString>::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "IDENTIFIER" ) );
    if ( cove_name_it != mParameters.constEnd() )
    {
      coveName = cove_name_it.value();
    }
  }

  if ( coveName == QLatin1String( "" ) )
  {
    mErrors << QStringLiteral( "COVERAGE is mandatory" );
  }

  layerList = mConfigParser->mapLayerFromCoverage( coveName );
  if ( layerList.size() < 1 )
  {
    mErrors << QStringLiteral( "The layer for the COVERAGE '%1' is not found" ).arg( coveName );
  }

  bool conversionSuccess;
  // BBOX
  bool bboxOk = false;
  double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
  // WIDTh and HEIGHT
  int width = 0, height = 0;
  // CRS
  QString crs = QLatin1String( "" );

  // read BBOX
  QMap<QString, QString>::const_iterator bbIt = mParameters.constFind( QStringLiteral( "BBOX" ) );
  if ( bbIt == mParameters.constEnd() )
  {
    minx = 0;
    miny = 0;
    maxx = 0;
    maxy = 0;
  }
  else
  {
    bboxOk = true;
    QString bbString = bbIt.value();
    minx = bbString.section( QStringLiteral( "," ), 0, 0 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    miny = bbString.section( QStringLiteral( "," ), 1, 1 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    maxx = bbString.section( QStringLiteral( "," ), 2, 2 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    maxy = bbString.section( QStringLiteral( "," ), 3, 3 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
  }
  if ( !bboxOk )
  {
    mErrors << QStringLiteral( "The BBOX is mandatory and has to be xx.xxx,yy.yyy,xx.xxx,yy.yyy" );
  }

  // read WIDTH
  width = mParameters.value( QStringLiteral( "WIDTH" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess );
  if ( !conversionSuccess )
    width = 0;
  // read HEIGHT
  height = mParameters.value( QStringLiteral( "HEIGHT" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess );
  if ( !conversionSuccess )
  {
    height = 0;
  }

  if ( width < 0 || height < 0 )
  {
    mErrors << QStringLiteral( "The WIDTH and HEIGHT are mandatory and have to be integer" );
  }

  crs = mParameters.value( QStringLiteral( "CRS" ), QLatin1String( "" ) );
  if ( crs == QLatin1String( "" ) )
  {
    mErrors << QStringLiteral( "The CRS is mandatory" );
  }

  if ( mErrors.count() != 0 )
  {
    throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
  }

  QgsCoordinateReferenceSystem requestCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs );
  if ( !requestCRS.isValid() )
  {
    mErrors << QStringLiteral( "Could not create request CRS" );
    throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
  }

  QgsRectangle rect( minx, miny, maxx, maxy );

  QgsMapLayer* layer = layerList.at( 0 );
  QgsRasterLayer* rLayer = qobject_cast<QgsRasterLayer*>( layer );
  if ( rLayer && wcsLayersId.contains( rLayer->id() ) )
  {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    if ( !mAccessControl->layerReadPermission( rLayer ) )
    {
      throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "You are not allowed to access to this coverage" ) );
    }
#endif

    // RESPONSE_CRS
    QgsCoordinateReferenceSystem responseCRS = rLayer->crs();
    crs = mParameters.value( QStringLiteral( "RESPONSE_CRS" ), QLatin1String( "" ) );
    if ( crs != QLatin1String( "" ) )
    {
      responseCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs );
      if ( !responseCRS.isValid() )
      {
        responseCRS = rLayer->crs();
      }
    }

    // transform rect
    if ( requestCRS != rLayer->crs() )
    {
      QgsCoordinateTransform t( requestCRS, rLayer->crs() );
      rect = t.transformBoundingBox( rect );
    }

    QTemporaryFile tempFile;
    tempFile.open();
    QgsRasterFileWriter fileWriter( tempFile.fileName() );

    // clone pipe/provider
    QgsRasterPipe* pipe = new QgsRasterPipe();
    if ( !pipe->set( rLayer->dataProvider()->clone() ) )
    {
      mErrors << QStringLiteral( "Cannot set pipe provider" );
      throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
    }

    // add projector if necessary
    if ( responseCRS != rLayer->crs() )
    {
      QgsRasterProjector * projector = new QgsRasterProjector;
      projector->setCrs( rLayer->crs(), responseCRS );
      if ( !pipe->insert( 2, projector ) )
      {
        mErrors << QStringLiteral( "Cannot set pipe projector" );
        throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
      }
    }

    QgsRasterFileWriter::WriterError err = fileWriter.writeRaster( pipe, width, height, rect, responseCRS );
    if ( err != QgsRasterFileWriter::NoError )
    {
      mErrors << QStringLiteral( "Cannot write raster error code: %1" ).arg( err );
      throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
    }
    delete pipe;
    QByteArray* ba = nullptr;
    ba = new QByteArray();
    *ba = tempFile.readAll();

    return ba;
  }
  return nullptr;
}
Beispiel #21
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 TestPSD::testPSD() {

  Kst::VectorPtr vp = Kst::kst_cast<Kst::Vector>(_store.createObject<Kst::Vector>());
  Q_ASSERT(vp);
  vp->resize(10);
  vp->setDescriptiveName("tempVector");
  for (int i = 0; i < 10; i++){
    vp->value()[i] = i;
  }

  Kst::PSDPtr psd = Kst::kst_cast<Kst::PSD>(_store.createObject<Kst::PSD>());
  psd->change(vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
  QCOMPARE(psd->vector()->descriptiveName(), QLatin1String("tempVector"));
  QCOMPARE(psd->output(), PSDUndefined);
  QVERIFY(!psd->apodize());
  QVERIFY(!psd->removeMean());
  QVERIFY(!psd->average());
  QCOMPARE(psd->frequency(), 0.0);
  QCOMPARE(psd->apodizeFxn(), WindowUndefined);
  QCOMPARE(psd->gaussianSigma(), 0.0);
  Kst::VectorPtr vpVX = psd->vX();
  Kst::VectorPtr vpVY = psd->vY();

  QCOMPARE(vpVX->length(), 1);
  QVERIFY(vpVX->value()[0] != vpVX->value()[0]);
  QCOMPARE(vpVY->length(), 1);
  QVERIFY(vpVY->value()[0] != vpVY->value()[0]);

  for(int j = 0; j < vpVX->length(); j++){
      QCOMPARE(vpVX->value()[j], 0.0);
  }

  psd->setOutput(PSDAmplitudeSpectralDensity);
  psd->setApodize(true);
  psd->setRemoveMean(true);
  psd->setAverage(true);
  psd->setFrequency(0.1);
  psd->setApodizeFxn(WindowOriginal);
  psd->setGaussianSigma(0.2);

  QCOMPARE(psd->vector()->descriptiveName(), QLatin1String("tempVector"));
  QCOMPARE(psd->output(), PSDAmplitudeSpectralDensity);
  QVERIFY(psd->apodize());
  QVERIFY(psd->removeMean());
  QVERIFY(psd->average());
  QCOMPARE(psd->frequency(), 0.1);
  QCOMPARE(psd->apodizeFxn(), WindowOriginal);
  QCOMPARE(psd->gaussianSigma(), 0.2);

//   doTest(psd->update(0) == Kst::Object::UPDATE);
//   doTest(psd->propertyString() == ps);
//    doTest(!psd->curveHints().curveName() == "");
//   printf("Curve name [%s]", kstCHL[0].curveName());
//   printf("X Vector name [%s]", kstCHL[0].xVectorName());
//   printf("Y Vector name [%s]", kstCHL[0].yVectorName());

  QTemporaryFile tf;
  tf.open();
  QXmlStreamWriter xml;
  xml.setDevice(&tf);
  xml.setAutoFormatting(true);
  psd->save(xml);
  QFile::remove(tf.fileName());

  QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
  QDomElement e = n.toElement();

  //FIXME: should use factory, not this constructor.  This constructor is no longer
  // used anywhere in kst.
//   Kst::PSDPtr psdDOM = new Kst::PSD(&_store, e);

//   QCOMPARE(psdDOM->tag().tagString(), QLatin1String("psdDOMPsd"));
//   QCOMPARE(psdDOM->output(), PSDAmplitudeSpectralDensity);
//   QVERIFY(psdDOM->apodize());
//   QVERIFY(psdDOM->removeMean());
//   QVERIFY(psdDOM->average());
//   QCOMPARE(psdDOM->frequency(), 128.0);
//   QCOMPARE(psdDOM->apodizeFxn(), WindowOriginal);
//   QCOMPARE(psdDOM->gaussianSigma(), 0.01);

//   Kst::VectorPtr vpVX = psdDOM->vX();
//   for(int j = 0; j < vpVX->length(); j++){
//       printf("[%d][%lf]", j, vpVX->value()[j]);
//   }
//   Kst::VectorPtr vpVY = psdDOM->vY();
}
 void CQTOpenGLLuaMainWindow::Execute() {
    /* Save script */
    Save();
    /* Change cursor */
    QApplication::setOverrideCursor(Qt::WaitCursor);
    /* Stop simulation */
    m_pcMainWindow->SuspendExperiment();
    /* Clear the message table */
    m_pcLuaMessageTable->clearContents();
    m_pcLuaMessageTable->setRowCount(1);
    /* Create temporary file to contain the bytecode */
    QTemporaryFile cByteCode;
    if(! cByteCode.open()) {
       SetMessage(0, "ALL", "Can't create bytecode file.");
       QApplication::restoreOverrideCursor();
       return;
    }
    /*
     * Compile script
     */
    /* Check for luac 5.1 */
    QString cLuaC = DetectLuaC();
    if(cLuaC == "") {
       /* luac 5.1 not found, fall back to sending the script directly to robots */
       for(size_t i = 0; i < m_vecControllers.size(); ++i) {
          m_vecControllers[i]->SetLuaScript(m_strFileName.toStdString());
       }
    }
    else {
       QProcess cLuaCompiler;
       cLuaCompiler.start(cLuaC, QStringList() << "-o" << cByteCode.fileName() << m_strFileName);
       if(! cLuaCompiler.waitForFinished()) {
          SetMessage(0, "ALL", QString(cLuaCompiler.readAllStandardError()));
          QApplication::restoreOverrideCursor();
          return;
       }
       if(cLuaCompiler.exitCode() != 0) {
          SetMessage(0, "ALL", QString(cLuaCompiler.readAllStandardError()));
          QApplication::restoreOverrideCursor();
          return;
       }
       SetMessage(0, "ALL", "Compilation successful.");
       /* Set the script for all the robots */
       for(size_t i = 0; i < m_vecControllers.size(); ++i) {
          m_vecControllers[i]->SetLuaScript(cByteCode.fileName().toStdString());
       }
    }
    /* Update Lua state if visible */
    if(m_pcLuaVariableDock->isVisible()) {
       static_cast<CQTOpenGLLuaStateTreeModel*>(m_pcLuaVariableTree->model())->SetLuaState(
          m_vecControllers[m_unSelectedRobot]->GetLuaState());
    }
    if(m_pcLuaFunctionDock->isVisible()) {
       static_cast<CQTOpenGLLuaStateTreeModel*>(m_pcLuaFunctionTree->model())->SetLuaState(
          m_vecControllers[m_unSelectedRobot]->GetLuaState());
    }
    /* Resume simulation */
    m_pcMainWindow->ResumeExperiment();
    QApplication::restoreOverrideCursor();
    statusBar()->showMessage(tr("Execution started"), 2000);
 }
Beispiel #24
0
QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem,
    const QString& layerName,
    QList<QTemporaryFile*>& filesToRemove,
    QList<QgsMapLayer*>& layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );
  QString providerString;
  QString formatString = remoteVDSElem.attribute( QStringLiteral( "format" ) );
  if ( formatString.compare( QLatin1String( "gml" ), Qt::CaseInsensitive ) == 0 )
  {
    providerString = QStringLiteral( "WFS" );
  }
  else
  {
    providerString = formatString;
  }

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

  QgsVectorLayer* vl = nullptr;

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

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

  //create vector layer

  //SOS has a special datasource key...
  if ( formatString.compare( QLatin1String( "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() ) )
  {
    QgsDebugMsg( "vl is not valid" );
  }

  layersToRemove.push_back( vl );
  filesToRemove.push_back( tmpFile );
  return vl;
}
Beispiel #25
0
QString createObjectsAndTypesPage(PandaDocument* document)
{
    static QTemporaryFile file(QDir::tempPath() + "/pandaRef_XXXXXX.html");
    file.open();
    file.resize(0);

    QTextStream out(&file);
    out << "<!DOCTYPE html>\n"
        "<html lang=\"en\">\n"
        " <head>\n"
        "  <meta charset=\"utf-8\">\n"
        "  <title>List of available objects and types for Panda</title>\n"
        " </head>\n"
        " <body>\n";

    out << "  <h1>Types</h1>\n";

    auto dataEntriesList = DataFactory::entries();
    std::sort(dataEntriesList.begin(), dataEntriesList.end(), dataTypeIdLessThan);

    std::vector<EnrichedDataEntry> dataEntries;
    // Copy entries and get additional info
    for(auto d : dataEntriesList)
    {
        EnrichedDataEntry e = *d;
        auto tmpData = DataFactory::create(d->fullType, "", "", nullptr);
        if(tmpData)
        {
            e.description = tmpData->getDescription();
            e.trait = tmpData->getDataTrait();
        }

        dataEntries.push_back(e);
    }

    for(const auto& d : dataEntries)
    {
        out << "   <h2>" << QString::fromStdString(d.description) << "</h2>\n"
            << "    <p>Type: " << toHtml(d.className) << "</p>\n"
            << "    <p>Id: " << d.fullType << "</p>\n";

        bool hasConversions = false;
        for(const auto& d2 : dataEntries)
        {
            if(d.fullType == d2.fullType)
                continue;

            if(!d.trait || !d2.trait)
                continue;

            if(canConvert(d.trait, d2.trait))
            {
                if(!hasConversions)
                {
                    out << "    <p>Can be converted to: ";
                    hasConversions = true;
                }
                else
                    out << ", ";
                out << QString::fromStdString(d2.description);
            }
        }
        if(!hasConversions)
            out << "    <p>Has no known conversion";
        out << "</p>\n";

        auto widgets = DataWidgetFactory::getInstance()->getWidgetNames(d.fullType);
        if(widgets.empty())
            out << "    <p>No widgets for this type</p>\n";
        else
        {
            out << "    <p>Widgets available: ";
            bool first = true;
            for(const auto& w : widgets)
            {
                if(first)
                    first = false;
                else
                    out << ", ";
                out << w;
            }
            out << "</p>\n";
        }
    }

    out << "  <h1>Objects</h1>\n";

    std::vector<ObjectFactory::ClassEntry> objectsEntries;
    for(const auto& object : ObjectFactory::registryMap())
        objectsEntries.push_back(object.second);
    std::sort(objectsEntries.begin(), objectsEntries.end(), objectsMenuLessThan);

    for(const auto& o : objectsEntries)
    {
        out << "   <h2>" << QString::fromStdString(o.menuDisplay) << "</h2>\n";
        out << "	<p>In module: " << toHtml(o.moduleName) << "</p>\n";
        out << "    <p>Type: " << toHtml(o.className) << "</p>\n";
        out << "    <p>" << QString::fromStdString(o.description) << "</p>\n";

        if(o.creator)
        {
            auto object = o.creator->create(document);

            auto datas = object->getDatas();
            if(!datas.empty())
                out << "    <h3>Datas</h3>\n";
            for(auto d : datas)
            {
                out << "     <p>" << QString::fromStdString(d->getName()) << ": "
                    << QString::fromStdString(d->getDescription()) << ". "
                    << QString::fromStdString(d->getHelp()) << "</p>\n";
            }
        }
    }

    out << " </body>\n"
        "</html>\n";

    return file.fileName();
}