コード例 #1
0
void StagingDirDiff::stagingTreeDiffException(GitException e)
{
    qCritical() << __func__ << ":" << __LINE__<< " " << e.what();
}
コード例 #2
0
int main(int argc, char** argv)
{
  QApplication myApp(argc, argv);
  myApp.setOrganizationName("CommonTK");
  myApp.setApplicationName("CommandLineModuleExplorer");

  ctkCommandLineParser cmdLineParser;
  cmdLineParser.setArgumentPrefix("--", "-");
  cmdLineParser.setStrictModeEnabled(true);

  cmdLineParser.addArgument("module", "", QVariant::String, "Path to a CLI module (executable)");
  //cmdLineParser.addArgument("module-xml", "", QVariant::String, "Path to a CLI XML description.");

  cmdLineParser.addArgument("validate-module", "", QVariant::String, "Path to a CLI module");
  cmdLineParser.addArgument("validate-xml", "", QVariant::String, "Path to a CLI XML description.");
  cmdLineParser.addArgument("verbose", "v", QVariant::Bool, "Be verbose.");
  cmdLineParser.addArgument("help", "h", QVariant::Bool, "Print this help text.");

  bool parseOkay = false;
  QHash<QString, QVariant> args = cmdLineParser.parseArguments(argc, argv, &parseOkay);

  QTextStream out(stdout, QIODevice::WriteOnly);

  if(!parseOkay)
  {
    out << "Error parsing command line arguments: " << cmdLineParser.errorString() << '\n';
    return EXIT_FAILURE;
  }

  if (args.contains("help"))
  {
    out << "Usage:\n" << cmdLineParser.helpText();
    out.flush();
    return EXIT_SUCCESS;
  }

  if (args.contains("validate-module"))
  {
    if (args.contains("validate-xml"))
    {
      out << "Ignoring \"validate-xml\" option.\n\n";
    }

    QString input = args["validate-module"].toString();
    if (!QFile::exists(input))
    {
      qCritical() << "Module does not exist:" << input;
      return EXIT_FAILURE;
    }

    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);
    process.start(input, QStringList("--xml"));

    if (!process.waitForFinished() || process.exitStatus() == QProcess::CrashExit ||
        process.error() != QProcess::UnknownError)
    {
      qWarning() << "The executable at" << input << "could not be started:" << process.errorString();
      return EXIT_FAILURE;
    }

    process.waitForReadyRead();
    QByteArray xml = process.readAllStandardOutput();

    if (args.contains("verbose"))
    {
      qDebug() << xml;
    }

    // validate the outputted xml description
    QBuffer xmlInput(&xml);
    xmlInput.open(QIODevice::ReadOnly);

    ctkCmdLineModuleXmlValidator validator(&xmlInput);
    if (!validator.validateInput())
    {
      qCritical() << validator.errorString();
      return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
  }
  else if (args.contains("validate-xml"))
  {
    QFile input(args["validate-xml"].toString());
    if (!input.exists())
    {
      qCritical() << "XML description does not exist:" << input.fileName();
      return EXIT_FAILURE;
    }
    input.open(QIODevice::ReadOnly);

    ctkCmdLineModuleXmlValidator validator(&input);
    if (!validator.validateInput())
    {
      qCritical() << validator.errorString();
      return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
  }


  //ctkCmdLineModuleDescription* descr = ctkCmdLineModuleDescription::parse(&input);

  ctkCLModuleExplorerMainWindow mainWindow;

  if (args.contains("module"))
  {
    mainWindow.addModule(args["module"].toString());
  }

  mainWindow.show();

  return myApp.exec();
}
コード例 #3
0
//----------------------------------------------------------------------------
int main(int argv, char** argc)
{
  QApplication app(argv, argc);

  qApp->setOrganizationName("CTK");
  qApp->setOrganizationDomain("commontk.org");
  qApp->setApplicationName("ctkExampleHostedApp");

  ctkCommandLineParser parser;
  parser.setArgumentPrefix("--", "-"); // Use Unix-style argument names

  // Add command line argument names
  parser.addArgument("hostURL", "", QVariant::String, "Hosting system URL");
  parser.addArgument("applicationURL", "", QVariant::String, "Hosted Application URL");
  parser.addArgument("help", "h", QVariant::Bool, "Show this help text");

  bool ok = false;
  QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
  if (!ok)
    {
    QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
                                              << parser.errorString() << "\n";
    return EXIT_FAILURE;
    }

  // Show a help message
   if (parsedArgs.contains("help"))
     {
     print_usage();
     QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
     return EXIT_SUCCESS;
     }

  if(parsedArgs.count() != 2)
    {
    qCritical() << "Wrong number of command line arguments.";
    print_usage();
    QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
    return EXIT_FAILURE;
    }

  QString hostURL = parsedArgs.value("hostURL").toString();
  QString appURL = parsedArgs.value("applicationURL").toString();
  qDebug() << "appURL is: " << appURL << " . Extracted port is: " << QUrl(appURL).port();

  // setup the plugin framework
  ctkProperties fwProps;
  fwProps.insert("dah.hostURL", hostURL);
  fwProps.insert("dah.appURL", appURL);
  ctkPluginFrameworkFactory fwFactory(fwProps);
  QSharedPointer<ctkPluginFramework> framework = fwFactory.getFramework();

  try
    {
    framework->init();
    }
  catch (const ctkPluginException& exc)
    {
    qCritical() << "Failed to initialize the plug-in framework:" << exc;
    return EXIT_FAILURE;
    }

#ifdef CMAKE_INTDIR
  QString pluginPath = CTK_PLUGIN_DIR CMAKE_INTDIR "/";
#else
  QString pluginPath = CTK_PLUGIN_DIR;
#endif

  qApp->addLibraryPath(pluginPath);

  // Construct the name of the plugin with the business logic
  // (thus the actual logic of the hosted app)
  QString pluginName("org_commontk_dah_exampleapp");
  if(parser.unparsedArguments().count() > 0)
    {
    pluginName = parser.unparsedArguments().at(0);
    }

  // try to find the plugin and install all plugins available in
  // pluginPath containing the string "org_commontk_dah" (but do not start them)
  QSharedPointer<ctkPlugin> appPlugin;
  QStringList libFilter;
  libFilter << "*.dll" << "*.so" << "*.dylib";
  QDirIterator dirIter(pluginPath, libFilter, QDir::Files);
  while(dirIter.hasNext())
    {
    try
      {
      QString fileLocation = dirIter.next();
      if (fileLocation.contains("org_commontk_dah"))
        {
        QSharedPointer<ctkPlugin> plugin = framework->getPluginContext()->installPlugin(QUrl::fromLocalFile(fileLocation));
        if (fileLocation.contains(pluginName))
          {
          appPlugin = plugin;
          }
        //plugin->start(ctkPlugin::START_TRANSIENT);
        }
      }
    catch (const ctkPluginException& e)
      {
      qCritical() << e.what();
      }
    }

  // if we did not find the business logic: abort
  if(!appPlugin)
    {
    qCritical() << "Could not find plugin.";
    qCritical() << "  Plugin name: " << pluginName;
    qCritical() << "  Plugin path: " << pluginPath;
    return EXIT_FAILURE;
    }

  // start the plugin framework
  framework->start();

  // start the plugin with the business logic
  try
    {
    appPlugin->start();
    }
  catch (const ctkPluginException& e)
    {
    qCritical() << e;
    }

  return app.exec();
}
コード例 #4
0
ファイル: SiteResponseModel.cpp プロジェクト: arkottke/strata
void SiteResponseModel::run()
{
    m_okToContinue = true;
    setHasResults(false);

    // Check the input -- FIMXE add more thorough checks
    if (m_siteProfile->rowCount() < 2) {
        qCritical() << "Need at least one soil layer!";
        m_okToContinue = false;
    }

    if (!m_motionLibrary->rowCount()) {
        qCritical() << "Need at least one input motion!";
        m_okToContinue = false;
    }

    if (!m_okToContinue)
        return;

    m_outputCatalog->clear();
    m_outputCatalog->log()->append(tr("<b>Starting Strata Calculation</b>"));

    // Determine the number of sites to be used in the computation
    const int siteCount = m_siteProfile->isVaried() ? m_siteProfile->profileCount() : 1;

    // Initialize the random number generator
    m_randNumGen->init();

    // Initialize the output
    m_outputCatalog->initialize(siteCount, m_motionLibrary);

    // Setup the progress bar with the number of steps
    const int motionCount = m_motionLibrary->motionCount();
    const int totalCount = motionCount * siteCount;
    emit progressRangeChanged(0, totalCount);
    emit progressChanged(0);

    m_outputCatalog->log()->append(tr("%1 Trial(s) (%2 Site(s) and %3 Motion(s) )")
                                   .arg(totalCount)
                                   .arg(siteCount)
                                   .arg(motionCount));

    int count = 0;
    for (int i = 0; i < siteCount; ++i) {
        // Break if not okay to continue
        if ( !m_okToContinue )
            break;

        m_outputCatalog->log()->append((
                                           QString(tr("[%1 of %2] Generating site and soil properties")).arg(i+1).arg(siteCount)));

        // Create the sublayers -- this randomizes the properties
        m_siteProfile->createSubLayers(m_outputCatalog->log());

        // FIXME -- check the site profile to ensure that the waves can be
        // computed for the intial coniditions
        int motionCountOffset = 0;
        for (int j = 0; j < m_motionLibrary->rowCount(); ++j ) {
            if (!m_motionLibrary->motionAt(j)->enabled()) {
                // Skip the disabled motion
                ++motionCountOffset;
                continue;
            }

            if (!m_okToContinue)
                // Break if not okay to continue
                break;

            // Output status
            m_outputCatalog->log()->append(QString(tr("\t[%1 of %2] Computing site response for motion: %3"))
                                           .arg(j - motionCountOffset + 1)
                                           .arg(motionCount)
                                           .arg(m_motionLibrary->motionAt(j)->name()));

            // Compute the site response
            if (!m_calculator->run(m_motionLibrary->motionAt(j), m_siteProfile) && m_okToContinue) {
                m_outputCatalog->log()->append(tr("\tWave propagation error -- removing site."));
                // Error in the calculation -- need to remove the site
                m_outputCatalog->removeLastSite();
                // Reset site count
                --i;
                break;
            }

            if (!m_okToContinue)
                // Break if not okay to continue
                break;

            // Generate the output
            m_outputCatalog->saveResults(j - motionCountOffset, m_calculator);

            // Increment the progress bar
            ++count;
            emit progressChanged(count);

            // Reset the sublayers
            m_siteProfile->resetSubLayers();
        }
    }

    if (m_okToContinue) {
        // Compute the statistics of the output
        m_outputCatalog->log()->append(tr("Computing statistics."));
        m_outputCatalog->finalize();
        setHasResults(true);
    } else {
        m_outputCatalog->log()->append(tr("<b>Canceled by the user.</b>"));
        setHasResults(false);
    }
}
コード例 #5
0
void StatusSubscribe::socketError(int errorNum, const QString &errorMsg)
{
    const QString errorString = QString("Error %1: ").arg(errorNum) + errorMsg;
    qCritical() << errorString;
}
コード例 #6
0
ファイル: loader.cpp プロジェクト: dmastrovito/braingl
bool Loader::loadVTK()
{
    QString fn = m_fileName.path();

    LoaderVTK* lv = new LoaderVTK( fn );

    if ( !lv->load() )
    {
        qCritical() << "Couldn't load vtk file";
        QStringList status = lv->getStatus();
        for ( int i = 0; i < status.size(); ++i )
        {
            qCritical() << status[i];
        }
        return false;
    }

    if ( lv->getPrimitiveType() == 1 )
    {
        std::vector<float>* points = lv->getPoints();
        std::vector<int> triangles = lv->getPolys();

        if ( triangles[0] != 3 )
        {
            qCritical() << "*ERROR* " << fn << " can only load triangle polygon data";
            return false;
        }

        unsigned int numPoints = lv->getNumPoints();
        unsigned int numTriangles = lv->getNumPolys();

        TriangleMesh2* mesh = new TriangleMesh2( numPoints, numTriangles );

        for ( unsigned int i = 0; i < numPoints; ++i )
        {
            mesh->addVertex( points->at( i * 3 ), points->at( i * 3 + 1 ), points->at( i * 3 + 2 ) );
        }

        for ( unsigned int i = 0; i < numTriangles; ++i )
        {
            mesh->addTriangle( triangles[i * 4 + 1], triangles[i * 4 + 2], triangles[i * 4 + 3] );
        }

        std::vector<std::vector<float> > values = lv->getPointData();

        float min = std::numeric_limits<float>().max();
        float max = -std::numeric_limits<float>().max();

        if ( values.size() > 0 )
        {
            std::vector<float> data = values[0];
            if ( data.size() == numPoints )
            {
                for ( unsigned int i = 0; i < numPoints; ++i )
                {
                    min = qMin( min, data[i] );
                    max = qMax( max, data[i] );
                    mesh->setVertexData( i, data[i] );
                }
            }
        }

        std::vector<unsigned char> colors = lv->getPointColors();
        if ( colors.size() == points->size() )
        {
            for ( unsigned int i = 0; i < numPoints; ++i )
            {
                mesh->setVertexColor( i, ( (float)colors[i * 3] ) /255.,
                                         ( (float)colors[i * 3 + 1] ) /255.,
                                         ( (float)colors[i * 3 + 2] ) /255., 1.0 );
            }
        }

        mesh->finalize();
        DatasetMesh* dataset = new DatasetMesh( mesh, fn );
        if ( min != max )
        {
            dataset->properties().set( Fn::Property::D_MIN, min );
            dataset->properties().set( Fn::Property::D_MAX, max );
        }
        m_dataset.push_back( dataset );
        delete lv;
        return true;
    }

    if ( lv->getPrimitiveType() == 2 )
    {

        DatasetFibers* dataset = new DatasetFibers( fn, lv );
        m_dataset.push_back( dataset );

        delete lv;
        return true;
    }

    return false;
}
コード例 #7
0
ファイル: loader.cpp プロジェクト: dmastrovito/braingl
bool Loader::loadGlyphset()
{
    QString glyphsetname = m_fileName.path();
    QFile glyphsetfile( glyphsetname );
    if ( !glyphsetfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "glyphset file unreadable" );
    }
    QTextStream gts( &glyphsetfile );
    //TODO: Will windows have a problem with this?
    QString trunk = QFileInfo( glyphsetname ).path();

    //glyphsetfile has three lines: 1: nifti (skip), 2: surfaceset(s), 3: connectivity matrix

    //1: TODO: skip nifti for now
    QString gnl = gts.readLine();
    qDebug() << "skipping: " << gnl;

    //2: load surfaceset
    gnl = gts.readLine();
    QStringList datasetNames = gnl.split( " " );
    bool two = ( datasetNames.length() > 1 );
    QString datasetName = datasetNames.at( 0 );

    gnl = gts.readLine();
    QStringList sl2 = gnl.split( " " );

    QString connectivityName;
    if ( sl2.at( 0 ).startsWith( "http" ) )
    {
        connectivityName = sl2.at( 0 );
    }
    else
    {
        connectivityName = trunk + QDir::separator() + sl2.at( 0 );
    }
    float mt = 0.8;
    if ( sl2.length() > 1 )
    {
        mt = sl2.at( 1 ).toFloat();
        qDebug() << "minimum threshold: " << mt;
    }
    else
    {
        qDebug() << "no minimum threshold in glyphset file, default of " << mt << " used.";
    }
    float maxt = 1.0;
    if ( sl2.length() > 2 )
    {
        maxt = sl2.at( 2 ).toFloat();
    }

    DatasetGlyphset* dataset = new DatasetGlyphset( glyphsetname, mt, maxt );

    qDebug() << "loading glyph set: " << datasetName;
    if ( two )
    {
        qDebug() << "...and loading glyph set: " << datasetNames.at( 1 );
        if ( datasetNames.length() > 2 )
        {
            qCritical() << "only two hemispheres supported";
        }
    }

    QFile setfile( trunk + QDir::separator() + datasetName );
    if ( !setfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "set file unreadable" );
    }
    QTextStream ts( &setfile );
    QString nl;

    QString onl;
    QTextStream* ots;
    std::vector<QString> others;
    if ( two )
    {
        QFile othersetfile( trunk + QDir::separator() + datasetNames.at( 1 ) );
        if ( !othersetfile.open( QIODevice::ReadOnly ) )
        {
            qCritical( "second set file unreadable" );
        }
        ots = new QTextStream( &othersetfile );
        qDebug() << "ots initialized";
        while ( !ots->atEnd() )
        {
            onl = ots->readLine();
            others.push_back( onl );
        }

    }

    int k = 0;
    while ( !ts.atEnd() )
    {
        nl = ts.readLine();
        qDebug() << "!" << nl;
        if ( two )
        {
            onl = others.at( k );
            qDebug() << onl;
            k++;
        }

        //For commenting out stuff in the setfiles
        if ( !nl.startsWith( "#" ) )
        {
            QStringList sl = nl.split( " " );
            QString fullname = trunk + QDir::separator() + sl.at( 0 );

            LoaderFreesurfer lf;

            if ( !lf.loadASC( fullname ) )
            {
                qCritical() << "unable to load: " << fullname;
                return false;
            }

            float x = 0;
            float y = 0;
            float z = 0;
            if ( sl.length() > 1 )
                x = sl.at( 1 ).toFloat();
            if ( sl.length() > 2 )
                y = sl.at( 2 ).toFloat();
            if ( sl.length() > 3 )
                z = sl.at( 3 ).toFloat();
            QVector3D s( x, y, z );
            std::vector<float>* points = lf.getPoints();
            std::vector<int> triangles = lf.getTriangles();
            int numPoints = points->size() / 3;
            int numTriangles = triangles.size() / 3;

            int onumPoints = 0;
            int onumTriangles = 0;
            std::vector<float>* opoints = new std::vector<float>();
            std::vector<int> otriangles;
            QVector3D* os = new QVector3D( 0, 0, 0 );
            LoaderFreesurfer olf;
            if ( two )
            {
                QStringList osl;
                osl = onl.split( " " );
                QString ofullname = trunk + QDir::separator() + osl.at( 0 );

                if ( !olf.loadASC( ofullname ) )
                {
                    qCritical() << "unable to load: " << ofullname;
                    return false;
                }
                float ox = 0;
                float oy = 0;
                float oz = 0;

                if ( osl.length() > 1 )
                    ox = osl.at( 1 ).toFloat();
                if ( osl.length() > 2 )
                    oy = osl.at( 2 ).toFloat();
                if ( osl.length() > 3 )
                    oz = osl.at( 3 ).toFloat();

                os = new QVector3D( ox, oy, oz );
                opoints = olf.getPoints();
                otriangles = olf.getTriangles();
                onumPoints = opoints->size() / 3;
                onumTriangles = otriangles.size() / 3;
            }

            TriangleMesh2* mesh = new TriangleMesh2( numPoints + onumPoints, numTriangles + onumTriangles );

            for ( int i = 0; i < numPoints; ++i )
            {
                mesh->addVertex( points->at( i * 3 ) + s.x(), points->at( i * 3 + 1 ) + s.y(), points->at( i * 3 + 2 ) + s.z() );
            }
            for ( int i = 0; i < numTriangles; ++i )
            {
                //TODO: Check orientation change (0,2,1)...
                mesh->addTriangle( triangles[i * 3], triangles[i * 3 + 2], triangles[i * 3 + 1] );
            }

            if ( two )
            {
                dataset->m_tris_middle = numTriangles;
                dataset->m_points_middle = numPoints;
                dataset->m_is_split = true;

                for ( int i = 0; i < onumPoints; ++i )

                {
                    mesh->addVertex( opoints->at( i * 3 ) + os->x(), opoints->at( i * 3 + 1 ) + os->y(), opoints->at( i * 3 + 2 ) + os->z() );
                }
                for ( int i = 0; i < onumTriangles; ++i )
                {
                    //TODO: Check orientation change (0,2,1)...
                    mesh->addTriangle( otriangles[i * 3] + onumPoints, otriangles[i * 3 + 2] + onumPoints, otriangles[i * 3 + 1] + onumPoints );
                }
            }

            mesh->finalize();

            dataset->addMesh( mesh, sl.at( 0 ) );
        }
    }

    //fourth thing on the line: name of roi...
    //no roi: initialize all nodes true
    dataset->initROI();
    if ( sl2.length() > 3 )
    {

        QString roiname = trunk + QDir::separator() + sl2.at( 3 );
        qDebug() << "loading ROI: " << roiname;
        dataset->loadROI( roiname, dataset->roi );
        if ( sl2.length() > 4 )
        {
            QString roiname2 = trunk + QDir::separator() + sl2.at( 4 );
            qDebug() << "loading ROI2: " << roiname2;
            dataset->loadROI( roiname2, dataset->roi2 );
        }
    }

    //3: load connectivity
    qDebug() << "loading connectivity";
    dataset->readConnectivity( connectivityName );

    //TODO: init conn.-crap...
    //dataset->setMinthresh( mt );

    dataset->setProperties();
    dataset->addSecondSurfaceSelector();
    m_dataset.push_back( dataset );

    return true;
}
コード例 #8
0
void TermiosHelper::setBaudRate(QPortSettings::BaudRate baudRate)
{
    speed_t baud = B9600;

    switch ( baudRate ) {
    case QPortSettings::BAUDR_50:
        baud = B50;
        break;
    case QPortSettings::BAUDR_75:
        baud = B75;
        break;
    case QPortSettings::BAUDR_110:
        baud = B110;
        break;
    case QPortSettings::BAUDR_134:
        baud = B134;
        break;
    case QPortSettings::BAUDR_150:
        baud = B150;
        break;
    case QPortSettings::BAUDR_200:
        baud = B200;
        break;
    case QPortSettings::BAUDR_300:
        baud = B300;
        break;
    case QPortSettings::BAUDR_600:
        baud = B600;
        break;
    case QPortSettings::BAUDR_1200:
        baud = B1200;
        break;
    case QPortSettings::BAUDR_1800:
        baud = B1800;
        break;
    case QPortSettings::BAUDR_2400:
        baud = B2400;
        break;
    case QPortSettings::BAUDR_4800:
        baud = B4800;
        break;
    case QPortSettings::BAUDR_9600:
        baud = B9600;
        break;
    case QPortSettings::BAUDR_19200:
        baud = B19200;
        break;
    case QPortSettings::BAUDR_38400:
        baud = B38400;
        break;
    case QPortSettings::BAUDR_57600:
        baud = B57600;
        break;
        //case QPortSettings::BAUDR_76800:
        //  baud = B76800;
        //  break;
    case QPortSettings::BAUDR_115200:
        baud = B115200;
        break;
    case QPortSettings::BAUDR_230400:
#ifdef B230400
        baud = B230400;
#else
        baud = (speed_t)230400;
#endif
        break;
    case QPortSettings::BAUDR_460800:
#ifdef B460800
        baud = B460800;
#else
        baud = (speed_t)460800;
#endif
        break;
    case QPortSettings::BAUDR_500000:
#ifdef B500000
        baud = B500000;
#else
        baud = (speed_t)500000;
#endif
        break;
    case QPortSettings::BAUDR_576000:
#ifdef B576000
        baud = B576000;
#else
        baud = (speed_t)576000;
#endif
        break;
    case QPortSettings::BAUDR_921600:
#ifdef B921600
        baud = B921600;
#else
        baud = (speed_t)921600;
#endif
        break;
    default:
        qWarning() << "TermiosHelper::setBaudRate(" << baudRate << "): " \
                      "Unsupported baud rate";
    }

    //#ifdef Q_OS_MAC
    //  if ( ioctl( fileDescriptor_, IOSSIOSPEED, &baud ) == -1 )
    //          {
    //      qCritical() <<  QString("TermiosHelper::setBaudRate(file: %1) failed: %2(%3)")
    //                   .arg(fileDescriptor_)
    //                   .arg(strerror(errno))
    //                   .arg(errno);
    //              return false;
    //          }
    //#else

    qCritical() << "Baud rate is now: " << baud;

    if ( cfsetspeed(currentAttrs_, baud) == -1 ) {
        qCritical() <<  QString("TermiosHelper::setBaudRate(file: %1) failed: %2(%3)")
                        .arg(fileDescriptor_)
                        .arg(strerror(errno))
                        .arg(errno);
    }
    //#endif
}
コード例 #9
0
ファイル: Plot2DHistogram.cpp プロジェクト: slovelan/NRAODev
void Plot2DHistogram::drawColumn (QPainter * painter, const QwtColumnRect & rect,
        const QwtIntervalSample & sample) const{
    QBrush brush( m_defaultColor );
    if ( !m_colored ){
        painter->setPen( m_defaultColor);
    }
    else {
        QColor sampleColor(m_defaultColor);
        if ( m_pipeline ){
            QwtInterval xRange = sample.interval;
            double midPt = (xRange.minValue() + xRange.maxValue()) / 2;
            std::array<double,3> normRGB;
            m_pipeline->convert( midPt, normRGB );
            if ( normRGB[0] >= 0 && normRGB[1] >= 0 && normRGB[2] >= 0 ){
                sampleColor.setRgbF(normRGB[0], normRGB[1], normRGB[2]);
            }
        }
        painter->setPen( sampleColor );
        brush.setColor( sampleColor );
    }
    painter->setBrush( brush );
    QRectF r = rect.toRect();
    if ( QwtPainter::roundingAlignment( painter ) ){
        r.setLeft( qRound( r.left() ) );
        r.setRight( qRound( r.right() ) );
        r.setTop( qRound( r.top() ) );
        r.setBottom( qRound( r.bottom() ) );
    }
    if ( m_drawStyle == Carta::Data::PlotStyles::PLOT_STYLE_FILL ){
        QwtPainter::fillRect( painter, r, brush );
    }
    else if ( m_drawStyle == Carta::Data::PlotStyles::PLOT_STYLE_LINE ){
        double middle = ( r.left() + r.right() ) / 2;
        QwtPainter::drawLine( painter, middle, r.bottom(), middle, r.top() );
    }
    else if ( m_drawStyle != Carta::Data::PlotStyles::PLOT_STYLE_OUTLINE ){
            qCritical() << "Unrecognized draw style="<< m_drawStyle;
    }


    if ( m_drawStyle == Carta::Data::PlotStyles::PLOT_STYLE_OUTLINE ||
            ( m_drawStyle == Carta::Data::PlotStyles::PLOT_STYLE_FILL && m_colored ) ){
        //Draw a black outline for colored fill style
        if ( m_drawStyle == Carta::Data::PlotStyles::PLOT_STYLE_FILL && m_colored ){
            QColor outlineC( "black" );
            painter->setPen( outlineC );
        }

        //Draw the top
        double top = r.top();
        double right = r.right();
        QwtPainter::drawLine( painter, r.left(), top, r.right(), top );
        //Draw the left vertical line
        QwtPainter::drawLine( painter, r.left(), m_lastY, r.left(), top );
        //Store the top for the next call.
        if ( top > 0 ){
            m_lastY = top;
        }
        if ( right > 0 ){
            m_lastX = right;
        }
    }
}
コード例 #10
0
int main(int argc, char **argv){
    QApplication app(argc, argv, true);

#ifdef Q_OS_WIN32
    app.setFont(QFont("Microsoft YaHei"));
#endif

#ifdef Q_OS_LINUX
    app.setFont(QFont("WenQuanYi Micro Hei"));
#endif

    //just for debug
    //qInstallMessageHandler(crashMessageOutput);

    loadTranslate(app);

#ifdef Q_OS_UNIX
    bool disabledrootcheck = false;
    //disabledrootcheck = true;
    QStringList allappargs = app.arguments();
    if (!disabledrootcheck)
    {
        QProcess whoamip;
        whoamip.start("whoami");
        whoamip.waitForFinished();
        if (QString(whoamip.readAll()).remove("\r").remove("\n") != "root")
        {
            QString argsconc = "";
            QString argsconcSingleQuote = "";
            for (int i = 1; i < allappargs.size(); ++i)
            {
                argsconc += QString("\"%1\" ").arg(allappargs.at(i));
                argsconcSingleQuote += QString("'%1' ").arg(allappargs.at(i));
            }
            argsconc += "\"rootcheck=no\"";
            argsconcSingleQuote += "'rootcheck=no'";
#ifdef Q_OS_LINUX
            QString gksulocation = checkforgraphicalsu("gksu");
            if (gksulocation != "REQCNOTFOUND")
            {
                QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc));
                return 0;
            }
            QString kdesulocation = checkforgraphicalsu("kdesu");
            if (kdesulocation != "REQCNOTFOUND")
            {
                QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc));
                return 0;
            }
            QString gnomesulocation = checkforgraphicalsu("gnomesu");
            if (gnomesulocation != "REQCNOTFOUND")
            {
                QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc));
                return 0;
            }
            QString kdesudolocation = checkforgraphicalsu("kdesudo");
            if (kdesudolocation != "REQCNOTFOUND")
            {
                QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc));
                return 0;
            }
            QMessageBox rootmsgb;
            rootmsgb.setIcon(QMessageBox::Warning);
            rootmsgb.setWindowTitle(uninstaller::tr("Must run as root"));
            rootmsgb.setTextFormat(Qt::RichText);
            rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB));
            rootmsgb.setStandardButtons(QMessageBox::Ok);
            switch (rootmsgb.exec())
            {
                case QMessageBox::Ok:
                    break;
                default:
                    break;
            }
