예제 #1
0
void ImageResize::resize(const EmailSettingsContainer& settings)
{
    d->count = 0;
    int i    = 1;

    for (QList<EmailItem>::const_iterator it = settings.itemsList.constBegin();
         it != settings.itemsList.constEnd(); ++it)
    {
        QString tmp;

        ImageResizePriv::Task *t = new ImageResizePriv::Task;
        t->orgUrl                = (*it).orgUrl;
        t->settings              = settings;

        KTempDir tmpDir(KStandardDirs::locateLocal("tmp", t->settings.tempFolderName + t->settings.tempPath), 0700);
        tmpDir.setAutoRemove(false);
        QFileInfo fi(t->orgUrl.fileName());
        t->destName = tmpDir.name() + QString("%1.%2").arg(fi.baseName()).arg(t->settings.format().toLower());

        QMutexLocker lock(&d->mutex);
        d->todo << t;
        d->condVar.wakeAll();
        i++;
    }
}
NS_IMETHODIMP
nsDeviceContextSpecAndroid::GetSurfaceForPrinter(gfxASurface** aSurface)
{
  nsCAutoString tmpDir(getenv("TMPDIR"));
  nsresult rv = 
    NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mTempFile));
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsCAutoString filename("tmp-printing.pdf");  
  mTempFile->AppendNative(filename);
  rv = mTempFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0660);
  NS_ENSURE_SUCCESS(rv, rv);  
  
  nsCOMPtr<nsIFileOutputStream> stream = do_CreateInstance("@mozilla.org/network/file-output-stream;1");
  rv = stream->Init(mTempFile, -1, -1, 0);
  NS_ENSURE_SUCCESS(rv, rv);  

  nsRefPtr<gfxASurface> surface;

  // XXX: what should we do hear for size? screen size?
  gfxSize surfaceSize(480, 800);

  surface = new gfxPDFSurface(stream, surfaceSize);
  
  
  NS_ABORT_IF_FALSE(surface, "valid address expected");
  surface.swap(*aSurface);
  return NS_OK;
}
void Rectangle::checkHit(Rectangle *r){
    wle::AABB fr1 = this->getFrame();
    wle::AABB fr2 = r->getFrame();
   // std::cout << fr1 << "\t\t" << fr2 <<std::endl;
    if(fr1.intersects(fr2)){
        //conservation of momentum
        sf::Vector2i tmpDir(*direction_);
        direction_->x = r->direction_->x;   direction_->y = r->direction_->y;
        r->direction_->x = tmpDir.x;        r->direction_->y = tmpDir.y;
        sf::Vector2f tmpSpeed(*speed_);
        speed_->x = r->speed_->x;   speed_->y = r->speed_->y;
        r->speed_->x = tmpSpeed.x;  r->speed_->y = tmpSpeed.y;

        double diff_x = fr1.getCenter().getX() - fr2.getCenter().getX();
        double diff_y = fr1.getCenter().getY() - fr2.getCenter().getY();

		sf::Vector2f newPos(shape_->getPosition().x + diff_x/2, shape_->getPosition().y + diff_y/2);
		setEffectivePosition(newPos);

		sf::Vector2f newPos2(r->shape_->getPosition().x - diff_x/2, r->shape_->getPosition().y - diff_y/2);
		r->setEffectivePosition(newPos2);
		
		//for fun! Color them towards grey
		sf::Color clr1 = shape_->getFillColor();
		sf::Color clr2 = r->shape_->getFillColor();
		sf::Color newClr((clr1.r + clr2.r)/2, (clr1.g + clr2.g)/2, (clr1.b + clr2.b)/2);
		shape_->setFillColor(newClr);
		r->shape_->setFillColor(newClr);
    }
}
예제 #4
0
dir::dir(std::string dir, std::string workingDir){
   _dir=dir;
   _workingDir=workingDir;
   fs::path tmpDir(dir);
   fs::path tmpWorkingDir(workingDir);
   fs::path full_path= tmpDir / tmpWorkingDir;
   //need to join using boost
   _totalDir=full_path.string();
}
예제 #5
0
static void SetupCrashHandler()
{
    ScopedMem<WCHAR> symDir;
    ScopedMem<WCHAR> tmpDir(path::GetTempPath());
    if (tmpDir)
        symDir.Set(path::Join(tmpDir, L"SumatraPDF-symbols"));
    else
        symDir.Set(AppGenDataFilename(L"SumatraPDF-symbols"));
    ScopedMem<WCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME));
    InstallCrashHandler(crashDumpPath, symDir);
}
예제 #6
0
std::string FileUtils::tempPath()
{
#ifdef PLATFORM_UNIX
	std::string tmpDir(notNullString(getenv("TMPDIR")));
	if (tmpDir.empty())
	{
		tmpDir = "/tmp";
	}
	return tmpDir;
#else
	char buffer[MAX_PATH+1];
	GetTempPath(MAX_PATH+1,buffer);
	return toUnixPathSeparators(buffer);
#endif
}
예제 #7
0
QString QgsMSUtils::createTempFilePath()
{


  //save the content of the file into a temporary location
  //generate a name considering the current time
  //struct timeval currentTime;
  //gettimeofday(&currentTime, NULL);

  time_t seconds;
  time( &seconds );
  srand( seconds );

  int randomNumber = rand();
  QString tempFileName = QString::number( randomNumber );
  QString tempFilePath;
  //on windows, store the temporary file in current_path/tmp directory,
  //on unix, store it in /tmp/qgis_wms_serv
#ifndef WIN32
  QDir tempFileDir( "/tmp/qgis_map_serv" );
  if ( !tempFileDir.exists() ) //make sure the directory exists
  {
    QDir tmpDir( "/tmp" );
    tmpDir.mkdir( "qgis_map_serv" );
  }
  tempFilePath = "/tmp/qgis_map_serv/" + tempFileName;
#else
  QDir tempFileDir( QDir::currentPath() + "/tmp" );
  if ( !tempFileDir.exists() )
  {
    QDir currentDir( QDir::currentPath() );
    currentDir.mkdir( "tmp" );
  }
  tempFilePath = QDir::currentPath() + "/tmp" + "/" + tempFileName;
#endif //WIN32

  QFileInfo testFile( tempFilePath );
  while ( testFile.exists() )
  {
    //change the name
    tempFilePath += "1";
    testFile.setFile( tempFilePath );
  }
  QgsMapServerLogger::instance()->printMessage( tempFilePath );
  return tempFilePath;
}
예제 #8
0
void Population::savePopulation(QString dir)
{
    QDir tmpDir(dir);
    tmpDir.mkpath(dir);
    QFile *fileScore = new QFile(dir + "score.save");
    QFile *fileSettings = new QFile(dir + "sets.save");

    if (! fileSettings -> open(QIODevice::WriteOnly | QIODevice::Text) ||
            ! fileScore -> open(QIODevice::WriteOnly | QIODevice::Text))
    {
        // Error while trying to write file
    }
    else
    {
        // Everything is OK
        QTextStream outSettings(fileSettings);
        QTextStream outScore(fileScore);

        outSettings << populationSize << "\n";
        outSettings << currentTest << "\n";
        outSettings << curGeneration << "\n";
        outSettings << maxMutationsCount << "\n";
        outSettings << bestResult << "\n";

        outSettings << vehiclePointsNum << "\n";
        outSettings << vehicleMaxWheelsNum << "\n";
        outSettings << vehicleVectorLength << "\n";
        outSettings << vehicleWheelsSize << "\n";

        outSettings << populationType << "\n";
        outSettings << populationSide << "\n";

        for(int i = 0; i < populationSize; ++i)
            vehData[i] -> save(dir + "veh" + QString::number(i) + ".save");

        for(int i = 0; i < populationSize; ++i)
        {
            QString tmp = "";
            tmp.setNum(resData[i], 'f', 5);
            outScore << tmp << "\n";
        }
    }

    fileSettings -> close();
    fileScore -> close();
}
예제 #9
0
bool createTemporaryDir(QString &path)
{
  QString baseName = QCoreApplication::applicationName();
  if (baseName.isEmpty())
  {
    baseName = QLatin1String("mitk_temp");
  }

  QString templateName = QDir::tempPath() + QLatin1Char('/') + baseName + QLatin1String("-XXXXXX");
  QTemporaryDir tmpDir(templateName);
  tmpDir.setAutoRemove(false);

  if (tmpDir.isValid())
  {
    path = tmpDir.path();
    return true;
  }
  return false;
}
예제 #10
0
파일: DataManager.cpp 프로젝트: CaF2/hw
QStringList DataManager::entryList(
    const QString & subDirectory,
    QDir::Filters filters,
    const QStringList & nameFilters,
    bool withDLC
) const
{
    QDir tmpDir(QString("physfs://%1").arg(subDirectory));
    QStringList result = tmpDir.entryList(nameFilters, filters);

    // sort case-insensitive
    QMap<QString, QString> sortedFileNames;
    QString absolutePath = datadir->absolutePath().toLocal8Bit().data();
    foreach ( QString fn, result)
    {
        // Filter out DLC entries if desired
        QString realDir = PHYSFS_getRealDir(QString(subDirectory + "/" + fn).toLocal8Bit().data());
        if(withDLC || realDir == absolutePath)
            sortedFileNames.insert(fn.toLower(), fn);
    }
예제 #11
0
    static std::string CreateTemporaryPath(const char* extension)
    {
#if BOOST_HAS_FILESYSTEM_V3 == 1
      boost::filesystem::path tmpDir = boost::filesystem::temp_directory_path();
#elif defined(__linux__)
      boost::filesystem::path tmpDir("/tmp");
#else
#error Support your platform here
#endif

      // We use UUID to create unique path to temporary files
      std::string filename = "Orthanc-" + Orthanc::Toolbox::GenerateUuid();

      if (extension != NULL)
      {
        filename.append(extension);
      }

      tmpDir /= filename;
      return tmpDir.string();
    }
예제 #12
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int retCode = 1;    // by default it's error

#ifdef DEBUG
    // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for
    // regular termination so that leaks aren't checked on exceptions,
    // aborts, etc. where some clean-up might not take place)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
    //_CrtSetBreakAlloc(421);
    TryLoadMemTrace();
#endif

    //BenchMD5();

    DisableDataExecution();
    // ensure that C functions behave consistently under all OS locales
    // (use Win32 functions where localized input or output is desired)
    setlocale(LC_ALL, "C");

    RunUnitTests();

    // don't show system-provided dialog boxes when accessing files on drives
    // that are not mounted (e.g. a: drive without floppy or cd rom drive
    // without a cd).
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
    srand((unsigned int)time(NULL));

    // don't bother sending crash reports when running under Wine
    // as they're not helpful
    if (!RunningUnderWine()) {
        ScopedMem<TCHAR> symDir;
        ScopedMem<TCHAR> tmpDir(path::GetTempPath());
        if (tmpDir)
            symDir.Set(path::Join(tmpDir, _T("SumatraPDF-symbols")));
        else
            symDir.Set(AppGenDataFilename(_T("SumatraPDF-symbols")));
        ScopedMem<TCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME));
        InstallCrashHandler(crashDumpPath, symDir);
    }

    ScopedOle ole;
    InitAllCommonControls();
    ScopedGdiPlus gdiPlus(true);
    mui::Initialize();
    uimsg::Initialize();

    ScopedMem<TCHAR> prefsFilename(GetPrefsFileName());
    if (!file::Exists(prefsFilename)) {
        // guess the ui language on first start
        CurrLangNameSet(Trans::GuessLanguage());
        gFavorites = new Favorites();
    } else {
        assert(gFavorites == NULL);
        Prefs::Load(prefsFilename, gGlobalPrefs, gFileHistory, &gFavorites);
        CurrLangNameSet(gGlobalPrefs.currentLanguage);
    }
    prefsFilename.Set(NULL);

    CommandLineInfo i;
    GetCommandLineInfo(i);

    if (i.showConsole)
        RedirectIOToConsole();
    if (i.makeDefault)
        AssociateExeWithPdfExtension();
    if (i.pathsToBenchmark.Count() > 0) {
        BenchFileOrDir(i.pathsToBenchmark);
        if (i.showConsole)
            system("pause");
    }
    if (i.exitImmediately)
        goto Exit;
    gCrashOnOpen = i.crashOnOpen;

    gGlobalPrefs.bgColor = i.bgColor;
    gGlobalPrefs.fwdSearch.offset = i.fwdSearch.offset;
    gGlobalPrefs.fwdSearch.width = i.fwdSearch.width;
    gGlobalPrefs.fwdSearch.color = i.fwdSearch.color;
    gGlobalPrefs.fwdSearch.permanent = i.fwdSearch.permanent;
    gGlobalPrefs.escToExit = i.escToExit;
    gGlobalPrefs.cbxR2L = i.cbxR2L;
    gPolicyRestrictions = GetPolicies(i.restrictedUse);
    gRenderCache.colorRange[0] = i.colorRange[0];
    gRenderCache.colorRange[1] = i.colorRange[1];
    DebugGdiPlusDevice(gUseGdiRenderer);
    DebugAlternateChmEngine(!gUseEbookUI);

    if (i.inverseSearchCmdLine) {
        str::ReplacePtr(&gGlobalPrefs.inverseSearchCmdLine, i.inverseSearchCmdLine);
        gGlobalPrefs.enableTeXEnhancements = true;
    }
    CurrLangNameSet(i.lang);

    if (!RegisterWinClass(hInstance))
        goto Exit;
    if (!InstanceInit(hInstance, nCmdShow))
        goto Exit;

    if (i.hwndPluginParent) {
        if (!SetupPluginMode(i))
            goto Exit;
    }

    if (i.printerName) {
        // note: this prints all PDF files. Another option would be to
        // print only the first one
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings);
            if (!ok)
                retCode++;
        }
        --retCode; // was 1 if no print failures, turn 1 into 0
        goto Exit;
    }

    if (i.fileNames.Count() == 0 && gGlobalPrefs.rememberOpenedFiles && gGlobalPrefs.showStartPage) {
        // make the shell prepare the image list, so that it's ready when the first window's loaded
        SHFILEINFO sfi;
        SHGetFileInfo(_T(".pdf"), 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    }

    WindowInfo *win = NULL;
    bool isFirstWin = true;

    for (size_t n = 0; n < i.fileNames.Count(); n++) {
        if (i.reuseInstance && !i.printDialog) {
            OpenUsingDde(i.fileNames.At(n), i, isFirstWin);
        } else {
            win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin);
            if (!win) {
                retCode++;
                continue;
            }
            if (i.printDialog)
                OnMenuPrint(win, i.exitOnPrint);
        }
        isFirstWin = false;
    }
    if (i.fileNames.Count() > 0 && isFirstWin) {
        // failed to create any window, even though there
        // were files to load (or show a failure message for)
        goto Exit;
    }

    if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitOnPrint)
        goto Exit;

    if (isFirstWin) {
        win = CreateAndShowWindowInfo();
        if (!win)
            goto Exit;
    }

    UpdateUITextForLanguage(); // needed for RTL languages
    if (isFirstWin)
        UpdateToolbarAndScrollbarState(*win);

    // Make sure that we're still registered as default,
    // if the user has explicitly told us to be
    if (gGlobalPrefs.pdfAssociateShouldAssociate && win)
        RegisterForPdfExtentions(win->hwndFrame);

    if (gGlobalPrefs.enableAutoUpdate && gWindows.Count() > 0)
        AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true);

