Example #1
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    app.addLibraryPath(app.applicationDirPath() + "/lib");

    QCommandLineParser parser;
    QList<QCommandLineOption> optionList;
    optionList.append({{"d", "debug"}, "Log debug messages."});
    optionList.append({{"c", "console"}, "Output log to the console."});
    optionList.append({{"p", "port"}, "Application connection port.", "port", "1067"});
    optionList.append({"database", "The name of the database file.", "database", "softphoneDatabase.db3"});
    parser.addOptions(optionList);
    parser.process(app);

    bool debugOutput = parser.isSet("debug");
    Logger::getInstance().enableDebugOutput(debugOutput);

    bool consoleOutput = parser.isSet("console");
    Logger::getInstance().enableConsoleOutput(consoleOutput);

    SpThreadServer *server = new SpThreadServer();
    server->setPort(quint16(parser.value("port").toInt()));
    server->setDatabasePath(parser.value("database"));
    server->start();

    app.exec();
    server->deleteLater();
}
Example #2
0
    void Arguments::parse()
    {
        QCommandLineParser parser;
        parser.setApplicationDescription("Unit tests");
        parser.addHelpOption();

        static const QString rootOptionName = "r";
        static const QString dbOptionName   = "d";
        parser.addOptions({
            {{rootOptionName, "test_root"}, "Set tests root path. Have to be specified"   , "root"},
            {{dbOptionName  , "db_path"  }, "Set main database path. Have to be specified", "db"  },
            {"gtest_shuffle", "Shuffle tests"},
        });

        if (!parser.parse(qApp->arguments()))
            parser.showHelp();

        auto tmpRootPath = parser.value(rootOptionName);
        auto tmpDbPath   = parser.value(dbOptionName);

        if (tmpRootPath.isEmpty() || tmpDbPath.isEmpty())
            parser.showHelp();

        m_rootPath = tmpRootPath;
        m_dbPath   = tmpDbPath;
    }