#endif
#ifdef Q_OS_MAC
            /*
            QProcess osascriptProc;
            osascriptProc.start("osascript");
            osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data());
            osascriptProc.closeWriteChannel();
            osascriptProc.waitForFinished(-1);
            */
            //qDebug() << QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc);
            //QProcess::startDetached(QString("osascript -e 'do shell script \"%1 %2\" with administrator privileges'").arg(app.applicationFilePath()).arg(argsconc));
            QProcess::startDetached("osascript", QStringList() << "-e" << QString("do shell script \"'%1' %2\" with administrator privileges").arg(app.applicationFilePath()).arg(argsconcSingleQuote));
            return 0;
#endif
        }
    }
    #endif
    qmlRegisterType<BootMaker>("com.deepin.bootmaker", 1, 0, "BootMaker");
    qmlRegisterType<DOverrideWindow>("com.deepin.usbcreator", 1, 0, "DOverrideWindow");
    qmlRegisterType<DWindow>("com.deepin.usbcreator", 1, 0, "DWindow");
    qmlRegisterType<DIcon>("com.deepin.usbcreator", 1, 0, "DIcon");
    qmlRegisterType<DDropArea>("com.deepin.usbcreator", 1, 0, "DDropArea");

    QQmlApplicationEngine engine;
    engine.addImportPath("qrc:/qml/");