#ifndef THREAD_BASED_FILEWATCH
    const UINT_PTR timerID = SetTimer(NULL, -1, FILEWATCH_DELAY_IN_MS, NULL);
#endif

    if (i.stressTestPath) {
        gIsStressTesting = true;
        StartStressTest(win, i.stressTestPath, i.stressTestFilter,
                        i.stressTestRanges, i.stressTestCycles, &gRenderCache);
    }

    retCode = RunMessageLoop();

#ifndef THREAD_BASED_FILEWATCH
    KillTimer(NULL, timerID);
#endif

    CleanUpThumbnailCache(gFileHistory);

Exit:
    while (gWindows.Count() > 0) {
        DeleteWindowInfo(gWindows.At(0));
    }
    while (gEbookWindows.Count() > 0) {
        DeleteEbookWindow(gEbookWindows.At(0), true);
    }

#ifndef DEBUG
    // leave all the remaining clean-up to the OS
    // (as recommended for a quick exit)
    ExitProcess(retCode);
#endif

    DeleteObject(gBrushNoDocBg);
    DeleteObject(gBrushLogoBg);
    DeleteObject(gBrushAboutBg);
    DeleteObject(gDefaultGuiFont);
    DeleteBitmap(gBitmapReloadingCue);

    delete gFavorites;

    mui::Destroy();

    DrainUiMsgQueue();
    uimsg::Destroy();

    // it's still possible to crash after this (destructors of static classes,
    // atexit() code etc.) point, but it's very unlikely
    if (!RunningUnderWine())
        UninstallCrashHandler();

#ifdef DEBUG
    // output leaks after all destructors of static objects have run
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

    return retCode;
}
예제 #13
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int retCode = 1;    // by default it's error

#ifdef DEBUG
    // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for
    // regular termination so that leaks aren't checked on exceptions,
    // aborts, etc. where some clean-up might not take place)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
    //_CrtSetBreakAlloc(421);
    TryLoadMemTrace();
#endif

    DisableDataExecution();
    // ensure that C functions behave consistently under all OS locales
    // (use Win32 functions where localized input or output is desired)
    setlocale(LC_ALL, "C");
    // don't show system-provided dialog boxes when accessing files on drives
    // that are not mounted (e.g. a: drive without floppy or cd rom drive
    // without a cd).
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(DEBUG) || defined(SVN_PRE_RELEASE_VER)
    if (str::StartsWith(lpCmdLine, "/tester")) {
        extern int TesterMain(); // in Tester.cpp
        return TesterMain();
    }

    if (str::StartsWith(lpCmdLine, "/regress")) {
        extern int RegressMain(); // in Regress.cpp
        return RegressMain();
    }