Example #3
0
OvenCLIApplication::OvenCLIApplication(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
    // parse the command line parameters
    QCommandLineParser parser;

    parser.addOptions({
        { CLI_INPUT_PARAMETER, "Path to file that you would like to bake.", "input" },
        { CLI_OUTPUT_PARAMETER, "Path to folder that will be used as output.", "output" },
        { CLI_TYPE_PARAMETER, "Type of asset.", "type" },
        { CLI_DISABLE_TEXTURE_COMPRESSION_PARAMETER, "Disable texture compression." }
    });

    parser.addHelpOption();
    parser.process(*this);

    if (parser.isSet(CLI_INPUT_PARAMETER) && parser.isSet(CLI_OUTPUT_PARAMETER)) {
        BakerCLI* cli = new BakerCLI(this);
        QUrl inputUrl(QDir::fromNativeSeparators(parser.value(CLI_INPUT_PARAMETER)));
        QUrl outputUrl(QDir::fromNativeSeparators(parser.value(CLI_OUTPUT_PARAMETER)));
        QString type = parser.isSet(CLI_TYPE_PARAMETER) ? parser.value(CLI_TYPE_PARAMETER) : QString::null;

        if (parser.isSet(CLI_DISABLE_TEXTURE_COMPRESSION_PARAMETER)) {
            qDebug() << "Disabling texture compression";
            TextureBaker::setCompressionEnabled(false);
        }

        QMetaObject::invokeMethod(cli, "bakeFile", Qt::QueuedConnection, Q_ARG(QUrl, inputUrl),
                                    Q_ARG(QString, outputUrl.toString()), Q_ARG(QString, type));
    } else {
        parser.showHelp();
        QCoreApplication::quit();
    }

}
Example #4
0
int main(int ac, char *av[])
{
    // This line is absolutely mandatory for being able to have multiple
    // QOpenGLWidgets in different windows!!!
    QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

    QCoreApplication::setApplicationName("Omnidome");
    QCoreApplication::setApplicationVersion(OMNIDOME_VERSION_STRING);

    QCommandLineParser parser;
    parser.setApplicationDescription("Test helper");
    parser.addHelpOption();
    parser.addVersionOption();

    /// Start gui
    QApplication _a(ac, av);


    QFile file(":/qss_icons/style.qss");

    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());
    _a.setStyleSheet(styleSheet);


    parser.addOptions({
        // An option with a value
        {{"p", "plugin-directory"},
            QCoreApplication::translate("main", "Plugin directory <directory>."),
            QCoreApplication::translate("main", "plugin-directory")},
    });

    parser.process(_a);
    const QStringList args = parser.positionalArguments();

    // Load plugins
    {
        std::vector<QDir> _pluginDirs;
        if (parser.value("plugin-directory").isEmpty()) {
            _pluginDirs.push_back(parser.value("plugin-directory"));
        }
        PluginLoader _pluginLoader(_pluginDirs);
    }

    ui::MainWindow _w;
    _w.setWindowState(Qt::WindowMaximized);
    _w.move(QApplication::primaryScreen()->geometry().topLeft());

    if (ac == 2)
    {
        _w.openProjection(av[1]);
    }

    return _a.exec();
}
Example #5
0
int main(int argc, char* argv[])
{
    QScopedPointer<QCoreApplication> app(createApplication(argc, argv));

    QCoreApplication::setOrganizationName("ARKottke");
    QCoreApplication::setApplicationName("Strata");
    QCoreApplication::setApplicationVersion(VERSION);

    QCommandLineParser parser;
    parser.setApplicationDescription(
        "Strata - site response with RVT and simulated properties");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addOptions({
        {   {"b", "batch"},
            QCoreApplication::translate("main", "Batch mode without a GUI")
        },
    });
    parser.addPositionalArgument(
        "file",
        QCoreApplication::translate(
            "main",
            "Strata JSON or binary files to process. Multiple files"
            "are only supported by batch mode (-b)."),
        "file1 [file2 file3...]");

    parser.process(*app.data());
    const QStringList args = parser.positionalArguments();

    if (qobject_cast<QApplication *>(app.data())) {
        // GUI Version
#ifndef DEBUG
        qInstallMessageHandler(myMessageOutput);
#endif
        qobject_cast<QApplication *>(app.data())->setWindowIcon(QIcon(":/images/application-icon.svg"));
        MainWindow * mainWindow = new MainWindow;
        if (args.size())
            mainWindow->open(args.at(0));
        mainWindow->showMaximized();
    } else {
        // start non-GUI version...
        qInstallMessageHandler(myMessageOutput);

        if (args.size() < 1) {
            qFatal("At least one file must be specified.");
            return 1;
        }
        BatchRunner *br = new BatchRunner(args);
        Q_UNUSED(br);
    }

    return app.data()->exec();
}
Example #6
0
std::tuple<QStringList, float, float>
processArgs(const QApplication &app)
{
    QCommandLineParser parser;
    parser.setApplicationDescription("Animates a mesh by interpolating "
                                     "multiple poses.");

    parser.addPositionalArgument("pose files", "Mesh pose files (2 or more).",
                                 "<pose files...>");

    parser.addOptions({
        {{"d", "duration"},
         "Duration of the animation (default: number of poses minus one).",
         "seconds"},
        {{"f", "fps"}, "Frames per second (default: 25).", "fps", "25"},
    });

    parser.addHelpOption();
    parser.addVersionOption();

    parser.process(app);

    const QStringList files = parser.positionalArguments();
    if (files.size() < 2)
    {
        parser.showHelp(1);
    }

    bool valid;
    float duration = files.size() - 1.0f;
    if (parser.isSet("duration"))
    {
        duration = parser.value("duration").toDouble(&valid);
        if (!valid || duration <= 0.0f)
        {
            parser.showHelp(1);
        }
    }

    float fps = parser.value("fps").toDouble(&valid);
    if (!valid || fps <= 0.0f)
    {
        parser.showHelp(1);
    }

    return std::make_tuple(files, duration, fps);
}
Example #7
0
int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    QApplication::setApplicationName(TConfiguration::getAppName());
    QApplication::setApplicationVersion(TConfiguration::getVersion());
    QApplication::setApplicationDisplayName(TConfiguration::getAppName());
    QCommandLineParser parser;

    parser.setApplicationDescription(TConfiguration::getDescription());
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("SMIL_INDEX", QCoreApplication::translate("main", "Path to SMIL index"));

    parser.addOptions(
    {
        {{"f", "fullscreen"}, "Starts in fullscreen mode"},
         {{"w", "window"}, "Starts in windows mode"}
    });
    MainWindow w;
    parser.process(app);

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0)
        w.setInitialSmilIndex(args.at(0));
    else
        w.setInitialSmilIndex("");

    if (parser.isSet("f"))
        w.showFullScreen();
    else if (parser.isSet("w"))
    {
        w.setMinimumSize(980, 540);
        w.show();
    }
    else
    {
        w.setMinimumSize(980, 540);
        w.show();
    }