#ifdef Q_OS_WIN32
    if (CheckIsXP()){
        app.setFont(QFont("SimHei", 12));
        engine.load(QUrl("qrc:/qml/xp-fix-mainui.qml"));
    }
    else{
        engine.load(QUrl("qrc:/qml/mainui.qml"));
    }
#else
   engine.load(QUrl("qrc:/qml/mainui.qml"));
#endif

   app.setOverrideCursor( QCursor( Qt::ArrowCursor ) );

    QList<QObject *> roots = engine.rootObjects();
    QObject *topLevel = roots.value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

    if (!window) {
        qCritical("load qrc:/qml/mainui.qml error!!");
    }

    QIcon icon;
    icon.addFile(":/image/deepin-boot-maker.png");
    window->setIcon(icon);
    window->show();
    window->setTitle(QApplication::tr("Deepin Boot Maker"));
    return app.exec();
}
コード例 #11
0
ファイル: pony.cpp プロジェクト: Schiwi/qt-ponies
Pony::Pony(const QString path, ConfigWindow *config, QWidget *parent) :
    QMainWindow(parent), sleeping(false), in_interaction(false), current_interaction_delay(0), gen(QDateTime::currentMSecsSinceEpoch()), label(this), config(config), dragging(false), mouseover(false)
{
    setAttribute(Qt::WA_TranslucentBackground, true);
    setAttribute(Qt::WA_ShowWithoutActivating);

#if defined QT_MAC_USE_COCOA && QT_VERSION >= 0x040800
    // Removes shadows that lag behind animation on OS X. QT 4.8+ needed.
    setAttribute(Qt::WA_MacNoShadow, true);
#endif

#ifdef QT_MAC_USE_COCOA
    // On OS X, tool windows are hidden when another program gains focus.
    Qt::WindowFlags windowflags = Qt::FramelessWindowHint;
#else
    Qt::WindowFlags windowflags = Qt::FramelessWindowHint | Qt::Tool;
#endif

    always_on_top = config->getSetting<bool>("general/always-on-top");
    if(always_on_top) {
        windowflags |= Qt::WindowStaysOnTopHint;
    }

#ifdef Q_WS_X11
    if(config->getSetting<bool>("general/bypass-wm")) {
        // Bypass the window manager
        windowflags |= Qt::X11BypassWindowManagerHint;
    }
#endif

    setWindowFlags( windowflags );

    // TODO: always on top toggle, we have to preserve the skip taskbar/pager flags, so we have to do
    //       it by using Xlib
#ifdef Q_WS_X11
    // Qt on X11 does not support the skip taskbar/pager window flags, we have to set them ourselves
    // We let Qt initialize the other window properties, which aren't deleted when we replace them with ours
    // (they probably are appended on show())
    Atom window_state = XInternAtom( QX11Info::display(), "_NET_WM_STATE", False );
    Atom window_props[] = {
        XInternAtom( QX11Info::display(), "_NET_WM_STATE_SKIP_TASKBAR", False ),
        XInternAtom( QX11Info::display(), "_NET_WM_STATE_SKIP_PAGER"  , False )
    };

    XChangeProperty( QX11Info::display(), window()->winId(), window_state, XA_ATOM, 32, PropModeReplace, (unsigned char*)&window_props, 2 );
#endif

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(display_menu(const QPoint &)));

    // Setup speech label
    text_label.hide();
    text_label.setAttribute(Qt::WA_ShowWithoutActivating);
    text_label.setWindowFlags(windowflags);
    text_label.setAlignment(Qt::AlignHCenter);
    text_label.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