#endif
#ifdef SUPPORTS_AUTO_UPDATE
    if (str::StartsWith(lpCmdLine, "-autoupdate")) {
        bool quit = AutoUpdateMain();
        if (quit)
            return 0;
    }
#endif

    RunUnitTests();

    srand((unsigned int)time(NULL));

    {
        ScopedMem<WCHAR> symDir;
        ScopedMem<WCHAR> tmpDir(path::GetTempPath());
        if (tmpDir)
            symDir.Set(path::Join(tmpDir, L"SumatraPDF-symbols"));
        else
            symDir.Set(AppGenDataFilename(L"SumatraPDF-symbols"));
        ScopedMem<WCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME));
        InstallCrashHandler(crashDumpPath, symDir);
    }

    ScopedOle ole;
    InitAllCommonControls();
    ScopedGdiPlus gdiPlus(true);
    mui::Initialize();
    uitask::Initialize();

    LoadPrefs();

    CommandLineInfo i;
    GetCommandLineInfo(i);

    SetCurrentLang(i.lang ? i.lang : gGlobalPrefs->currLangCode);

    if (i.showConsole)
        RedirectIOToConsole();
    if (i.makeDefault)
        AssociateExeWithPdfExtension();
    if (i.pathsToBenchmark.Count() > 0) {
        BenchFileOrDir(i.pathsToBenchmark);
        if (i.showConsole)
            system("pause");
    }
    if (i.exitImmediately)
        goto Exit;
    gCrashOnOpen = i.crashOnOpen;

    gUserPrefs->mainWindowBackground = i.bgColor;
    if (gUserPrefs->forwardSearch.highlightColor != i.forwardSearch.highlightColor ||
        gUserPrefs->forwardSearch.highlightOffset != i.forwardSearch.highlightOffset ||
        gUserPrefs->forwardSearch.highlightPermanent != i.forwardSearch.highlightPermanent ||
        gUserPrefs->forwardSearch.highlightWidth != i.forwardSearch.highlightWidth) {
        gGlobalPrefs->enableTeXEnhancements = true;
    }
    gUserPrefs->forwardSearch = i.forwardSearch;
    gUserPrefs->escToExit = i.escToExit;
    gGlobalPrefs->cbxR2L = i.cbxR2L;
    gPolicyRestrictions = GetPolicies(i.restrictedUse);
    gRenderCache.colorRange[0] = i.colorRange[0];
    gRenderCache.colorRange[1] = i.colorRange[1];
    DebugGdiPlusDevice(gUseGdiRenderer);
    DebugAlternateChmEngine(gUserPrefs->ebookUI.traditionalEbookUI);

    if (i.inverseSearchCmdLine) {
        str::ReplacePtr(&gGlobalPrefs->inverseSearchCmdLine, i.inverseSearchCmdLine);
        gGlobalPrefs->enableTeXEnhancements = true;
    }

    if (!RegisterWinClass(hInstance))
        goto Exit;
    if (!InstanceInit(hInstance, nCmdShow))
        goto Exit;

    if (i.hwndPluginParent) {
        if (!SetupPluginMode(i))
            goto Exit;
    }

    if (i.printerName) {
        // note: this prints all PDF files. Another option would be to
        // print only the first one
        for (size_t n = 0; n < i.fileNames.Count(); n++) {
            bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings);
            if (!ok)
                retCode++;
        }
        --retCode; // was 1 if no print failures, turn 1 into 0
        goto Exit;
    }

    if (i.fileNames.Count() == 0 && gGlobalPrefs->rememberOpenedFiles && gGlobalPrefs->showStartPage) {
        // make the shell prepare the image list, so that it's ready when the first window's loaded
        SHFILEINFO sfi;
        SHGetFileInfo(L".pdf", 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    }

    if (!i.reuseInstance && gUserPrefs->reuseInstance && FindWindow(FRAME_CLASS_NAME, 0))
        i.reuseInstance = true;

    WindowInfo *win = NULL;
    bool isFirstWin = true;

    for (size_t n = 0; n < i.fileNames.Count(); n++) {
        if (i.reuseInstance && !i.printDialog) {
            OpenUsingDde(i.fileNames.At(n), i, isFirstWin);
        } else {
            win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin);
            if (!win) {
                retCode++;
                continue;
            }
            if (i.printDialog)
                OnMenuPrint(win, i.exitWhenDone);
        }
        isFirstWin = false;
    }
    if (i.fileNames.Count() > 0 && isFirstWin) {
        // failed to create any window, even though there
        // were files to load (or show a failure message for)
        goto Exit;
    }

    if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitWhenDone)
        goto Exit;

    if (isFirstWin) {
        win = CreateAndShowWindowInfo();
        if (!win)
            goto Exit;
    }

    UpdateUITextForLanguage(); // needed for RTL languages
    if (isFirstWin)
        UpdateToolbarAndScrollbarState(*win);

    // Make sure that we're still registered as default,
    // if the user has explicitly told us to be
    if (gGlobalPrefs->pdfAssociateShouldAssociate && win)
        RegisterForPdfExtentions(win->hwndFrame);

    if (gGlobalPrefs->enableAutoUpdate && gWindows.Count() > 0)
        AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true);

    if (i.stressTestPath)
        StartStressTest(&i, win, &gRenderCache);

    if (gFileHistory.Get(0)) {
        gFileExistenceChecker = new FileExistenceChecker();
        gFileExistenceChecker->Start();
    }

    retCode = RunMessageLoop();

    CleanUpThumbnailCache(gFileHistory);

Exit:
    while (gWindows.Count() > 0) {
        DeleteWindowInfo(gWindows.At(0));
    }
    while (gEbookWindows.Count() > 0) {
        DeleteEbookWindow(gEbookWindows.At(0), true);
    }

#ifndef DEBUG

    // leave all the remaining clean-up to the OS
    // (as recommended for a quick exit)
    ExitProcess(retCode);

#else

    CrashIf(gFileExistenceChecker);

    DeleteObject(gBrushNoDocBg);
    DeleteObject(gBrushLogoBg);
    DeleteObject(gBrushAboutBg);
    DeleteObject(gDefaultGuiFont);
    DeleteBitmap(gBitmapReloadingCue);

    gFileHistory.UpdateStatesSource(NULL);
    DeleteGlobalPrefs(gGlobalPrefs);

    mui::Destroy();
    uitask::Destroy();
    trans::Destroy();

    // it's still possible to crash after this (destructors of static classes,
    // atexit() code etc.) point, but it's very unlikely
    UninstallCrashHandler();

    // output leaks after all destructors of static objects have run
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

    return retCode;
#endif
}
예제 #14
0
파일: main.cpp 프로젝트: Aurenos/Cockatrice
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    if (app.arguments().contains("--debug-output"))
    {
#if QT_VERSION < 0x050000
        qInstallMsgHandler(myMessageOutput);
#else
        qInstallMessageHandler(myMessageOutput);
#endif
    }
#ifdef Q_OS_WIN
    app.addLibraryPath(app.applicationDirPath() + "/plugins");
#endif

#if QT_VERSION < 0x050000
    // gone in Qt5, all source files _MUST_ be utf8-encoded
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif

    QCoreApplication::setOrganizationName("Cockatrice");
    QCoreApplication::setOrganizationDomain("cockatrice.de");
    QCoreApplication::setApplicationName("Cockatrice");

    if (translationPath.isEmpty()) {
#ifdef Q_OS_MAC
        translationPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined(Q_OS_WIN)
        translationPath = app.applicationDirPath() + "/translations";
#endif
    }

    rng = new RNG_SFMT;
    settingsCache = new SettingsCache;
    db = new CardDatabase;

    qtTranslator = new QTranslator;
    translator = new QTranslator;
    installNewTranslator();

    qsrand(QDateTime::currentDateTime().toTime_t());
    
#if QT_VERSION < 0x050000
    const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
    const QString dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
    if (!db->getLoadSuccess())
        if (db->loadCardDatabase(dataDir + "/cards.xml"))
            settingsCache->setCardDatabasePath(dataDir + "/cards.xml");
    if (settingsCache->getTokenDatabasePath().isEmpty())
        settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml");
    if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
        QDir().mkpath(dataDir + "/decks");
        settingsCache->setDeckPath(dataDir + "/decks");
    }
    if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) {
        QDir().mkpath(dataDir + "/replays");
        settingsCache->setReplaysPath(dataDir + "/replays");
    }
    if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
        QDir().mkpath(dataDir + "/pics");
        settingsCache->setPicsPath(dataDir + "/pics");
    }
    if (!QDir().mkpath(settingsCache->getPicsPath() + "/CUSTOM"))
        qDebug() << "Could not create " + settingsCache->getPicsPath().toUtf8() + "/CUSTOM. Will fall back on default card images.";
        