//        parser.showHelp(0);

    return app.exec();
}
void tst_QCommandLineParser::testCpp11StyleInitialization()
{
#if defined(Q_COMPILER_INITIALIZER_LISTS) && defined(Q_COMPILER_UNIFORM_INIT)
    QCoreApplication app(empty_argc, empty_argv);

    QCommandLineParser parser;
    // primarily check that this compiles:
    parser.addOptions({
        { "a",                "The A option." },
        { { "v", "verbose" }, "The verbose option." },
        { { "i", "infile" },  "The input file.", "value" },
    });
    // but do a very basic functionality test, too:
    QVERIFY(parser.parse({"tst_QCommandLineParser", "-a", "-vvv", "--infile=in.txt"}));
    QCOMPARE(parser.optionNames(), (QStringList{"a", "v", "v", "v", "infile"}));
    QCOMPARE(parser.value("infile"), QString("in.txt"));
#else
    QSKIP("This test requires C++11 uniform initialization support in the compiler.");
#endif
}
Example #9
0
int main(int argc, char *argv[])
{
  QtSingleApplication app(argc, argv);
  QApplication::setApplicationName("niftykb");
  QApplication::setApplicationVersion("0.1");

  // process command line arguments
  QCommandLineParser parser;
  parser.addVersionOption();
  parser.addHelpOption();
  parser.addOptions({
    {"hide", QCommandLineParser::tr("Hide window on start. Overrides any settings")},
    {"show", QCommandLineParser::tr("Show window on start. Overrides any settings")},
  });
  parser.process(app);

  // Only run single instance
  if (app.isRunning()) {
    // TODO: hide/show the running instance
    // TODO: allow multiple with command line arguments
    return !app.sendMessage("show");
  }

  // Init global struct
  Global::g_global_struct = new Global();
  GlobalShortcutEngine::engine = GlobalShortcutEngine::platformInit();
  g.s.load();
  MainWindow w(0, &parser);
  g.mw = &w;
  app.setActivationWindow(&w);

  if (!parser.isSet("hide")) {
    w.show();
  }

  return app.exec();
}
Example #10
0
int main(int argc, char *argv[]) {
  QCoreApplication app(argc, argv);
  QCommandLineParser parser;
  parser.addHelpOption();

#if 0
  // A boolean option with a single name (-p)
  QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy"));
  parser.addOption(showProgressOption);

  // A boolean option with multiple names (-f, --force)
  QCommandLineOption forceOption
    (QStringList() << "f" << "force",
     QCoreApplication::translate("main", "Overwrite existing files."));
  parser.addOption(forceOption);

  // An option with a value
  QCommandLineOption targetDirectoryOption
    (QStringList() << "t" << "target-directory",
     QCoreApplication::translate("main", "Copy all source files into <directory>."),
     QCoreApplication::translate("main", "directory"));
  parser.addOption(targetDirectoryOption);
#elif 0
  parser.addOptions(
    {
      // A boolean option with a single name (-p)
      {"p", QCoreApplication::translate("main", "Show progress during copy") },
      // A boolean option with multiple names (-f, --force)
      { {"f", "force"}, QCoreApplication::translate("main", "Overwrite existing files.") },
      // An option with a value
      { {"t", "target-directory"} ,
          QCoreApplication::translate("main", "Copy all source files into <directory>."),
          QCoreApplication::translate("main", "directory") }
    });
#elif 1
  parser.addOptions(
    {
      // A boolean option with a single name (-p)
      {"p", "Show progress during copy" },
      // A boolean option with multiple names (-f, --force)
      { {"f", "force"}, "Overwrite existing files XXX." },
      // An option with a value
      { {"t", "target-directory"} , "Copy all source files into <directory>.", "directory" }
    });
#else
  parser.addOptions(
    {
      { {"soap", "s"}, "Start Borne in SOAP mode" },
      { {"ws", "w"}, "Start Borne in WS mode" },
      { {"debug", "d"}, "Start Borne with debug logs enable" },
      { "newmotion", "Connect Charging Station to Newmotion (SOAP or WS)" },
      { "eurisko", "Connect Charging Station to Eurisko (192.168.0.156)" },
        { "version", "Choose Ocpp Version (1.5 by default)", "version", "1.5" },
      { "ipsupervision",  "Connect to given Supervision (ip)", "ip" },
      { "ipserversoap",  "Soap server: listen to request on given (local) ip", "ip"},
    });
#endif

  // Process the actual command line arguments given by the user
  parser.process(app);

  // Option call back
  //bool force = parser.isSet(forceOption);
  bool force = parser.isSet("force");
  QString targetDir = parser.value("t");

  cout << (force?"force ON":"force off") << endl;
  cout << "targetDir:" << targetDir.toStdString()  << endl;
  cout << endl;
}
int main(int argc, char *argv[])
{
  try
  {
    QCommandLineParser parser;
    parser.setApplicationDescription("Plex Media Player");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addOptions({{{"l", "licenses"}, "Show license information"}});
    parser.addOptions({{{"a", "from-auto-update"}, "When invoked from auto-update"}});

    char **newArgv = appendCommandLineArguments(argc, argv, g_qtFlags);
    argc += g_qtFlags.size();

    // Suppress SSL related warnings on OSX
    // See https://bugreports.qt.io/browse/QTBUG-43173 for more info
    //
#ifdef Q_OS_MAC
    qputenv("QT_LOGGING_RULES", "qt.network.ssl.warning=false");
#endif

    // Qt calls setlocale(LC_ALL, "") in a bunch of places, which breaks
    // float/string processing in mpv and ffmpeg.
#ifdef Q_OS_UNIX
    qputenv("LC_ALL", "C");
    qputenv("LC_NUMERIC", "C");
#endif

    detectOpenGLEarly();

    preinitQt();

    QGuiApplication app(argc, newArgv);
    app.setWindowIcon(QIcon(":/images/icon.png"));

    // Get the arguments from the app, this is the parsed version of newArgc and newArgv
    QStringList args = app.arguments();

    // Remove the qt flags above so that our command line parser doesn't get cranky.
    for (auto flag : g_qtFlags)
      args.removeAll(flag);

    // Now parse the command line.
    parser.process(args);

    if (parser.isSet("licenses"))
    {
      ShowLicenseInfo();
      return EXIT_SUCCESS;
    }

    // init breakpad.
    setupCrashDumper();

    UniqueApplication* uniqueApp = new UniqueApplication();
    if (!uniqueApp->ensureUnique())
      return EXIT_SUCCESS;

#ifdef Q_OS_UNIX
    // install signals handlers for proper app closing.
    SignalManager signalManager(&app);
    Q_UNUSED(signalManager);
#endif

    Log::Init();

    // Quit app and apply update if we find one.
    if (UpdateManager::CheckForUpdates())
    {
      app.quit();
      return 0;
    }

    detectOpenGLLate();

#ifdef Q_OS_WIN32
    initD3DDevice();
#endif

    Codecs::preinitCodecs();

    // Initialize all the components. This needs to be done
    // early since most everything else relies on it
    //
    ComponentManager::Get().initialize();

    // enable remote inspection if we have the correct setting for it.
    if (SettingsComponent::Get().value(SETTINGS_SECTION_MAIN, "remoteInspector").toBool())
      qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "0.0.0.0:9992");

    QtWebEngine::initialize();

    // start our helper
    HelperLauncher::Get().connectToHelper();

    // load QtWebChannel so that we can register our components with it.
    QQmlApplicationEngine *engine = Globals::Engine();

    KonvergoWindow::RegisterClass();
    Globals::SetContextProperty("components", &ComponentManager::Get().getQmlPropertyMap());

    // the only way to detect if QML parsing fails is to hook to this signal and then see
    // if we get a valid object passed to it. Any error messages will be reported on stderr
    // but since no normal user should ever see this it should be fine
    //
    QObject::connect(engine, &QQmlApplicationEngine::objectCreated, [=](QObject* object, const QUrl& url)
    {
      Q_UNUSED(url);

      if (object == nullptr)
        throw FatalException(QObject::tr("Failed to parse application engine script."));

      KonvergoWindow* window = Globals::MainWindow();

      QObject* webChannel = qvariant_cast<QObject*>(window->property("webChannel"));
      Q_ASSERT(webChannel);
      ComponentManager::Get().setWebChannel(qobject_cast<QWebChannel*>(webChannel));

      QObject::connect(uniqueApp, &UniqueApplication::otherApplicationStarted, window, &KonvergoWindow::otherAppFocus);
    });
    engine->load(QUrl(QStringLiteral("qrc:/ui/webview.qml")));

    Log::UpdateLogLevel();

    // run our application
    int ret = app.exec();

    delete uniqueApp;
    Globals::EngineDestroy();

    Log::Uninit();
    return ret;
  }
  catch (FatalException& e)
  {
    QLOG_FATAL() << "Unhandled FatalException:" << qPrintable(e.message());
    QApplication errApp(argc, argv);

    auto  msg = new ErrorMessage(e.message(), true);
    msg->show();

    errApp.exec();

    Log::Uninit();
    return 1;
  }
}
Example #12
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addOptions({
            { "nogui", QString("Using command line arguments, do not show GUI.") },
            { { "p", "path" }, QString("Path for job files or shape files."), QString("path") },
            { { "g", "align" }, QString("Input is not aligned. Find lowest cost alignment.") },
            { { "s", "sourceShape" }, QString("Path for source shape file."), QString("source") },
            { { "t", "targetShape" }, QString("Path for target shape file."), QString("target") },
            { { "a", "auto" }, QString("Automatically try to find initial correspondence. Not used for job files.") },
			{ { "j", "job" }, QString("Job file to load."), QString("job") },
			{ { "f", "folder" }, QString("Folder for a shape dataset."), QString("folder") },
            { { "z", "output" }, QString("Folder for output JSON file."), QString("output") },
			{ { "q", "quiet" }, QString("Skip visualization.") },
            { { "m", "asymmetry" }, QString("Ignore symmetry groups. Used for evaluation.") },

            /* Actual paramteres */
            { { "k", "k" }, QString("(k) parameter for DP search."), QString("k") },
            { { "o", "roundtrip" }, QString("Compute least cost from source to target, and target to source.") },
            { { "c", "cut" }, QString("Allow part cuts/joins.") },

			/* Experiments */
			{ { "e", "experiment" }, QString("Perform hard coded experiments.") },
	});

    if (!parser.parse(QCoreApplication::arguments())) {
        QString errorText = parser.errorText();
        std::cout << qPrintable(errorText);
        return CommandLineError;
    }
	else
		parser.process(a);

	QString path = parser.value("p");
	QDir::setCurrent(path);

	/// Experiments:
	if (parser.isSet("e"))
	{
		QVariantMap options;
        //options["k"].setValue(6);
        //options["isQuietMode"].setValue(true);
		options["isOutputMatching"].setValue(true);
		options["isSaveReport"].setValue(true);
		options["isLogJobs"].setValue(true);

		QString sourceShape = "C:/Development/GeoTopo/standalone/ChairWood2/Woodchair2.xml";
		QString targetShape = "C:/Development/GeoTopo/standalone/chairVK2110/chair2110.xml";

		srand(time(nullptr));

        for (int i = 0; i < 1; i++)
		{
			auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, options));
			bp->jobUID = (double(rand()) / RAND_MAX) * 10;
			bp->run();

			for (auto & report : bp->jobReports){
				int time = report["search_time"].toInt();
				double c = report["min_cost"].toDouble();

				std::cout << "cost = " << c << " , time = " << time << std::endl;
			}

			//std::swap(sourceShape, targetShape);
		}

		return 0;
	}

    /// Process shape sets:
    if(parser.isSet("folder"))
    {
		QElapsedTimer timer; timer.start();

        QString dataset = parser.value("folder");
        QDir d("");
        QString dir_name = QDir(dataset).dirName();

		// 1) get sorted set of pairs to compare
        QVector< QPair<int, int> > shapePairs;
		auto folders = shapesInDataset(dataset);
		auto folderKeys = folders.keys();
		for (int i = 0; i < folderKeys.size(); i++)
			for (int j = i + 1; j < folderKeys.size(); j++)
                shapePairs << qMakePair(i,j);
		int shapePairsCount = shapePairs.size();
		int curShapePair = 0;

        QMap< QString,QPair<int,int> > pair_idx;

		// 2) perform correspondence for shape pairs
		{
			// Remove previous log file
			d.remove("log.txt");

			// go over pairs
			for (auto shapePair : shapePairs)
			{
				QProcess p;
                QString source = folders[folders.keys().at(shapePair.first)]["graphFile"].toString();
                QString target = folders[folders.keys().at(shapePair.second)]["graphFile"].toString();

				auto sg = QFileInfo(source).baseName();
				auto tg = QFileInfo(target).baseName();

                pair_idx[sg+tg] = qMakePair(shapePair.first, shapePair.second);

				std::cout << QString("Now: %1 / %2").arg(sg).arg(tg).leftJustified(35, ' ', true).toStdString();

				QStringList pargs;

                // Inputs
				pargs << "-s" << source << "-t" << target;	

                // Forward search options
                if (parser.isSet("o")) pargs << "-o";
                if (parser.isSet("k")) pargs << "-k" << parser.value("k");
				if (parser.isSet("q")) pargs << "-q";
                if (parser.isSet("c")) pargs << "-c";
                if (parser.isSet("m")) pargs << "-m";

                // Execute as a seperate process
				p.start(a.applicationFilePath(), pargs);
				p.waitForFinished(-1);

                // Show progress to user
				auto percent = (double(curShapePair++) / shapePairsCount) * 100.0;
				std::cout << QString("[%1 %] - %2 - ").arg((int)percent).arg(shapePairsCount-curShapePair).toStdString();
				int secPerPercent = (timer.elapsed() / 1000) / (percent + 1);
				int timeMinLeft = (secPerPercent * (100 - percent)) / 60;
				std::cout << QString("Time (%1s=%2m) ETA(%3m)\n").arg(timer.elapsed() / 1000).arg(timer.elapsed() / 60000).arg(timeMinLeft).toStdString();
			}
		}

		// 3) prepare results folder
		QString job_name = QString("job_%1").arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_hh_mm_ss"));
		d.mkpath(job_name);

        // 4) collect all pair-wise results
		{
            // output sorted set of shape names
			{
                QFile file(d.absolutePath() + "/" + job_name + "/" + "_" + dir_name + "_shapes.txt");
				if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
					QTextStream out(&file);
					for (int i = 0; i < folderKeys.size(); i++)
						out << QString("%1 %2\n").arg(i).arg(folderKeys.at(i));
				}
			}

			// read log and record the minimum costs and correspondence results
			{
				QFile ff(d.absolutePath() + "/" + "log.txt");
				ff.open(QFile::ReadOnly | QFile::Text);
				QTextStream in(&ff);
				auto datasetLogLines = in.readAll().split("\n", QString::SkipEmptyParts);

				// Record final results
                QJsonArray results;

                for(int idx = 0; idx < datasetLogLines.size(); idx++)
                {
                    // Read matching pair info
                    auto log_line = datasetLogLines[idx].split(",", QString::SkipEmptyParts);
                    QJsonObject matching;
                    matching["source"] = log_line.at(0);
                    matching["target"] = log_line.at(1);
                    matching["cost"] = log_line.at(2).toDouble();

                    // Get correspondence data
                    QString correspondenceFile = log_line.at(3);
                    bool isSwapped = (log_line.at(4).toInt() % 2) == 0;
                    QJsonArray correspondence;
                    {
                        // Open correspondence file
                        QFile cf(correspondenceFile);
                        cf.open(QFile::ReadOnly | QFile::Text);
                        QTextStream cfin(&cf);
                        auto corrLines = cfin.readAll().split("\n", QString::SkipEmptyParts);

                        // Read correspondence file (swapping if needed)
                        for (auto line : corrLines)
                        {
                            auto matched_pair = line.split(" ", QString::SkipEmptyParts);
                            QString sid = matched_pair.at(0);
                            QString tid = matched_pair.at(1);
                            if (isSwapped) std::swap(sid, tid);

                            QJsonArray part_pair;
                            part_pair.push_back(sid);
                            part_pair.push_back(tid);
                            correspondence.push_back(part_pair);
                        }
                    }
                    matching["correspondence"] = correspondence;

                    // Thumbnail files if any
                    QString correspondenceThumb = log_line.back();
                    if(correspondenceThumb != "null"){
                        QString targetThumb = QFileInfo(correspondenceThumb).fileName();
                        targetThumb = QString(d.absolutePath() + "/" + job_name + "/" + targetThumb);
                        QFile::copy(correspondenceThumb, targetThumb);
                        matching["thumbnail"] = targetThumb;
                    }

                    // indexing
                    auto sg = QFileInfo(log_line.at(0)).baseName();
                    auto tg = QFileInfo(log_line.at(1)).baseName();
                    auto pi = pair_idx[sg+tg];
                    matching["i"] = pi.first;
                    matching["j"] = pi.second;

                    // Record result
                    results.push_back(matching);
                }

				// Write all results in JSON format
				{
					QJsonDocument saveDoc(results);

                    QString jsonFilename = d.absolutePath() + "/" + job_name + "/_" + dir_name + "_corr.json";

                    // User specified output folder
                    if(parser.isSet("output")) jsonFilename = parser.value("output") + "/" + dir_name + "_corr.json";

                    QFile saveFile( jsonFilename );
                    saveFile.open( QIODevice::WriteOnly );
                    saveFile.write( saveDoc.toJson() );
				}
			}
		}

		return folders.size();
    }

	MainWindow w;
	//w.show();

    /// Here we perform the actual pair-wise correspondence:
    QString jobs_filename;

    if(parser.isSet("nogui") || parser.isSet("auto") || parser.isSet("sourceShape"))
    {
        if (parser.isSet("auto") || parser.isSet("sourceShape") || parser.isSet("targetShape"))
		{
			QString sourceShape = parser.value("sourceShape");
			QString targetShape = parser.value("targetShape");
			QVariantMap options;

            if(parser.isSet("g")) options["align"].setValue(true);
            if(parser.isSet("o")) options["roundtrip"].setValue(true);
            if(parser.isSet("k")) options["k"].setValue(parser.value("k").toInt());
			if(parser.isSet("q")) options["isQuietMode"].setValue(true);
            if(parser.isSet("c")) options["isAllowCutsJoins"].setValue(true);
            if(parser.isSet("m")) options["isIgnoreSymmetryGroups"].setValue(true);

            if(options["roundtrip"].toBool() || options["align"].toBool())
			{
				options["isManyTypesJobs"].setValue(true);
				options["isOutputMatching"].setValue(true);

				QTimer::singleShot(1, [sourceShape, targetShape, options]
				{
					int numJobs = 0;

					auto cur_options = options;

					QVector< QVector<QVariantMap> > reports;

					int numIter = 1;

					// Command line now only supports two tests.. GUI has more options
					if (cur_options["align"].toBool()) numIter = 2;

					for (int iter = 0; iter < numIter; iter++)
					{
						auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, cur_options));

						bp->jobUID = numJobs++;
						bp->run();

						reports << bp->jobReports;

						if (cur_options["roundtrip"].toBool())
						{
							auto bp2 = QSharedPointer<BatchProcess>(new BatchProcess(targetShape, sourceShape, cur_options));

							bp2->jobUID = numJobs++;
							bp2->run();

							reports << bp2->jobReports;
						}

						cur_options["isFlip"].setValue(true);
					}

					// Look at reports
					double minEnergy = 1.0;
					int totalTime = 0;
					QVariantMap minJob;
					for (auto & reportVec : reports)
					{
						for (auto & report : reportVec)
						{
							totalTime += report["search_time"].toInt();

							double c = report["min_cost"].toDouble();
							if (c < minEnergy){
								minEnergy = c;
								minJob = report;
							}
						}
					}

					std::cout << "\nJobs computed: " << numJobs << "\n";
					std::cout << minEnergy << " - " << qPrintable(minJob["img_file"].toString());

					// Aggregate results
					{
						QFile file("log.txt");
						if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
						{
                            QString thumb_filename = minJob["img_file"].toString();

							QTextStream out(&file);
                            out << sourceShape << "," << targetShape << "," << minJob["min_cost"].toDouble() << ","
                                << minJob["match_file"].toString() << "," << minJob["job_uid"].toInt() << ","
                                << (thumb_filename.isEmpty() ? "null" : thumb_filename) << "\n";
						}
                    }
                }); // end of QTimer::singleShot
            }
            else
            {
                auto bp = new BatchProcess(sourceShape, targetShape, options);
                QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
                QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
                bp->start();
            }

			return a.exec();
		}
		else
		{
			jobs_filename = parser.value("job");
			if (jobs_filename.isEmpty()){
				std::cout << "Please provide a job file.";
				return CommandLineError;
			}
		}

		std::cout << "Not enough arguments.";
		return CommandLineError;
    }
    else
	{
		jobs_filename = QFileDialog::getOpenFileName(&w, "Load Jobs", "", "Jobs File (*.json)");
    }

    QTimer::singleShot(0, [&] {
        BatchProcess * bp = new BatchProcess(jobs_filename);
        QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
		QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
        bp->start();
    });

    return a.exec();
}
Example #13
0
int main(int argc, char *argv[])
{
    QCoreApplication::setApplicationName("Embedded IDE");
    QCoreApplication::setOrganizationName("none");
    QCoreApplication::setOrganizationDomain("unknown.tk");

    QApplication app(argc, argv);
    QApplication::setWindowIcon(QIcon(":/images/embedded-ide.svg"));
    QTranslator tr;
    for(const auto& p: AppConfig::langPaths()) {
        if (tr.load(QLocale::system().name(), p)) {
            if (app.installTranslator(&tr)) {
                qDebug() << "load translations" << QLocale::system().name();
                break;
            }
        }
    }

    auto checkConfig = [&app, &tr](AppConfig *config) {
        app.setStyleSheet( config->useDarkStyle()?
            AppConfig::readEntireTextFile(":/qdarkstyle/style.qss"): ""
        );
        auto selectedLang = config->language();
        if (!selectedLang.isEmpty()) {
            for(const auto& p: AppConfig::langPaths()) {
                if (tr.load(selectedLang, p)) {
                    if (app.installTranslator(&tr)) {
                        qDebug() << "load translations" << QLocale::system().name();
                        break;
                    }
                }
            }
        }
    };
    QObject::connect(&AppConfig::instance(), &AppConfig::configChanged, [&checkConfig](AppConfig *config)
    {
        checkConfig(config);
        switch (config->networkProxyType()) {
        case AppConfig::NetworkProxyType::None:
            QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
            break;
        case AppConfig::NetworkProxyType::System:
            QNetworkProxyFactory::setUseSystemConfiguration(true);
            break;
        case AppConfig::NetworkProxyType::Custom:
            QNetworkProxy proxy(
                        QNetworkProxy::HttpProxy, config->networkProxyHost(),
                        static_cast<quint16>(config->networkProxyPort().toInt()));
            if (config->networkProxyUseCredentials()) {
                proxy.setUser(config->networkProxyUsername());
                proxy.setPassword(config->networkProxyPassword());
            }
            QNetworkProxy::setApplicationProxy(proxy);
            break;
        }
    });
    AppConfig::instance().load();
    checkConfig(&AppConfig::instance());


    QCommandLineParser opt;
    opt.addHelpOption();
    opt.addVersionOption();
    opt.addPositionalArgument("filename", "Makefile filename");
    opt.addOptions({
                       { { "e", "exec" }, "Execute stript or file", "execname" },
                       { { "d", "debug"}, "Enable debug" },
                       { { "s", "stacktrace" }, "Add stack trace to debug" }
                   });
    opt.process(app);

    if (opt.isSet("exec")) {
        QString execname = opt.value("exec");
        QProcess::startDetached(execname);
        return 0;
    }

    if (opt.isSet("debug")) {
        QString debugString = "[%{type}] %{appname} (%{file}:%{line}) - %{message}";
        if (opt.isSet("stacktrace"))
            debugString += "\n\t%{backtrace separator=\"\n\t\"}";
        qSetMessagePattern(debugString);
    } else
        qSetMessagePattern("");

    MainWindow w;
    w.show();

    if (!opt.positionalArguments().isEmpty()) {
        QString path = opt.positionalArguments().first();
        QTimer::singleShot(0, [path, &w]() { w.openProject(path); });
    }

    return QApplication::exec();
}
Example #14
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
	
	QCommandLineParser parser;
    parser.addHelpOption();
    parser.addPositionalArgument("file", QCoreApplication::translate("main", "The file to open."));
    parser.addOptions({
        { { "c", "curve" }, QString("Extract a curve.") },
        { { "s", "sheet" }, QString("Extract a sheet.") },
        { { "b", "box" }, QString("Uses bounding box.") },
		{ { "n", "nonmanifold" }, QString("Object is not clean.") },
		{ { "h", "concavehull" }, QString("Reconstruct using concavehull.") },
		{ { "v", "voxelize" }, QString("Reconstruct using voxels.") },
		{ { "r", "remesh" }, QString("Remesh to increase density.") },
		{ { "m", "medial" }, QString("Follow medial axis during skeletonization.") },
		{ { "f", "features" }, QString("Respect small features.") },
		{ { "V", "voxelparam" }, QString("Voxels size."), QString("voxel_param") },
		{ { "R", "remeshparam" }, QString("Remesh size."), QString("remesh_param") }
    });

	if (!parser.parse(QCoreApplication::arguments())) {
        QString errorText = parser.errorText();
        std::cout << qPrintable(errorText);
        return CommandLineError;
    }
	else
		parser.process(a);

    if(QCoreApplication::arguments().size() == 1)
    {
        std::cout << qPrintable(parser.helpText());
        return CommandLineHelpRequested;
    }

    // Perform operations
    {
		double VoxelParam = 0.05, RemeshParam = 0.02;

		if (parser.isSet("voxelparam")) VoxelParam = parser.value("voxelparam").toDouble();
		if (parser.isSet("remeshparam")) RemeshParam = parser.value("remeshparam").toDouble();

        QString filename = parser.positionalArguments().at(0);
        nurbs_plugin plugin(filename, !parser.isSet("nonmanifold"), 
			parser.isSet("b"), parser.isSet("h"), parser.isSet("v"), 
			parser.isSet("r"), parser.isSet("m"), parser.isSet("f"),
			VoxelParam, RemeshParam);

		if (parser.isSet("curve"))
		{
			auto c = plugin.toCurve();

			// Save control points
			QFile file("curve_output.points");
			if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return CommandLineError;
			QTextStream out(&file);
			out << QString("%1\n").arg(c.GetNumCtrlPoints());
			for (auto p : c.mCtrlPoint) out << QString("%1 %2 %3\n").arg(p.x()).arg(p.y()).arg(p.z());
		}

		if (parser.isSet("sheet"))
		{
			auto s = plugin.toSheet();

			// Save control points
			QFile file("sheet_output.points");
			if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return CommandLineError;
			QTextStream out(&file);
			out << QString("%1\n").arg(s.mNumUCtrlPoints);
			out << QString("%1\n").arg(s.mNumVCtrlPoints);
			for (auto row : s.mCtrlPoint) 
				for (auto p : row)
					out << QString("%1 %2 %3\n").arg(p.x()).arg(p.y()).arg(p.z());
		}
    }

    return CommandLineOk;
}