Exemplo n.º 1
0
IDEApplication::IDEApplication(int& argc, char **argv)
    : QApplication(argc, argv),
      mSettings(NULL)
{
    setOrganizationName(PROJECT_ORGANIZATION);
    setApplicationName(PROJECT_NAME);
    setApplicationVersion(PROJECT_VERSION);
    setWindowIcon(QIcon(":/images/arduide.png"));

    // translation support
    initializeTranslator();

    // fix the data path
    mDataPath = QDir(DATA_PATH).absolutePath();

    registerMetaTypes();

    // initialize Grantlee
    initializeTemplates();

    // start the GUI
    initializeGui();

    // check the settings are correct, or start the wizard
    initializeSettings();

    // further gui initialization
    mMainWindow->initialize();

    // initialize the plugins
    initializePlugins();
}
Exemplo n.º 2
0
void ScriptEngine::init() {
    if (_isInitialized) {
        return; // only initialize once
    }

    _isInitialized = true;

    auto entityScriptingInterface = DependencyManager::get<EntityScriptingInterface>();
    entityScriptingInterface->init();

    // register various meta-types
    registerMetaTypes(this);
    registerMIDIMetaTypes(this);
    registerEventTypes(this);
    registerMenuItemProperties(this);
    registerAnimationTypes(this);
    registerAvatarTypes(this);
    registerAudioMetaTypes(this);

    if (_controllerScriptingInterface) {
        _controllerScriptingInterface->registerControllerTypes(this);
    }

    qScriptRegisterMetaType(this, EntityItemPropertiesToScriptValue, EntityItemPropertiesFromScriptValueHonorReadOnly);
    qScriptRegisterMetaType(this, EntityItemIDtoScriptValue, EntityItemIDfromScriptValue);
    qScriptRegisterMetaType(this, RayToEntityIntersectionResultToScriptValue, RayToEntityIntersectionResultFromScriptValue);
    qScriptRegisterSequenceMetaType<QVector<QUuid>>(this);
    qScriptRegisterSequenceMetaType<QVector<EntityItemID>>(this);

    qScriptRegisterSequenceMetaType<QVector<glm::vec2> >(this);
    qScriptRegisterSequenceMetaType<QVector<glm::quat> >(this);
    qScriptRegisterSequenceMetaType<QVector<QString> >(this);

    QScriptValue xmlHttpRequestConstructorValue = newFunction(XMLHttpRequestClass::constructor);
    globalObject().setProperty("XMLHttpRequest", xmlHttpRequestConstructorValue);

    QScriptValue printConstructorValue = newFunction(debugPrint);
    globalObject().setProperty("print", printConstructorValue);

    QScriptValue audioEffectOptionsConstructorValue = newFunction(AudioEffectOptions::constructor);
    globalObject().setProperty("AudioEffectOptions", audioEffectOptionsConstructorValue);

    qScriptRegisterMetaType(this, injectorToScriptValue, injectorFromScriptValue);
    qScriptRegisterMetaType(this, inputControllerToScriptValue, inputControllerFromScriptValue);
    qScriptRegisterMetaType(this, avatarDataToScriptValue, avatarDataFromScriptValue);
    qScriptRegisterMetaType(this, animationDetailsToScriptValue, animationDetailsFromScriptValue);

    registerGlobalObject("Script", this);
    registerGlobalObject("Audio", &AudioScriptingInterface::getInstance());
    registerGlobalObject("Controller", _controllerScriptingInterface);
    registerGlobalObject("Entities", entityScriptingInterface.data());
    registerGlobalObject("Quat", &_quatLibrary);
    registerGlobalObject("Vec3", &_vec3Library);
    registerGlobalObject("Uuid", &_uuidLibrary);
    registerGlobalObject("AnimationCache", DependencyManager::get<AnimationCache>().data());

    // constants
    globalObject().setProperty("TREE_SCALE", newVariant(QVariant(TREE_SCALE)));
}
Exemplo n.º 3
0
MixxxApplication::MixxxApplication(int& argc, char** argv)
        : QApplication(argc, argv),
          m_fakeMouseSourcePointId(0),
          m_fakeMouseWidget(NULL),
          m_activeTouchButton(Qt::NoButton),
          m_pTouchShift(NULL) {
    registerMetaTypes();
}
Exemplo n.º 4
0
 void Processor::start(ui::MainWindow * const mainWindow) {
     
     registerMetaTypes();
     
     m_thread = createThread(mainWindow);
     
     QObject::connect(m_thread, &ProcessorThread::phaseChanged, mainWindow, &ui::MainWindow::setPhase);
     QObject::connect(m_thread, &ProcessorThread::inputCountChanged, mainWindow, &ui::MainWindow::setInputCount);
     QObject::connect(m_thread, &ProcessorThread::hashingProgressChanged, mainWindow, &ui::MainWindow::setHashingProgress);
     QObject::connect(m_thread, &ProcessorThread::comparisonProgressChanged, mainWindow, &ui::MainWindow::setComparisonProgress);
     
     m_thread->start();
 }
