Example #1
0
// Start the whole thing
int main(int argc,char *argv[]){

  // Make sure  we're linked against the right library version
  if(fxversion[0]!=FOX_MAJOR || fxversion[1]!=FOX_MINOR || fxversion[2]!=FOX_LEVEL){
    fxerror("FOX Library mismatch; expected version: %d.%d.%d, but found version: %d.%d.%d.\n",FOX_MAJOR,FOX_MINOR,FOX_LEVEL,fxversion[0],fxversion[1],fxversion[2]);
    }

  // Make application
  FXApp application("ShutterBug");

  // Open display
  application.init(argc,argv);

  // Main window
  new ShutterBug(&application);

  // Create app
  application.create();

  // Run
  return application.run();
  }
Example #2
0
void CollectionView::removeBook(BookDescriptionPtr book) {
	if (book.isNull()) {
		return;
	}

	if (book == mySelectedBook) {
		mySelectedBook = 0;
	}

	CollectionModel &cModel = collectionModel();

	ZLResourceKey boxKey("removeBookBox");
	const std::string message =
		ZLStringUtil::printf(ZLDialogManager::dialogMessage(boxKey), book->title());
	if (ZLDialogManager::instance().questionBox(boxKey, message,
		ZLDialogManager::YES_BUTTON, ZLDialogManager::NO_BUTTON) == 0) {
		cModel.removeAllMarks();
		BookList().removeFileName(book->fileName());
		
		cModel.removeBook(book);
		if (cModel.paragraphsNumber() == 0) {
			setStartCursor(0);
		} else {
			size_t index = startCursor().paragraphCursor().index();
			if (index >= cModel.paragraphsNumber()) {
				index = cModel.paragraphsNumber() - 1;
			}
			while (!((ZLTextTreeParagraph*)cModel[index])->parent()->isOpen()) {
				--index;
			}
			gotoParagraph(index);
		}
		rebuildPaintInfo(true);
		selectBook(mySelectedBook);
		application().refreshWindow();
		myCollection.rebuild(false);
	}
}
Example #3
0
bool MoviesMainForm::handleMenuCommand(UInt16 itemId)
{
    bool    handled = false;

    switch (itemId)
    {
        case changeLocationMenuItem:
            Application::popupForm(changeLocationForm);
            handled = true;
            break;

        case viewTheatresMenuItem:
            theatresButton_.hit();
            handled = true;
            break;

        case viewMoviesMenuItem:
            moviesButton_.hit();
            handled = true;
            break;

        case refreshDataMenuItem:
            MoriartyApplication& app=application();
            if (!app.preferences().moviesLocation.empty())
                sendEvent(MoriartyApplication::appFetchMoviesEvent);
            handled = true;
            break;

        case mainPageMenuItem:
            doneBackButton_.hit();
            handled = true;
            break;

        default:
            handled = MoriartyForm::handleMenuCommand(itemId);
    }
    return handled;
}
Example #4
0
int main(int argc, char* argv[])
{
    QApplication application(argc, argv);

    application.setApplicationName(PROJECT_NAME);
    application.setOrganizationName(ORGANIZATION_NAME);
    application.setOrganizationDomain(ORGANIZATION_DOMAIN);

    // Check for other instances already running

    QLocalSocket singleInstanceSocket;
    singleInstanceSocket.connectToServer(PROJECT_NAME);

    if (singleInstanceSocket.waitForConnected(500))
    {
        singleInstanceSocket.close();
        qCritical() << "Application is already started";
        return EXIT_FAILURE;
    }

    // Initialize single instance server to prevent other instances to start

    QLocalServer::removeServer(PROJECT_NAME);
    QLocalServer singleInstanceServer;

    if (!singleInstanceServer.listen(PROJECT_NAME))
    {
        qCritical() << "Unable to start single instance server";
        return EXIT_FAILURE;
    }

    application.setQuitOnLastWindowClosed(false);

    MainWindow mainWindow;
    mainWindow.show();

    return application.exec();
}
void VlcStreamerService::start()
{
	QSocketNotifier		*snSignal;
	struct sigaction	act;

	QCoreApplication *app = application();

	snSignal = new QSocketNotifier(_sigFd[1], QSocketNotifier::Read);
	QObject::connect(snSignal, SIGNAL(activated(int)), app, SLOT(quit()));
	
	act.sa_handler = _Handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_RESTART;
	sigaction(SIGINT, &act, 0);
	sigaction(SIGTERM, &act, 0);

	_app = new VlcStreamerApp();
	if(_app->Setup()) {
		QObject::connect(app, SIGNAL(aboutToQuit()), _app, SLOT(Stop()));
		return;
	}
	app->quit();
}
Example #6
0
int main(int argc, char **argv) {
	QPEApplication application(argc, argv);

	ZLQtTimeManager::createInstance();
	ZLUnixFSManager::createInstance();
	QDialogManager::createInstance();
	QImageManager::createInstance();
	QDeviceInfo::createInstance();

	FBReader *reader = new FBReader(new QPaintContext(), argc == 1 ? std::string() : argv[1]);
	ZLDialogManager::instance().createApplicationWindow(reader);
	reader->initWindow();
	int code = application.exec();
	delete reader;

	QDeviceInfo::deleteInstance();
	QImageManager::deleteInstance();
	QDialogManager::deleteInstance();
	ZLUnixFSManager::deleteInstance();
	ZLQtTimeManager::deleteInstance();

	return code;
}
Example #7
0
int Test::main( int argc, char *argv[] ) noexcept {

#ifdef AIDKIT_GCC
	set_terminate( __gnu_cxx::__verbose_terminate_handler );
#endif
	QApplication application( argc, argv );
	QStringList arguments = application.arguments();

	// if there aren't any parameters then we want the 'silent' mode:
	// http://doc.qt.io/qt-5/qtest-overview.html#qt-test-command-line-arguments

	if ( arguments.length() == 1 ) {
		arguments.append( "-silent" );
	}

	// Execute the tests and print which have failed:

	QVector< Test * > failedTests = executeTests( arguments );
	for ( Test *test : failedTests ) {
		cerr << "Test failed: '" << test->name() << "'!" << endl;
	}
	return failedTests.size();
}
Example #8
0
TEST_F(ControllerEngineTest, connectControl_ByFunctionAllowDuplicateConnections) {
    // Test that duplicate connections are allowed when passing callbacks as functions.
    auto co = std::make_unique<ControlObject>(ConfigKey("[Test]", "co"));
    auto pass = std::make_unique<ControlObject>(ConfigKey("[Test]", "passed"));

    ScopedTemporaryFile script(makeTemporaryFile(
        "var reaction = function(value) { "
        "  var pass = engine.getValue('[Test]', 'passed');"
        "  engine.setValue('[Test]', 'passed', pass + 1.0); };"
        "engine.connectControl('[Test]', 'co', reaction);"
        "engine.connectControl('[Test]', 'co', reaction);"
        // engine.trigger() has no way to know which connection to a ControlObject
        // to trigger, so it should trigger all of them.
        "engine.trigger('[Test]', 'co');"));

    cEngine->evaluate(script->fileName());
    EXPECT_FALSE(cEngine->hasErrors(script->fileName()));
    // ControlObjectScript connections are processed via QueuedConnection. Use
    // processEvents() to cause Qt to deliver them.
    application()->processEvents();
    // The counter should have been incremented exactly twice.
    EXPECT_DOUBLE_EQ(2.0, pass->get());
}
Example #9
0
int main(int argc, char **argv)
{
    Q_INIT_RESOURCE(htmls);
    Q_INIT_RESOURCE(data);

#if defined(Q_WS_X11)
    // See if -style oxygen has been passed as a command line argument
    int hasStyle = -1;
    int hasOxygen = -1;
    for (int i = 0; i < argc; ++i) {
        if (QLatin1String(argv[i]) == QLatin1String("-style"))
            hasStyle = i;
        if (QLatin1String(argv[i]) == QLatin1String("oxygen"))
            hasOxygen = i;
    }
    bool keepOxygen = (hasStyle + 1 == hasOxygen);
#endif
    BrowserApplication application(argc, argv);
    if (!application.isRunning())
        return 0;

#if defined(Q_WS_X11)
    if (!keepOxygen
        && application.style()->objectName() == QLatin1String("oxygen")) {
        qWarning() << "Oxygen style has been detected, loading Plastique style." << endl
                   << " - KDE's 4.2's Oxygen style has too many issues with Qt 4.5 features that Arora uses and while many of the issues have been fixed for KDE 4.3, KDE 4.2 users get a really ugly Arora."
                   << "Once KDE 4.3 is released this check will be removed."
                   << "If you are still want to use Oxygen add the arguments -style oxygen on the command line.";
        application.setStyle(QLatin1String("plastique"));
    }
#endif
#ifdef Q_OS_WIN
    application.setStyle(new ExplorerStyle);
#endif
    application.newMainWindow();
    return application.exec();
}
Example #10
0
int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

    QTranslator translator;
    QString language = SETTINGS.value("language", getDefaultLanguage()).toString();

    if (language != "EN") {
        QString resource = ":/locale/"+AppNameLower+"_"+language.toLower()+".qm";
        if (QFileInfo(resource).exists()) {
            translator.load(resource);
            application.installTranslator(&translator);
        }
    }

    QCoreApplication::setOrganizationName(ParentName);
    QCoreApplication::setApplicationName(AppName);

    MainWindow window;


    QString maximized = SETTINGS.value("Geometry/maximized", "").toString();
    QString windowx = SETTINGS.value("Geometry/windowx", "").toString();
    QString windowy = SETTINGS.value("Geometry/windowy", "").toString();

    if (maximized == "true") {
        window.showMaximized();
    } else {
        window.show();
    }

    if (windowx == "" && windowy == "") {
        window.move(QApplication::desktop()->screen()->rect().center() - window.rect().center());
    }

    return application.exec();
}
Example #11
0
   //Det borde vara möjligt att titta på stylen för att avgöra om en
   //cell är en grupp cell. Då borde det gå att kopiera in underceller
   //också.
   //
   // Kontrollera på stylen hur cellerna ska kopieras. Speciellt ska
   // gruppceller specialbehandlas så att deras subceller också
   // kopieras. Just nu funkar det att kopiera enstaka celler. Men
   // inte gruppceller.
  void PasteCellsCommand::execute()
  {
    try
    {
      vector<Cell *> cells = application()->pasteboard();

      // Insert new cells before this position.
      if(!cells.empty())
      {
        //Reverse iterator!!!!!
        //vector<Cell *>::reverse_iterator i = cells.rbegin();
        //for(;i != cells.rend();++i)
        // AF, Not reverse
        vector<Cell *>::iterator i = cells.begin();
        for(;i != cells.end();++i)
        {
          try
          {
            pasteCell( (*i) );
          }
          catch(exception &e)
          {
            throw e;
          }
        }
      }

      //2006-01-18 AF, set docuement changed
      document()->setChanged( true );
    }
    catch(exception &e)
    {
      // 2006-01-30 AF, add exception
      string str = string("PasteCellsCommand(), Exception: \n") + e.what();
      throw runtime_error( str.c_str() );
    }
  }