#ifdef Q_WS_X11
    // Same as above
    XChangeProperty( QX11Info::display(), text_label.window()->winId(), window_state, XA_ATOM, 32, PropModeReplace, (unsigned char*)&window_props, 2 );
#endif

    // Initially place the pony randomly on the screen, keeping a 50 pixel border
    x_pos = 50 + gen()%(QApplication::desktop()->availableGeometry(this).width()-100);
    y_pos = 50 + gen()%(QApplication::desktop()->availableGeometry(this).height()-100);

    move(x_pos, y_pos);

    directory = path;

    QFile ifile(QString("%1/%2/pony.ini").arg(ConfigWindow::getSetting<QString>("general/pony-directory"), path));
    if(!ifile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCritical() << "Cannot open pony.ini for pony:"<< path;
        qCritical() << ifile.errorString();
        throw std::exception();
    }

    name = path;

    if( ifile.isOpen() ) {
        QString line;
        QTextStream istr(&ifile);

        while (!istr.atEnd() ) {
            line = istr.readLine();

            if(line[0] != '\'' && !line.isEmpty()) {
                std::vector<QVariant> csv_data;
                CSVParser::ParseLine(csv_data, line, ',');

                if(csv_data[0] == "Name") {
                    name = csv_data[1].toString(); //Name,"name"
                }
                else if(csv_data[0] == "Behavior") {
                    Behavior b(this, path, csv_data);
                    behaviors.insert({b.name, std::move(b)});
                }
                else if(csv_data[0] == "Speak") {
                    std::shared_ptr<Speak> s = std::make_shared<Speak>(this, path, csv_data);
                    speak_lines.insert({s->name, std::move(s)});
                }
            }
        }

        ifile.close();
    }else{
        qCritical() << "Cannot read pony.ini for pony:"<< path;
        throw std::exception();
    }

    if(behaviors.size() == 0) {
        qCritical() << "Pony:"<<name<<"has no defined behaviors.";
        throw std::exception();
    }

    menu = new QMenu(this);
    QAction *sleep_action = new QAction(trUtf8("Sleeping"),menu);
    sleep_action->setCheckable(true);
    connect(sleep_action, SIGNAL(toggled(bool)), this, SLOT(toggle_sleep(bool)));

    menu->addAction(name)->setEnabled(false);
    menu->addSeparator();
    menu->addAction(sleep_action);
    menu->addAction(trUtf8("Remove %1").arg(name), config, SLOT(remove_pony()));
    menu->addAction(trUtf8("Remove every %1").arg(name), config, SLOT(remove_pony_all()));

    // Select behaviour that will can be choosen randomly
    for(auto &i: behaviors) {
        if(i.second.skip_normally == false) {
            random_behaviors.push_back(&i.second);
        }
    }

    if(random_behaviors.size() == 0) {
        qCritical() << "Pony:"<<name<<"has no defined behaviors that can be randomly selected.";
        throw std::exception();
    }


    std::sort(random_behaviors.begin(), random_behaviors.end(), [](const Behavior *val1, const Behavior *val2){ return val1->probability < val2->probability;} );
    total_behavior_probability = 0;
    for(auto &i: random_behaviors) {
        total_behavior_probability += i->probability;
    }

    // Select speech line that will be choosen randomly
    for(auto &i: speak_lines) {
        if(i.second->skip_normally == false) {
            random_speak_lines.push_back(i.second.get());
        }
    }

    // Select behaviors that will be used for sleeping
    for(auto &i: behaviors) {
        if(i.second.movement_allowed == Behavior::Movement::Sleep) {
           sleep_behaviors.push_back(&i.second);
        }
    }

    // Select behaviors that will be used for dragging
    for(auto &i: behaviors) {
        if(i.second.movement_allowed == Behavior::Movement::Dragged) {
           drag_behaviors.push_back(&i.second);
        }
    }

    // Select behaviors that will be used for mouseover
    for(auto &i: behaviors) {
        if(i.second.movement_allowed == Behavior::Movement::MouseOver) {
           mouseover_behaviors.push_back(&i.second);
        }
    }

    current_behavior = nullptr;
    change_behavior();
    this->show();

}
コード例 #12
0
ファイル: GreeterApp.cpp プロジェクト: alien999999999/sddm
    GreeterApp::GreeterApp(int &argc, char **argv) : QGuiApplication(argc, argv) {
        // point instance to this
        self = this;

        // Parse arguments
        bool testing = false;

        if (arguments().contains("--test-mode"))
            testing = true;

        // get socket name
        QString socket = parameter(arguments(), "--socket", "");

        // get theme path
        QString themePath = parameter(arguments(), "--theme", "");

        // create view
        m_view = new QQuickView();
        m_view->setResizeMode(QQuickView::SizeRootObjectToView);

        m_view->engine()->addImportPath(IMPORTS_INSTALL_DIR);

        // read theme metadata
        m_metadata = new ThemeMetadata(QString("%1/metadata.desktop").arg(themePath));

        // Translations
        // Components translation
        m_components_tranlator = new QTranslator();
        if (m_components_tranlator->load(QLocale::system(), "", "", COMPONENTS_TRANSLATION_DIR))
            installTranslator(m_components_tranlator);

        // Theme specific translation
        m_theme_translator = new QTranslator();
        if (m_theme_translator->load(QLocale::system(), "", "",
                           QString("%1/%2/").arg(themePath, m_metadata->translationsDirectory())))
            installTranslator(m_theme_translator);

        // get theme config file
        QString configFile = QString("%1/%2").arg(themePath).arg(m_metadata->configFile());

        // read theme config
        m_themeConfig = new ThemeConfig(configFile);

        // create models

        m_sessionModel = new SessionModel();
        m_screenModel = new ScreenModel();
        m_userModel = new UserModel();
        m_proxy = new GreeterProxy(socket);
        m_keyboard = new KeyboardModel();

        if(!testing && !m_proxy->isConnected()) {
            qCritical() << "Cannot connect to the daemon - is it running?";
            exit(EXIT_FAILURE);
        }

        // Set numlock upon start
        if (m_keyboard->enabled()) {
            if (mainConfig.Numlock.get() == MainConfig::NUM_SET_ON)
                m_keyboard->setNumLockState(true);
            else if (mainConfig.Numlock.get() == MainConfig::NUM_SET_OFF)
                m_keyboard->setNumLockState(false);
        }

        m_proxy->setSessionModel(m_sessionModel);

        // connect proxy signals
        QObject::connect(m_proxy, SIGNAL(loginSucceeded()), m_view, SLOT(close()));

        // set context properties
        m_view->rootContext()->setContextProperty("sessionModel", m_sessionModel);
        m_view->rootContext()->setContextProperty("screenModel", m_screenModel);
        m_view->rootContext()->setContextProperty("userModel", m_userModel);
        m_view->rootContext()->setContextProperty("config", *m_themeConfig);
        m_view->rootContext()->setContextProperty("sddm", m_proxy);
        m_view->rootContext()->setContextProperty("keyboard", m_keyboard);

        // get theme main script
        QString mainScript = QString("%1/%2").arg(themePath).arg(m_metadata->mainScript());

        // set main script as source
        m_view->setSource(QUrl::fromLocalFile(mainScript));

        // connect screen update signals
        connect(m_screenModel, SIGNAL(primaryChanged()), this, SLOT(show()));

        show();
    }