Exemplo n.º 5
0
int
main(int argc,
     char **argv) {
  registerMetaTypes();

  App app(argc, argv);

  MainWindow mainWindow;
  mainWindow.show();

  app.exec();

  mxexit(0);
}
Exemplo n.º 6
0
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    this->setWindowState(this->windowState() ^ Qt::WindowFullScreen);

    this->setWindowIcon(QPixmap(":/Resources/icon.png"));

    widgetsList.push_back(new LoadingWidget(this));
    widgetsList.push_back(new SettingsWidget(this));
    widgetsList.push_back(new HomeWidget(this));
    widgetsList.push_back(new GalleryWidget(this));
    //widgetsList.push_back(new VideoplayerWidget(this));
    widgetsList.push_back(new DesktopWidget(this));

    initializeCursors();

    registerMetaTypes();
    startSensorThread();
}
namespace Gaussian1dFitService
{
// register metatypes with QT so that we can pass Results and InputParameters via signals/slots
static bool
registerMetaTypes()
{
    std::cerr << "Registering metatype\n";
    std::cerr << "Gaussian1dFitService::Results = "
              << qRegisterMetaType < Gaussian1dFitService::ResultsG1dFit > ( "ResultsG1dFit" ) <<
        "\n";
    std::cerr << "Gaussian1dFitService::InputParameters = "
              << qRegisterMetaType < Gaussian1dFitService::InputParametersG1dFit > (
        "InputParametersG1dFit" )
              << "\n";
    return true;
}

static bool initOnce_ = registerMetaTypes();

// private exception class
class Interrupt
{ };

ResultsG1dFit::ResultsG1dFit()
{
    //    std::cerr << "Results constructor from thread " << QThread::currentThread () << "\n";
    status_ = Error;
    diffSq = 0 / 0.0;
    rms = 0 / 0.0;
}

/*

Results::Results(const Results & r)
{
    std::cerr << "Results copy-constructor " << r.testImage.width ()
              << "x" << r.testImage.height () << " from thread " << QThread::currentThread () << "\n";

    testImage = r.testImage;
}
*/

Manager::Manager( QObject * parent ) :
    QObject( parent ),
    worker_( interruptRequested_ )
{
    // initialize internal fields
    interruptRequested_ = false;
    hasPendingInput_ = false;
    workerBusy_ = false;

    // connect worker and manager
    connect( & worker_, SIGNAL( progress( ResultsG1dFit ) ),
             this, SLOT( onProgress( ResultsG1dFit ) ) );
    connect( & worker_, SIGNAL( done( ResultsG1dFit ) ),
             this, SLOT( onDone( ResultsG1dFit ) ) );
    connect( & worker_, SIGNAL( error( QString ) ),
             this, SLOT( onError( QString ) ) );
    connect( & worker_, SIGNAL( interrupt() ),
             this, SLOT( onInterrupt() ) );
    connect( this, SIGNAL( privateGo( InputParametersG1dFit ) ),
             & worker_, SLOT( onGoFromService( InputParametersG1dFit ) ) );

    // move the worker to a separate thread
    worker_.moveToThread( & workerThread_ );
    workerThread_.start();
}

void
Manager::request( InputParametersG1dFit input )
{
    //    std::cerr << "Manager::request " << input.toString() << "\n";

    // if worker is running, ask for interrupt
    if ( workerBusy_ ) {
        interruptRequested_ = true;
    }
    pendingInput_ = input;
    hasPendingInput_ = true;
    schedulePending();
}

// if there is a pending request, and worker is not busy, ask worker
// to process the pending request
// otherwise do nothing
void
Manager::schedulePending()
{
    if ( ! hasPendingInput_ ) {
        return;
    }
    if ( workerBusy_ ) {
        return;
    }

    hasPendingInput_ = false;
    interruptRequested_ = false;
    workerBusy_ = true;

    // tell worker to start working on the request
    emit privateGo( pendingInput_ );
}

Worker::Worker( bool & interruptFlagRef )
    : interruptFlag_( interruptFlagRef )
{ }

Worker::~Worker()
{ }

// throws an exception if the interrupt flag is set
void
Worker::checkForInterrupts()
{
    if ( interruptFlag_ == true ) {
        throw Interrupt();
    }
}

void
Worker::onGoFromService( InputParametersG1dFit input )
{
    try {
        doWork( input );
    }
    catch ( Interrupt & ) {
        // std::cerr << "*** Worker interrupted ***\n";
        emit interrupt();
    }
    catch ( std::runtime_error & e ) {
        qDebug() << "Worker runtime-exception: " << e.what();
        emit error( QString( "runtime-exception: %1" ).arg( e.what() ) );
    }
    catch ( std::exception & e ) {
        qDebug() << "Worker std-exception: " << e.what();
        emit error( QString( "std-exception: %1" ).arg( e.what() ) );
    }
    catch ( std::string & s ) {
        qDebug() << "Worker exception: " << s.c_str();
        emit error( QString( "exception: %1" ).arg( s.c_str() ) );
    }
    catch ( QString & s ) {
        qDebug() << "Worker exception: " << s;
        emit error( QString( "exception: %1" ).arg( s ) );
    }
    catch ( char * s ) {
        qDebug() << "Worker exception: " << s;
        emit error( QString( "exception: %1" ).arg( s ) );
    }
    catch ( ... ) {
        qDebug() << "Worker uncaught exception...";
        emit error( "Uncaught exception" );
    }
    qDebug() << "Exiting onGoFromService";
} // Worker::onGoFromService

void
Worker::doWork( InputParametersG1dFit input )
{
    // prepare results (partial)
    ResultsG1dFit res;
    res.input = input;
    res.status_ = ResultsG1dFit::Partial;
    res.params.resize( res.input.nGaussians * 3 + res.input.poly, 0.0 );

    // handle null input (early exit)
    if ( input.isNull || input.nGaussians + input.poly <= 0 ) {
        res.status_ = ResultsG1dFit::Complete;
        res.diffSq = - 1;
        emit done( res );
        return;
    }

    // should we do all fitters?
    // heuristic fitter only if initial guess not present
    bool doHeuristic = ( int ( input.initGuess.size() ) != input.nGaussians * 3 + input.poly );

    // threshold accepting only if
    //   - multiple gaussians
    //   - or 1 gaussian and at least 1 polynomial term
    //   - it is enabled by the user
    //
    bool doLBTA = input.nGaussians > 1 || ( input.nGaussians == 1 && input.poly > 0 );
    if ( ! input.randomHeuristicsEnabled ) {
        doLBTA = false;
    }

    // levenberg/marquardt if there is at least 1 gaussian
    bool doLM = input.nGaussians > 0;

    //    doLBTA = false;
    //    doLM = false;

    // initialize timer for reporting progress
    QTime progressTimer;
    progressTimer.restart();
    bool firstProgressNeeded = true;

    int iteration = 0;

    // set up the data source for the various gaussian fitters
    Optimization::Gaussian1DFitting::FitterInput dataInterface( input.data );
    dataInterface.x1 = input.left;
    dataInterface.x2 = input.right;
    dataInterface.nGaussians = input.nGaussians;
    dataInterface.nPolyTerms = input.poly;
    dataInterface.precomputeRangeMinMax();
    dataInterface.ranges.resize( dataInterface.numParams() );
    double range12 = dataInterface.rangeMax - dataInterface.rangeMin;
    for ( int i = 0 ; i < dataInterface.nGaussians ; i++ ) {
        // center
        dataInterface.ranges[i * 3 + 0].set( input.left, input.right );

        // amplitude
        dataInterface.ranges[i * 3 + 1].set( dataInterface.rangeMin - 0.1 * range12,
                                             dataInterface.rangeMax + 0.1 * range12 );
        qDebug() << "Data range:" << dataInterface.rangeMin << dataInterface.rangeMax;

        //        dataInterface.ranges[i*3+1].set( -10, 10);
        // variance controlling term
        dataInterface.ranges[i * 3 + 2].set( - 1.0 / ( 2 * 0.25 ),
                                             - 1.0 /
                                             ( 2 * ( dataInterface.x2 - dataInterface.x1 ) *
                                               ( dataInterface.x2 - dataInterface.x1 ) ) );
    }

    // ----------------------------------------------------------------------
    // run the heuristic fitter
    // ----------------------------------------------------------------------
    if ( doHeuristic ) {
        Optimization::Gaussian1DFitting::HeuristicFitter hFitter( dataInterface );

        // start fitting
        iteration = 0;
        while ( true ) {
            iteration++;
            checkForInterrupts();
            bool fitDone = hFitter.iterate();

            // report progress:
            //   - after 100ms if it's the first time
            //   - after that every 1000ms
            bool reportProgress = progressTimer.elapsed() > 1000 ||
                                  ( progressTimer.elapsed() > 100 && firstProgressNeeded );
            bool copyResults = fitDone || reportProgress;
            if ( copyResults ) {
                res.params = hFitter.getResults();
                res.diffSq = dataInterface.calculateDiffSq( res.params );
                res.rms = sqrt( res.diffSq / dataInterface.data.size() );
                if ( int ( res.params.size() ) != input.nGaussians * 3 + input.poly ) {
                    throw std::runtime_error(
                              "Gaussian1dFitService::Worker - mismatch in result size" );
                }
            }

            if ( reportProgress ) {
                firstProgressNeeded = false;
                progressTimer.restart();
                res.status_ = res.Partial;
                res.info = QString( "Heuristics #%1" ).arg( iteration );
                checkForInterrupts();
                emit progress( res );
            }

            if ( fitDone ) {
                break;
            }
        }
        qDebug() << "Heuristic fitter produced diffSq = " << res.diffSq;

    }
    else {
        // if caller provided initial guess, use that instead
        res.params = input.initGuess;
        res.diffSq = dataInterface.calculateDiffSq( res.params );
        res.rms = sqrt( res.diffSq / dataInterface.data.size() );
        res.status_ = res.Partial;
        res.info = QString( "Initial guess" );
        qDebug() << "Initial guess has diffSq = " << res.diffSq;
    }

    // ----------------------------------------------------------------------
    // setup the LBTA fitter
    // ----------------------------------------------------------------------
    if ( doLBTA ) {
        Optimization::Gaussian1DFitting::LBTAFitter taFitter( dataInterface );
        taFitter.setInitialParams( res.params );

        // start fitting
        iteration = 0;
        while ( true ) {
            iteration++;
            checkForInterrupts();

            //        dbg(1) << "Calling taFitter.iterate()\n";
            bool taDone = taFitter.iterate();

            // report progress:
            //   - after 100ms if it's the first time
            //   - after that every 1000ms
            bool reportProgress = progressTimer.elapsed() > 1000 ||
                                  ( progressTimer.elapsed() > 100 && firstProgressNeeded );
            bool copyResults = taDone || reportProgress;
            if ( copyResults ) {
                res.params = taFitter.getResults();
                res.diffSq = dataInterface.calculateDiffSq( res.params );
                res.rms = sqrt( res.diffSq / dataInterface.data.size() );
                if ( int ( res.params.size() ) != input.nGaussians * 3 + input.poly ) {
                    throw std::runtime_error(
                              "Gaussian1dFitService::Worker - mismatch in result size" );
                }
            }

            if ( reportProgress ) {
                firstProgressNeeded = false;
                progressTimer.restart();
                res.status_ = res.Partial;
                res.info = QString( "TA #%1" ).arg( iteration );
                checkForInterrupts();
                emit progress( res );
            }

            if ( taDone ) {
                break;
            }
        }
        qDebug() << "LBTA fitter produced diffSq = " << res.diffSq;

    }

    if ( doLM ) {
        // ----------------------------------------------------------------------
        // setup up the lev-mar fitter
        // ----------------------------------------------------------------------
        Optimization::Gaussian1DFitting::LMFitter lmfitter( dataInterface );
        lmfitter.setInitialParams( res.params );

        // start fitting
        iteration = 0;
        while ( true ) {
            iteration++;
            checkForInterrupts();
            bool lmDone = lmfitter.iterate();

            // report progress:
            //   - after 100ms if it's the first time
            //   - after that every 1000ms
            bool reportProgress = progressTimer.elapsed() > 1000 ||
                                  ( progressTimer.elapsed() > 100 && firstProgressNeeded );
            bool copyResults = lmDone || reportProgress;
            if ( copyResults ) {
                res.params = lmfitter.getResults();
                res.diffSq = dataInterface.calculateDiffSq( res.params );

                // TODO: fix up RMS to account for NANs
                res.rms = sqrt( res.diffSq / dataInterface.data.size() );
                if ( int ( res.params.size() ) != input.nGaussians * 3 + input.poly ) {
                    throw std::runtime_error(
                              "Gaussian1dFitService::Worker - mismatch in result size" );
                }
            }

            if ( reportProgress ) {
                firstProgressNeeded = false;
                progressTimer.restart();
                res.status_ = res.Partial;
                res.info = QString( "LevMar #%1" ).arg( iteration );
                checkForInterrupts();
                emit progress( res );
            }

            if ( lmDone ) {
                break;
            }
        }
        qDebug() << "LevMar iteration = " << iteration;
        qDebug() << "LevMar fitter produced diffSq = " << res.diffSq;

//        {
//            QString s;
//            QTextStream out(&s);
//            for( size_t i = 0 ; i < res.params.size() ; i ++ ) {
//                if( i > 10) { out << "..."; break; }
//                out << res.params[i] << " ";
//            }
//            out << "\n";
//            dbg(1) << "   params: " << s;
//        }
    }

    res.status_ = res.Complete;
    res.info = "All done.";
    checkForInterrupts();
    emit done( res );
} // Worker::doWork

void
Manager::onProgress( ResultsG1dFit r )
{
    //    std::cerr << "Manager::onProgress: " << r.toString() << "\n";
    emit progress( r );
    emit results( r );
}

void
Manager::onDone( ResultsG1dFit r )
{
    //    std::cerr << "Manager::onDone: " << r.toString() << "\n";
    emit done( r );
    emit results( r );
    workerBusy_ = false;
    schedulePending();
}

void
Manager::onError( QString s )
{
    //    std::cerr << "Manager::onError: " << s << "\n";
    emit error( s );
    workerBusy_ = false;
    schedulePending();
}

void
Manager::onInterrupt()
{
    //    std::cerr << "Manager::onInterrupt\n";
    workerBusy_ = false;
    schedulePending();
}

//double Worker::getData( int x)
//{
//    if( x < 0 || x >= int(data.size()) ) {
//        LTHROW( QString("Gaussian1dFitService::Worker::getData() out of bounds x = %1").arg(x));
//        qDebug() << "Gaussian1dFitService::Worker::getData() out of bounds x = " << x << "\n";
//        return 0;
//    }
//    return data[x];
//}
}; // namespace Gaussian1dFitService
Exemplo n.º 8
0
ProxyBase::ProxyBase(QObject *parent) : QObject(parent)
{
	registerMetaTypes();
}
Exemplo n.º 9
0
void ScriptEngine::init() {
    if (_isInitialized) {
        return; // only initialize once
    }

    _isInitialized = true;

    _voxelsScriptingInterface.init();
    _particlesScriptingInterface.init();

    // register various meta-types
    registerMetaTypes(&_engine);
    registerVoxelMetaTypes(&_engine);
    registerEventTypes(&_engine);
    registerMenuItemProperties(&_engine);
    registerAnimationTypes(&_engine);
    registerAvatarTypes(&_engine);

    qScriptRegisterMetaType(&_engine, ParticlePropertiesToScriptValue, ParticlePropertiesFromScriptValue);
    qScriptRegisterMetaType(&_engine, ParticleIDtoScriptValue, ParticleIDfromScriptValue);
    qScriptRegisterSequenceMetaType<QVector<ParticleID> >(&_engine);

    qScriptRegisterMetaType(&_engine, ModelItemPropertiesToScriptValue, ModelItemPropertiesFromScriptValue);
    qScriptRegisterMetaType(&_engine, ModelItemIDtoScriptValue, ModelItemIDfromScriptValue);
    qScriptRegisterMetaType(&_engine, RayToModelIntersectionResultToScriptValue, RayToModelIntersectionResultFromScriptValue);
    qScriptRegisterSequenceMetaType<QVector<ModelItemID> >(&_engine);

    qScriptRegisterSequenceMetaType<QVector<glm::vec2> >(&_engine);
    qScriptRegisterSequenceMetaType<QVector<glm::quat> >(&_engine);
    qScriptRegisterSequenceMetaType<QVector<QString> >(&_engine);

    QScriptValue xmlHttpRequestConstructorValue = _engine.newFunction(XMLHttpRequestClass::constructor);
    _engine.globalObject().setProperty("XMLHttpRequest", xmlHttpRequestConstructorValue);

    QScriptValue printConstructorValue = _engine.newFunction(debugPrint);
    _engine.globalObject().setProperty("print", printConstructorValue);

    QScriptValue soundConstructorValue = _engine.newFunction(soundConstructor);
    QScriptValue soundMetaObject = _engine.newQMetaObject(&Sound::staticMetaObject, soundConstructorValue);
    _engine.globalObject().setProperty("Sound", soundMetaObject);

    QScriptValue injectionOptionValue = _engine.scriptValueFromQMetaObject<AudioInjectorOptions>();
    _engine.globalObject().setProperty("AudioInjectionOptions", injectionOptionValue);

    QScriptValue localVoxelsValue = _engine.scriptValueFromQMetaObject<LocalVoxels>();
    _engine.globalObject().setProperty("LocalVoxels", localVoxelsValue);
    
    qScriptRegisterMetaType(&_engine, injectorToScriptValue, injectorFromScriptValue);

    registerGlobalObject("Script", this);
    registerGlobalObject("Audio", &_audioScriptingInterface);
    registerGlobalObject("Controller", _controllerScriptingInterface);
    registerGlobalObject("Models", &_modelsScriptingInterface);
    registerGlobalObject("Particles", &_particlesScriptingInterface);
    registerGlobalObject("Quat", &_quatLibrary);
    registerGlobalObject("Vec3", &_vec3Library);
    registerGlobalObject("Uuid", &_uuidLibrary);
    registerGlobalObject("AnimationCache", &_animationCache);

    registerGlobalObject("Voxels", &_voxelsScriptingInterface);

    // constants
    QScriptValue globalObject = _engine.globalObject();
    globalObject.setProperty("TREE_SCALE", _engine.newVariant(QVariant(TREE_SCALE)));
    globalObject.setProperty("COLLISION_GROUP_ENVIRONMENT", _engine.newVariant(QVariant(COLLISION_GROUP_ENVIRONMENT)));
    globalObject.setProperty("COLLISION_GROUP_AVATARS", _engine.newVariant(QVariant(COLLISION_GROUP_AVATARS)));
    globalObject.setProperty("COLLISION_GROUP_VOXELS", _engine.newVariant(QVariant(COLLISION_GROUP_VOXELS)));
    globalObject.setProperty("COLLISION_GROUP_PARTICLES", _engine.newVariant(QVariant(COLLISION_GROUP_PARTICLES)));

    globalObject.setProperty("AVATAR_MOTION_OBEY_LOCAL_GRAVITY", _engine.newVariant(QVariant(AVATAR_MOTION_OBEY_LOCAL_GRAVITY)));
    globalObject.setProperty("AVATAR_MOTION_OBEY_ENVIRONMENTAL_GRAVITY", _engine.newVariant(QVariant(AVATAR_MOTION_OBEY_ENVIRONMENTAL_GRAVITY)));

    // let the VoxelPacketSender know how frequently we plan to call it
    _voxelsScriptingInterface.getVoxelPacketSender()->setProcessCallIntervalHint(SCRIPT_DATA_CALLBACK_USECS);
    _particlesScriptingInterface.getParticlePacketSender()->setProcessCallIntervalHint(SCRIPT_DATA_CALLBACK_USECS);
}
Exemplo n.º 10
0
bool Quassel::init() {
  if(_initialized)
    return true;  // allow multiple invocations because of MonolithicApplication

  if (_handleCrashes) {
    // we have crashhandler for win32 and unix (based on execinfo).
#if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
# ifndef Q_OS_WIN32
    // we only handle crashes ourselves if coredumps are disabled
    struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
    int rc = getrlimit(RLIMIT_CORE, limit);

    if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
# endif /* Q_OS_WIN32 */
      signal(SIGABRT, handleSignal);
      signal(SIGSEGV, handleSignal);
# ifndef Q_OS_WIN32
      signal(SIGBUS, handleSignal);
    }
    free(limit);
# endif /* Q_OS_WIN32 */
#endif /* Q_OS_WIN32 || HAVE_EXECINFO */
  }

  _initialized = true;
  qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

  registerMetaTypes();

  Network::setDefaultCodecForServer("ISO-8859-1");
  Network::setDefaultCodecForEncoding("UTF-8");
  Network::setDefaultCodecForDecoding("ISO-8859-15");

  if(isOptionSet("help")) {
    cliParser()->usage();
    return false;
  }

  if(isOptionSet("version")) {
    std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
    return false;
  }

  DEBUG = isOptionSet("debug");

  // set up logging
  if(Quassel::runMode() != Quassel::ClientOnly) {
    if(isOptionSet("loglevel")) {
      QString level = optionValue("loglevel");

      if(level == "Debug") _logLevel = DebugLevel;
      else if(level == "Info") _logLevel = InfoLevel;
      else if(level == "Warning") _logLevel= WarningLevel;
      else if(level == "Error") _logLevel = ErrorLevel;
    }

    QString logfilename = optionValue("logfile");
    if(!logfilename.isEmpty()) {
      _logFile = new QFile(logfilename);
      if(!_logFile->open(QIODevice::Append | QIODevice::Text)) {
        qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
        _logFile->deleteLater();
        _logFile = 0;
      }
    }
#ifdef HAVE_SYSLOG
    _logToSyslog = isOptionSet("syslog");
#endif
  }

  return true;
}
/*!
    Constructs a new abstract file task object with \a item.
*/
AbstractFileTask::AbstractFileTask(const FileTaskItem &item)
{
    registerMetaTypes();
    setTaskItem(item);
}
Exemplo n.º 12
0
#include "../../general/hlogger_p.h"
#include "../../utils/hsysutils_p.h"