Example #12
0
int main(int argc,char ** argv)
{

  TApplication application("app",&argc,argv);

  Signals::SignalSet signals("Meine Signale");
  Signals::Signal a(3.125);
  Signals::Signal b(3.125);
  a.SetSignalLength(200);
  b.SetSignalLength(200);
  a.CreateHeaviside(100,-1,1);
  b.CreateHeaviside(150,-2,2);

  unsigned int index=signals.SetSignal(-1,"signal",a);
  signals.SetSignal(index,"b",b);

  Tools::ASCIIOutStream streamout("test.sig");
  streamout<<signals;
  
  Tools::ASCIIInStream streamin("test.sig");
  Signals::SignalSet sigtest("Test");
  streamin>>sigtest;
  Signals::Signal& ra=sigtest.GetSignal(0,"signal");
  Signals::Signal& rb=sigtest.GetSignal(0,"b");

  TCanvas * canvas1=new TCanvas;
  a.Graph()->Draw("AL*");
  canvas1->Update();

  TCanvas * canvas2=new TCanvas;
  b.Graph()->Draw("AL*");
  canvas2->Update();

  application.Run(kTRUE);

  return 0;
}
Example #13
0
int main(int argc, char *argv[])
{
	QCoreApplication application(argc, argv);
	
	// Create and start a timer so we can measure our runtime
	QTime timer;
	timer.start();
	
	// Get our application's arguments
	QStringList strArgs= application.arguments();
	
	// If we weren't passed any extra arguments, just return and don't run the program
	if( strArgs.size() < 3 ) return application.exec();
	
	// Create our image handlers and destructor
	PNGHandler* pPNGHandler= new PNGHandler();
	SVGHandler* pSVGHandler= new SVGHandler();
	ImageDestructor* pDestructor= new ImageDestructor();
	
	// Open the image
	bool bOK= true;
	PNGImage image= pPNGHandler->OpenPNGFile( strArgs[1], bOK );
	if( !bOK ) {
		printf( "An error occurred loading " + strArgs[1].toLatin1() );
		return application.exec();;
	}
	
	SVGImage destructedImage;
	pDestructor->DestructImage( image, QRect( 0,0,image.width,image.height), destructedImage );
	
	// Write the image to file
	pSVGHandler->WriteSVGFile( destructedImage, strArgs[2] );
	
	printf( "Finished processing in %d milliseconds", timer.elapsed() );

	return application.exec();
}
Example #14
0
int main(int argc, char** argv)
{
    glutInit(&argc,argv);

    // access to the compiled resource file (icons etc.)
    // On linux, this file can be generated using the command line: rcc -binary SofaSimpleGUI.qrc -o SofaSimpleGUI.rcc
    // See http://qt-project.org/doc/qt-4.8/resources.html
    // TODO: create a build rule to update it automatically when needed
    // Note that icons can also be chosen by QStyle
    std::string path_to_resource = std::string(QTSOFA_SRC_DIR) + "/SofaSimpleGUI.rcc";
//    std::cout<<"path to resource = " << path_to_resource << std::endl;
    QResource::registerResource(path_to_resource.c_str());

    std::string fileName = std::string(QTSOFA_SRC_DIR) + "/../examples/oneTet.scn";
    std::vector<std::string> plugins;
    sofa::helper::parse("Simple glut application featuring a Sofa scene.")
            .option(&plugins,'l',"load","load given plugins")
            .option(&fileName,'f',"file","scene file to load")
            (argc,argv);


    // Read command lines arguments.
    QApplication application(argc,argv);

    // Instantiate the main window and make it visible.
    QSofaMainWindow mainWindow;
    mainWindow.initSofa(plugins,fileName);
    mainWindow.setWindowTitle("qtSofa");
    mainWindow.resize(800,600);
    mainWindow.show();
    mainWindow.sofaScene.play();


    // Run main loop.
    return application.exec();
}
int main(int argc, char** argv)
{
	std::string filename;
	if (argc < 2)
	{
		cgogn_log_info("topogical_analysis") << "USAGE: " << argv[0] << " [filename]";
		filename = std::string(DEFAULT_MESH_PATH) + std::string("/tet/hand.tet");
		cgogn_log_info("topogical_analysis") << "Using default mesh \"" << filename << "\".";
	}
	else
		filename = std::string(argv[1]);

	QApplication application(argc, argv);
	qoglviewer::init_ogl_context();

	// Instantiate the viewer.
	TopologicalAnalyser<CMap3> viewer;
	viewer.setWindowTitle("Topological Analysis");
	viewer.import(filename);
	viewer.show();

	// Run main loop.
	return application.exec();
}
Example #16
0
void MoviesMainForm::prepareMovieInfo(uint_t movie)
{
    assert(movie < movies.size());
    const Movie& mv=*(movies[movie]);
    
    DefinitionModel* model = new_nt DefinitionModel();
    if (NULL == model)
    {
        application().alert(notEnoughMemoryAlert);
        return;
    }
    Definition::Elements_t& elems = model->elements;

    TextElement* text;
    elems.push_back(text=new TextElement(mv.title));
    text->setStyle(StyleGetStaticStyle(styleNamePageTitle));

    elems.push_back(new LineBreakElement());

    Movie::TheatresByMovie_t::const_iterator end=mv.theatres.end();
    for (Movie::TheatresByMovie_t::const_iterator it=mv.theatres.begin(); it!=end; ++it)
    {   
        const TheatreByMovie& th=*(*it);
        BulletElement* bull;
        elems.push_back(bull=new BulletElement());
        bull->setStyle(StyleGetStaticStyle(styleNameHeader));
        elems.push_back(text=new TextElement(th.name));
        text->setParent(bull);
        text->setStyle(StyleGetStaticStyle(styleNameHeader));
        text->setHyperlink(buildUrl(urlSchemaTheatre, th.name.c_str()), hyperlinkUrl);
        elems.push_back(new LineBreakElement());
        elems.push_back(text=new TextElement(th.hours));
        text->setParent(bull);
    }
    infoRenderer_.setModel(model, Definition::ownModel);
}
Example #17
0
int main(int argc, char** argv)
{
	std::string surfaceMesh;
	if (argc < 2)
	{
		std::cout << "USAGE: " << argv[0] << " [filename]" << std::endl;
		surfaceMesh = std::string(DEFAULT_MESH_PATH) + std::string("aneurysm3D_1.off");
		std::cout << "Using default mesh : " << surfaceMesh << std::endl;
	}
	else
		surfaceMesh = std::string(argv[1]);

	QApplication application(argc, argv);
	qoglviewer::init_ogl_context();

	// Instantiate the viewer.
	Viewer viewer;
	viewer.setWindowTitle("simpleViewer");
	viewer.import(surfaceMesh);
	viewer.show();

	// Run main loop.
	return application.exec();
}
Example #18
0
int main(int argc, char** argv) {
    // Read command lines arguments.
    QApplication application(argc, argv);

    // Instantiate the viewer.
    Viewer viewer;

    // build your scene here

    //viewer.addRenderable(new Terrain(SIZE_TERRAIN));
    //viewer.addRenderable(new Human(0.5));
    Terrain * terrain = new Terrain(SIZE_TERRAIN);
    viewer.addRenderable(terrain);
    viewer.addRenderable(new Landscape());
    Human * human = new Human(1.0,Vec(0.0,0.0,30.0),Vec(0.0,0.0,HEIGHT_SCENE));
    viewer.addRenderable(new DynamicSystem(terrain,human));

    viewer.setWindowTitle("Projet Graphique 3D");
    // Make the viewer window visible on screen.
    viewer.show();

    // Run main loop.
    return application.exec();
}
Example #19
0
void DataService::start()
{

    try
    {
       //To do
          QCoreApplication *app = application();
           LOG4CXX_INFO( logger, "Service started" );
           LOG4CXX_INFO( logger, app->applicationFilePath().toStdString());
           DataTcpServer *server1 =new  DataTcpServer;//(app);
           server1->startServer(17002);

        // qDebug()<<"Service started";
         //qDebug()<<app->applicationFilePath();


    }
    catch(...)
    {
        qCritical()<< "Unknown error !";

    }

}
Example #20
0
int main(int argc, char *argv[])
{
    QApplication application(argc, argv);

	QPixmap pixmap("splash.png");
	QSplashScreen splash(pixmap);
	splash.setWindowFlags(Qt::WindowStaysOnTopHint);
	splash.setWindowFlags(Qt::FramelessWindowHint);
	splash.setMinimumSize(pixmap.size());
	splash.show();

	application.processEvents();
	splash.showMessage("Loading Trace Engine...");

	try {
		MainWindow win;
		//std::this_thread::sleep_for(std::chrono::milliseconds(5000));
		win.show();
		splash.finish(&win);
		return application.exec();
	} catch(std::runtime_error e) {
		splash.close();
		QMessageBox *err = new QMessageBox();
		err->setText(e.what());
		err->setModal(true);
		err->setIcon(QMessageBox::Critical);
		err->exec();
		delete err;
		application.quit();
		return -1;
    } catch(std::logic_error e) {
        return -1;
    }

	return -1;
}
Example #21
0
/***********************************************************************//**
 * @brief Main entry point
 *
 * @param[in] argc Number of arguments
 * @param[in] argv Arguments
 *
 * This is the main entry point of the ctlike application. It allocates a
 * ctlike object and executes the application.
 ***************************************************************************/