#ifdef Q_OS_MAC
    if(settingsCache->getHandBgPath().isEmpty() &&
        settingsCache->getStackBgPath().isEmpty() &&
        settingsCache->getTableBgPath().isEmpty() &&
        settingsCache->getPlayerBgPath().isEmpty())
    {
        QString srcDir = QLibraryInfo::location(QLibraryInfo::DataPath);
        QString destDir = dataDir + "/zonebg";
        QDir tmpDir(destDir);
        if(!tmpDir.exists())
        {
            // try to install the default images for the current user and set the settigs value
            settingsCache->copyPath(srcDir + "/zonebg", destDir);

            settingsCache->setHandBgPath(destDir + "/fabric_green.png");
            settingsCache->setStackBgPath(destDir + "/fabric_red.png");
            settingsCache->setTableBgPath(destDir + "/fabric_blue.png");
            settingsCache->setPlayerBgPath(destDir + "/fabric_gray.png");
        }
    }

    if(settingsCache->getSoundPath().isEmpty())
    {
        QString srcDir = QLibraryInfo::location(QLibraryInfo::DataPath);
        QString destDir = dataDir + "/sounds";
        QDir tmpDir(destDir);
        if(!tmpDir.exists())
        {
            // try to install the default sounds for the current user and set the settigs value
            settingsCache->copyPath(srcDir + "/sounds", destDir);

            settingsCache->setSoundPath(destDir);
        }
    }