#include <QtCore/QUrl>
#include <QtCore/QString>

#include <QtCore/QMetaType>

static bool registerMetaTypes()
{
    qRegisterMetaType<Herqq::Upnp::HUdn>("Herqq::Upnp::HUdn");
    return true;
}

static bool test = registerMetaTypes();

namespace Herqq
{

namespace Upnp
{

/*******************************************************************************
 * ControlPointHttpServer
 ******************************************************************************/
ControlPointHttpServer::ControlPointHttpServer(HControlPointPrivate* owner) :
    HHttpServer(owner->m_loggingIdentifier, owner),
    m_owner(owner)
{
    Q_ASSERT(m_owner);
Exemplo n.º 13
0
namespace RegionStatsService {

// register metatypes with QT so that we can pass Results and InputParameters via signals/slots
static bool registerMetaTypes() {
    std::cerr << "Registering metatype\n";
    std::cerr << " RegionStatsService::Results = "
              << qRegisterMetaType<RegionStatsService::ResultsRS>("ResultsRS") << "\n";
    std::cerr << " RegionStatsService::InputParameters = "
              << qRegisterMetaType<RegionStatsService::InputParametersRS>("InputParametersRS")
              << "\n";
    return true;
}
static bool initOnce_ = registerMetaTypes ();

// private exception class
//class Interrupt : public std::runtime_error
//{
//public:
//    Interrupt() : std::runtime_error("worker-interrupt") {}
//};

// private exception class
class Interrupt
{
};


ResultsRS::ResultsRS()
{
    status_ = Error;

    width = height = totalPixels = nanPixels = 0;
    min = max = average = sum = rms = bkgLevel = sumMinusBkg = maxMinusBkg = 0.0;
    maxPos = QPoint( -1, -1);
    depth = 0;
    currentFrame = 0;
    nFramesComputed = 0;
    beamArea = std::numeric_limits<double>::quiet_NaN();
    totalFluxDensity = std::numeric_limits<double>::quiet_NaN();
    aboveBackground = std::numeric_limits<double>::quiet_NaN();
}

/*

Results::Results(const Results & r)
{
    std::cerr << "Results copy-constructor " << r.testImage.width ()
              << "x" << r.testImage.height () << " from thread " << QThread::currentThread () << "\n";

    testImage = r.testImage;
}
*/


Manager::Manager(QObject *parent) :
    QObject(parent),
    worker_(interruptRequested_)
{
    // initialize internal fields
    interruptRequested_ = false;
    hasPendingInput_ = false;
    workerBusy_ = false;

    // connect worker and manager
    connect ( & worker_, SIGNAL( progress(ResultsRS)),
              this, SLOT(onProgress(ResultsRS)));
    connect ( & worker_, SIGNAL( done(ResultsRS)),
              this, SLOT(onDone(ResultsRS)));
    connect ( & worker_, SIGNAL( error(QString)),
              this, SLOT(onError(QString)));
    connect ( & worker_, SIGNAL( interrupt()),
              this, SLOT(onInterrupt()));
    connect ( this, SIGNAL(privateGo(InputParametersRS)),
              & worker_, SLOT(onGoFromService(InputParametersRS)));


    // move the worker to a separate thread
    worker_.moveToThread( & workerThread_);
    workerThread_.start ();
}


void Manager::request (InputParametersRS input)
{
    dbg(1) << "Manager::request " << input.toString() << "\n";

    // if worker is running, ask for interrupt
    if( workerBusy_) {
        interruptRequested_ = true;
    }
    pendingInput_ = input;
    hasPendingInput_ = true;
    schedulePending ();
}

// if there is a pending request, and worker is not busy, ask worker
// to process the pending request, otherwise do nothing
void Manager::schedulePending ()
{
    if( ! hasPendingInput_) return;
    if( workerBusy_) return;

    hasPendingInput_ = false;
    interruptRequested_ = false;
    workerBusy_ = true;
    // tell worker to start working on the request
    emit privateGo ( pendingInput_);
}

void Manager::go ()
{
}

Worker::Worker( bool & interruptFlagRef)
    : interruptFlag_( interruptFlagRef)
    , m_parser( 0)
{
//    fitsParser_ = 0;
//    currentFitsLocation_ = "";
}

// throws an exception if the interrupt flag is set
void Worker::throwIfInterrupt ()
{
    if( interruptFlag_ == true)
        throw Interrupt();
}


void Worker::onGoFromService (InputParametersRS input)
{
    try {

        doWork( input);

    } catch ( Interrupt & ) {
        // std::cerr << "*** Worker interrupted ***\n";
        dbg(1) << "RS interrupted\n";
        emit interrupt ();
    } catch ( std::runtime_error & e) {
        std::cerr << "Worker runtime-exception: " << e.what() << "\n";
        emit error( QString("runtime-exception: %1").arg(e.what()));
    } catch ( std::exception & e) {
        std::cerr << "Worker std-exception: " << e.what() << "\n";
        emit error( QString("std-exception: %1").arg(e.what()));
    } catch ( std::string & s) {
        std::cerr << "Worker exception: " << s << "\n";
        emit error( QString("exception: %1").arg(s.c_str()));
    } catch ( QString & s) {
        std::cerr << "Worker exception: " << s << "\n";
        emit error( QString("exception: %1").arg(s));
    } catch ( char * s) {
        std::cerr << "Worker exception: " << s << "\n";
        emit error( QString("exception: %1").arg(s));
    } catch (...) {
        std::cerr << "Worker uncaught exception...\n";
        dbg(1) << "Worker uncaught exception\n";
        emit error ( "Uncaught exception");
//        throw;
    }
}

void Worker::doWorkOld (InputParametersRS input)
{
    ResultsRS r;
    // for null input emit null output
    if( input.isNull) {
        r.status_ = ResultsRS::NullInput;
        emit done(r);
        return;
    }

    // initialize the parser if it's not already initialized
    if( ! m_parser)
        m_parser = new FitsParser();

    // if the parser is working on a different filename, reopen it
    if( currentFitsLocation_.uniqueId () != input.fitsLocation.uniqueId ()) {
        bool res = m_parser->loadFile ( input.fitsLocation);
        if( ! res)
            throw std::runtime_error("Could not open file");
        else
            currentFitsLocation_ = input.fitsLocation;
    }

    // get a reference to the fits header
    const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo ();

    // check for more input errors now that we have fits header
    input.left = clamp( input.left, 0, hdr.naxis1-1);
    input.right = clamp( input.right, 0, hdr.naxis1-1);
    input.top = clamp( input.top, 0, hdr.naxis2-1);
    input.bottom = clamp( input.bottom, 0, hdr.naxis2-1);
    if( input.left > input.right) std::swap( input.left, input.right);
    if( input.top > input.bottom) std::swap( input.top, input.bottom);

    // prepare results (partial)
    r.input = input; // save reference to (fixed) input
    r.width = r.input.right - r.input.left + 1;
    r.height = r.input.bottom - r.input.top + 1;
    r.totalPixels = r.width * r.height;
    r.status_ = ResultsRS::Partial;
    r.depth = hdr.totalFrames;
    r.currentFrame = r.input.currentFrame;
    throwIfInterrupt();
//    emit progress (r);

    int frame = r.input.currentFrame;

    // get the frame results for the current frame
    r.frames.resize( hdr.totalFrames);
    r.frames[ frame] = computeFrame( input, frame);
    ResultsRS::FrameRes & cfr = r.frames[ frame];
//    cfr = computeForFrame( input, frame);

    // copy out the relevant bits
    r.nanPixels = cfr.nanPixels;
    r.min = cfr.min;
    r.max = cfr.max;
    r.average = cfr.average;
    r.sum = cfr.sum;
    r.rms = cfr.rms;
    r.bkgLevel = cfr.bkgLevel;
    r.sumMinusBkg = cfr.sumMinusBkg;
    r.maxMinusBkg = cfr.maxMinusBkg;
    r.maxPos = cfr.maxPos;

    emit progress( r);

    // initialize timer for reporting progress
    QTime progressTimer;
    progressTimer.restart ();

    // now extract all the other frames
    for( int i = 0 ; i < hdr.totalFrames ; i ++ ) {
        throwIfInterrupt();
        if( i == frame) continue; // skip the current frame, we already did that one
        // compute the frame
        r.frames[i] = computeFrame( input, i);
        r.nFramesComputed = i + 1;
        // report progress every second or so, but not for the last frame...
        if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) {
            progressTimer.restart ();
            throwIfInterrupt ();
            emit progress( r);
        }
    }

    // we are done
    r.status_ = ResultsRS::Complete;
    r.nFramesComputed = r.depth;
    throwIfInterrupt ();
    emit done (r);
}

void Worker::doWork (InputParametersRS input)
{
    // if the last input is different from this input only in the frame number,
    // then we can re-use some of the results from previous invocation
    bool cacheValid = false;
    if( m_lastInput.fitsLocation.uniqueId() == input.fitsLocation.uniqueId()
            && ! m_lastInput.isNull
            && m_lastInput.bottom == input.bottom
            && m_lastInput.top == input.top
            && m_lastInput.left == input.left
            && m_lastInput.right == input.right)
    {
        cacheValid = true;
    } else {
        cacheValid = false;
        m_currRes = ResultsRS();
        m_currRes.nFramesComputed = 0;
    }

    m_lastInput = input;

    // for null input emit null output
    if( input.isNull) {
        m_currRes.status_ = ResultsRS::NullInput;
        emit done(m_currRes);
        return;
    }

    // initialize the parser if it's not already initialized
    if( ! m_parser)
        m_parser = new FitsParser();

    // if the parser is working on a different filename, reopen it
    if( currentFitsLocation_.uniqueId () != input.fitsLocation.uniqueId ()) {
        bool res = m_parser->loadFile ( input.fitsLocation);
        if( ! res)
            throw std::runtime_error("Could not open file");
        else
            currentFitsLocation_ = input.fitsLocation;
    }

    // get a reference to the fits header
    const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo ();

    // check for more input errors now that we have fits header
    input.left = clamp( input.left, 0, hdr.naxis1-1);
    input.right = clamp( input.right, 0, hdr.naxis1-1);
    input.top = clamp( input.top, 0, hdr.naxis2-1);
    input.bottom = clamp( input.bottom, 0, hdr.naxis2-1);
    if( input.left > input.right) std::swap( input.left, input.right);
    if( input.top > input.bottom) std::swap( input.top, input.bottom);


    // prepare results (partial)
    m_currRes.input = input; // save reference to (fixed) input
    m_currRes.width = m_currRes.input.right - m_currRes.input.left + 1;
    m_currRes.height = m_currRes.input.bottom - m_currRes.input.top + 1;
    m_currRes.totalPixels = m_currRes.width * m_currRes.height;
    m_currRes.depth = hdr.totalFrames;
    m_currRes.currentFrame = m_currRes.input.currentFrame;
    throwIfInterrupt();

    int frame = m_currRes.input.currentFrame;

    // get the frame results for the current frame, unless we can retrieve this already
    // from the last time
    m_currRes.frames.resize( hdr.totalFrames);
    if( cacheValid && frame < m_currRes.nFramesComputed) {

    } else {
        m_currRes.frames[ frame] = computeFrame( input, frame);
    }
    ResultsRS::FrameRes & cfr = m_currRes.frames[ frame];

    // copy out the relevant bits
    m_currRes.nanPixels = cfr.nanPixels;
    m_currRes.min = cfr.min;
    m_currRes.max = cfr.max;
    m_currRes.average = cfr.average;
    m_currRes.sum = cfr.sum;
    m_currRes.rms = cfr.rms;
    m_currRes.bkgLevel = cfr.bkgLevel;
    m_currRes.sumMinusBkg = cfr.sumMinusBkg;
    m_currRes.maxMinusBkg = cfr.maxMinusBkg;
    m_currRes.maxPos = cfr.maxPos;

    { // total flux
        double bmin = 0.0, bmaj = 0.0;
        bool ok = true;
        if( ok) bmin = hdr.bmin.toDouble( & ok);
        if( ok) bmaj = hdr.bmaj.toDouble( & ok);
        if( ok) {
            m_currRes.beamArea = bmin * bmaj * 1.13309003545679845240692073642916670254
                    / (hdr.cdelt1 * hdr.cdelt2);
            m_currRes.beamArea = fabs( m_currRes.beamArea);
            m_currRes.totalFluxDensity = m_currRes.sum / m_currRes.beamArea;
            m_currRes.aboveBackground = m_currRes.sumMinusBkg / m_currRes.beamArea;
        } else {
            m_currRes.totalFluxDensity = std::numeric_limits<double>::quiet_NaN();
            m_currRes.aboveBackground = std::numeric_limits<double>::quiet_NaN();
            m_currRes.beamArea = std::numeric_limits<double>::quiet_NaN();
        }
    }

    // if the results are already complete, we are done
    if( m_currRes.nFramesComputed == hdr.totalFrames) {
        m_currRes.status_ = ResultsRS::Complete;
        emit done (m_currRes);
        return;
    }

    // otherwise we'll have to compute the remaining frames, but in any case,
    // report a partial result right now with the current frame
    m_currRes.status_ = ResultsRS::Partial;
    emit progress( m_currRes);

    // initialize timer for reporting progress
    QTime progressTimer;
    progressTimer.restart ();

    // now extract all the other frames
    int startFrame = m_currRes.nFramesComputed;
    for( int i = startFrame ; i < hdr.totalFrames ; i ++ ) {
        throwIfInterrupt();
        if( i == frame) continue; // skip the current frame, we already did that one
        // compute the frame
        m_currRes.frames[i] = computeFrame( input, i);
        m_currRes.nFramesComputed = i + 1;
        // report progress every second or so, but not for the last frame...
        if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) {
            progressTimer.restart ();
            throwIfInterrupt ();
            emit progress( m_currRes);
        }
    }

    // we are done
    m_currRes.status_ = ResultsRS::Complete;
    m_currRes.nFramesComputed = m_currRes.depth;
    throwIfInterrupt ();
    emit done (m_currRes);
}

ResultsRS::FrameRes
Worker::computeFrame(InputParametersRS input, int frame)
{
    ResultsRS::FrameRes r;

    // prepare results (partial)
    r.width = input.right - input.left + 1;
    r.height = input.bottom - input.top + 1;
    r.totalPixels = r.width * r.height;

    // get the four corner average
    double cornerSum = 0.0; int cornerCount = 0;
    {
        double val = m_parser-> src( input.left, input.top, frame);
        if( ! isnan(val)) { cornerCount ++; cornerSum += val; }
    }{
        double val = m_parser-> src( input.left, input.bottom, frame);
        if( ! isnan(val)) { cornerCount ++; cornerSum += val; }
    }{
        double val = m_parser-> src( input.right, input.top, frame);
        if( ! isnan(val)) { cornerCount ++; cornerSum += val; }
    }{
        double val = m_parser-> src( input.right, input.bottom, frame);
        if( ! isnan(val)) { cornerCount ++; cornerSum += val; }
    }
    if( cornerCount > 0) {
        r.bkgLevel = cornerSum / cornerCount;
    } else {
        r.bkgLevel = std::numeric_limits<double>::quiet_NaN();
    }

//    const char * ptr = 0;
    double val;
    r.min = r.max = std::numeric_limits<double>::quiet_NaN();
    r.nanPixels = 0;
    r.sum = 0;
    for( int y = input.top ; y <= input.bottom ; y ++ ) {
        throwIfInterrupt();
        for( int x = input.left ; x <= input.right ; x ++ ) {
//            ptr = m_parser-> srcRaw ( x, y, frame);
//            val = m_parser-> raw2double( ptr);
            val = m_parser-> src( x, y, frame);
            if( std::isnan(val)) {
                r.nanPixels ++;
            } else {
                r.sum += val;
                if( isnan(r.min) || val < r.min) r.min = val;
                if( isnan(r.max) || val > r.max) {
                    r.max = val;
                    r.maxPos = QPoint( x, y);
                }
            }
        }
    }
    r.average = r.sum / (r.totalPixels - r.nanPixels);

    r.sumMinusBkg = r.sum - r.bkgLevel * (r.totalPixels - r.nanPixels);
    r.maxMinusBkg = r.max - r.bkgLevel;

    double sumSq = 0;
    for( int y = input.top ; y <= input.bottom ; y ++ ) {
        throwIfInterrupt();
        for( int x = input.left ; x <= input.right ; x ++ ) {
//            ptr = m_parser-> srcRaw ( x, y, frame);
//            val = m_parser-> raw2double( ptr);
            val = m_parser-> src( x, y, frame);
            if( ! std::isnan(val)) {
                sumSq += (val - r.average) * (val - r.average);
            }
        }
    }
    r.rms = sqrt( sumSq / (r.totalPixels - r.nanPixels - 1));

    return r;
}

void Manager::onProgress (ResultsRS r)
{
//    std::cerr << "Manager::onProgress: " << r.toString() << "\n";
    emit progress (r);
}

void Manager::onDone (ResultsRS r)
{
//    std::cerr << "Manager::onDone: " << r.toString() << "\n";
    emit done (r);
    workerBusy_ = false;
    schedulePending ();
}

void Manager::onError (QString s)
{
//    std::cerr << "Manager::onError: " << s << "\n";
    emit error (s);
    workerBusy_ = false;
    schedulePending ();
}

void Manager::onInterrupt ()
{
//    std::cerr << "Manager::onInterrupt\n";
    workerBusy_ = false;
    schedulePending ();
}




}; // namespace PSRVC
/*!
    Constructs a new abstract file task object with \a source and \a target.
*/
AbstractFileTask::AbstractFileTask(const QString &source, const QString &target)
{
    registerMetaTypes();
    setTaskItem(FileTaskItem(source, target));
}
Exemplo n.º 15
0
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Herqq UPnP Av. If not, see <http://www.gnu.org/licenses/>.
 */

#include "hrating.h"

#include <QtCore/QMetaType>

static bool registerMetaTypes()
{
    qRegisterMetaType<Herqq::Upnp::Av::HRating>("Herqq::Upnp::Av::HRating");
    return true;
}

static bool regMetaT = registerMetaTypes();

namespace Herqq
{

namespace Upnp
{

namespace Av
{

namespace
{
HRating::MpaaValues convertMpaa(const QString& arg)
{
    HRating::MpaaValues retVal = HRating::MPAA_Undefined;
Exemplo n.º 16
0
int main(int argc, char* argv[]) {
    namespace DU = util::directory;

    BibleTimeApp app(argc, argv); //for QApplication
    app.setApplicationName("bibletime");
    app.setApplicationVersion(BT_VERSION);

    showDebugMessages = QCoreApplication::arguments().contains("--debug");

#ifdef Q_WS_WIN
    // Use the default Qt message handler if --debug is not specified
    // This works with Visual Studio debugger Output Window
    if (showDebugMessages)
        qInstallMsgHandler( myMessageOutput );
#else
    qInstallMsgHandler( myMessageOutput );
#endif

#ifdef BT_ENABLE_TESTING
    if (QString(argv[1]) == QString("--run-tests")) {
        BibleTimeTest testClass;
        return QTest::qExec(&testClass);
    }
#endif

    /**
      \todo Reimplement "--ignore-session" and "--open-default-bible <key>"
            command line argument handling.
    */

#ifdef Q_WS_WIN

    // On Windows, add a path for Qt plugins to be loaded from
    app.addLibraryPath(app.applicationDirPath() + "/plugins");

    // Must set HOME var on Windows
    QString homeDir(getenv("APPDATA"));
    _putenv_s("HOME", qPrintable(homeDir));

#endif

    registerMetaTypes();

    if (!DU::initDirectoryCache()) {
        qFatal("Error initializing directory cache!");
        return EXIT_FAILURE;
    }

#ifdef Q_WS_WIN
    // change directory to the Sword or .sword directory in the $HOME dir so that
    // the sword.conf is found. It points to the sword/locales.d directory
    QString homeSwordDir = util::directory::getUserHomeDir().absolutePath();
    QDir dir;
    dir.setCurrent(homeSwordDir);
#endif

    // This is needed for languagemgr language names to work, they use \uxxxx escape sequences in string literals
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    //first install QT's own translations
    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name());
    app.installTranslator(&qtTranslator);
    //then our own
    QTranslator BibleTimeTranslator;
    BibleTimeTranslator.load( QString("bibletime_ui_").append(QLocale::system().name()), DU::getLocaleDir().canonicalPath());
    app.installTranslator(&BibleTimeTranslator);

    app.setProperty("--debug", QVariant(showDebugMessages));

    //Migrate configuration data, if neccessary
    util::migration::checkMigration();

//	setSignalHandler(signalHandler);

    BibleTime *mainWindow = new BibleTime();
    mainWindow->setAttribute(Qt::WA_DeleteOnClose);

    // a new BibleTime version was installed (maybe a completely new installation)
    if (CBTConfig::get(CBTConfig::bibletimeVersion) != BT_VERSION) {
        CBTConfig::set(CBTConfig::bibletimeVersion, BT_VERSION);
        mainWindow->saveConfigSettings();
    }

    // restore the workspace and process command line options
    //app.setMainWidget(bibletime_ptr); //no longer used in qt4 (QApplication)
    mainWindow->show();
    mainWindow->processCommandline(); //must be done after the bibletime window is visible

#ifndef NO_DBUS
    new BibleTimeDBusAdaptor(mainWindow);
    // connect to D-Bus and register as an object:
    QDBusConnection::sessionBus().registerService("info.bibletime.BibleTime");
    QDBusConnection::sessionBus().registerObject("/BibleTime", mainWindow);
#endif

    int r = app.exec();
    CLOSE_DEBUG_STREAM;
    return r;
}
/*!
    Constructs an empty abstract file task object.
*/
AbstractFileTask::AbstractFileTask()
{
    registerMetaTypes();
}