int main (int argc, char *argv[])
{
    // Initialise return code
    int rc = 1;

    // Create instance of application
    ctlike application(argc, argv);

    // Run application
    try {
        // Execute application
        application.execute();

        // Signal success
        rc = 0;
    }
    catch (std::exception &e) {

        // Extract error message
        std::string message = e.what();
        std::string signal  = "*** ERROR encounterted in the execution of"
                              " ctlike. Run aborted ...";

        // Write error in logger
        application.log << signal  << std::endl;
        application.log << message << std::endl;

        // Write error on standard output
        std::cout << signal  << std::endl;
        std::cout << message << std::endl;

    } // endcatch: catched any application error

    // Return
    return rc;
}
void CollectionView::editTagInfo(const std::string &tag) {
    if (tag.empty()) {
        return;
    }
    const bool tagIsSpecial = (tag == SpecialTagAllBooks) || (tag == SpecialTagNoTagsBooks);
    std::string tagValue = tagIsSpecial ? "" : tag;
    bool editNotClone = tag != SpecialTagAllBooks;
    bool includeSubtags = !tagIsSpecial && myCollection.hasSubtags(tag);
    const bool showIncludeSubtagsEntry = includeSubtags;
    const bool hasBooks = myCollection.hasBooks(tag);

    while (runEditTagInfoDialog(tagIsSpecial, tagValue, editNotClone, includeSubtags, showIncludeSubtagsEntry, hasBooks)) {
        ZLStringUtil::stripWhiteSpaces(tagValue);
        if (tagValue.empty()) {
            ZLDialogManager::instance().errorBox(ZLResourceKey("tagMustBeNonEmpty"));
            continue;
        }
        if (tagValue.find(',') != (size_t)-1) {
            ZLDialogManager::instance().errorBox(ZLResourceKey("tagMustNotContainComma"));
            continue;
        }
        collectionModel().removeAllMarks();
        if (tag == SpecialTagAllBooks) {
            myCollection.addTagToAllBooks(tagValue);
        } else if (tag == SpecialTagNoTagsBooks) {
            myCollection.addTagToBooksWithNoTags(tagValue);
        } else if (editNotClone) {
            myCollection.renameTag(tag, tagValue, includeSubtags);
        } else {
            myCollection.cloneTag(tag, tagValue, includeSubtags);
        }
        updateModel();
        application().refreshWindow();
        break;
    }
}
Example #23
0
int
main(int argc, char** argv)
{
	try
	{
		QApplication application(argc, argv);
		
		qRegisterMetaType< rl::math::Real >("rl::math::Real");
		qRegisterMetaType< rl::math::Transform >("rl::math::Transform");
		qRegisterMetaType< rl::math::Vector >("rl::math::Vector");
		qRegisterMetaType< rl::plan::VectorList >("rl::plan::VectorList");
		
		QObject::connect(&application, SIGNAL(lastWindowClosed()), &application, SLOT(quit()));
		
		MainWindow::instance()->show();
		
		return application.exec();
	}
	catch (const std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return -1;
	}
}
Example #24
0
int main(int argc, char * argv[])
{
#if (CISST_OS == CISST_LINUX_XENOMAI)
    mlockall(MCL_CURRENT | MCL_FUTURE);
#endif

    // set global component manager IP
    std::string globalComponentManagerIP;
    if (argc == 1) {
        std::cerr << "Using default, i.e. 127.0.0.1 to find global component manager" << std::endl;
        globalComponentManagerIP = "127.0.0.1";
    } else if (argc == 2) {
        globalComponentManagerIP = argv[1];
    } else {
        std::cerr << "Usage: " << argv[0] << " (global component manager IP)" << std::endl;
        return -1;
    }

    // log configuration
    cmnLogger::SetMask(CMN_LOG_ALLOW_ALL);
    cmnLogger::SetMaskDefaultLog(CMN_LOG_ALLOW_ALL);
    cmnLogger::AddChannel(std::cout, CMN_LOG_ALLOW_ERRORS_AND_WARNINGS);
    cmnLogger::SetMaskClassMatching("mts", CMN_LOG_ALLOW_ALL);
    cmnLogger::SetMaskClass("serverQtComponent", CMN_LOG_ALLOW_ALL);

    // create a Qt user interface
    QApplication application(argc, argv);

    // create our server component
    serverQtComponent * server = new serverQtComponent("Server");

    // Get the ComponentManager instance and set operation mode
    mtsComponentManager * componentManager;
    try {
        componentManager = mtsComponentManager::GetInstance(globalComponentManagerIP, "cisstMultiTaskCommandsAndEventsQtServer");
    } catch (...) {
        CMN_LOG_INIT_ERROR << "Failed to initialize component manager" << std::endl;
        return 1;
    }
    componentManager->AddComponent(server);

    //
    // TODO: Hide this waiting routine inside mtsComponentManager using events or other things.
    //
    osaSleep(0.5 * cmn_s);

    // create and start all components
    componentManager->CreateAll();
    componentManager->WaitForStateAll(mtsComponentState::READY);

    componentManager->StartAll();
    componentManager->WaitForStateAll(mtsComponentState::ACTIVE);

    // run Qt user interface
    application.exec();

    // kill all components and perform cleanup
    componentManager->KillAll();
    componentManager->WaitForStateAll(mtsComponentState::FINISHED, 2.0 * cmn_s);

    componentManager->Cleanup();
    return 0;
}
Example #25
0
int main(int argc, char * argv[])
{
    // parse options
    cmnCommandLineOptions options;
    std::string port;
    std::string configFile;
    unsigned int igtlPort;

    options.AddOptionOneValue("j", "json-config",
                              "json configuration file",
                              cmnCommandLineOptions::OPTIONAL_OPTION, &configFile);

    options.AddOptionOneValue("s", "serial-port",
                              "serial port (e.g. /dev/ttyUSB0, COM...)",
                              cmnCommandLineOptions::OPTIONAL_OPTION, &port);

    options.AddOptionNoValue("l", "log-serial",
                             "log all serial port read/writes in cisstLog.txt");

    options.AddOptionOneValue("i", "igtl-port",
                              "port used for OpenIGTLink server",
                              cmnCommandLineOptions::REQUIRED_OPTION, &igtlPort);

    // check that all required options have been provided
    std::string errorMessage;
    if (!options.Parse(argc, argv, errorMessage)) {
        std::cerr << "Error: " << errorMessage << std::endl;
        options.PrintUsage(std::cerr);
        return -1;
    }
    std::string arguments;
    options.PrintParsedArguments(arguments);
    std::cout << "Options provided:" << std::endl << arguments << std::endl;

    // log configuration
    if (options.IsSet("log-serial")) {
        std::cout << "Adding log for all serial port read/writes" << std::endl;
        cmnLogger::SetMask(CMN_LOG_ALLOW_ALL);
        cmnLogger::SetMaskFunction(CMN_LOG_ALLOW_ALL);
        cmnLogger::SetMaskDefaultLog(CMN_LOG_ALLOW_ALL);
        cmnLogger::SetMaskClassMatching("mtsNDISerial", CMN_LOG_ALLOW_ALL);
        cmnLogger::AddChannel(std::cerr, CMN_LOG_ALLOW_ERRORS_AND_WARNINGS);
    }

    // create a Qt user interface
    QApplication application(argc, argv);

    // create the components
    mtsNDISerial * tracker = new mtsNDISerial("NDI", 50.0 * cmn_ms);
    if (port != "") {
        tracker->SetSerialPort(port);
    }

    // configure the components
    std::string configPath = "";
    // if there's a config file passed as argument, try to locate it
    if (configFile != "") {
        if (cmnPath::Exists(configFile)) {
            configPath = configFile;
        } else {
            // search in current working directory and source tree
            cmnPath searchPath;
            searchPath.Add(cmnPath::GetWorkingDirectory());
            searchPath.Add(std::string(sawNDITracker_SOURCE_DIR) + "/../share", cmnPath::TAIL);
            configPath = searchPath.Find(configFile);
            // if still empty
            if (configPath.empty()) {
                std::cerr << "Failed to find configuration file \"" << configFile << "\"" << std::endl
                          << "Searched in: " << configPath << std::endl;
                return 1;
            }
        }
    }
    // configure
    tracker->Configure(configPath);

    // add the components to the component manager
    mtsManagerLocal * componentManager = mtsComponentManager::GetInstance();
    componentManager->AddComponent(tracker);

    // Qt widget
    mtsNDISerialControllerQtWidget * trackerWidget = new mtsNDISerialControllerQtWidget("NDI Widget");
    componentManager->AddComponent(trackerWidget);
    componentManager->Connect(trackerWidget->GetName(), "Controller",
                              tracker->GetName(), "Controller");

    // OpenIGTLink
    mtsOpenIGTLinkBridge * igtl = new mtsOpenIGTLinkBridge("NDI-igtl", 50.0 * cmn_ms);
    componentManager->AddComponent(igtl);

    // create and start all components
    componentManager->CreateAllAndWait(5.0 * cmn_s);
    componentManager->StartAllAndWait(5.0 * cmn_s);

    // create a main window to hold QWidgets
    QMainWindow * mainWindow = new QMainWindow();
    mainWindow->setCentralWidget(trackerWidget);
    mainWindow->setWindowTitle("sawNDITracker");
    mainWindow->show();

    // run Qt user interface
    application.exec();

    // kill all components and perform cleanup
    componentManager->KillAllAndWait(5.0 * cmn_s);
    componentManager->Cleanup();

    return 0;
}
Example #26
0
int main(int argc, char **argv)
{
    QApplication application(argc,argv);

    DGtal::Viewer3D viewer;

    DGtal::Z3i::Point center(0,0,0);
    DGtal::ImplicitRoundedHyperCube<Z3i::Space> myCube( center, 20, 2.8);
    DGtal::Z3i::Domain domain(myCube.getLowerBound(),
                              myCube.getUpperBound());

    DGtal::Z3i::DigitalSet mySet(domain);

    DGtal::Shapes<DGtal::Z3i::Domain>::euclideanShaper( mySet, myCube);


    viewer.show();
    // viewer << mySet << DGtal::Display3D::updateDisplay;


    //! [ImageSetDT-DT]
    typedef DGtal::SetPredicate<DGtal::Z3i::DigitalSet> Predicate;
    Predicate aPredicate(mySet);

    typedef DGtal::DistanceTransformation<Z3i::Space, Predicate, 2> DTL2;
    typedef DTL2::OutputImage OutputImage;
    DTL2 dt(domain,aPredicate);

    OutputImage result = dt.compute();
    //! [ImageSetDT-DT]

    OutputImage::Value maxDT = (*std::max_element(result.begin(),
                                result.end()));


    GradientColorMap<OutputImage::Value> gradient( 0, maxDT);
    gradient.addColor(DGtal::Color::Blue);
    gradient.addColor(DGtal::Color::Green);
    gradient.addColor(DGtal::Color::Yellow);
    gradient.addColor(DGtal::Color::Red);


    for(Z3i::Domain::ConstIterator it = domain.begin(),
            itend = domain.end(); it != itend;
            ++it)
        if (result(*it) != 0)
        {
            OutputImage::Value  val= result( *it );
            DGtal::Color c= gradient(val);

            viewer <<  DGtal::CustomColors3D(c,c) << *it    ;

        }


    viewer << DGtal::ClippingPlane(1,0,0,0);
    //@todo updateDisplay is in Display3D or Viewer3D (cf doc)?
    viewer << DGtal::Display3D::updateDisplay;

    return application.exec();


}
void ZLGtkApplicationWindow::handleKeyEventSlot(GdkEventKey *event) {
	application().doActionByKey(ZLGtkKeyUtil::keyName(event));
}
ZLViewWidget *ZLGtkApplicationWindow::createViewWidget() {
	ZLGtkViewWidget *viewWidget = new ZLGtkViewWidget(&application(), (ZLViewWidget::Angle)application().AngleStateOption.value());
	gtk_container_add(GTK_CONTAINER(myVBox), viewWidget->area());
	gtk_widget_show_all(myVBox);
	return viewWidget;
}
Example #29
0
int main(int argc, char *argv[])
{
  if (argc > 1)
  {
    QApplication application(argc, argv, FALSE);

    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    for (int counter = 1; counter < argc; counter++)
    {
      arguments = argv[counter];

      if (arguments.contains("-databaseURL="))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.contains("-username="******"-passwd="))
        passwd = arguments.right(arguments.length() - 8);
    }

    if (  (databaseURL != "") && (username != "") ) {
      QSqlDatabase *db;
      QString      hostName;
      QString      dbName;
      QString      port;

// Open the Database Driver
      db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db)
      {
        printf("Could not load the specified database driver.\n");
        exit(-1);
      }

//  Try to connect to the Database
      parseDatabaseURL(databaseURL, hostName, dbName, port);
      bool valport = FALSE;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db->setDatabaseName(dbName);
      db->setPort(iport);
      db->setUserName(username);
      if(!passwd.isEmpty())
        db->setPassword(passwd);
      db->setHostName(hostName);
      if (!db->open())
      {
        printf( "Host=%s, Database=%s, port=%s\n",
                (const char *)hostName,
                (const char *)dbName,
                (const char *)port );

        printf( "Could not log into database.  System Error: %s\n",
                (const char *)db->lastError().driverText() );
        exit(-1);
      }

      QSqlQuery().exec("SELECT login();");

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare("SELECT report_name, report_grade, report_source "
                  "  FROM report;");
      qry.exec();
      if(!qry.exec()) {
          QSqlError err = qry.lastError();
          printf("Error: %s\n\t%s\n", (const char*)err.driverText(),
                                    (const char*)err.databaseText());
          exit(-1);
      }
      QString fname;
      while(qry.next()) {
        fname = QString("%1-%2.xml").arg(qry.value(0).toString()).arg(qry.value(1).toString());
        fname.replace('/',"-");
        QFile file(fname);
        if(file.open(IO_WriteOnly))
        {
          QTextStream stream( &file );
          stream << qry.value(2).toString();
          file.close();
        }
        else
          printf("Error: Could not open file %s: %s\n", fname.latin1(), file.errorString().latin1());
      }
    }
    else if (databaseURL == "")
      printf("You must specify a Database URL by using the -databaseURL= parameter.\n");
    else if (username == "")
      printf("You must specify a Database Username by using the -username= parameter.\n");
  }
  else
    printf( "Usage: exportrpt -databaseURL='$' -username='******' -passwd='$'\n");
  return 0;
}
void QApplicationWindow::keyPressEvent(QKeyEvent *event) {
	application().doActionByKey(QKeyUtil::keyName(event));
}