#endif

    if (!settingsValid() || db->getLoadStatus() != Ok) {
        qDebug("main(): invalid settings or load status");
        DlgSettings dlgSettings;
        dlgSettings.show();
        app.exec();
    }

    if (settingsValid()) {
        qDebug("main(): starting main program");
        soundEngine = new SoundEngine;
        qDebug("main(): SoundEngine constructor finished");

        MainWindow ui;
        qDebug("main(): MainWindow constructor finished");

        QIcon icon(":/resources/appicon.svg");
        ui.setWindowIcon(icon);

        ui.show();
        qDebug("main(): ui.show() finished");

        app.exec();
    }

    qDebug("Event loop finished, terminating...");
    delete db;
    delete settingsCache;
    delete rng;
    PingPixmapGenerator::clear();
    CountryPixmapGenerator::clear();
    UserLevelPixmapGenerator::clear();

    return 0;
}
예제 #15
0
// InitializeArgs
//
bool ppParseArgs::InitializeArgs(int nbrArgs, char* args[])
{
    bool retVal = true;
    int opt;
    int tmpNbr;
    gtString tmp;
    unsigned long long tmpULL;

    if (nbrArgs == 1)
    {
        // no option is specified by the user.. just print the help
        m_isPrintHelp = true;
        return true;
    }

#if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS

    // To support windows style command line options
    for (int i = 1; i < nbrArgs; i++)
    {
        if (args[i][0] == '/')
        {
            args[i][0] = '-';
        }
    }

#endif // WINDOWS

    bool errorExit = false;
    int pos;
    int startPosition = 0;
    wchar_t optArgW[OS_MAX_PATH];

    while ((opt = ppGetOpt(nbrArgs, args, "C:D:F:P:T:M:Xbc:d:e:ghlo:vw:z:")) != -1)
    {
        memset(optArgW, 0, sizeof(optArgW));

        if (NULL != optArg)
        {
            mbstowcs(optArgW, optArg, OS_MAX_PATH - 1);
        }

        switch (opt)
        {
            case 'C':
                // Core Affinity Mask
                tmp = gtString(optArgW);

                if (tmp.toUnsignedLongLongNumber(tmpULL))
                {
                    m_coreAffinityMask = static_cast<AMDTUInt64>(tmpULL);

                    // check if -c is non negtive
                    if (static_cast<signed long long>(m_coreAffinityMask) <= 0)
                    {
                        fprintf(stderr, "Negative or zero core affinity mask value" HEX_FORMAT "is specified with option(-c).\n",
                                m_coreAffinityMask);
                        retVal = false;
                    }
                }
                else
                {
                    fprintf(stderr, "Invalid core affinity mask value(%s) is specified with option(-c).\n",
                            tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            // Comma separated device id list
            case 'D':
                tmp = gtString(optArgW);

                do
                {
                    pos = tmp.find(L",", startPosition);
                    gtString tmpStr;
                    int endPosition = (-1 != pos) ? (pos - 1) : tmp.length();
                    tmp.getSubString(startPosition, endPosition, tmpStr);

                    if (tmpStr.isIntegerNumber())
                    {
                        tmpStr.toIntNumber(tmpNbr);

                        if ((static_cast<AMDTUInt32>(tmpNbr) != AMDT_PWR_ALL_DEVICES) && tmpNbr < 0)
                        {
                            fprintf(stderr, "Invalid Device Id(%d) is specified with option(-D).\n",
                                    tmpNbr);
                            retVal = false;
                        }
                        else
                        {
                            m_deviceIDList.push_back(tmpNbr);
                        }
                    }
                    //else if (tmpStr.isAlnum(L"- _"))
                    //{
                    //    m_deviceNameList.push_back(tmpStr);
                    //}
                    else
                    {
                        fprintf(stderr, "Invalid argument(%s) is passed with option(-D).\n", tmpStr.asASCIICharArray());
                        retVal = false;
                        break;
                    }

                    startPosition = pos + 1;
                }
                while (-1 != pos);

                if (!m_deviceIDList.empty())
                {
                    m_hasProfileCounters = true;
                }
                else
                {
                    //fprintf(stderr, "Invalid devices(%s) are passed with option(-D).\n", tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            case 'F':
                // REPORT Option - Output file format CSV / TEXT
                m_reportFileFormat = gtString(optArgW);

                if (!m_reportFileFormat.compareNoCase(PP_REPORT_EXTENSION_CSV))
                {
                    m_reportType = PP_REPORT_TYPE_CSV;
                }
                else if (!m_reportFileFormat.compareNoCase(PP_REPORT_EXTENSION_TEXT))
                {
                    m_reportType = PP_REPORT_TYPE_TEXT;
                }
                else
                {
                    fprintf(stderr, "Unsupported output file format(%s) specified with option(-F).\n", m_reportFileFormat.asASCIICharArray());
                    retVal = false;
                }

                break;

            case 'P':
                // Pre defined comma seperated profile option string.
                // No support for number with this option
                tmp = gtString(optArgW);

                do
                {
                    pos = tmp.find(L",", startPosition);
                    gtString tmpStr;
                    int endPosition = (-1 != pos) ? (pos - 1) : tmp.length();
                    tmp.getSubString(startPosition, endPosition, tmpStr);

                    if (tmpStr.toUnsignedLongLongNumber(tmpULL))
                    {
                        fprintf(stderr, "Invalid argument(%llu) is passed with option(-P).\n", tmpULL);
                        retVal = false;
                        //break;
                    }
                    else if (tmpStr.isAlnum(L"- _"))
                    {
                        m_counterGroupNameList.push_back(tmpStr);
                    }
                    else
                    {
                        fprintf(stderr, "Invalid argument(%s) is passed with option(-P).\n",
                                tmpStr.asASCIICharArray());
                        retVal = false;
                    }

                    startPosition = pos + 1;
                }
                while (-1 != pos);

                if (!m_counterGroupNameList.empty())
                {
                    m_hasProfileCounters = true;
                }
                else
                {
                    fprintf(stderr, "Invalid argument(%s) is passed with option(-P).\n", tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            case 'T':
                // Sampling Interval
                tmp = gtString(optArgW);

                if (tmp.isIntegerNumber())
                {
                    tmp.toIntNumber(m_samplingInterval);

                    // check if -T is non negative
                    if (m_samplingInterval <= 0)
                    {
                        fprintf(stderr, "Negative or zero sampling interval value(%d) is specified with option(-T).\n",
                                m_samplingInterval);
                        retVal = false;
                    }
                }
                else
                {
                    fprintf(stderr, "Invalid sampling interval is specified with option(-T).\n");
                    retVal = false;
                }

                break;

            case 'M':
                tmp = gtString(optArgW);

                if (tmp.toUnsignedLongLongNumber(tmpULL))
                {
                    fprintf(stderr, "Invalid argument(%llu) is passed with option(-M).\n", tmpULL);
                    retVal = false;
                    //break;
                }
                else if ((tmp.isAlnum(L"- _")) && tmp.isEqual("counters"))
                {
                    // Process profile type
                    m_profileType = 0;
                }
                else if ((tmp.isAlnum(L"- _")) && tmp.isEqual("process"))
                {
                    // Process profile type
                    m_profileType = 1;
                    m_hasProfileCounters = true;
                }
                else
                {
                    fprintf(stderr, "Invalid argument(%s) is passed with option(-M).\n",
                            tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            case 'X':
                m_simulateGui = true;
                break;

            case 'b':
                // Terminate/Break the launched application after the profile run is complete
                m_terminateLaunchApp = true;
                break;

            case 'c':
                // Core Mask
                tmp = gtString(optArgW);

                if (tmp.toUnsignedLongLongNumber(tmpULL))
                {
                    m_coreMask = static_cast<AMDTUInt64>(tmpULL);

                    // check if -c is non negtive
                    if (static_cast<signed long long>(m_coreMask) <= 0)
                    {
                        fprintf(stderr, "Negative or zero core mask value" HEX_FORMAT " is specified with option(-c).\n",
                                m_coreMask);
                        retVal = false;
                    }
                }
                else
                {
                    fprintf(stderr, "Invalid core mask value(%s) is specified with option(-c).\n",
                            tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            case 'd':
                // Profile Duration
                tmp = gtString(optArgW);

                if (tmp.isIntegerNumber())
                {
                    tmp.toIntNumber(m_profileDuration);

                    if (m_profileDuration <= 0)
                    {
                        fprintf(stderr, "Negative or zero profile duration value(%d) is specified with option(-d).\n",
                                m_profileDuration);
                        retVal = false;
                    }
                }
                else
                {
                    fprintf(stderr, "Invalid profile duration value(%s) is specified with option(-d).\n",
                            tmp.asASCIICharArray());
                    retVal = false;
                }

                break;

            // Comma separated Counter Names. Multiple -e's are supported
            case 'e':
                tmp = gtString(optArgW);

                do
                {
                    pos = tmp.find(L",", startPosition);
                    gtString tmpStr;
                    int endPosition = (-1 != pos) ? (pos - 1) : tmp.length();
                    tmp.getSubString(startPosition, endPosition, tmpStr);

                    if (tmpStr.isIntegerNumber())
                    {
                        tmpStr.toIntNumber(tmpNbr);

                        if (tmpNbr < 0)
                        {
                            fprintf(stderr, "Invalid Counter Id(%d) is specified with option(-e).\n",
                                    tmpNbr);
                            retVal = false;
                        }

                        m_counterIDList.push_back(tmpNbr);
                    }
                    else if (tmpStr.isAlnum(L"- _"))
                    {
                        m_counterNameList.push_back(tmpStr);
                    }

                    else
                    {
                        fprintf(stderr, "Invalid argument(%s) is passed with option(-e).\n", tmpStr.asASCIICharArray());
                        retVal = false;
                        break;
                    }

                    startPosition = pos + 1;
                }
                while (-1 != pos);

                if ((!m_counterIDList.empty()) || (!m_counterNameList.empty()))
                {
                    m_hasProfileCounters = true;
                }
                else
                {
                    fprintf(stderr, "Invalid counters(%s) are passed with option(-e).\n", tmp.asASCIICharArray());
                }

                break;

            case 'g':
                m_isGroupByDevice = true;
                fprintf(stderr, "Unsupported option -P.\n");
                retVal = false;
                break;

            case 'h':
                m_isPrintHelp = true;
                break;

            case 'l':
                m_isListCounters = true;
                break;

            case 'o':
                // Output file
                m_isReportPathSet = true;
                m_reportFile = gtString(optArgW);
                break;

            case 'z':
            {
                // DB file
                m_exportToDb  = true;
                m_dbFileOutDir = gtString(optArgW);
                osFilePath tmpFilePath(m_dbFileOutDir);
                osDirectory tmpDir(tmpFilePath);

                if (!tmpDir.exists())
                {
                    fprintf(stderr, "Directory not found: (%s).\n", m_dbFileOutDir.asASCIICharArray());
                    retVal = false;
                }
            }
            break;

            case 'v':
                m_isPrintVersion = true;
                break;

            case 'w':
                m_workingDir = gtString(optArgW);
                break;

            case PP_BAD_CHAR:
                // exit
                errorExit = true;
                break;

            default:
                fprintf(stderr, "Invalid Option(%c).\n", (char)opt);
                errorExit = true;
        }
    }

    if (errorExit)
    {
        exit(-1);
    }

    if (optIndex < nbrArgs)
    {
        int i = 0;

        while ((i + optIndex) < nbrArgs)
        {
            if (m_launchApp.isEmpty())
            {
                memset(optArgW, 0, sizeof(optArgW));
                mbstowcs(optArgW, args[i + optIndex], OS_MAX_PATH - 1);
                m_launchApp = optArgW;
            }
            else
            {
                memset(optArgW, 0, sizeof(optArgW));
                mbstowcs(optArgW, args[i + optIndex], OS_MAX_PATH - 1);

                m_launchAppArgs.append(optArgW);
                m_launchAppArgs.append(L" ");
            }

            i++;
        }
    }

    return retVal;
} // InitializeArgs
예제 #16
0
vec3 & TransformDirection(vec3 & direction, const mat4 & matrix)
{
	vec4 tmpDir(direction, 0.0f);
	direction = vec3(matrix * tmpDir);
	return direction;
}
예제 #17
0
bool ImageResize::imageResize(const EmailSettingsContainer& settings,
                              const KUrl& orgUrl, const QString& destName, QString& err)
{
    EmailSettingsContainer emailSettings = settings;
    QFileInfo fi(orgUrl.path());

    if (!fi.exists() || !fi.isReadable())
    {
        err = i18n("Error opening input file");
        return false;
    }

    QFileInfo tmp(destName);
    QFileInfo tmpDir(tmp.dir().absolutePath());

    kDebug() << "tmpDir: " << tmp.dir().absolutePath();

    if (!tmpDir.exists() || !tmpDir.isWritable())
    {
        err = i18n("Error opening temporary folder");
        return false;
    }

    QImage img;

    // Check if RAW file.
    QString rawFilesExt(KDcrawIface::KDcraw::rawFiles());
    if (rawFilesExt.toUpper().contains( fi.suffix().toUpper() ))
        KDcrawIface::KDcraw::loadDcrawPreview(img, orgUrl.path());
    else
        img.load(orgUrl.path());

    int sizeFactor = emailSettings.size();

    if ( !img.isNull() )
    {
        int w = img.width();
        int h = img.height();

        if( w > sizeFactor || h > sizeFactor )
        {
            if( w > h )
            {
                h = (int)( (double)( h * sizeFactor ) / w );

                if ( h == 0 ) h = 1;

                w = sizeFactor;
                Q_ASSERT( h <= sizeFactor );
            }
            else
            {
                w = (int)( (double)( w * sizeFactor ) / h );

                if ( w == 0 ) w = 1;

                h = sizeFactor;
                Q_ASSERT( w <= sizeFactor );
            }

            const QImage scaledImg(img.scaled(w, h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));

            if ( scaledImg.width() != w || scaledImg.height() != h )
            {
                err = i18n("Cannot resize image. Aborting.");
                return false;
            }

            img = scaledImg;
        }

        QString destPath = destName;

        KExiv2Iface::KExiv2 meta;

        meta.load(orgUrl.path());
        meta.setImageProgramId(QString("Kipi-plugins"), QString(kipiplugins_version));
        meta.setImageDimensions(img.size());

        if (emailSettings.format() == QString("JPEG"))
        {
            if ( !img.save(destPath, emailSettings.format().toLatin1(), emailSettings.imageCompression) )
            {
                err = i18n("Cannot save resized image (JPEG). Aborting.");
                return false;
            }
            else
            {
                meta.save(destPath);
            }
        }
        else if (emailSettings.format() == QString("PNG"))
        {
            QByteArray data((const char*)img.bits(), img.numBytes());
            KIPIPlugins::KPWriteImage wImageIface;
            wImageIface.setImageData(data, img.width(), img.height(), false, true, QByteArray(), meta);
            if ( !wImageIface.write2PNG(destPath) )
            {
                err = i18n("Cannot save resized image (PNG). Aborting.");
                return false;
            }
        }

        return true;
    }

    return false;
}
예제 #18
0
void ThumbGenerator::loadFile(QImage& image, const QFileInfo& fi)
{
    if (GalleryUtil::IsMovie(fi.filePath()))
    {
        bool thumbnailCreated = false;
        QDir tmpDir("/tmp/mythgallery");
        if (!tmpDir.exists())
        {
            if (!tmpDir.mkdir(tmpDir.absolutePath()))
            {
                VERBOSE(VB_IMPORTANT, "Unable to create temp dir for movie "
                        "thumbnail creation: " + tmpDir.absolutePath());
            }
        }

        if (tmpDir.exists())
        {
            QString cmd = "mplayer -nosound -frames 1 -vo png:z=6 \"" +
                          fi.absoluteFilePath() + "\"";
            MythSystem ms(cmd, kMSRunShell);
            ms.SetDirectory(tmpDir.absolutePath());
            ms.Run();
            if (ms.Wait() == GENERIC_EXIT_OK)
            {
                QFileInfo thumb(tmpDir.filePath("00000001.png"));
                if (thumb.exists())
                {
                    QImage img(thumb.absoluteFilePath());
                    image = img;
                    thumbnailCreated = true;
                }
            }
        }

        if (!thumbnailCreated)
        {
            QImage *img = GetMythUI()->LoadScaleImage("gallery-moviethumb.png");
            if (img)
            {
                image = *img;
            }
        }
    }
    else
    {
#ifdef EXIF_SUPPORT
        // Try to get thumbnail from exif data
        ExifData *ed = exif_data_new_from_file(fi.absoluteFilePath()
                                               .toLocal8Bit().constData());
        if (ed && ed->data)
        {
            image.loadFromData(ed->data, ed->size);
        }

        if (ed)
            exif_data_free(ed);

        if (image.width() > m_width && image.height() > m_height)
            return;
#endif

        image.load(fi.absoluteFilePath());
    }
}
예제 #19
0
float dynamixObjective(GAGenome &c) {
  GA1DArrayGenome<double> &genome = (GA1DArrayGenome<double> &)c;
  // get MPI rank and size
  int rank, size;
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);

  // variables and output
  double g1 = genome.gene(0);
  double g2 = genome.gene(1);
  double g1_c = genome.gene(2);
  float output = 1.0;

  pid_t pid;
  int status;

  // array of strings for commands + arguments
  char * args [10];
  for (int ii = 0; ii < 10; ii++) {
    args[ii] = new char [1000];
  }

  std::string arg = "/extra/scratch/foo";

  // names for original directory and job directory
  // TODO pass as cmd line params
  pid = getpid();
  std::string tmpDir ("/extra/scratch/dynamix");
  // job directory name
  char jobFmt [] = "%s%.12e_%.12e_%.12e_%d_%d";
  char jobDir [1000];
  sprintf(jobDir, jobFmt, tmpDir.c_str(), g1, g2, g1_c, rank, size);
  std::cout << jobDir << std::endl;
  std::string dynDir ("/home/andyras/git/dynamix/dm/");
  std::string dynInsDir (dynDir + "ins/");
  std::string dynamix (dynDir + "bin/dynamix");
  std::string changeParam (dynDir + "tools/changeParam.py");
  char sciFmt [] = "%.12e";
  char g1Str [100];
  char g2Str [100];
  char g1_cStr [100];
  sprintf(g1Str, sciFmt, g1);
  sprintf(g2Str, sciFmt, g2);
  sprintf(g1_cStr, sciFmt, g1_c);

  std::string jobInsDir (jobDir + std::string("/ins/"));
  std::string jobOutsDir (jobDir + std::string("/outs/"));

  // ---- set up job directory ---- //

  // -- create job directory -- //
  // making the output directory so that the top directory gets made too

  strncpy(args[0], "mkdir", 6);
  strncpy(args[1], "-p", 3);
  strncpy(args[2], jobOutsDir.c_str(), jobOutsDir.length()+1);
  args[3] = NULL;

  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 4; ii++) {
    fprintf(stdout, " %s", args[ii]);
  }
  fprintf(stdout, "\n");

  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child process
    // make directory
    execv("/bin/mkdir", args);
    // just in case
    _exit(EXIT_FAILURE);
  }
  else { // parent process
    waitpid(pid, &status, 0);
  }

  // -- copy inputs to job dir -- //
  std::string dynInsDirNoSlash = dynInsDir;

  while (dynInsDirNoSlash.at(dynInsDirNoSlash.size()-1) == '/') {
    std::cerr << "About to erase slash from " << dynInsDirNoSlash << std::endl;
    dynInsDirNoSlash.erase(dynInsDirNoSlash.end()-1);
    std::cerr << "Erased slash from " << dynInsDirNoSlash << std::endl;
  }

  // construct arguments
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
    args[ii] = new char [1000];
  }
  strncpy(args[0], "cp", strlen("cp") + 1);
  strncpy(args[1], "-r", strlen("-r") + 1);
  strncpy(args[2], dynInsDirNoSlash.c_str(), dynInsDirNoSlash.length() + 1);
  strncpy(args[3], jobDir, strlen(jobDir) + 1);
  args[4] = NULL;


  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 10; ii++) fprintf(stdout, " %s", args[ii]);
  fprintf(stdout, "\n");

  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child
    execv("/bin/cp", args);
    _exit(EXIT_FAILURE);
  }
  else { // parent
    waitpid(pid, &status, 0);
  }



  std::string jobDirParamFile (jobDir + std::string("/ins/parameters.in"));
  // construct arguments
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
    args[ii] = new char [1000];
  }
  // change parameter
  strncpy(args[0], changeParam.c_str(), changeParam.length() + 1);
  strncpy(args[1], "-f", strlen("-f") + 1);
  strncpy(args[2], jobDirParamFile.c_str(), jobDirParamFile.length() + 1);
  strncpy(args[3], "gamma1", strlen(jobDir) + 1);
  strncpy(args[4], g1Str, strlen(g1Str) + 1);
  args[5] = NULL;

  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 10; ii++) fprintf(stdout, " %s", args[ii]);
  fprintf(stdout, "\n");

  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child
    execv("changeParam.py", args);
    _exit(EXIT_FAILURE);
  }
  else { // parent
    waitpid(pid, &status, 0);
  }



  // construct arguments
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
    args[ii] = new char [1000];
  }
  // change parameter
  strncpy(args[0], changeParam.c_str(), changeParam.length() + 1);
  strncpy(args[1], "-f", strlen("-f") + 1);
  strncpy(args[2], jobDirParamFile.c_str(), jobDirParamFile.length() + 1);
  strncpy(args[3], "gamma2", strlen(jobDir) + 1);
  strncpy(args[4], g2Str, strlen(g2Str) + 1);
  args[5] = NULL;

  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 10; ii++) fprintf(stdout, " %s", args[ii]);
  fprintf(stdout, "\n");

  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child
    execv("changeParam.py", args);
    _exit(EXIT_FAILURE);
  }
  else { // parent
    waitpid(pid, &status, 0);
  }



  // construct arguments
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
    args[ii] = new char [1000];
  }
  // change parameter
  strncpy(args[0], changeParam.c_str(), changeParam.length() + 1);
  strncpy(args[1], "-f", strlen("-f") + 1);
  strncpy(args[2], jobDirParamFile.c_str(), jobDirParamFile.length() + 1);
  strncpy(args[3], "gamma1_c", strlen(jobDir) + 1);
  strncpy(args[4], g1_cStr, strlen(g1_cStr) + 1);
  args[5] = NULL;

  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 10; ii++) fprintf(stdout, " %s", args[ii]);
  fprintf(stdout, "\n");

  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child
    execv("changeParam.py", args);
    _exit(EXIT_FAILURE);
  }
  else { // parent
    waitpid(pid, &status, 0);
  }



  // ---- run code ---- //
  //

  // construct arguments
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
    args[ii] = new char [1000];
  }
  strncpy(args[0], dynamix.c_str(), dynamix.length() + 1);
  strncpy(args[1], "-i", strlen("-i") + 1);
  strncpy(args[2], jobInsDir.c_str(), jobInsDir.length() + 1);
  strncpy(args[3], "-o", strlen("-o") + 1);
  strncpy(args[4], jobOutsDir.c_str(), jobOutsDir.length() + 1);
  args[5] = NULL;

  fprintf(stdout, "COMMAND:");
  for (int ii = 0; ii < 10; ii++) fprintf(stdout, " %s", args[ii]);
  fprintf(stdout, "\n");

  int flag;
  flag = dynamixMain(5, args);

  /*
  if ((pid = fork()) < 0) { // fork fails
    fprintf(stdout, "Fork bork\n");
    _exit(EXIT_FAILURE);
  }
  else if (pid == 0) { // child
    execv("dynamix", args);
    _exit(EXIT_FAILURE);
  }
  else { // parent
    waitpid(pid, &status, 0);
  }
  */

  // ---- check for success ---- //
  //
  // ---- read in outputs ---- //
  //
  // ---- calculate objective ---- //
  //
  // ---- remove job directory ---- //

  // clean up
  for (int ii = 0; ii < 10; ii++) {
    delete [] args[ii];
  }

  return output;
}
예제 #20
0
///////////////////////////
//                       //
//  PACKING OPERATIONS   //
//                       //
///////////////////////////
void
ProjectPackager::runPack()
{

RG_DEBUG << "ProjectPackager::runPack()";

    m_info->setText(tr("Packing project..."));

    // go into spinner mode
    m_progress->setMaximum(0);

    QStringList audioFiles = getAudioFiles();

    // the base tmp directory where we'll assemble all the files
    m_packTmpDirName = QString("%1/rosegarden-project-packager-tmp").arg(QDir::homePath());

    // the data directory where audio and other files will go
    QFileInfo fi(m_filename);
    m_packDataDirName = fi.baseName();

RG_DEBUG << "using tmp data directory: " << m_packTmpDirName << "/" << 
    m_packDataDirName;

    QDir tmpDir(m_packTmpDirName);

    // get the original filename saved by RosegardenMainWindow and the name of
    // the new one we'll be including in the bundle (name isn't changing, path
    // component changes from one to the other)
    // QFileInfo::baseName() given /tmp/foo/bar/rat.rgp returns rat
    //
    // m_filename comes in already having an .rgp extension, but the file
    // was saved .rg
    QString oldName = QString("%1/%2.rg").arg(fi.path()).arg(fi.baseName());
    QString newName = QString("%1/%2.rg").arg(m_packTmpDirName).arg(fi.baseName());

    // if the tmp directory already exists, just hose it
    rmdirRecursive(m_packTmpDirName);

    // make the temporary working directory
    if (tmpDir.mkdir(m_packTmpDirName)) {

    } else {
        puke(tr("<qt><p>Could not create temporary working directory.</p>%1</qt>").arg(m_abortText));
        return;
    }

    m_info->setText(tr("Copying audio files..."));

    // leave spinner mode
    m_progress->setMaximum(100);
    m_progress->setValue(0);

    // count total audio files
    int af = 0;
    QStringList::const_iterator si;
    for (si = audioFiles.constBegin(); si != audioFiles.constEnd(); ++si)
        af++;
    int afStep = ((af == 0) ? 1 : (100 / af));

    // make the data subdir
    tmpDir.mkdir(m_packDataDirName);    

    // copy the audio files (do not remove the originals!)
    af = 0;
    for (si = audioFiles.constBegin(); si != audioFiles.constEnd(); ++si) {

        // comes in with full path and filename
        QString srcFile = (*si);
        QString srcFilePk = QString("%1.pk").arg(srcFile);

        // needs the filename split away from the path, so we can replace the
        // path with the new one
        QFileInfo fi(*si);
        QString filename = QString("%1.%2").arg(fi.baseName()).arg(fi.completeSuffix());

        QString dstFile = QString("%1/%2/%3").arg(m_packTmpDirName).arg(m_packDataDirName).arg(filename);
        QString dstFilePk = QString("%1.pk").arg(dstFile);

RG_DEBUG << "cp " << srcFile << " " << dstFile;
RG_DEBUG << "cp " << srcFilePk << " " << dstFilePk;

        if (!QFile::copy(srcFile, dstFile)) {
            puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(srcFile).arg(dstFile));
            return;
        }

        // Try to copy the .wav.pk file derived from transforming the name of
        // the .wav file.  We don't trap the fail condition for this one and
        // allow it to fail silently without complaining or aborting.  If the
        // .wav.pk files are missing, they will be generated again as needed.
        //
        // Legacy .rgp files ship with improperly named .wav.pk files, from
        // a bug in the original rosegarden-project-package script.  You'd wind
        // up with an .rgp that contained, for example:
        //
        //   emergence-rg-0014.wav.pk
        //   RG-AUDIO-0014.wav.pk
        //
        // That is why this version of the project packager doesn't screw around
        // with the original filenames!
        QFile::copy(srcFilePk, dstFilePk);

        m_progress->setValue(afStep * ++af);
    }

    // deal with adding any extra files
    QStringList extraFiles;

    // first, if the composition includes synth plugins, there may be assorted
    // random audio files, soundfonts, and who knows what else in use by these
    // plugins
    //
    // obtain a list of these files, and rewrite the XML to update the referring
    // path from its original source to point to our bundled copy instead
    QString newPath = QString("%1/%2").arg(m_packTmpDirName).arg(m_packDataDirName);
    extraFiles = getPluginFilesAndRewriteXML(oldName, newPath);

    // If we do the above here and add it to extraFiles then if the user has any
    // other extra files to add by hand, it all processes out the same way with
    // no extra bundling code required (unless we want to flac any random extra
    // .wav files, and I say no, let's not get that complicated)

    // Copy the modified .rg file to the working tmp dir