コード例 #13
0
ファイル: adsi.cpp プロジェクト: ihehui/HHSharedLibs
bool ADSI::loadLibrary(const QString &fileName)
{

    if(!adsiLibrary) {
        adsiLibrary = new QLibrary(this);
    }
    if(adsiLibrary->isLoaded()) {
        m_lastErrorString = "Library '" + fileName + "'already loaded!";
        qCritical() << m_lastErrorString;
        return false;
    }

//    adsiLibrary->unload();
    adsiLibrary->setFileName(fileName);
    adsiLibrary->load();
    if(!adsiLibrary->isLoaded()) {
        m_lastErrorString = "Failed to load library '" + fileName + "'!" + adsiLibrary->errorString();
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_Open = (AD_OpenFunction) adsiLibrary->resolve("AD_Open");
    if(!m_AD_Open) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_Open' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_Close = (AD_CloseFunction) adsiLibrary->resolve("AD_Close");
    if(!m_AD_Close) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_Close' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetLastErrorCode = (AD_GetLastErrorCodeFunction) adsiLibrary->resolve("AD_GetLastErrorCode");
    if(!m_AD_GetLastErrorCode) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetLastErrorCode' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetLastErrorString = (AD_GetLastErrorStringFunction) adsiLibrary->resolve("AD_GetLastErrorString");
    if(!m_AD_GetLastErrorString) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetLastErrorString' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_DefaultNamingContext = (AD_DefaultNamingContextFunction) adsiLibrary->resolve("AD_DefaultNamingContext");
    if(!m_AD_DefaultNamingContext) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_DefaultNamingContext' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_ObjectExists = (AD_ObjectExistsFunction) adsiLibrary->resolve("AD_ObjectExists");
    if(!m_AD_ObjectExists) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_ObjectExists' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_RenameObject = (AD_RenameObjectFunction) adsiLibrary->resolve("AD_RenameObject");
    if(!m_AD_RenameObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_RenameObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_MoveObject = (AD_MoveObjectFunction) adsiLibrary->resolve("AD_MoveObject");
    if(!m_AD_MoveObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_MoveObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_DeleteObject = (AD_DeleteObjectFunction) adsiLibrary->resolve("AD_DeleteObject");
    if(!m_AD_DeleteObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_DeleteObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_UnlockObject = (AD_UnlockObjectFunction) adsiLibrary->resolve("AD_UnlockObject");
    if(!m_AD_UnlockObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_UnlockObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_EnableObject = (AD_EnableObjectFunction) adsiLibrary->resolve("AD_EnableObject");
    if(!m_AD_EnableObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_EnableObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_IsObjectDisabled = (AD_IsObjectDisabledFunction) adsiLibrary->resolve("AD_IsObjectDisabled");
    if(!m_AD_IsObjectDisabled) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_IsObjectDisabled' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetAccountExpire = (AD_SetAccountExpireFunction) adsiLibrary->resolve("AD_SetAccountExpire");
    if(!m_AD_SetAccountExpire) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetAccountExpire' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetPasswordExpire = (AD_SetPasswordExpireFunction) adsiLibrary->resolve("AD_SetPasswordExpire");
    if(!m_AD_SetPasswordExpire) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetPasswordExpire' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetUserCannotChangePassword = (AD_SetUserCannotChangePasswordFunction) adsiLibrary->resolve("AD_SetUserCannotChangePassword");
    if(!m_AD_SetUserCannotChangePassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetUserCannotChangePassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetUserCannotChangePassword = (AD_GetUserCannotChangePasswordFunction) adsiLibrary->resolve("AD_GetUserCannotChangePassword");
    if(!m_AD_GetUserCannotChangePassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetUserCannotChangePassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetUserPasswordChange = (AD_SetUserPasswordChangeFunction) adsiLibrary->resolve("AD_SetUserPasswordChange");
    if(!m_AD_SetUserPasswordChange) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetUserPasswordChange' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetUserPasswordChange = (AD_GetUserPasswordChangeFunction) adsiLibrary->resolve("AD_GetUserPasswordChange");
    if(!m_AD_GetUserPasswordChange) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetUserPasswordChange' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetObjectAttribute = (AD_GetObjectAttributeFunction) adsiLibrary->resolve("AD_GetObjectAttribute");
    if(!m_AD_GetObjectAttribute) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetObjectAttribute' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_ModifyAttribute = (AD_ModifyAttributeFunction) adsiLibrary->resolve("AD_ModifyAttribute");
    if(!m_AD_ModifyAttribute) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_ModifyAttribute' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_CreateOU = (AD_CreateOUFunction) adsiLibrary->resolve("AD_CreateOU");
    if(!m_AD_CreateOU) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_CreateOU' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetAllOUs = (AD_GetAllOUsFunction) adsiLibrary->resolve("AD_GetAllOUs");
    if(!m_AD_GetAllOUs) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetAllOUs' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetObjectsInOU = (AD_GetObjectsInOUFunction) adsiLibrary->resolve("AD_GetObjectsInOU");
    if(!m_AD_GetObjectsInOU) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetObjectsInOU' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_CreateUser = (AD_CreateUserFunction) adsiLibrary->resolve("AD_CreateUser");
    if(!m_AD_CreateUser) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_CreateUser' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetPassword = (AD_SetPasswordFunction) adsiLibrary->resolve("AD_SetPassword");
    if(!m_AD_SetPassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetPassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_ComputerName = (ComputerNameFunction) adsiLibrary->resolve("ComputerName");
    if(!m_ComputerName) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'ComputerName' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_UserNameOfCurrentThread = (UserNameOfCurrentThreadFunction) adsiLibrary->resolve("UserNameOfCurrentThread");
    if(!m_UserNameOfCurrentThread) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'UserNameOfCurrentThread' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    return true;
}
コード例 #14
0
ファイル: schematiclayer.cpp プロジェクト: 0xB767B/LibrePCB
SchematicLayer::SchematicLayer(int id) :
    QObject(0), mId(id), mName(), mColor(), mColorHighlighted(), mIsVisible(false)
{
    Q_ASSERT(mId >= 0);

    switch (mId)
    {
        case Grid:
            mName = tr("Grid");
            mColor = Qt::white;                 // background
            mColorHighlighted = Qt::lightGray;  // lines
            mIsVisible = true;
            break;

        case OriginCrosses:
            mName = tr("Origin Crosses");
            mColor = QColor(0, 0, 0, 50);
            mColorHighlighted = QColor(0, 0, 0, 80);
            mIsVisible = true;
            break;

        case SymbolOutlines:
            mName = tr("Symbol Outlines");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = true;
            break;

        case SymbolGrabAreas:
            mName = tr("Symbol Grab Areas");
            mColor = QColor(255, 255, 0, 30);
            mColorHighlighted = QColor(255, 255, 0, 50);
            mIsVisible = true;
            break;

        case SymbolPinCircles:
            mName = tr("Symbol Pin Circles");
            mColor = Qt::green;             // optional pin
            mColorHighlighted = Qt::red;    // required pin
            mIsVisible = true;
            break;

        case SymbolPinNames:
            mName = tr("Symbol Pin Names");
            mColor = QColor(64, 64, 64, 255);
            mColorHighlighted = Qt::gray;
            mIsVisible = true;
            break;

        case ComponentNames:
            mName = tr("Component Names");
            mColor = QColor(32, 32, 32, 255);
            mColorHighlighted = Qt::darkGray;
            mIsVisible = true;
            break;

        case ComponentValues:
            mName = tr("Component Values");
            mColor = QColor(80, 80, 80, 255);
            mColorHighlighted = Qt::gray;
            mIsVisible = true;
            break;

        case NetLabels:
            mName = tr("Net Labels");
            mColor = Qt::darkGreen;
            mColorHighlighted = Qt::green;
            mIsVisible = true;
            break;

        case Nets:
            mName = tr("Nets");
            mColor = Qt::darkGreen;
            mColorHighlighted = Qt::green;
            mIsVisible = true;
            break;

        case Busses:
            mName = tr("Busses");
            mColor = Qt::darkBlue;
            mColorHighlighted = Qt::blue;
            mIsVisible = true;
            break;

#ifdef QT_DEBUG
        case DEBUG_GraphicsItemsBoundingRect:
            mName = tr("DEBUG_GraphicsItemsBoundingRect");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;

        case DEBUG_GraphicsItemsTextsBoundingRect:
            mName = tr("DEBUG_GraphicsItemsTextsBoundingRect");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;

        case DEBUG_SymbolPinNetSignalNames:
            mName = tr("DEBUG_SymbolPinNetSignalNames");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;

        case DEBUG_NetLinesNetSignalNames:
            mName = tr("DEBUG_NetLinesNetSignalNames");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;

        case DEBUG_InvisibleNetPoints:
            mName = tr("DEBUG_InvisibleNetPoints");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;

        case DEBUG_ComponentSymbolsCount:
            mName = tr("DEBUG_ComponentSymbolsCount");
            mColor = Qt::darkRed;
            mColorHighlighted = Qt::red;
            mIsVisible = false;
            break;
#endif

        default:
            if (mId >= UserDefinedBaseId)
            {
                // TODO: this is a user-defined layer...
            }
            else
            {
                qCritical() << "invalid schematic layer id:" << mId;
            }
            break;
    }
}
コード例 #15
0
ファイル: profile.cpp プロジェクト: kingctan/qTox
Profile* Profile::loadProfile(QString name, QString password)
{
    if (ProfileLocker::hasLock())
    {
        qCritical() << "Tried to load profile "<<name<<", but another profile is already locked!";
        return nullptr;
    }

    if (!ProfileLocker::lock(name))
    {
        qWarning() << "Failed to lock profile "<<name;
        return nullptr;
    }

    // Check password
    {
        QString path = Settings::getInstance().getSettingsDirPath() + name + ".tox";
        QFile saveFile(path);
        qDebug() << "Loading tox save "<<path;

        if (!saveFile.exists())
        {
            qWarning() << "The tox save file "<<path<<" was not found";
            ProfileLocker::unlock();
            return nullptr;
        }

        if (!saveFile.open(QIODevice::ReadOnly))
        {
            qCritical() << "The tox save file " << path << " couldn't' be opened";
            ProfileLocker::unlock();
            return nullptr;
        }

        qint64 fileSize = saveFile.size();
        if (fileSize <= 0)
        {
            qWarning() << "The tox save file"<<path<<" is empty!";
            ProfileLocker::unlock();
            return nullptr;
        }

        QByteArray data = saveFile.readAll();
        if (tox_is_data_encrypted((uint8_t*)data.data()))
        {
            if (password.isEmpty())
            {
                qCritical() << "The tox save file is encrypted, but we don't have a password!";
                ProfileLocker::unlock();
                return nullptr;
            }

            uint8_t salt[TOX_PASS_SALT_LENGTH];
            tox_get_salt(reinterpret_cast<uint8_t *>(data.data()), salt);
            auto tmpkey = *Core::createPasskey(password, salt);

            data = Core::decryptData(data, tmpkey);
            if (data.isEmpty())
            {
                qCritical() << "Failed to decrypt the tox save file";
                ProfileLocker::unlock();
                return nullptr;
            }
        }
        else
        {
            if (!password.isEmpty())
                qWarning() << "We have a password, but the tox save file is not encrypted";
        }
    }

    return new Profile(name, password, false);
}
コード例 #16
0
ファイル: serialport-win32.cpp プロジェクト: ascrnet/RespeQt
bool StandardSerialPortBackend::setSpeed(int speed)
{
//    qDebug() << "!d" << tr("DBG -- Serial Port setSpeed...");

    DCB dcb;
    COMMTIMEOUTS to;

    /* Adjust parameters */
    dcb.DCBlength = sizeof dcb;
    dcb.BaudRate = speed;
    dcb.fBinary = TRUE;
    dcb.fParity = FALSE;

    dcb.fOutxCtsFlow = FALSE;
    dcb.fOutxDsrFlow = FALSE;
    dcb.fDtrControl = DTR_CONTROL_DISABLE;
    dcb.fDsrSensitivity = FALSE;
    dcb.fTXContinueOnXoff = FALSE;
    dcb.fOutX = FALSE;
    dcb.fInX = FALSE;
    dcb.fErrorChar = FALSE;
    dcb.fNull = FALSE;
    dcb.fRtsControl = RTS_CONTROL_DISABLE;
    dcb.fAbortOnError = FALSE;
    dcb.fDummy2 = 0;
    dcb.wReserved = 0;
    dcb.XonLim = 0;
    dcb.XoffLim = 0;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
/*    if (speed > 100000) {
        dcb.StopBits = TWOSTOPBITS;
    } else*/ {
        dcb.StopBits = ONESTOPBIT;
    }
    dcb.XonChar = 0;
    dcb.XoffChar = 0;
    dcb.ErrorChar = 0;
    dcb.EofChar = 0;
    dcb.EvtChar = 0;
    dcb.wReserved1 = 0;

    /* Set serial port state */
    if (!SetCommState(mHandle, &dcb)) {
        qCritical() << "!e" << tr("Cannot set serial port speed to %1: %2")
                       .arg(speed)
                       .arg(lastErrorMessage());
        return false;
    }

    /* Adjust serial port timeouts */
    to.ReadIntervalTimeout = 0;
    to.ReadTotalTimeoutMultiplier = 100;
    to.ReadTotalTimeoutConstant = 0;
    to.WriteTotalTimeoutMultiplier = 100;
    to.WriteTotalTimeoutConstant = 0;

    /* Set serial port timeouts */
    if (!SetCommTimeouts(mHandle, &to)) {
        qCritical() << "!e" << tr("Cannot set serial port timeouts: %1").arg(lastErrorMessage());
        return false;
    }

    emit statusChanged(tr("%1 bits/sec").arg(speed));
    qWarning() << "!i" << tr("Serial port speed set to %1.").arg(speed);
    mSpeed = speed;
    return true;
}
コード例 #17
0
void HIDCaptureThread::run()
{
	bool bAutoGenerateData = false;//For testing purpose
	bool bButtonValueChanged = false;
	USBHIDDeviceNameSpace::strcJoystickPosition currentJoyPos;
	m_bIsRunning = true;
	emit receiveThreadStarted(QDateTime::currentDateTime().toString(MainAppInfo::stdDateTimeFormat()));

	int res;
	unsigned char buf[255];
	hid_device *handle;

	if(!bAutoGenerateData)
	{
		memset(buf,0x00,sizeof(buf));
		struct hid_device_info *devs, *cur_dev;
		devs = hid_enumerate(0x0, 0x0);
		cur_dev = devs;	
		//while (cur_dev) {
		//	printf("Device Found\n  type: %04hx %04hx\n  path: %s\n  serial_number: %ls", cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
		//	printf("\n");
		//	printf("  Manufacturer: %ls\n", cur_dev->manufacturer_string);
		//	printf("  Product:      %ls\n", cur_dev->product_string);
		//	printf("  Release:      %hx\n", cur_dev->release_number);
		//	printf("  Interface:    %d\n",  cur_dev->interface_number);
		//	printf("\n");
		//	cur_dev = cur_dev->next;
		//}
		hid_free_enumeration(devs);

		// Open the device using the VID, PID, and optionally the Serial number.
		handle = hid_open(m_VendorID, m_ProductID, NULL);
		if (!handle) {
			//printf("unable to open device\n");
			emit receiveThreadStopped(QDateTime::currentDateTime().toString(MainAppInfo::stdDateTimeFormat()));
			qCritical("HIDCaptureThread: Could not open HID Device");
			m_bIsRunning = false;
			return;
		}
		// Set the hid_read() function to be non-blocking.
		hid_set_nonblocking(handle, 1);
	}
	else
	{
		m_HIDData[0] = 0;
		m_HIDData[1] = 0;
		m_HIDData[2] = 0;
		m_HIDData[3] = 0;
	}
	while(m_bAbortRunning==false)
	{
		// Try to read from the device. There should be no
		// data here, but execution should not block.
		if(!bAutoGenerateData)
		{
			res = hid_read(handle, buf, sizeof(buf));
		}
		else
		{
			res = 4;//We are going to generate these results
		}
		if (res>1)
		{
			if(!bAutoGenerateData)
			{
				//emit captureThreadTriggered();
				if(buf[0] > 127)
				{
					m_HIDData[0] = (buf[0] - 128);
				}
				else
				{
					m_HIDData[0] = (buf[0] + 128);
				}
				if(buf[1] > 127)
				{
					m_HIDData[1] = (buf[1] - 128);
				}
				else
				{
					m_HIDData[1] = (buf[1] + 128);
				}
				m_HIDData[2] = buf[2];
				m_HIDData[3] = buf[3];
				//Hereafter the center is at position(x,y) (127|128),(127|128) --> (m_HIDData[0],m_HIDData[1])
				//The left point(x) is < 127, right point(x) is > 128 --> m_HIDData[0]
				//The top point(y) is < 127, bottom point(y) is > 128 --> m_HIDData[1]
				//The Buttons are at m_HIDData[2]; LeftButton = 1, RightButton = 2
				//TriggerInput is also at m_HIDData[2], emulates Button;(BNC; inside = TTL, outside = GND) only rising edge(send only a single packet as response)!

			}
			else//Generate some dummy data for testing
			{
				m_HIDData[0] = m_HIDData[0]+1;
				m_HIDData[1] = m_HIDData[1]+1;
				//m_HIDData[2] = m_HIDData[2]+2;
				//m_HIDData[3] = m_HIDData[3]+2;
			}		

			if(m_bActivateButtonTriggers)
			{
				unsigned char cSignalVal;
				cNewButtonByteVal = (m_HIDData[2] & m_cButtonMask);
				switch (m_ButtonDetectCaptureMethod)
				{
				case USBHIDDeviceNameSpace::MaskedValueChanged :
					if (cOldButtonByteVal != cNewButtonByteVal)//any change within masked measurement
					{
						emit receiveThreadButtonTriggered(cNewButtonByteVal,cOldButtonByteVal ^ cNewButtonByteVal);//Signal(Difference, Press and Release)
						bButtonValueChanged = true;						
					}
					cOldButtonByteVal = cNewButtonByteVal;
					break;	
				case USBHIDDeviceNameSpace::MaskedValueChangedHigh :
					cSignalVal = (~cOldButtonByteVal) & cNewButtonByteVal;
					if(cSignalVal)//any change from low to high
					{
						emit receiveThreadButtonTriggered(cNewButtonByteVal,cSignalVal);//Signal(Positive Changes, Press)
						bButtonValueChanged = true;
					}
					cOldButtonByteVal = cNewButtonByteVal;
					break;
				case USBHIDDeviceNameSpace::MaskedValueChangedLow :
					cSignalVal = cOldButtonByteVal & (~cNewButtonByteVal);
					if(cSignalVal)//any change from high to low
					{
						emit receiveThreadButtonTriggered(cNewButtonByteVal,cSignalVal);//Signal(Positive Changes, Release)
						bButtonValueChanged = true;
					}
					cOldButtonByteVal = cNewButtonByteVal;
					break;	
				}
			}

			//Maintain a history
			currentJoyPos.Xpos = m_HIDData[0];
			currentJoyPos.Ypos = m_HIDData[1];
			while(m_JostickHistory.size() > m_nJoystickHistorySize)
			{
				m_JostickHistory.pop_front();//Maximum size reached
			}
			if (m_bActivateJoystickTrigger)//Is the trigger activated?
			{
				if(m_JostickHistory.size()>0)//Do we already have a history?
				{
					if(!((m_JostickHistory.last().Xpos == currentJoyPos.Xpos) && (m_JostickHistory.last().Ypos == currentJoyPos.Ypos)))//Only when value changed!
					{
						if((m_bActivateJoystickStabilisation)&&(m_nJoystickStabilisationThreshold>0))
						{
							if( ((m_JostickHistory.last().Xpos - m_nJoystickStabilisationThreshold) > currentJoyPos.Xpos) || \
								((m_JostickHistory.last().Xpos + m_nJoystickStabilisationThreshold) < currentJoyPos.Xpos) || \
							    ((m_JostickHistory.last().Ypos - m_nJoystickStabilisationThreshold) > currentJoyPos.Ypos) || \
								((m_JostickHistory.last().Ypos + m_nJoystickStabilisationThreshold) < currentJoyPos.Ypos) )
								//Only when value changed enough!!	
							{
								EmitFilteredData();//Send the trigger
								if (!OutputCapturedData()) m_bAbortRunning = true;
							}							
						}
						else
						{
							EmitFilteredData();//Send the trigger
							if (!OutputCapturedData()) m_bAbortRunning = true;
						}
					}					
				}
				else
				{
					EmitFilteredData();//Send the trigger, first record!
					if (!OutputCapturedData()) m_bAbortRunning = true;
				}
			}
			//else if ((m_bActivateButtonTriggers) && (bButtonValueChanged))
			//{
			//	
			//}
			m_JostickHistory.append(currentJoyPos);//Now add the new data record
		}
		//QThread::msleep(10);
	}
	if(!bAutoGenerateData)
		hid_close(handle);
	CloseOutputFile();
	m_bAbortRunning = false;
	m_bIsRunning = false;
	emit receiveThreadStopped(QDateTime::currentDateTime().toString(MainAppInfo::stdDateTimeFormat()));
	return;
}
コード例 #18
0
ファイル: serialport-win32.cpp プロジェクト: ascrnet/RespeQt
QByteArray StandardSerialPortBackend::readCommandFrame()
{
//    qDebug() << "!d" << tr("DBG -- Serial Port readCommandFrame...");

    QByteArray data;
    DWORD mask;

    switch (mMethod) {
    case 0:
        mask = EV_RING;
        break;
    case 1:
        mask = EV_DSR;
        break;
    case 2:
        mask = EV_CTS;
        break;
    case 3:
        mask = EV_RXCHAR;
    }

    if (!SetCommMask(mHandle, mask)) {
        qCritical() << "!e" << tr("Cannot set serial port event mask: %1").arg(lastErrorMessage());
        return data;
    }

    int retries = 0, totalRetries = 0;
    do {
        data.clear();
        OVERLAPPED ov;

        memset(&ov, 0, sizeof(ov));
        ov.hEvent = CreateEvent(0, true, false, 0);

        HANDLE events[2];
        events[0] = ov.hEvent;
        events[1] = mCancelHandle;

        if (!WaitCommEvent(mHandle, &mask, &ov)) {
            if (GetLastError() == ERROR_IO_PENDING) {
                DWORD x = WaitForMultipleObjects(2, events, false, INFINITE);
                CloseHandle(ov.hEvent);
                if (x == WAIT_OBJECT_0 + 1) {
                    data.clear();
                    return data;
                }
                if (x == WAIT_FAILED) {
                    qCritical() << "!e" << tr("Cannot wait for serial port event: %1").arg(lastErrorMessage());
                    data.clear();
                    return data;
                }
            } else {
                CloseHandle(ov.hEvent);
                qCritical() << "!e" << tr("Cannot wait for serial port event: %1").arg(lastErrorMessage());
                return data;
            }
        }

        if (!PurgeComm(mHandle, PURGE_RXCLEAR)) {
            qCritical() << "!e" << tr("Cannot clear serial port read buffer: %1").arg(lastErrorMessage());
            return data;
        }

//        qDebug() << "!d" << tr("DBG -- Serial Port, just about to readDataFrame...");

        data = readDataFrame(4, false);

        if (!data.isEmpty()) {

//            qDebug() << "!d" << tr("DBG -- Serial Port, data not empty: [%1]").arg(data.data());

            if(mask != EV_RXCHAR) { // 
                do {
                    GetCommModemStatus(mHandle, &mask);
                } while (mask && !mCanceled);
            }
            break;
        } else {
            retries++;
            totalRetries++;
            if (retries == 2) {
                retries = 0;
                if (mHighSpeed) {
                    setNormalSpeed();
                } else {
                    setHighSpeed();
                }
            }
        }
//    } while (totalRetries < 100);
    } while (1);
    return data;
}
コード例 #19
0
ファイル: loader.cpp プロジェクト: dmastrovito/braingl
bool Loader::loadSet()
{
    QString fn = m_fileName.path();

    DatasetMesh* dataset = new DatasetMesh( fn, Fn::DatasetType::MESH_BINARY );

    qDebug() << "loading surface set: " << fn;

    QFile setfile( fn );
    if ( !setfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "set file unreadable" );
    }
    QTextStream ts( &setfile );
    QString nl;
    //TODO: Will windows have a problem with this?
    QString trunk = QFileInfo( fn ).path();
    while ( !ts.atEnd() )
    {
        nl = ts.readLine();
        //For commenting out stuff in the setfiles
        if ( !nl.startsWith( "#" ) )
        {
            QStringList sl = nl.split( " " );
            QString fullname = trunk + QDir::separator() + sl.at( 0 );
            float x = 0;
            float y = 0;
            float z = 0;
            if ( sl.length() > 1 )
                x = sl.at( 1 ).toFloat();
            if ( sl.length() > 2 )
                y = sl.at( 2 ).toFloat();
            if ( sl.length() > 3 )
                z = sl.at( 3 ).toFloat();
            QVector3D s( x, y, z );

            LoaderFreesurfer lf;

            if ( !lf.loadASC( fullname ) )
            {
                qCritical() << "unable to load: " << fn;
                return false;
            }

            std::vector<float>* points = lf.getPoints();
            std::vector<int> triangles = lf.getTriangles();
            int numPoints = points->size() / 3;
            int numTriangles = triangles.size() / 3;

            TriangleMesh2* mesh = new TriangleMesh2( numPoints, numTriangles );
            for ( int i = 0; i < numPoints; ++i )
            {
                mesh->addVertex( points->at( i * 3 ) + s.x(), points->at( i * 3 + 1 ) + s.y(), points->at( i * 3 + 2 ) + s.z() );
            }
            for ( int i = 0; i < numTriangles; ++i )
            {
                //TODO: Check orientation change (0,2,1)...
                mesh->addTriangle( triangles[i * 3], triangles[i * 3 + 2], triangles[i * 3 + 1] );
            }
            mesh->finalize();

            dataset->addMesh( mesh, sl.at( 0 ) );
        }
    }
    qDebug() << "surfaces read...";
    dataset->initProperties();
    dataset->setProperties();
    dataset->finalizeProperties();
    m_dataset.push_back( dataset );

    return true;
}
コード例 #20
0
ファイル: serialport-win32.cpp プロジェクト: ascrnet/RespeQt
bool StandardSerialPortBackend::open()
{
    Sleep(250);        // 
    if (isOpen()) {
        close();
    }
//    qDebug() << "!d" << tr("DBG -- Serial Port Open...");

    QString name = respeqtSettings->serialPortName();

    mHandle = (CreateFile(
        (WCHAR*)name.utf16(),
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
        0
    ));
    if (mHandle == INVALID_HANDLE_VALUE) {
        qCritical() << "!e" << tr("Cannot open serial port '%1': %2").arg(name, lastErrorMessage());
        return false;
    }
    if (!EscapeCommFunction(mHandle, CLRRTS)) {
        qCritical() << "!e" << tr("Cannot clear RTS line in serial port '%1': %2").arg(name, lastErrorMessage());
        return false;
    }
    if (!EscapeCommFunction(mHandle, CLRDTR)) {
        qCritical() << "!e" << tr("Cannot clear DTR line in serial port '%1': %2").arg(name, lastErrorMessage());
        return false;
    }

    mMethod = respeqtSettings->serialPortHandshakingMethod();

    mCanceled = false;

    mCancelHandle = CreateEvent(0, true, false, 0);

    if (!setNormalSpeed()) {
        close();
        return false;
    }

    QString m;
    switch (mMethod) {
    case 0:
        m = "RI";
        break;
    case 1:
        m = "DSR";
        break;
    case 2:
        m = "CTS";
        break;
    case 3:
        m = "NO";
    }
    /* Notify the user that emulation is started */
    qWarning() << "!i" << tr("Emulation started through standard serial port backend on '%1' with %2 handshaking")
                  .arg(respeqtSettings->serialPortName())
                  .arg(m);

    return true;
}
コード例 #21
0
ファイル: loader.cpp プロジェクト: dmastrovito/braingl
bool Loader::loadMEG()
{
    QString fn = m_fileName.path();

    DatasetMeshTimeSeries* dataset = new DatasetMeshTimeSeries( fn, Fn::DatasetType::MESH_TIME_SERIES );

    qDebug() << "loading meg set: " << fn;

    QFile setfile( fn );
    if ( !setfile.open( QIODevice::ReadOnly ) )
    {
        qCritical( "set file unreadable" );
    }
    QTextStream ts( &setfile );
    QString nl;
    //TODO: Will windows have a problem with this?
    QString trunk = QFileInfo( fn ).path();
    while ( !ts.atEnd() )
    {
        nl = ts.readLine();
        //For commenting out stuff in the setfiles
        if ( nl.startsWith( "#meg") )
        {
            QStringList sl = nl.split( " " );
            bool ok;
            int count = sl[1].toInt( &ok );
            if ( ok )
            {
                qDebug() << count << "meg data files in set definition";
                for ( int i = 1; i <= count; ++i )
                {
                    QString numberString = QString::number( i );
                    int nss = numberString.size();
                    for ( int k = 0; k < 3 - nss; ++k )
                    {
                        numberString = "0" + numberString;
                    }
                    QFile dataFile( trunk + QDir::separator() + numberString + ".txt" );
                    if ( !dataFile.open( QIODevice::ReadOnly ) )
                    {
                        qCritical() << "data file unreadable, skipping"  << numberString + ".txt";
                        continue;
                    }
                    std::vector<float>data;
                    QTextStream ds( &dataFile );
                    while( !ds.atEnd() )
                    {
                        nl = ds.readLine();
                        float val = nl.toFloat( &ok );
                        if ( ok )
                        {
                            data.push_back( val );
                        }
                        else
                        {
                            break;
                        }
                    }
                    if ( !ok )
                    {
                        qCritical() << "error while reading data file, skipping" << numberString + ".txt";
                        continue;
                    }
                    else
                    {
                        dataset->addData( data );
                    }
                }
            }
            else
            {
                qCritical() << "can't read count meg data files";
            }
        }
        else if ( !nl.startsWith( "#" ) )
        {
            QStringList sl = nl.split( " " );
            QString fullname = trunk + QDir::separator() + sl.at( 0 );
            float x = 0;
            float y = 0;
            float z = 0;
            if ( sl.length() > 1 )
                x = sl.at( 1 ).toFloat();
            if ( sl.length() > 2 )
                y = sl.at( 2 ).toFloat();
            if ( sl.length() > 3 )
                z = sl.at( 3 ).toFloat();
            QVector3D s( x, y, z );

            TriangleMesh2* mesh;
            std::vector<float>* points;
            std::vector<int> triangles;

            if ( fullname.endsWith( ".asc" ) )
            {
                LoaderFreesurfer lf;

                if ( !lf.loadASC( fullname ) )
                {
                    qCritical() << "unable to load: " << fn;
                    return false;
                }

                points = lf.getPoints();
                triangles = lf.getTriangles();

                int numPoints = points->size() / 3;
                int numTriangles = triangles.size() / 3;


                if ( numPoints > 0 && numTriangles > 0 )
                {
                    mesh = new TriangleMesh2( numPoints, numTriangles );
                    for ( int i = 0; i < numPoints; ++i )
                    {
                        mesh->addVertex( points->at( i * 3 ) + s.x(), points->at( i * 3 + 1 ) + s.y(), points->at( i * 3 + 2 ) + s.z() );
                    }
                    for ( int i = 0; i < numTriangles; ++i )
                    {
                        mesh->addTriangle( triangles[i * 3], triangles[i * 3 + 2], triangles[i * 3 + 1] );
                    }
                    mesh->finalize();

                    dataset->addMesh( mesh, sl.at( 0 ) );
                }
            }

            if ( fullname.endsWith( ".vtk" ) )
            {
                LoaderVTK* lv = new LoaderVTK( fullname );

                if ( !lv->load() )
                {
                    qCritical() << lv->getStatus();
                    return false;
                }

                if ( lv->getPrimitiveType() == 1 )
                {
                    points = lv->getPoints();
                    triangles = lv->getPolys();

                    if ( triangles[0] != 3 )
                    {
                        qCritical() << "*ERROR* " << fn << " can only load triangle polygon data";
                        return false;
                    }

                    int numPoints = lv->getNumPoints();
                    int numTriangles = lv->getNumPolys();

                    if ( numPoints > 0 && numTriangles > 0 )
                    {
                        mesh = new TriangleMesh2( numPoints, numTriangles );
                        for ( int i = 0; i < numPoints; ++i )
                        {
                            mesh->addVertex( points->at( i * 3 ), points->at( i * 3 + 1 ), points->at( i * 3 + 2 ) );
                        }

                        for ( int i = 0; i < numTriangles; ++i )
                        {
                            mesh->addTriangle( triangles[i * 4 + 1], triangles[i * 4 + 2], triangles[i * 4 + 3] );
                        }

                        mesh->finalize();

                        dataset->addMesh( mesh, sl.at( 0 ) );
                    }
                }
            }
        }
    }
    dataset->setProperties();
    m_dataset.push_back( dataset );

    return true;
}
コード例 #22
0
ファイル: serialport-win32.cpp プロジェクト: ascrnet/RespeQt
bool AtariSioBackend::open()
{
    qCritical() << "!e" << tr("AtariSIO is only available under Linux.");
    return false;
}
コード例 #23
0
ファイル: sf2_player.cpp プロジェクト: uro5h/lmms
void sf2Instrument::updateSampleRate()
{
	double tempRate;

	// Set & get, returns the true sample rate
	fluid_settings_setnum( m_settings, (char *) "synth.sample-rate", Engine::mixer()->processingSampleRate() );
	fluid_settings_getnum( m_settings, (char *) "synth.sample-rate", &tempRate );
	m_internalSampleRate = static_cast<int>( tempRate );

	if( m_font )
	{
		// Now, delete the old one and replace
		m_synthMutex.lock();
		fluid_synth_remove_sfont( m_synth, m_font->fluidFont );
		delete_fluid_synth( m_synth );

		// New synth
		m_synth = new_fluid_synth( m_settings );
		m_fontId = fluid_synth_add_sfont( m_synth, m_font->fluidFont );
		m_synthMutex.unlock();

		// synth program change (set bank and patch)
		updatePatch();
	}
	else
	{
		// Recreate synth with no soundfonts
		m_synthMutex.lock();
		delete_fluid_synth( m_synth );
		m_synth = new_fluid_synth( m_settings );
		m_synthMutex.unlock();
	}

	m_synthMutex.lock();
	if( Engine::mixer()->currentQualitySettings().interpolation >=
			Mixer::qualitySettings::Interpolation_SincFastest )
	{
		fluid_synth_set_interp_method( m_synth, -1, FLUID_INTERP_7THORDER );
	}
	else
	{
		fluid_synth_set_interp_method( m_synth, -1, FLUID_INTERP_DEFAULT );
	}
	m_synthMutex.unlock();
	if( m_internalSampleRate < Engine::mixer()->processingSampleRate() )
	{
		m_synthMutex.lock();
		if( m_srcState != NULL )
		{
			src_delete( m_srcState );
		}
		int error;
		m_srcState = src_new( Engine::mixer()->currentQualitySettings().libsrcInterpolation(), DEFAULT_CHANNELS, &error );
		if( m_srcState == NULL || error )
		{
			qCritical( "error while creating libsamplerate data structure in Sf2Instrument::updateSampleRate()" );
		}
		m_synthMutex.unlock();
	}
	updateReverb();
	updateChorus();
	updateReverbOn();
	updateChorusOn();
	updateGain();

	// Reset last MIDI pitch properties, which will be set to the correct values
	// upon playing the next note
	m_lastMidiPitch = -1;
	m_lastMidiPitchRange = -1;
}
コード例 #24
0
ファイル: moegraphicssurface.cpp プロジェクト: NexusTools/MOE
void MoeGraphicsSurface::hadOGLErr(QString err) {
    _oglError = err;
    qCritical() << "OpenGL Error" << err;
    emit OpenGLError(err);
}
コード例 #25
0
ファイル: main.cpp プロジェクト: magland/mountainlab_devel
int main(int argc, char *argv[])
{
	QStringList required_params,optional_params;
	required_params << "clipsize" << "labels";
	CLParams params=get_command_line_params(argc,argv,required_params,optional_params);

	if (!params.success) {
		qCritical() << params.error_message;
		usage(); return -1;
	}
	if (params.unnamed_parameters.count()!=6) {
		usage(); return -1;
	}

	QString inpath1=params.unnamed_parameters[0];
	QString inpath2=params.unnamed_parameters[1];
	QString inpath_TL1=params.unnamed_parameters[2];
	QString inpath_TL2=params.unnamed_parameters[3];
	QString outpath1=params.unnamed_parameters[4];
	QString outpath2=params.unnamed_parameters[5];

	QString outpath_TL=QFileInfo(outpath1).path()+"/"+QFileInfo(outpath1).completeBaseName()+".TL.mda";
	QString outpath_TM=QFileInfo(outpath1).path()+"/"+QFileInfo(outpath1).completeBaseName()+".TM.mda";

	QMap<QString,QVariant> runparams;

	int clipsize=params.named_parameters["clipsize"].toInt();
	if ((clipsize<=2)||(clipsize>=1000)) {
		qCritical() << "invalid clipsize" << clipsize;
		usage(); return -1;
	}
	runparams["clipsize"]=clipsize;

	QStringList labels=params.named_parameters["labels"].split(",");
	if (labels.count()!=2) {
		qCritical() << "invalid labels" << params.named_parameters["labels"];
		usage(); return -1;
	}
	runparams["labels"]=labels;

	FILE *inf1=fopen(inpath1.toLatin1().data(),"rb");
	if (!inf1) {printf("Unable to open input file1 for reading.\n"); return -1;}
	FILE *inf2=fopen(inpath2.toLatin1().data(),"rb");
	if (!inf2) {printf("Unable to open input file2 for reading.\n"); return -1;}
	FILE *inf_TL1=fopen(inpath_TL1.toLatin1().data(),"rb");
	if (!inf_TL1) {printf("Unable to open input_TL1 file for reading.\n"); return -1;}
	FILE *inf_TL2=fopen(inpath_TL2.toLatin1().data(),"rb");
	if (!inf_TL2) {printf("Unable to open input_TL2 file for reading.\n"); return -1;}
	FILE *outf1=fopen(outpath1.toLatin1().data(),"wb");
	if (!outf1) {printf("Unable to open output file1 for writing.\n"); return -1;}
	FILE *outf2=fopen(outpath2.toLatin1().data(),"wb");
	if (!outf2) {printf("Unable to open output file2 for writing.\n"); return -1;}
	FILE *outf_TL=fopen(outpath_TL.toLatin1().data(),"wb");
	if (!outf_TL) {printf("Unable to open output_TL file for writing.\n"); return -1;}
	FILE *outf_TM=fopen(outpath_TM.toLatin1().data(),"wb");
	if (!outf_TM) {printf("Unable to open output_TM file for writing.\n"); return -1;}

	qDebug()  << "Running extractclips2" << inpath1 << inpath2 << inpath_TL1 << inpath_TL2 << outpath1 << outpath2 << outpath_TM << runparams["clipsize"].toInt();
	if (!extractclips2(inf1,inf2,inf_TL1,inf_TL2,outf1,outf2,outf_TL,outf_TM,runparams)) {
		qCritical() << "Problem in extractclips.";
	}

	fclose(inf1);
	fclose(inf2);
	fclose(inf_TL1);
	fclose(inf_TL2);
	fclose(outf1);
	fclose(outf2);
	fclose(outf_TL);
	fclose(outf_TM);

	return 0;
}
コード例 #26
0
void cRenderQueue::slotRenderQueue()
{
	int queueFinished = 0;

	WriteLog("cRenderQueue::slotRenderQueue()");
	gQueue->stopRequest = false;

	while (!gQueue->stopRequest)
	{
		int queueTotalLeft = gQueue->GetQueueSize();
		cQueue::structQueueItem queueItem = gQueue->GetNextFromList();
		if (queueItem.filename == "") break; // last item reached

		emit updateProgressAndStatus(QFileInfo(queueItem.filename).fileName(),
																 QObject::tr("Queue Item %1 of %2").arg(queueFinished + 1).arg(queueTotalLeft
																		 + queueFinished),
																 (1.0 * queueFinished / (queueTotalLeft + queueFinished)),
																 cProgressText::progress_QUEUE);

		if (QFile::exists(queueItem.filename))
		{
			cSettings parSettings(cSettings::formatFullText);
			parSettings.LoadFromFile(queueItem.filename);
			parSettings.Decode(queuePar, queueParFractal, queueAnimFrames, queueKeyframes);

			queuePar->Set("image_preview_scale", 0);

			bool result = false;
			switch (queueItem.renderType)
			{
				case cQueue::queue_STILL:
					result = RenderStill(queueItem.filename);
					break;
				case cQueue::queue_FLIGHT:
				{
					result = RenderFlight();
				}
					break;
				case cQueue::queue_KEYFRAME:
				{
					result = RenderKeyframe();
				}
					break;
			}

			if (result)
			{
				gQueue->RemoveQueueItem(queueItem);
				queueFinished++;
			}
			else
			{
				break;
			}
		}
		else
		{
			cErrorMessage::showMessage("Cannot load file!\n", cErrorMessage::errorMessage);
			qCritical() << "\nSetting file " << queueItem.filename << " not found\n";
		}
	}

	emit updateProgressAndStatus(QObject::tr("Queue Render"),
															 QObject::tr("Queue Done"),
															 1.0,
															 cProgressText::progress_QUEUE);

	emit finished();
}
コード例 #27
0
//----------------------------------------------------------------------------
void print_usage()
{
  qCritical() << "Usage:";
  qCritical() << "  " << QFileInfo(qApp->arguments().at(0)).fileName() << " --hostURL url1 --applicationURL url2 <plugin-name>";
}
コード例 #28
0
ファイル: main.cpp プロジェクト: mhall119/trojita
int main(int argc, char *argv[])
{

    QGuiApplication app(argc, argv);

    QCommandLineParser parser;
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    parser.setApplicationDescription(QGuiApplication::translate("main", "Trojita is a fast Qt IMAP e-mail client"));
    parser.addHelpOption();
    QCommandLineOption phoneViewOption(QStringList() << QLatin1String("p") << QLatin1String("phone"), QGuiApplication::translate("main",
        "If running on Desktop, start in a phone sized window."));
    parser.addOption(phoneViewOption);
    QCommandLineOption tabletViewOption(QStringList() << QLatin1String("t") << QLatin1String("tablet"), QGuiApplication::translate("main",
        "If running on Desktop, start in a tablet sized window."));
    parser.addOption(tabletViewOption);
    QCommandLineOption testabilityOption(QLatin1String("testability"), QGuiApplication::translate("main",
        "DO NOT USE: autopilot sets this automatically"));
    parser.addOption(testabilityOption);
    parser.process(app);

    QQuickView viewer;
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);

    viewer.engine()->rootContext()->setContextProperty("tablet", QVariant(false));
    viewer.engine()->rootContext()->setContextProperty("phone", QVariant(false));
    if (parser.isSet(tabletViewOption)) {
        qDebug() << "running in tablet mode";
        viewer.engine()->rootContext()->setContextProperty("tablet", QVariant(true));
    } else if (parser.isSet(phoneViewOption)) {
        qDebug() << "running in phone mode";
        viewer.engine()->rootContext()->setContextProperty("phone", QVariant(true));
    } else if (qgetenv("QT_QPA_PLATFORM") != "ubuntumirclient") {
        // Default to tablet size on X11
        viewer.engine()->rootContext()->setContextProperty("tablet", QVariant(true));
    }

    if (parser.isSet(testabilityOption) || getenv("QT_LOAD_TESTABILITY")) {
        QLibrary testLib(QLatin1String("qttestability"));
        if (testLib.load()) {
            typedef void (*TasInitialize)(void);
            TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
            if (initFunction) {
                initFunction();
            } else {
                qCritical("Library qttestability resolve failed!");
            }
        } else {
            qCritical("Library qttestability load failed!");
        }
    }

    QString qmlFile;
    const QString filePath = QLatin1String("qml/trojita/main.qml");
    QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
    paths.prepend(QCoreApplication::applicationDirPath());
    Q_FOREACH (const QString &path, paths) {
        QString myPath = path + QLatin1Char('/') + filePath;
        if (QFile::exists(myPath)) {
            qmlFile = myPath;
            break;
        }
    }
コード例 #29
0
int main(int argc, char *argv[])
{
    LibCallRecorder::installMessageHandler();

    qmlRegisterType< LocaleListModel >(
                "kz.dpurgin.callrecorder.LocaleListModel", 1, 0, "LocaleListModel");
    qmlRegisterType< Settings >("kz.dpurgin.callrecorder.Settings", 1, 0, "Settings");

    int retval = -1;

    try
    {
        QScopedPointer< QGuiApplication > app(SailfishApp::application(argc, argv));

        app->setOrganizationName("kz.dpurgin");
        app->setApplicationName("harbour-callrecorder");

        QScopedPointer< QTranslator > uiTranslator(LibCallRecorder::createTranslator("ui"));
        app->installTranslator(uiTranslator.data());

        QScopedPointer< Database > db(new Database());

        QScopedPointer< EventsTableModel > eventsModel(new EventsTableModel(db.data()));
        QScopedPointer< BlackListTableModel > blackListModel(new BlackListTableModel(db.data()));
        QScopedPointer< PhoneNumbersTableModel > phoneNumbersModel(
                    new PhoneNumbersTableModel(db.data()));
        QScopedPointer< WhiteListTableModel > whiteListModel(new WhiteListTableModel(db.data()));

        QScopedPointer< FileSystemHelper > fileSystemHelper(new FileSystemHelper());

    //    QScopedPointer< Settings > settings(new Settings());

        QScopedPointer< QQuickView > view(SailfishApp::createView());

        view->engine()->addImportPath("/usr/share/harbour-callrecorder/lib/imports");

        view->setSource(SailfishApp::pathTo("qml/main.qml"));
        view->show();

        view->rootContext()->setContextProperty("eventsModel", eventsModel.data());
        view->rootContext()->setContextProperty("blackListModel", blackListModel.data());
        view->rootContext()->setContextProperty("phoneNumbersModel", phoneNumbersModel.data());
        view->rootContext()->setContextProperty("whiteListModel", whiteListModel.data());

        view->rootContext()->setContextProperty("fileSystemHelper", fileSystemHelper.data());

        view->rootContext()->setContextProperty("license",
                                                "Call Recorder for SailfishOS"
                                                "\nCopyright (C) 2014-2015 Dmitriy Purgin <*****@*****.**>"
                                                "\nhttps://github.com/dpurgin/harbour-callrecorder"
                                                "\n"
                                                "\nThis program is free software: you can redistribute it and/or modify"
                                                " it under the terms of the GNU General Public License as published by"
                                                " the Free Software Foundation, either version 3 of the License, or"
                                                " (at your option) any later version."
                                                "\n"
                                                "\nThis program is distributed in the hope that it will be useful,"
                                                " but WITHOUT ANY WARRANTY; without even the implied warranty of"
                                                " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the"
                                                " GNU General Public License for more details."
                                                "\n"
                                                "\nYou should have received a copy of the GNU General Public License"
                                                " along with this program.  If not, see <http://www.gnu.org/licenses/>.");

        view->rootContext()->setContextProperty("VERSION", QLatin1String(VERSION));

    //    view->rootContext()->setContextProperty("settings", settings.data());

        retval = app->exec();
    }
    catch (CallRecorderException& e)
    {
        qCritical() << "Exception occured: " << e.qWhat();
    }
    catch (std::exception& e)
    {
        qCritical() << "Exception occured: " << e.what();
    }
    catch (...)
    {
        qCritical() << "Unhandled exception occured";
    }

    return retval;
}
コード例 #30
0
ファイル: main.cpp プロジェクト: 01iv3r/OpenPilot
static void displayError(const QString &t)
{
    qCritical("%s", qPrintable(t));
}