Example #1
0
int main(int argc, char ** argv)
{
    QUrl source("qrc:view.qml");

    QGuiApplication app(argc, argv);

    QCommandLineParser parser;
#ifndef QT_NO_NETWORKPROXY
    QCommandLineOption proxyHostOption("host", "The proxy host to use.", "host");
    parser.addOption(proxyHostOption);
    QCommandLineOption proxyPortOption("port", "The proxy port to use.", "port", "0");
    parser.addOption(proxyPortOption);
#endif // !QT_NO_NETWORKPROXY
    parser.addPositionalArgument("file", "The file to use.");
    QCommandLineOption helpOption = parser.addHelpOption();
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    QStringList arguments = QCoreApplication::arguments();
    if (!parser.parse(arguments)) {
        qWarning() << parser.helpText() << '\n' << parser.errorText();
        exit(1);
    }
    if (parser.isSet(helpOption)) {
        qWarning() << parser.helpText();
        exit(0);
    }
#ifndef QT_NO_NETWORKPROXY
    if (parser.isSet(proxyHostOption))
        proxyHost = parser.value(proxyHostOption);
    if (parser.isSet(proxyPortOption)) {
        bool ok = true;
        proxyPort = parser.value(proxyPortOption).toInt(&ok);
        if (!ok || proxyPort < 1 || proxyPort > 65535) {
            qWarning() << parser.helpText() << "\nNo valid port given. It should\
                          be a number between 1 and 65535";
            exit(1);
        }
    }
#endif // !QT_NO_NETWORKPROXY
    if (parser.positionalArguments().count() == 1)
        source = QUrl::fromLocalFile(parser.positionalArguments().first());

    QQuickView view;
    view.engine()->setNetworkAccessManagerFactory(new MyNetworkAccessManagerFactory);

    view.setSource(source);
    view.show();

    return app.exec();
}
void tst_QCommandLineParser::testUnknownOptionErrorHandling()
{
    QFETCH(QCommandLineParser::SingleDashWordOptionMode, parsingMode);
    QFETCH(QStringList, args);
    QFETCH(QStringList, expectedUnknownOptionNames);
    QFETCH(QString, expectedErrorText);

    QCoreApplication app(empty_argc, empty_argv);
    QCommandLineParser parser;
    parser.setSingleDashWordOptionMode(parsingMode);
    QVERIFY(parser.addOption(QCommandLineOption(QStringList() << "b" << "bool", QStringLiteral("a boolean option"))));
    QCOMPARE(parser.parse(args), expectedErrorText.isEmpty());
    QCOMPARE(parser.unknownOptionNames(), expectedUnknownOptionNames);
    QCOMPARE(parser.errorText(), expectedErrorText);
}
Example #3
0
void parseCommandLine()
{
  QCommandLineParser parser;
  parser.setApplicationDescription("An Ask Mona browser.");
  const auto helpOption = parser.addHelpOption();
  const auto versionOption = parser.addVersionOption();
  QCommandLineOption dataDirectoryOption(QStringList() << "d" << "datadir", "All data are saved into <directory>. Default is application directory.", "directory");
  parser.addOption(dataDirectoryOption);
  QCommandLineOption langOption(QStringList() << "l" << "lang", "Set application language.", "language");
  parser.addOption(langOption);

  if (!parser.parse(QCoreApplication::arguments())) {
    cout << qPrintable(parser.errorText()) << endl;
    exit(1);
  }
  if (parser.isSet(versionOption)) {
    cout << qPrintable(QCoreApplication::applicationName()) << " " << qPrintable(QCoreApplication::applicationVersion()) << endl;
    exit(0);
  }
  if (parser.isSet(helpOption)) {
    parser.showHelp();
    exit(0);
  }
  if (parser.isSet(dataDirectoryOption)) {
    setDataDir(parser.value(dataDirectoryOption));
  }
  auto translater = new QTranslator();
  QLocale l = QLocale::system();
  if (parser.isSet(langOption)) {
    l = QLocale(parser.value(langOption));
  }
  if (translater->load(l, ":/translations/")) {
    qApp->installTranslator(translater);
  } else {
    qWarning() << "Couldn't load language" << l.name();
  }
}
Example #4
0
bool Settings::parseCommandLine()
{
    QCommandLineParser parser;
    parser.setApplicationDescription("MapMaker\n\n"
                                     "Usage: mapmaker -m map.json -i imagesDirectory");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption mapFilenameOption(QStringList() << "m" << "map",
                                         tr("Map filename"),
                                         /* valueName */ tr("map.mmj"),
                                         /* defaultValue */ QString());
    parser.addOption(mapFilenameOption);

    QCommandLineOption imagesDirectoryOption(QStringList() << "i" << "imgdir",
                                             tr("Images directory"),
                                             /* valueName */ tr("directory"),
                                             /* defaultValue */ QString());
    parser.addOption(imagesDirectoryOption);

    if (parser.parse(qApp->arguments())) {
        parser.process(qApp->arguments());
    } else {
        qerr << parser.errorText() << endl;
    }

    if (!parser.positionalArguments().isEmpty())
        mapFilename_ = parser.positionalArguments().first();

    QString mapFilename = parser.value(mapFilenameOption);
    if (!mapFilename.isEmpty())
        mapFilename_ = mapFilename;
    commandline_.imagesDirectory_ = parser.value(imagesDirectoryOption);

    return true;
}
// Parse the command line a use options to override the MapConfig defaults
bool parseCommandLine(MapConfig& config, QString& error)
{
    QCommandLineParser parser;
    const QCommandLineOption helpOption = parser.addHelpOption();

    QCommandLineOption server(QStringList() << "s" << "server-url",
            QCoreApplication::translate("main", "Map tile server URL with trailing /"),
            QCoreApplication::translate("main", "URL"));
    parser.addOption(server);

    QCommandLineOption format(QStringList() << "f" << "image-format",
            QCoreApplication::translate("main", "Map tile image format (e.g. png)"),
            QCoreApplication::translate("main", "format"));
    parser.addOption(format);
    
    QCommandLineOption min_zoom(QStringList() << "min-zoom",
            QCoreApplication::translate("main", "Map minimum zoom level"),
            QCoreApplication::translate("main", "zoom"));
    parser.addOption(min_zoom);

    QCommandLineOption max_zoom(QStringList() << "max-zoom",
            QCoreApplication::translate("main", "Map maximum zoom level"),
            QCoreApplication::translate("main", "zoom"));
    parser.addOption(max_zoom);

    QCommandLineOption tile_size(QStringList() << "t" << "tile-size",
            QCoreApplication::translate("main", "Map tile size in pixels (e.g. 256)"),
            QCoreApplication::translate("main", "size"));
    parser.addOption(tile_size);

    QCommandLineOption cache_size(QStringList() << "c" << "cache-size",
            QCoreApplication::translate("main", "Map tile cache size in tiles (e.g. 512)"),
            QCoreApplication::translate("main", "cache"));
    parser.addOption(cache_size);

    if (!parser.parse(QGuiApplication::arguments())) {
        error = parser.errorText();
        return true;
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        return false;
    }

    if (parser.isSet(server)) {
        QString s = parser.value(server);
        QHostInfo info = QHostInfo::fromName(s);
        if (info.error() == QHostInfo::NoError) {
            config.server = s;
        } else {
            qDebug() << "Invalid map tile server URL: " << s;
        }
    }
    if (parser.isSet(format)) {
        config.format = parser.value(format);
    }
    if (parser.isSet(min_zoom)) {
        QVariant range(parser.value(min_zoom));
        config.min_zoom = range.toInt();
    }
    if (parser.isSet(max_zoom)) {
        QVariant range(parser.value(max_zoom));
        config.max_zoom = range.toInt();
    }
    if (parser.isSet(tile_size)) {
        QVariant range(parser.value(tile_size));
        config.tile_size = range.toInt();
    }
    if (parser.isSet(cache_size)) {
        QVariant range(parser.value(cache_size));
        config.cache_size = size_t(range.toInt());
    }
    return false;
}
Example #6
0
VHACDUtilApp::VHACDUtilApp(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
    vhacd::VHACDUtil vUtil;

    // parse command-line
    QCommandLineParser parser;
    parser.setApplicationDescription("High Fidelity Object Decomposer");
    parser.addHelpOption();

    const QCommandLineOption helpOption = parser.addHelpOption();

    const QCommandLineOption splitOption("split", "split input-file into one mesh per output-file");
    parser.addOption(splitOption);

    const QCommandLineOption fattenFacesOption("f", "fatten faces");
    parser.addOption(fattenFacesOption);

    const QCommandLineOption generateHullsOption("g", "output convex hull approximations");
    parser.addOption(generateHullsOption);

    const QCommandLineOption inputFilenameOption("i", "input file", "filename.fbx");
    parser.addOption(inputFilenameOption);

    const QCommandLineOption outputFilenameOption("o", "output file", "filename.obj");
    parser.addOption(outputFilenameOption);

    const QCommandLineOption outputCentimetersOption("c", "output units are centimeters");
    parser.addOption(outputCentimetersOption);

    const QCommandLineOption startMeshIndexOption("s", "start-mesh index", "0");
    parser.addOption(startMeshIndexOption);

    const QCommandLineOption endMeshIndexOption("e", "end-mesh index", "0");
    parser.addOption(endMeshIndexOption);

    const QCommandLineOption minimumMeshSizeOption("m", "minimum mesh (diagonal) size to consider", "0");
    parser.addOption(minimumMeshSizeOption);

    const QCommandLineOption maximumMeshSizeOption("x", "maximum mesh (diagonal) size to consider", "0");
    parser.addOption(maximumMeshSizeOption);

    const QCommandLineOption vHacdResolutionOption("resolution", "Maximum number of voxels generated during the "
                                                   "voxelization stage (range=10,000-16,000,000)", "100000");
    parser.addOption(vHacdResolutionOption);

    const QCommandLineOption vHacdDepthOption("depth", "Maximum number of clipping stages. During each split stage, parts "
                                              "with a concavity higher than the user defined threshold are clipped "
                                              "according the \"best\" clipping plane (range=1-32)", "20");
    parser.addOption(vHacdDepthOption);


    const QCommandLineOption vHacdAlphaOption("alpha", "Controls the bias toward clipping along symmetry "
                                              "planes (range=0.0-1.0)", "0.05");
    parser.addOption(vHacdAlphaOption);

    const QCommandLineOption vHacdBetaOption("beta", "Controls the bias toward clipping along revolution "
                                             "axes (range=0.0-1.0)", "0.05");
    parser.addOption(vHacdBetaOption);

    const QCommandLineOption vHacdGammaOption("gamma", "Controls the maximum allowed concavity during the "
                                              "merge stage (range=0.0-1.0)", "0.00125");
    parser.addOption(vHacdGammaOption);

    const QCommandLineOption vHacdDeltaOption("delta", "Controls the bias toward maximaxing local "
                                              "concavity (range=0.0-1.0)", "0.05");
    parser.addOption(vHacdDeltaOption);

    const QCommandLineOption vHacdConcavityOption("concavity", "Maximum allowed concavity (range=0.0-1.0)", "0.0025");
    parser.addOption(vHacdConcavityOption);

    const QCommandLineOption vHacdPlanedownsamplingOption("planedownsampling", "Controls the granularity of the search for"
                                                          " the \"best\" clipping plane (range=1-16)", "4");
    parser.addOption(vHacdPlanedownsamplingOption);

    const QCommandLineOption vHacdConvexhulldownsamplingOption("convexhulldownsampling", "Controls the precision of the "
                                                               "convex-hull generation process during the clipping "
                                                               "plane selection stage (range=1-16)", "4");
    parser.addOption(vHacdConvexhulldownsamplingOption);

    // pca
    // mode

    const QCommandLineOption vHacdMaxVerticesPerCHOption("maxvertices", "Controls the maximum number of triangles per "
                                                         "convex-hull (range=4-1024)", "64");
    parser.addOption(vHacdMaxVerticesPerCHOption);

    // minVolumePerCH
    // convexhullApproximation


    if (!parser.parse(QCoreApplication::arguments())) {
        qCritical() << parser.errorText() << endl;
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        Q_UNREACHABLE();
    }

    bool outputCentimeters = parser.isSet(outputCentimetersOption);

    bool fattenFaces = parser.isSet(fattenFacesOption);
    bool generateHulls = parser.isSet(generateHullsOption);
    bool splitModel = parser.isSet(splitOption);


    QString inputFilename;
    if (parser.isSet(inputFilenameOption)) {
        inputFilename = parser.value(inputFilenameOption);
    }

    QString outputFilename;
    if (parser.isSet(outputFilenameOption)) {
        outputFilename = parser.value(outputFilenameOption);
    }


    if (inputFilename == "") {
        cerr << "input filename is required.";
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (outputFilename == "") {
        cerr << "output filename is required.";
        parser.showHelp();
        Q_UNREACHABLE();
    }

    int startMeshIndex = -1;
    if (parser.isSet(startMeshIndexOption)) {
        startMeshIndex = parser.value(startMeshIndexOption).toInt();
    }

    int endMeshIndex = -1;
    if (parser.isSet(endMeshIndexOption)) {
        endMeshIndex = parser.value(endMeshIndexOption).toInt();
    }

    float minimumMeshSize = 0.0f;
    if (parser.isSet(minimumMeshSizeOption)) {
        minimumMeshSize = parser.value(minimumMeshSizeOption).toFloat();
    }

    float maximumMeshSize = 0.0f;
    if (parser.isSet(maximumMeshSizeOption)) {
        maximumMeshSize = parser.value(maximumMeshSizeOption).toFloat();
    }

    int vHacdResolution = 100000;
    if (parser.isSet(vHacdResolutionOption)) {
        vHacdResolution = parser.value(vHacdResolutionOption).toInt();
    }

    int vHacdDepth = 20;
    if (parser.isSet(vHacdDepthOption)) {
        vHacdDepth = parser.value(vHacdDepthOption).toInt();
    }

    float vHacdAlpha = 0.05f;
    if (parser.isSet(vHacdAlphaOption)) {
        vHacdAlpha = parser.value(vHacdAlphaOption).toFloat();
    }

    float vHacdBeta = 0.05f;
    if (parser.isSet(vHacdBetaOption)) {
        vHacdBeta = parser.value(vHacdBetaOption).toFloat();
    }

    float vHacdGamma = 0.00125f;
    if (parser.isSet(vHacdGammaOption)) {
        vHacdGamma = parser.value(vHacdGammaOption).toFloat();
    }

    float vHacdDelta = 0.05f;
    if (parser.isSet(vHacdDeltaOption)) {
        vHacdDelta = parser.value(vHacdDeltaOption).toFloat();
    }

    float vHacdConcavity = 0.0025f;
    if (parser.isSet(vHacdConcavityOption)) {
        vHacdConcavity = parser.value(vHacdConcavityOption).toFloat();
    }

    int vHacdPlanedownsampling = 4;
    if (parser.isSet(vHacdPlanedownsamplingOption)) {
        vHacdPlanedownsampling = parser.value(vHacdPlanedownsamplingOption).toInt();
    }

    int vHacdConvexhulldownsampling = 4;
    if (parser.isSet(vHacdConvexhulldownsamplingOption)) {
        vHacdConvexhulldownsampling = parser.value(vHacdConvexhulldownsamplingOption).toInt();
    }

    int vHacdMaxVerticesPerCH = 64;
    if (parser.isSet(vHacdMaxVerticesPerCHOption)) {
        vHacdMaxVerticesPerCH = parser.value(vHacdMaxVerticesPerCHOption).toInt();
    }

    if (!splitModel && !generateHulls && !fattenFaces) {
        cerr << "\nNothing to do!  Use -g or -f or --split\n\n";
        parser.showHelp();
        Q_UNREACHABLE();
    }


    // load the mesh 

    FBXGeometry fbx;
    auto begin = std::chrono::high_resolution_clock::now();
    if (!vUtil.loadFBX(inputFilename, fbx)){
        cout << "Error in opening FBX file....";
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto loadDuration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();


    if (splitModel) {
        QVector<QString> infileExtensions = {"fbx", "obj"};
        QString baseFileName = fileNameWithoutExtension(outputFilename, infileExtensions);
        int count = 0;
        foreach (const FBXMesh& mesh, fbx.meshes) {
            foreach (const FBXMeshPart &meshPart, mesh.parts) {
                QString outputFileName = baseFileName + "-" + QString::number(count) + ".obj";
                writeOBJ(outputFileName, fbx, outputCentimeters, count);
                count++;
                (void)meshPart; // quiet warning
            }
        }
    }

    if (generateHulls) {
        VHACD::IVHACD::Parameters params;
        vhacd::ProgressCallback pCallBack;

        //set parameters for V-HACD
        params.m_callback = &pCallBack; //progress callback
        params.m_resolution = vHacdResolution;
        params.m_depth = vHacdDepth;
        params.m_concavity = vHacdConcavity;
        params.m_delta = vHacdDelta;
        params.m_planeDownsampling = vHacdPlanedownsampling;
        params.m_convexhullDownsampling = vHacdConvexhulldownsampling;
        params.m_alpha = vHacdAlpha;
        params.m_beta = vHacdBeta;
        params.m_gamma = vHacdGamma;
        params.m_pca = 0; // 0  enable/disable normalizing the mesh before applying the convex decomposition
        params.m_mode = 0; // 0: voxel-based (recommended), 1: tetrahedron-based
        params.m_maxNumVerticesPerCH = vHacdMaxVerticesPerCH;
        params.m_minVolumePerCH = 0.0001; // 0.0001
        params.m_callback = 0; // 0
        params.m_logger = 0; // 0
        params.m_convexhullApproximation = true; // true
        params.m_oclAcceleration = true; // true

        //perform vhacd computation
        begin = std::chrono::high_resolution_clock::now();

        FBXGeometry result;
        if (!vUtil.computeVHACD(fbx, params, result, startMeshIndex, endMeshIndex,
                                minimumMeshSize, maximumMeshSize)) {
            cout << "Compute Failed...";
        }
        end = std::chrono::high_resolution_clock::now();
        auto computeDuration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count();

        int totalVertices = 0;
        int totalTriangles = 0;
        int totalMeshParts = 0;
        foreach (const FBXMesh& mesh, result.meshes) {
            totalVertices += mesh.vertices.size();
            foreach (const FBXMeshPart &meshPart, mesh.parts) {
                totalTriangles += meshPart.triangleIndices.size() / 3;
                // each quad was made into two triangles
                totalTriangles += 2 * meshPart.quadIndices.size() / 4;
                totalMeshParts++;
            }
        }

        int totalHulls = result.meshes[0].parts.size();
        cout << endl << "Summary of V-HACD Computation..................." << endl;
        cout << "File Path          : " << inputFilename.toStdString() << endl;
        cout << "Number Of Meshes   : " << totalMeshParts << endl;
        cout << "Total vertices     : " << totalVertices << endl;
        cout << "Total Triangles    : " << totalTriangles << endl;
        cout << "Total Convex Hulls : " << totalHulls << endl;
        cout << "Total FBX load time: " << (double)loadDuration / 1000000000.00 << " seconds" << endl;
        cout << "V-HACD Compute time: " << (double)computeDuration / 1000000000.00 << " seconds" << endl;

        writeOBJ(outputFilename, result, outputCentimeters);
    }

    if (fattenFaces) {
        FBXGeometry newFbx;
        FBXMesh result;

        // count the mesh-parts
        unsigned int meshCount = 0;
        foreach (const FBXMesh& mesh, fbx.meshes) {
            meshCount += mesh.parts.size();
        }

        if (startMeshIndex < 0) {
            startMeshIndex = 0;
        }
        if (endMeshIndex < 0) {
            endMeshIndex = meshCount;
        }

        unsigned int meshPartCount = 0;
        result.modelTransform = glm::mat4(); // Identity matrix
        foreach (const FBXMesh& mesh, fbx.meshes) {
            vUtil.fattenMeshes(mesh, result, meshPartCount, startMeshIndex, endMeshIndex);
        }

        newFbx.meshes.append(result);
        writeOBJ(outputFilename, newFbx, outputCentimeters);
    }
}
Example #7
0
int main(int argc, char* argv[])
{
    qInstallMessageHandler(messageHandler);

    Application application(argc, argv);
    application.setApplicationName("CasparCG Client");
    application.setApplicationVersion(QString("%1.%2.%3.%4").arg(MAJOR_VERSION).arg(MINOR_VERSION).arg(REVISION_VERSION).arg(BUILD_VERSION));

    qDebug("Starting %s %s", qPrintable(application.applicationName()), qPrintable(application.applicationVersion()));

    CommandLineArgs args;
    QCommandLineParser parser;
    switch (parseCommandLine(parser, &args))
    {
        case CommandLineOk:
            break;
        case CommandLineError:
            qCritical("Unable to parse command line: %s", qPrintable(parser.errorText()));
            parser.showHelp();
            return 0;
        case CommandLineVersionRequested:
            parser.showVersion();
            return 0;
        case CommandLineHelpRequested:
            parser.showHelp();
            return 0;
    }

    QSplashScreen splashScreen(QPixmap(":/Graphics/Images/SplashScreen.png"));
    splashScreen.show();

    loadDatabase(&args);
    DatabaseManager::getInstance().initialize();

    loadStyleSheets(application);
    loadFonts(application);

    EventManager::getInstance().initialize();
    GpiManager::getInstance().initialize();

    MainWindow window;
    splashScreen.finish(&window);

    loadConfiguration(application, window, &args);

    window.show();

    LibraryManager::getInstance().initialize();
    DeviceManager::getInstance().initialize();
    AtemDeviceManager::getInstance().initialize();
    TriCasterDeviceManager::getInstance().initialize();
    OscDeviceManager::getInstance().initialize();
    OscWebSocketManager::getInstance().initialize();

    int returnValue = application.exec();

    EventManager::getInstance().uninitialize();
    DatabaseManager::getInstance().uninitialize();
    GpiManager::getInstance().uninitialize();
    OscWebSocketManager::getInstance().uninitialize();
    OscDeviceManager::getInstance().uninitialize();
    TriCasterDeviceManager::getInstance().uninitialize();
    AtemDeviceManager::getInstance().uninitialize();
    DeviceManager::getInstance().uninitialize();
    LibraryManager::getInstance().uninitialize();

    return returnValue;
}
Example #8
0
bool
parseCommandLine( QCoreApplication& app, QCommandLineParser& parser, CliOptions& options, qint32& profileId,
                  QString& errmsg )
{
    parser.setApplicationDescription( "RedTimer Command Line Interface" );

    // Commands
    QMap<QString,QString> commands;
    commands.insert( "create", "Create a new issue" );
    commands.insert( "issue",  "Get the current issue ID" );
    commands.insert( "start",  "Start issue tracking" );
    commands.insert( "stop",   "Stop issue tracking" );

    QStringList descr;
    QMapIterator<QString, QString> cmd( commands );
    while( cmd.hasNext() )
    {
        cmd.next();

        QString data;
        QTextStream out( &data );
        out.setFieldAlignment( QTextStream::AlignLeft );
        out << qSetFieldWidth(10) << cmd.key() << cmd.value();
        descr.push_back( data );
    }

    parser.addPositionalArgument( "command", descr.join("\n"), "create|issue|start|stop" );

    // Program parameters
    parser.addOption( {"profile-id", "Redmine instance to send the command to", "ID"} );

    // Command parameters
    parser.addOption( {"assignee-id",        "Redmine assignee ID",      "ID"} );
    parser.addOption( {"issue-id",           "Redmine issue ID",         "ID"} );
    parser.addOption( {"parent-id",          "Redmine parent issue ID",  "ID"} );
    parser.addOption( {"project-id",         "Redmine project ID",       "ID"} );
    parser.addOption( {"tracker-id",         "Redmine tracker ID",       "ID"} );
    parser.addOption( {"version-id",         "Redmine version ID",       "ID"} );
    parser.addOption( {"external-id",        "External issue ID",        "text"} );
    parser.addOption( {"external-parent-id", "External parent issue ID", "text"} );
    parser.addOption( {"subject",            "Issue subject",            "text"} );
    parser.addOption( {"description",        "Issue description",        "text"} );

    // General parameters
    parser.addHelpOption();
    parser.addVersionOption();

    // Process command line options
    if( !parser.parse(app.arguments()) )
    {
        errmsg = parser.errorText();
        return false;
    }

    if( parser.isSet("help") )
        return false;


    // Get the command

    const QStringList positionalArguments = parser.positionalArguments();

    if( positionalArguments.isEmpty() )
    {
        errmsg = "No command specified.";
        return false;
    }

    if( positionalArguments.size() > 1 )
    {
        errmsg = "Several commands specified.";
        return false;
    }

    options.command = positionalArguments.first();

    if( commands.find(options.command) == commands.end() )
    {
        errmsg = QString("Command '%1' not found.").arg(options.command);
        return false;
    }

    auto getNumericId = [&]( const QString& option, qint32& id )
    {
        if( !parser.isSet(option) )
            return true;

        QString idString = parser.value( option );
        bool ok;
        id = idString.toInt( &ok );

        if( !ok )
        {
            errmsg = QString("Option '--%1' expects a numeric ID.").arg(option);
            return false;
        }

        return true;
    };

    auto getString = [&]( const QString& option, QString& str, bool allowWhitespaces )
    {
        if( !parser.isSet(option) )
            return true;

        str = parser.value( option );

        if( !allowWhitespaces && str.contains( QRegularExpression("\\W")) )
        {
            errmsg = QString("Option '--%1' must not contain whitespaces.").arg(option);
            return false;
        }

        return true;
    };

    if( !getNumericId("profile-id", profileId) )
        return false;

    if( !getNumericId("assignee-id", options.assigneeId) )
        return false;

    if( !getNumericId("issue-id", options.issueId) )
        return false;

    if( !getNumericId("parent-id", options.parentId) )
        return false;

    if( !getNumericId("project-id", options.projectId) )
        return false;

    if( !getNumericId("tracker-id", options.trackerId) )
        return false;

    if( !getNumericId("version-id", options.versionId) )
        return false;

    if( !getString("external-id", options.externalId, false) )
        return false;

    if( !getString("external-parent-id", options.externalParentId, false) )
        return false;

    if( !getString("description", options.description, true) )
        return false;

    if( !getString("subject", options.subject, true) )
        return false;

    auto isValid = [&]( const QString option, bool allowed )
    {
        if( allowed && !parser.isSet(option) )
        {
            errmsg = QString("Option '--%1' required by command '%2'.").arg(option).arg(options.command);
            return false;
        }
        else if( !allowed && parser.isSet(option) )
        {
            errmsg = QString("Option '--%1' not allowed for command '%2'.").arg(option).arg(options.command);
            return false;
        }

        return true;
    };

    // Required: issue-id
    if( options.command == "start" )
    {
        // Required
        if( !isValid("issue-id", true) )
            return false;

        // Not allowed
        if( !isValid("assignee-id", false) )
            return false;
        if( !isValid("parent-id", false) )
            return false;
        if( !isValid("project-id", false) )
            return false;
        if( !isValid("tracker-id", false) )
            return false;
        if( !isValid("version-id", false) )
            return false;
        if( !isValid("external-id", false) )
            return false;
        if( !isValid("external-parent-id", false) )
            return false;
        if( !isValid("subject", false) )
            return false;
        if( !isValid("description", false) )
            return false;
    }
    else if( options.command == "create" )
    {
        // Required
        if( !isValid("project-id", true) )
            return false;
        if( !isValid("subject", true) )
            return false;

        // Not allowed
        if( !isValid("issue-id", false) )
            return false;

        // Exclusive
        if( parser.isSet("parent-id") && parser.isSet("external-parent-id") )
        {
            errmsg = "Options '--parent-id' and '--external-parent-id' may not be combined.";
            return false;
        }
    }
    else
    {
        // Not allowed
        if( !isValid("assignee-id", false) )
            return false;
        if( !isValid("issue-id", false) )
            return false;
        if( !isValid("parent-id", false) )
            return false;
        if( !isValid("project-id", false) )
            return false;
        if( !isValid("tracker-id", false) )
            return false;
        if( !isValid("version-id", false) )
            return false;
        if( !isValid("external-id", false) )
            return false;
        if( !isValid("external-parent-id", false) )
            return false;
        if( !isValid("subject", false) )
            return false;
        if( !isValid("description", false) )
            return false;
    }

    return true;
}
Example #9
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 #10
0
AssignmentClientApp::AssignmentClientApp(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
#   ifndef WIN32
    setvbuf(stdout, NULL, _IOLBF, 0);
#   endif

    // setup a shutdown event listener to handle SIGTERM or WM_CLOSE for us
#   ifdef _WIN32
    installNativeEventFilter(&ShutdownEventListener::getInstance());
#   else
    ShutdownEventListener::getInstance();
#   endif

    // parse command-line
    QCommandLineParser parser;
    parser.setApplicationDescription("High Fidelity Assignment Client");
    parser.addHelpOption();

    const QCommandLineOption helpOption = parser.addHelpOption();

    const QCommandLineOption clientTypeOption(ASSIGNMENT_TYPE_OVERRIDE_OPTION,
                                              "run single assignment client of given type", "type");
    parser.addOption(clientTypeOption);

    const QCommandLineOption poolOption(ASSIGNMENT_POOL_OPTION, "set assignment pool", "pool-name");
    parser.addOption(poolOption);

    const QCommandLineOption portOption(ASSIGNMENT_CLIENT_LISTEN_PORT_OPTION,
                                        "UDP port for this assignment client (or monitor)", "port");
    parser.addOption(portOption);

    const QCommandLineOption walletDestinationOption(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION,
                                                     "set wallet destination", "wallet-uuid");
    parser.addOption(walletDestinationOption);

    const QCommandLineOption assignmentServerHostnameOption(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION,
                                                            "set assignment-server hostname", "hostname");
    parser.addOption(assignmentServerHostnameOption);

    const QCommandLineOption assignmentServerPortOption(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION,
                                                        "set assignment-server port", "port");
    parser.addOption(assignmentServerPortOption);

    const QCommandLineOption numChildsOption(ASSIGNMENT_NUM_FORKS_OPTION, "number of children to fork", "child-count");
    parser.addOption(numChildsOption);

    const QCommandLineOption minChildsOption(ASSIGNMENT_MIN_FORKS_OPTION, "minimum number of children", "child-count");
    parser.addOption(minChildsOption);

    const QCommandLineOption maxChildsOption(ASSIGNMENT_MAX_FORKS_OPTION, "maximum number of children", "child-count");
    parser.addOption(maxChildsOption);

    const QCommandLineOption monitorPortOption(ASSIGNMENT_CLIENT_MONITOR_PORT_OPTION, "assignment-client monitor port", "port");
    parser.addOption(monitorPortOption);

    const QCommandLineOption httpStatusPortOption(ASSIGNMENT_HTTP_STATUS_PORT, "http status server port", "http-status-port");
    parser.addOption(httpStatusPortOption);

    const QCommandLineOption logDirectoryOption(ASSIGNMENT_LOG_DIRECTORY, "directory to store logs", "log-directory");
    parser.addOption(logDirectoryOption);

    if (!parser.parse(QCoreApplication::arguments())) {
        qCritical() << parser.errorText() << endl;
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        Q_UNREACHABLE();
    }

    const QVariantMap argumentVariantMap = HifiConfigVariantMap::mergeCLParametersWithJSONConfig(arguments());

    unsigned int numForks = 0;
    if (parser.isSet(numChildsOption)) {
        numForks = parser.value(numChildsOption).toInt();
    }

    unsigned int minForks = 0;
    if (parser.isSet(minChildsOption)) {
        minForks = parser.value(minChildsOption).toInt();
    }

    unsigned int maxForks = 0;
    if (parser.isSet(maxChildsOption)) {
        maxForks = parser.value(maxChildsOption).toInt();
    }

    unsigned short monitorPort = 0;
    if (parser.isSet(monitorPortOption)) {
        monitorPort = parser.value(monitorPortOption).toUShort();
    }

    if (!numForks && minForks) {
        // if the user specified --min but not -n, set -n to --min
        numForks = minForks;
    }

    quint16 httpStatusPort { 0 };
    if (parser.isSet(httpStatusPortOption)) {
        httpStatusPort = parser.value(httpStatusPortOption).toUShort();
    }

    QString logDirectory;

    if (parser.isSet(logDirectoryOption)) {
        logDirectory = parser.value(logDirectoryOption);
    }


    Assignment::Type requestAssignmentType = Assignment::AllTypes;
    if (argumentVariantMap.contains(ASSIGNMENT_TYPE_OVERRIDE_OPTION)) {
        requestAssignmentType = (Assignment::Type) argumentVariantMap.value(ASSIGNMENT_TYPE_OVERRIDE_OPTION).toInt();
    }
    if (parser.isSet(clientTypeOption)) {
        requestAssignmentType = (Assignment::Type) parser.value(clientTypeOption).toInt();
    }

    QString assignmentPool;
    // check for an assignment pool passed on the command line or in the config
    if (argumentVariantMap.contains(ASSIGNMENT_POOL_OPTION)) {
        assignmentPool = argumentVariantMap.value(ASSIGNMENT_POOL_OPTION).toString();
    }
    if (parser.isSet(poolOption)) {
        assignmentPool = parser.value(poolOption);
    }

    QUuid walletUUID;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        walletUUID = argumentVariantMap.value(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION).toString();
    }
    if (parser.isSet(walletDestinationOption)) {
        walletUUID = parser.value(walletDestinationOption);
    }

    QString assignmentServerHostname;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        assignmentServerHostname = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION).toString();
    }
    if (parser.isSet(assignmentServerHostnameOption)) {
        assignmentServerHostname = parser.value(assignmentServerHostnameOption);
    }

    // check for an overriden assignment server port
    quint16 assignmentServerPort = DEFAULT_DOMAIN_SERVER_PORT;
    if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) {
        assignmentServerPort = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION).toUInt();
    }

    if (parser.isSet(assignmentServerPortOption)) {
        assignmentServerPort = parser.value(assignmentServerPortOption).toInt();
    }

    // check for an overidden listen port
    quint16 listenPort = 0;
    if (argumentVariantMap.contains(ASSIGNMENT_CLIENT_LISTEN_PORT_OPTION)) {
        listenPort = argumentVariantMap.value(ASSIGNMENT_CLIENT_LISTEN_PORT_OPTION).toUInt();
    }

    if (parser.isSet(numChildsOption)) {
        if (minForks && minForks > numForks) {
            qCritical() << "--min can't be more than -n";
            parser.showHelp();
            Q_UNREACHABLE();
        }
        if (maxForks && maxForks < numForks) {
            qCritical() << "--max can't be less than -n";
            parser.showHelp();
            Q_UNREACHABLE();
        }
    }

    QThread::currentThread()->setObjectName("main thread");

    DependencyManager::registerInheritance<LimitedNodeList, NodeList>();

    if (numForks || minForks || maxForks) {
        AssignmentClientMonitor* monitor =  new AssignmentClientMonitor(numForks, minForks, maxForks,
                                                                        requestAssignmentType, assignmentPool,
                                                                        listenPort, walletUUID, assignmentServerHostname,
                                                                        assignmentServerPort, httpStatusPort, logDirectory);
        monitor->setParent(this);
        connect(this, &QCoreApplication::aboutToQuit, monitor, &AssignmentClientMonitor::aboutToQuit);
    } else {
        AssignmentClient* client = new AssignmentClient(requestAssignmentType, assignmentPool, listenPort,
                                                        walletUUID, assignmentServerHostname,
                                                        assignmentServerPort, monitorPort);
        client->setParent(this);
        connect(this, &QCoreApplication::aboutToQuit, client, &AssignmentClient::aboutToQuit);
    }
}
Example #11
0
CommandLineParseResult parseCommandLine(QCommandLineParser &parser, CLOptions *options, QString *errorMessage)
{

    parser.addPositionalArgument("log", QCoreApplication::translate("main", "File where the log will be saved."));

    // A file bname (-f, --force)
    const QCommandLineOption forceOption(QStringList() << "f" << "force",
                                         QCoreApplication::translate("main", "Force log file overwrite if applicable."));

    parser.addOption(forceOption);

    // The voltageToCurrent gain (-g, --gain)
    const QCommandLineOption gainOption(QStringList() << "g" << "gain",
                                        QCoreApplication::translate("main", "Microamps per volt setting for electrode activation circuit."),
                                        QCoreApplication::translate("main", "currentGain"));
    parser.addOption(gainOption);

    // Help and version options
    const QCommandLineOption helpOption = parser.addHelpOption();
    const QCommandLineOption versionOption = parser.addVersionOption();

    if (!parser.parse(QCoreApplication::arguments())) {
        *errorMessage = parser.errorText();
        return CommandLineError;
    }

    if (parser.isSet(versionOption))
        return CommandLineVersionRequested;

    if (parser.isSet(helpOption))
        return CommandLineHelpRequested;

    if (parser.isSet(forceOption)) {
        options->force = true;
    }
    else
    {
        options->force = false;
    }


    const QStringList positionalArguments = parser.positionalArguments();
    if (positionalArguments.isEmpty()) {
        *errorMessage = "A save location for the log file was not provided.";
        return CommandLineError;
    }
    if (positionalArguments.size() > 1) {
        *errorMessage = "Several 'log' arguments specified.";
        return CommandLineError;
    }

    QString fname = positionalArguments.first();
    if (!fname.endsWith(".json")) {
        fname.append(".json");
    }

    options->fid = QFileInfo(fname);

    if (!QDir(options->fid.absoluteDir()).exists() ) {
        *errorMessage = "Selected log file save directory does not exist: " + options->fid.path();
        return CommandLineError;
    }
    if (options->fid.exists() && options->fid.isFile() && !options->force) {
        *errorMessage = "Selected log file already exists, use the -f option if you wish to overwrite: " + options->fid.absoluteFilePath();
        return CommandLineError;
    }

    if (parser.isSet(gainOption)) {
        const double gain = parser.value(gainOption).toDouble();
        if (gain < 0) {
            *errorMessage = "The voltage to current gain cannot be negative,";
            return CommandLineError;
        }
        options->currentGain = gain;
    }
    else
    {
        cout << "Warning: no current gain was not provided. Assuming 10uA/3.3V." << endl;
        options->currentGain = 10.0/3.3;
    }

    return CommandLineOk;
}
Example #12
0
CommandLineParseResult parseCommandLine(QCommandLineParser &parser, const QStringList &arguments, ParsedOptions &options) {
    QCommandLineOption basePackageOption(QStringList() << "b" << "base-package",
                                        "Path to the base package dir",
                                        "directory");
    parser.addOption(basePackageOption);

    QCommandLineOption newPackageOption(QStringList() << "n" << "new-package",
                                        "Path to the new package dir",
                                        "directory");
    parser.addOption(newPackageOption);

    QCommandLineOption outputOption(QStringList() << "o" << "output",
                                        "Path to the result package file",
                                        "filepath");
    parser.addOption(outputOption);

    const QCommandLineOption helpOption = parser.addHelpOption();

    CommandLineParseResult result = CommandLineError;

    do {
        if (!parser.parse(arguments)) {
            std::cerr << parser.errorText().toStdString();
            break;
        }

        if (parser.isSet(helpOption)) {
            result = CommandLineHelpRequested;
            break;
        }

        if (parser.isSet(basePackageOption)) {
            const QString baseDir = parser.value(basePackageOption);
            if (!QDir(baseDir).exists()) {
                std::cerr << "Directory not found: " << baseDir.toStdString();
                break;
            } else {
                options.m_BaseDir = baseDir;
            }
        } else {
            std::cerr << "Base package path is missing" << std::endl;
            break;
        }

        if (parser.isSet(newPackageOption)) {
            const QString newDir = parser.value(newPackageOption);
            if (!QDir(newDir).exists()) {
                std::cerr << "Directory not found: " << newDir.toStdString();
                break;
            } else {
                options.m_NewDir = newDir;
            }
        } else {
            std::cerr << "New package path is missing" << std::endl;
            break;
        }

        if (parser.isSet(outputOption)) {
            options.m_JsonPath = parser.value(outputOption);
        } else {
            options.m_JsonPath = DEFAULT_OUTPUT_NAME;
        }
    } while (false);

    return result;
}
Example #13
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;
}
Example #14
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QCoreApplication::setApplicationVersion(QT_VERSION_STR);
    QCoreApplication::setApplicationName(QStringLiteral("imagegestures"));
    QGuiApplication::setApplicationDisplayName(QStringLiteral("Image Gestures Example"));

    QCommandLineParser commandLineParser;
    const QCommandLineOption disablePanOption("no-pan", "Disable pan gesture");
    commandLineParser.addOption(disablePanOption);
    const QCommandLineOption disablePinchOption("no-pinch", "Disable pinch gesture");
    commandLineParser.addOption(disablePinchOption);
    const QCommandLineOption disableSwipeOption("no-swipe", "Disable swipe gesture");
    commandLineParser.addOption(disableSwipeOption);
    const QCommandLineOption helpOption = commandLineParser.addHelpOption();
    commandLineParser.addPositionalArgument(QStringLiteral("Directory"),
                                            QStringLiteral("Directory to display"));

    const QString description = QGuiApplication::applicationDisplayName()
        + QLatin1String("\n\nEnable \"debug\" on the logging category \"qt.examples.imagegestures\" in order to\n"
                        "in order to obtain verbose information about Qt's gesture event processing,\n"
                        "for example by setting the environment variables QT_LOGGING_RULES to\n"
                        "qt.examples.imagegestures.debug=true\n");
    commandLineParser.setApplicationDescription(description);

    if (!commandLineParser.parse(QCoreApplication::arguments())) {
        showHelp(commandLineParser, commandLineParser.errorText());
        return -1;
    }
    if (commandLineParser.isSet(helpOption)) {
        showHelp(commandLineParser);
        return 0;
    }

    QStringList arguments = commandLineParser.positionalArguments();
    if (!arguments.isEmpty() && !QFileInfo(arguments.front()).isDir()) {
        showHelp(commandLineParser,
                 QLatin1Char('"') + QDir::toNativeSeparators(arguments.front())
                 + QStringLiteral("\" is not a directory."));
        return -1;
    }

    QList<Qt::GestureType> gestures;
    if (!commandLineParser.isSet(disablePanOption))
        gestures << Qt::PanGesture;
    if (!commandLineParser.isSet(disablePinchOption))
        gestures << Qt::PinchGesture;
    if (!commandLineParser.isSet(disableSwipeOption))
        gestures << Qt::SwipeGesture;

    MainWidget w;
    w.grabGestures(gestures);
    w.show();

    if (arguments.isEmpty()) {
        const QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
        const QString directory =
            QFileDialog::getExistingDirectory(&w, "Select image folder",
                                              picturesLocations.isEmpty() ? QString() : picturesLocations.front());
        if (directory.isEmpty())
            return 0;
        arguments.append(directory);
    }

    w.openDirectory(arguments.front());

    return app.exec();
}
Example #15
0
ATPClientApp::ATPClientApp(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
    // parse command-line
    QCommandLineParser parser;
    parser.setApplicationDescription("High Fidelity ATP-Client");

    const QCommandLineOption helpOption = parser.addHelpOption();

    const QCommandLineOption verboseOutput("v", "verbose output");
    parser.addOption(verboseOutput);

    const QCommandLineOption uploadOption("T", "upload local file", "local-file-to-send");
    parser.addOption(uploadOption);

    const QCommandLineOption authOption("u", "set usename and pass", "username:password");
    parser.addOption(authOption);

    const QCommandLineOption outputFilenameOption("o", "output filename", "output-file-name");
    parser.addOption(outputFilenameOption);

    const QCommandLineOption domainAddressOption("d", "domain-server address", "127.0.0.1");
    parser.addOption(domainAddressOption);

    const QCommandLineOption listenPortOption("listenPort", "listen port", QString::number(INVALID_PORT));
    parser.addOption(listenPortOption);

    if (!parser.parse(QCoreApplication::arguments())) {
        qCritical() << parser.errorText() << endl;
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        Q_UNREACHABLE();
    }

    _verbose = parser.isSet(verboseOutput);
    if (!_verbose) {
        QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtDebugMsg, false);
        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtInfoMsg, false);
        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtWarningMsg, false);

        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtDebugMsg, false);
        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtInfoMsg, false);
        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtWarningMsg, false);
    }

    QStringList posArgs = parser.positionalArguments();
    if (posArgs.size() != 1) {
        qDebug() << "give remote url argument";
        parser.showHelp();
        Q_UNREACHABLE();
    }

    _url = QUrl(posArgs[0]);
    if (_url.scheme() != "atp") {
        qDebug() << "url should start with atp:";
        parser.showHelp();
        Q_UNREACHABLE();
    }

    int domainPort = 40103;
    if (_url.port() != -1) {
        domainPort = _url.port();
    }

    if (parser.isSet(outputFilenameOption)) {
        _localOutputFile = parser.value(outputFilenameOption);
    }

    if (parser.isSet(uploadOption)) {
        _localUploadFile = parser.value(uploadOption);
    }

    if (parser.isSet(authOption)) {
        QStringList pieces = parser.value(authOption).split(":");
        if (pieces.size() != 2) {
            qDebug() << "-u should be followed by username:password";
            parser.showHelp();
            Q_UNREACHABLE();
        }

        _username = pieces[0];
        _password = pieces[1];
        _waitingForLogin = true;
    }

    if (parser.isSet(listenPortOption)) {
        _listenPort = parser.value(listenPortOption).toInt();
    }

    _domainServerAddress = QString("127.0.0.1") + ":" + QString::number(domainPort);
    if (parser.isSet(domainAddressOption)) {
        _domainServerAddress = parser.value(domainAddressOption);
    } else if (!_url.host().isEmpty()) {
        QUrl domainURL;
        domainURL.setScheme("hifi");
        domainURL.setHost(_url.host());
        _domainServerAddress = domainURL.toString();
    }

    DependencyManager::registerInheritance<LimitedNodeList, NodeList>();

    DependencyManager::set<StatTracker>();
    DependencyManager::set<AccountManager>([&]{ return QString(HIGH_FIDELITY_ATP_CLIENT_USER_AGENT); });
    DependencyManager::set<AddressManager>();
    DependencyManager::set<NodeList>(NodeType::Agent, _listenPort);

    auto accountManager = DependencyManager::get<AccountManager>();
    accountManager->setIsAgent(true);
    accountManager->setAuthURL(NetworkingConstants::METAVERSE_SERVER_URL());

    auto nodeList = DependencyManager::get<NodeList>();

    // setup a timer for domain-server check ins
    _domainCheckInTimer = new QTimer(nodeList.data());
    connect(_domainCheckInTimer, &QTimer::timeout, nodeList.data(), &NodeList::sendDomainServerCheckIn);
    _domainCheckInTimer->start(DOMAIN_SERVER_CHECK_IN_MSECS);

    // start the nodeThread so its event loop is running
    // (must happen after the checkin timer is created with the nodelist as it's parent)
    nodeList->startThread();

    const DomainHandler& domainHandler = nodeList->getDomainHandler();
    connect(&domainHandler, SIGNAL(hostnameChanged(const QString&)), SLOT(domainChanged(const QString&)));
    connect(&domainHandler, &DomainHandler::domainConnectionRefused, this, &ATPClientApp::domainConnectionRefused);

    connect(nodeList.data(), &NodeList::nodeAdded, this, &ATPClientApp::nodeAdded);
    connect(nodeList.data(), &NodeList::nodeKilled, this, &ATPClientApp::nodeKilled);
    connect(nodeList.data(), &NodeList::nodeActivated, this, &ATPClientApp::nodeActivated);
    connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &ATPClientApp::notifyPacketVersionMismatch);
    nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer
                                                 << NodeType::EntityServer << NodeType::AssetServer << NodeType::MessagesMixer);

    if (_verbose) {
        QString username = accountManager->getAccountInfo().getUsername();
        qDebug() << "cached username is" << username << ", isLoggedIn =" << accountManager->isLoggedIn();
    }

    if (!_username.isEmpty()) {

        connect(accountManager.data(), &AccountManager::newKeypair, this, [&](){
            if (_verbose) {
                qDebug() << "new keypair has been created.";
            }
        });

        connect(accountManager.data(), &AccountManager::loginComplete, this, [&](){
            if (_verbose) {
                qDebug() << "login successful";
            }
            _waitingForLogin = false;
            go();
        });
        connect(accountManager.data(), &AccountManager::loginFailed, this, [&](){
            qDebug() << "login failed.";
            _waitingForLogin = false;
            go();
        });
        accountManager->requestAccessToken(_username, _password);
    }

    auto assetClient = DependencyManager::set<AssetClient>();
    assetClient->init();

    if (_verbose) {
        qDebug() << "domain-server address is" << _domainServerAddress;
    }

    DependencyManager::get<AddressManager>()->handleLookupString(_domainServerAddress, false);

    QTimer* _timeoutTimer = new QTimer(this);
    _timeoutTimer->setSingleShot(true);
    connect(_timeoutTimer, &QTimer::timeout, this, &ATPClientApp::timedOut);
    _timeoutTimer->start(TIMEOUT_MILLISECONDS);
}
Example #16
0
ACClientApp::ACClientApp(int argc, char* argv[]) :
    QCoreApplication(argc, argv)
{
    // parse command-line
    QCommandLineParser parser;
    parser.setApplicationDescription("High Fidelity AC client");

    const QCommandLineOption helpOption = parser.addHelpOption();

    const QCommandLineOption verboseOutput("v", "verbose output");
    parser.addOption(verboseOutput);

    const QCommandLineOption authOption("u", "set usename and pass", "username:password");
    parser.addOption(authOption);

    const QCommandLineOption domainAddressOption("d", "domain-server address", "127.0.0.1");
    parser.addOption(domainAddressOption);

    const QCommandLineOption cacheSTUNOption("s", "cache stun-server response");
    parser.addOption(cacheSTUNOption);

    const QCommandLineOption listenPortOption("listenPort", "listen port", QString::number(INVALID_PORT));
    parser.addOption(listenPortOption);

    if (!parser.parse(QCoreApplication::arguments())) {
        qCritical() << parser.errorText() << endl;
        parser.showHelp();
        Q_UNREACHABLE();
    }

    if (parser.isSet(helpOption)) {
        parser.showHelp();
        Q_UNREACHABLE();
    }

    _verbose = parser.isSet(verboseOutput);
    if (!_verbose) {
        QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtDebugMsg, false);
        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtInfoMsg, false);
        const_cast<QLoggingCategory*>(&networking())->setEnabled(QtWarningMsg, false);

        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtDebugMsg, false);
        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtInfoMsg, false);
        const_cast<QLoggingCategory*>(&shared())->setEnabled(QtWarningMsg, false);
    }
    

    QString domainServerAddress = "127.0.0.1:40103";
    if (parser.isSet(domainAddressOption)) {
        domainServerAddress = parser.value(domainAddressOption);
    }

    if (_verbose) {
        qDebug() << "domain-server address is" << domainServerAddress;
    }

    int listenPort = INVALID_PORT;
    if (parser.isSet(listenPortOption)) {
        listenPort = parser.value(listenPortOption).toInt();
    }

    if (parser.isSet(authOption)) {
        QStringList pieces = parser.value(authOption).split(":");
        if (pieces.size() != 2) {
            qDebug() << "-u should be followed by username:password";
            parser.showHelp();
            Q_UNREACHABLE();
        }

        _username = pieces[0];
        _password = pieces[1];
    }

    DependencyManager::registerInheritance<LimitedNodeList, NodeList>();

    DependencyManager::set<AccountManager>([&]{ return QString("Mozilla/5.0 (HighFidelityACClient)"); });
    DependencyManager::set<AddressManager>();
    DependencyManager::set<NodeList>(NodeType::Agent, listenPort);

    auto accountManager = DependencyManager::get<AccountManager>();
    accountManager->setIsAgent(true);
    accountManager->setAuthURL(NetworkingConstants::METAVERSE_SERVER_URL());

    auto nodeList = DependencyManager::get<NodeList>();

    // setup a timer for domain-server check ins
    QTimer* domainCheckInTimer = new QTimer(nodeList.data());
    connect(domainCheckInTimer, &QTimer::timeout, nodeList.data(), &NodeList::sendDomainServerCheckIn);
    domainCheckInTimer->start(DOMAIN_SERVER_CHECK_IN_MSECS);

    // start the nodeThread so its event loop is running
    // (must happen after the checkin timer is created with the nodelist as it's parent)
    nodeList->startThread();

    const DomainHandler& domainHandler = nodeList->getDomainHandler();
    connect(&domainHandler, SIGNAL(domainURLChanged(QUrl)), SLOT(domainChanged(QUrl)));
    connect(&domainHandler, &DomainHandler::domainConnectionRefused, this, &ACClientApp::domainConnectionRefused);

    connect(nodeList.data(), &NodeList::nodeAdded, this, &ACClientApp::nodeAdded);
    connect(nodeList.data(), &NodeList::nodeKilled, this, &ACClientApp::nodeKilled);
    connect(nodeList.data(), &NodeList::nodeActivated, this, &ACClientApp::nodeActivated);
    connect(nodeList.data(), &NodeList::packetVersionMismatch, this, &ACClientApp::notifyPacketVersionMismatch);
    nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet() << NodeType::AudioMixer << NodeType::AvatarMixer
                                                 << NodeType::EntityServer << NodeType::AssetServer << NodeType::MessagesMixer);

    if (_verbose) {
        QString username = accountManager->getAccountInfo().getUsername();
        qDebug() << "cached username is" << username << ", isLoggedIn =" << accountManager->isLoggedIn();
    }

    if (!_username.isEmpty()) {

        connect(accountManager.data(), &AccountManager::newKeypair, this, [&](){
            if (_verbose) {
                qDebug() << "new keypair has been created.";
            }
        });

        connect(accountManager.data(), &AccountManager::loginComplete, this, [&](){
            if (_verbose) {
                qDebug() << "login successful";
            }
        });
        connect(accountManager.data(), &AccountManager::loginFailed, this, [&](){
            qDebug() << "login failed.";
        });
        accountManager->requestAccessToken(_username, _password);
    }

    DependencyManager::get<AddressManager>()->handleLookupString(domainServerAddress, false);

    QTimer* doTimer = new QTimer(this);
    doTimer->setSingleShot(true);
    connect(doTimer, &QTimer::timeout, this, &ACClientApp::timedOut);
    doTimer->start(4000);
}