RG_DEBUG << "cp " << oldName << " " << newName;

    // copy m_filename(.rgp) as $tmp/m_filename.rg
    if (!QFile::copy(oldName, newName)) {
        puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(oldName).arg(newName));
        return;
    }

    QMessageBox::StandardButton reply = QMessageBox::information(this,
            tr("Rosegarden"),
            tr("<qt><p>Rosegarden can add any number of extra files you may desire to a project package.  For example, you may wish to include an explanatory text file, a soundfont, a bank definition for ZynAddSubFX, or perhaps some cover art.</p><p>Would you like to include any additional files?</p></qt>"),
            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);

    while (reply == QMessageBox::Yes) {

        // it would take some trouble to make the last used paths thing work
        // here, where we're building a list of files from potentially anywhere,
        // so we'll just use the open_file path as it was last set elsewhere,
        // and leave it at that until somebody complains
        QSettings settings;
        settings.beginGroup(LastUsedPathsConfigGroup);
        QString directory = settings.value("open_file", QDir::homePath()).toString();
        settings.endGroup();

        // must iterate over a copy of the QStringList returned by
        // (Q)FileDialog::getOpenFileNames for some reason
        //
        // NOTE: This still doesn't work.  I can only add one filename.
        // Something broken in the subclass of QFileDialog?  Bad code?  I'm just
        // leaving it unresolved for now. One file at a time at least satisfies
        // the bare minimum requirements
        QStringList files =  FileDialog::getOpenFileNames(this, "Open File", directory, tr("All files") + " (*)", 0, 0);
        extraFiles << files;
       
        //!!!  It would be nice to show the list of files already chosen and
        // added, in some nice little accumulator list widget, but this would
        // require doing something more complicated than using QMessageBox
        // static convenience functions, and it's probably just not worth it
        reply =  QMessageBox::information(this,
                tr("Rosegarden"),
                tr("<qt><p>Would you like to include any additional files?</p></qt>"),
                QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    }

    m_info->setText(tr("Copying plugin data and extra files..."));

    // reset progress bar
    m_progress->setValue(0);

    // count total audio files
    int ef = 0;
    for (si = extraFiles.constBegin(); si != extraFiles.constEnd(); ++si)
        ef++;
    int efStep = ((ef == 0) ? 1 : (100 / ef));

    // copy the extra files (do not remove the originals!)
    // (iterator previously declared)
    ef = 0;
    for (si = extraFiles.constBegin(); si != extraFiles.constEnd(); ++si) {
    
        // each QStringList item from the FileDialog will include the full path
        QString srcFile = (*si);

        // so we cut it up to swap the source dir for the dest dir while leaving
        // the complete filename stuck on the end
        QFileInfo efi(*si);
        QString basename = QString("%1.%2").arg(efi.baseName()).arg(efi.completeSuffix());
        QString dstFile = QString("%1/%2/%3").arg(m_packTmpDirName).arg(m_packDataDirName).arg(basename);

RG_DEBUG << "cp " << srcFile << " " << dstFile;

        if (!QFile::copy(srcFile, dstFile)) {
            puke(tr("<qt>Could not copy<br>%1<br>  to<br>%2<br><br>Processing aborted.</qt>").arg(srcFile).arg(dstFile));
            return;
        }

        m_progress->setValue(efStep * ++ef);
    }

    // and now we have everything discovered, uncovered, added, smothered,
    // scattered and splattered, and we're ready to pack the files and
    // get the hell out of here!
    startAudioEncoder(audioFiles);
}
예제 #21
0
  /*
   *
   *  @param   file    Pointer to the file
   *  @param   debug   Turn on debug printing
   *
   *  @ingroup inputfiles
   */
  void ct2ctml(const char* file, const int debug) {

#ifdef HAS_NO_PYTHON
    /*
     *  Section to bomb out if python is not
     *  present in the computation environment.
     */
    string ppath = file;
    throw CanteraError("ct2ctml", 
		       "python cti to ctml conversion requested for file, " + ppath +
		       ", but not available in this computational environment");
#endif

    time_t aclock;
    time( &aclock );
    int ia = static_cast<int>(aclock);
    string path =  tmpDir()+"/.cttmp"+int2str(ia)+".pyw";
    ofstream f(path.c_str());
    if (!f) {
      throw CanteraError("ct2ctml","cannot open "+path+" for writing.");
    }

    f << "from ctml_writer import *\n"
      << "import sys, os, os.path\n"
      << "file = \"" << file << "\"\n"
      << "base = os.path.basename(file)\n"
      << "root, ext = os.path.splitext(base)\n"
      << "dataset(root)\n"
      << "execfile(file)\n"
      << "write()\n";
    f.close();
    string logfile = tmpDir()+"/ct2ctml.log";
#ifdef _WIN32
    string cmd = pypath() + " " + "\"" + path + "\"" + "> " + logfile + " 2>&1";
#else
    string cmd = "sleep " + sleep() + "; " + "\"" + pypath() + "\"" + 
      " " + "\"" + path + "\"" + " &> " + logfile;
#endif
#ifdef DEBUG_PATHS
    writelog("ct2ctml: executing the command " + cmd + "\n");
#endif
    if (debug > 0) {
      writelog("ct2ctml: executing the command " + cmd + "\n");
      writelog("ct2ctml: the Python command is: " + pypath() + "\n");
    }

    int ierr = 0;
    try {
      ierr = system(cmd.c_str());
    }
    catch (...) {
      ierr = -10;
	  if (debug > 0) {
	    writelog("ct2ctml: command execution failed.\n");
	  }
    }

    /*
     * This next section may seem a bit weird. However, it is in
     * response to an issue that arises when running cantera with
     * cygwin, using cygwin's python intepreter. Basically, the
     * xml file is written to the local directory by the last
     * system command. Then, the xml file is read immediately
     * after by an ifstream() c++ command. Unfortunately, it seems
     * that the directory info is not being synched fast enough so
     * that the ifstream() read fails, even though the file is
     * actually there. Putting in a sleep system call here fixes
     * this problem. Also, having the xml file pre-existing fixes
     * the problem as well. There may be more direct ways to fix
     * this bug; however, I am not aware of them.
     * HKM -> During the solaris port, I found the same thing.
     *        It probably has to do with NFS syncing problems.
     *        3/3/06
     */
#ifndef _WIN32
    string sss = sleep();
    if (debug > 0) {
      writelog("sleeping for " + sss + " secs+\n");
    }
    cmd = "sleep " + sss;
    try {
      ierr = system(cmd.c_str());
    }
    catch (...) {
      ierr = -10;
      writelog("ct2ctml: command execution failed.\n");
    }
#else
    // This command works on windows machines if Windows.h and Winbase.h are included
    // Sleep(5000);
#endif
    // show the contents of the log file on the screen
    try {
      char ch=0;
      string s = "";
      ifstream ferr("ct2ctml.log");
      if (ferr) {
	    while (!ferr.eof()) {
	      ferr.get(ch);
	      s += ch;
	      if (ch == '\n') {
	        writelog(s);
	        s = "";
	      }
	    }
	    ferr.close();
      }
      else {
            if (debug > 0) {
	      writelog("cannot open ct2ctml.log for reading.\n");
	    }
      }
    }
    catch (...) {
      writelog("ct2ctml: caught something \n");; 
    }
    if (ierr != 0) {
      string msg = cmd;
	  writelog("ct2ctml: throw cantera error \n");; 
      throw CanteraError("ct2ctml", 
			 "could not convert input file to CTML.\n "
			 "Command line was: \n" + msg);
    }

    // if the conversion succeeded and DEBUG_PATHS is not defined,
    // then clean up by deleting the temporary Python file.
#ifndef DEBUG_PATHS
    //#ifdef _WIN32
    //cmd = "cmd /C rm " + path;
    if (debug == 0)
      remove(path.c_str());
    else {
      writelog("ct2ctml: retaining temporary file "+path+"\n");
    }
#else
    if (debug > 0) {
      writelog("ct2ctml: retaining temporary file "+path+"\n");
    }
#endif
  }
예제 #22
0
void ThumbGenerator::loadFile(QImage& image, const QFileInfo& fi)
{
    static int sequence = 0;

    if (GalleryUtil::IsMovie(fi.filePath()))
    {
        bool thumbnailCreated = false;
        QDir tmpDir("/tmp/mythgallery");
        if (!tmpDir.exists())
        {
            if (!tmpDir.mkdir(tmpDir.absolutePath()))
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Unable to create temp dir for movie thumbnail creation: " +
                    tmpDir.absolutePath());
            }
        }

        if (tmpDir.exists())
        {
            QString thumbFile = QString("%1.png")
                .arg(++sequence,8,10,QChar('0'));

            QString cmd = "mythpreviewgen";
            QStringList args;
            args << logPropagateArgs.split(" ", QString::SkipEmptyParts);
            args << "--infile" << '"' + fi.absoluteFilePath() + '"';
            args << "--outfile" << '"' + tmpDir.filePath(thumbFile) + '"';

            MythSystemLegacy ms(cmd, args, kMSRunShell);
            ms.SetDirectory(tmpDir.absolutePath());
            ms.Run();
            if (ms.Wait() == GENERIC_EXIT_OK)
            {
                QFileInfo thumb(tmpDir.filePath(thumbFile));
                if (thumb.exists())
                {
                    QImage img(thumb.absoluteFilePath());
                    image = img;
                    thumbnailCreated = true;
                }
            }
        }

        if (!thumbnailCreated)
        {
            QImage *img = GetMythUI()->LoadScaleImage("gallery-moviethumb.png");
            if (img)
            {
                image = *img;
            }
        }
    }
    else
    {
#ifdef EXIF_SUPPORT
        // Try to get thumbnail from exif data
        ExifData *ed = exif_data_new_from_file(fi.absoluteFilePath()
                                               .toLocal8Bit().constData());
        if (ed && ed->data)
        {
            image.loadFromData(ed->data, ed->size);
        }

        if (ed)
            exif_data_free(ed);

        if (image.width() > m_width && image.height() > m_height)
            return;
#endif

#ifdef DCRAW_SUPPORT
        QString extension = fi.suffix();
        QSet<QString> dcrawFormats = DcrawFormats::getFormats();
        int rotateAngle;

        if (dcrawFormats.contains(extension) &&
            (rotateAngle = DcrawHandler::loadThumbnail(&image,
                                               fi.absoluteFilePath())) != -1 &&
            image.width() > m_width && image.height() > m_height)
        {
            if (rotateAngle != 0)
            {
                QMatrix matrix;
                matrix.rotate(rotateAngle);
                image = image.transformed(matrix);
            }

            return;
        }
#endif

        image.load(fi.absoluteFilePath());
    }
}
예제 #23
0
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    app.setApplicationName("ksvg2icns");
    app.setApplicationVersion(KICONTHEMES_VERSION_STRING);
    QCommandLineParser parser;
    parser.setApplicationDescription(app.translate("main", "Creates an icns file from an svg image"));
    parser.addPositionalArgument("iconname", app.translate("main", "The svg icon to convert"));
    parser.addHelpOption();

    parser.process(app);
    if (parser.positionalArguments().isEmpty()) {
        parser.showHelp();
        return 1;
    }

    bool isOk;

    // create a temporary dir to create an iconset
    QTemporaryDir tmpDir("ksvg2icns");
    tmpDir.setAutoRemove(true);

    isOk = tmpDir.isValid();
    EXIT_ON_ERROR(isOk, "Unable to create temporary directory\n");

    isOk = QDir(tmpDir.path()).mkdir("out.iconset");
    EXIT_ON_ERROR(isOk, "Unable to create out.iconset directory\n");

    const QString outPath = tmpDir.path() + "/out.iconset";

    const QStringList &args = app.arguments();
    EXIT_ON_ERROR(args.size() == 2,
                  "Usage: %s svg-image\n",
                  qPrintable(args.value(0)));

    const QString &svgFileName = args.at(1);

    // open the actual svg file
    QSvgRenderer svg;
    isOk = svg.load(svgFileName);
    EXIT_ON_ERROR(isOk, "Unable to load %s\n", qPrintable(svgFileName));

    // The sizes are from:
    // https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Optimizing/Optimizing.html

    struct OutFiles
    {
        int size;
        QString out1;
        QString out2;
    };

    // create the pngs in various resolutions
    const OutFiles outFiles[] = {
        { 1024, outPath + "/[email protected]", QString() },
        {  512, outPath + "/icon_512x512.png",    outPath + "/[email protected]" },
        {  256, outPath + "/icon_256x256.png",    outPath + "/[email protected]" },
        {  128, outPath + "/icon_128x128.png",    QString() },
        {   64, outPath + "/[email protected]",   QString() },
        {   32, outPath + "/icon_32x32.png",       outPath + "/[email protected]" },
        {   16, outPath + "/icon_16x16.png",       QString() }
    };

    for (size_t i = 0; i < sizeof(outFiles) / sizeof(OutFiles); ++i) {
        isOk = writeImage(svg, outFiles[i].size, outFiles[i].out1, outFiles[i].out2);
        if (!isOk) {
            return 1;
        }
    }

    // convert the iconset to icns using the "iconutil" command

    const QString outIcns = QFileInfo(svgFileName).baseName() + ".icns";

    const QStringList utilArgs = QStringList()
            << "-c" << "icns"
            << "-o" << outIcns
            << outPath;

    QProcess iconUtil;
    iconUtil.setProgram("iconUtil");
    iconUtil.setArguments(utilArgs);

    iconUtil.start("iconutil", utilArgs, QIODevice::ReadOnly);
    isOk = iconUtil.waitForFinished(-1);
    EXIT_ON_ERROR(isOk, "Unable to launch iconutil: %s\n", qPrintable(iconUtil.errorString()));

    EXIT_ON_ERROR(iconUtil.exitStatus() == QProcess::NormalExit, "iconutil crashed!\n");
    EXIT_ON_ERROR(iconUtil.exitCode() == 0, "iconutil returned %d\n", iconUtil.exitCode());

    return 0;
}