示例#1
0
文件: term.c 项目: gto76/race
int main(void) {
	setEnvironment();
	setOutput();
	setScoreboard();

	while(1) {
		setRaceMode();
		PLAYER ppp[numOfPlayers];
		setPlayer(&ppp, 0, STARTING_POSITION_X, 18, '1', 65, 66, 67, 68);
		setPlayer(&ppp, 1, STARTING_POSITION_X, 20, '2', 119, 115, 100, 97);
		players = &ppp;

		redrawScreen();
		splashScreen();
		countdown();

		setStartTime(&ppp); 
		char c;
		while (!weHaveAWinner(&ppp)) { 
			c = getc(stdin);
			checkMove(c, &ppp);
		}
		printWins();
		checkeredFlag();
		waitForEnter();
	}

	return EXIT_SUCCESS;
}	
QSplashScreen *Application::buildSplashScreen() {
	const QPixmap logoPixmap(":/images/logo.png");
	QDesktopWidget *desktop = QApplication::desktop();
	QRect desktopRect = desktop->availableGeometry();
	QPixmap splashPixmap(desktopRect.width(), desktopRect.height());
	QPainter painter;
	painter.begin(&splashPixmap);
	QLinearGradient backgroundGradient(
		splashPixmap.rect().width() / 2, 0,
		splashPixmap.rect().width() / 2, splashPixmap.rect().height());
    backgroundGradient.setColorAt(0, QColor::fromRgb(40, 50, 57));
    backgroundGradient.setColorAt(1, QColor::fromRgb(19, 25, 29));
    painter.fillRect(splashPixmap.rect(), backgroundGradient);
	QRect logoRect((splashPixmap.width() - logoPixmap.width()) / 2,
	               (splashPixmap.height() - logoPixmap.height()) / 2,
	               logoPixmap.width(),
	               logoPixmap.height());
	painter.drawPixmap(logoRect, logoPixmap);
	painter.end();
	QScopedPointer<QSplashScreen> splashScreen(new QSplashScreen(splashPixmap));
	if (desktopRect.width() > desktopRect.height()) {
		splashScreen->setAttribute(Qt::WA_LockLandscapeOrientation, true);
	} else {
		splashScreen->setAttribute(Qt::WA_LockPortraitOrientation, true);
	}
	return splashScreen.take();
}
示例#3
0
void MainLoop::start(bool tilesPresent) {
  if (options->getBoolValue(OptionId::MUSIC))
    jukebox->toggle(true);
  splashScreen();
  view->reset();
  if (!tilesPresent)
    view->presentText("", "You are playing a version of KeeperRL without graphical tiles. "
        "Besides lack of graphics and music, this "
        "is the same exact game as the full version. If you'd like to buy the full version, "
        "please visit keeperrl.com.\n \nYou can also get it by donating to any wildlife charity. "
        "More information on the website.");
  int lastIndex = 0;
  while (1) {
    jukebox->setType(MusicType::MAIN, true);
    auto choice = view->chooseFromList("", {
        "Play game", "Change settings", "View high scores", "View credits", "Quit"}, lastIndex, View::MAIN_MENU);
    if (!choice)
      continue;
    lastIndex = *choice;
    switch (*choice) {
      case 0: playGameChoice(); break;
      case 1: options->handle(view, OptionSet::GENERAL); break;
      case 2: highscores->present(view); break;
      case 3: showCredits(dataFreePath + "/credits.txt", view); break;
      case 4: finished = true; break;
    }
    if (finished)
      break;
  }
}
示例#4
0
//-------------------------------------------------------------------------------------------------
LuaWorker::LuaWorker(IConsole *pConsole)
    :QObject(NULL)
    ,IScriptEngine()
    ,ISyncContext()
    ,m_pConsole(pConsole)
    ,m_mtxTasks()
    ,m_luaState(NULL)
    ,m_pSysVar(NULL)
    ,m_vLuaTables()
{
    ILuaTable::setSyncContext(this);

    // Hier keine dynamische allokation, da diese im Hauptthread geschehen würde!
    if (m_pConsole==NULL)
        throw InternalError(tr("Can't create Lua worker with null console pointer"));

    m_vLuaTables.push_back(new LuaTabWindow());
    m_vLuaTables.push_back(new LuaTabSys());
    m_vLuaTables.push_back(new LuaTabMessageBox());
    m_vLuaTables.push_back(new LuaTabCanvas());


    init();
    initTables();

    splashScreen();
}
int Application::run() {
	QScopedPointer<QSplashScreen> splashScreen(buildSplashScreen());
    splashScreen->showFullScreen();
	QScopedPointer<QDeclarativeView> applicationWindow(buildRootView());
	splashScreen->finish(applicationWindow.data());
	applicationWindow->showFullScreen();
	return QApplication::exec();
}
示例#6
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("Innovators");
    app.setApplicationName("TrollEdit");
    app.setStartDragDistance(app.startDragDistance() * 2);

    // set splashScreen
    QPixmap pixmap(":/splash");
    QSplashScreen splashScreen(pixmap,Qt::WindowStaysOnTopHint);

    // find the directory of the program
    QFileInfo program(argv[0]);
    QString path = QApplication::applicationDirPath();

    MainWindow w(path);
    w.setWindowOpacity(0);

    // Load config from config_app.lua
    lua_State *L = w.getLuaState();
    luaL_openlibs(L);
    int width, height; QString style;
    QDir dir = QDir(path + CONFIG_DIR);
    //QFileInfoList configs = dir.entryInfoList(QStringList("*.lua"), QDir::Files | QDir::NoSymLinks);
    QFileInfo configFile(dir.absolutePath()+ QDir::separator() + "config_app.lua");

    window = reinterpret_cast<MainWindow*>(&w);
    lua_register(L, "setstyle", setstyle);
    loadConfig(L, qPrintable(configFile.absoluteFilePath()), &width, &height, &style);

    qDebug() << configFile.absoluteFilePath() << "width: " << width << " height: " << height << "\n style: " << style;
    //window size
    w.resize(width, height);
    
    //CSS style
    //w.setStyleSheet(style);

    //w.setStyleSheet();
    splashScreen.show();
 
    w.setWindowIcon (QIcon(":/icon16"));
    w.show();

    QTimer::singleShot(2000, &splashScreen, SLOT(close()));
    QTimer::singleShot(1000, &w, SLOT(wInit()));
    // open all files given as parameters

    //    w.newFile();
    //    w.open("../input/in.c"); // TEMP
    
    // open all files given as parameters
    for (int i = 1; i < argc; i++)
        w.open(argv[i]);

    return app.exec();
}
示例#7
0
/* 1 Thessalonians 5:9 - For God hath not appointed us to wrath,
 *   but to obtain salvation by our Lord Jesus Christ.
 *  <-||--> What an AmaZinG TRUTH!!!
 */
int main(int argc, char* argv[])
{
    QApplication App(argc, argv);
    std::ios::sync_with_stdio(false);
    QApplication::setApplicationVersion(PROGRAM_VERSION_FULL_STRING);
    QApplication::setApplicationDisplayName("DupLichaSe");
    QApplication::setApplicationName("DupLichaSe");
    QApplication::setOrganizationName("DeltoidCoorp");
    QApplication::setOrganizationDomain("blog.whiztim.com");

    QString fileName;
    const QStringList arguments = App.arguments();
    if(arguments.size() > 2)
    {
        std::cerr << QObject::tr("Invalid Argumentss passed!\n"
                                 "NOTE: Only One parameter Needed; and that is"
                                 "\ta path to an existing .dlsr file(DupLichaSe Result file)\nor\n"
                                 "NOTE: Start the Program without arguments!\n").toStdString();
        return -1;
    }
    else if(arguments.size() == 2)
    {
        fileName = arguments.at(1);
        if(!QFile::exists(fileName))
        {
            QString msg(QObject::tr("Failed to access: \"") + fileName +
                        QObject::tr("\"\n\tmaybe DupLichaSe does not have read permission here"));
            std::cerr << msg.toStdString() << std::endl;
            return -1;
        }
        if(not fileName.endsWith(".dlsr"))
        {
            QMessageBox msg(QMessageBox::Critical,
                            QObject::tr("DupLichaSe -- Error"),
                            QObject::tr("Invalid DupLichaSe Result file... Aborting The program"),
                            QMessageBox::Ok);
            return msg.exec();
        }
    }

    QPixmap splashPixmap(":/main/splashScreen.png");
    QSplashScreen splashScreen(splashPixmap);
    splashScreen.show();

    DLSMainWindow window;
    splashScreen.show();
    QTimer::singleShot(3300, &window, SLOT(show()));
    QTimer::singleShot(4400, &splashScreen, SLOT(close()));

    if(not fileName.isEmpty())
        window.loadResultsFromFile(fileName);

    return App.exec();
}
示例#8
0
文件: inviwo.cpp 项目: Ojaswi/inviwo
int main(int argc, char** argv) {
    std::string basePath = inviwo::filesystem::findBasePath();

    inviwo::LogCentral::init();
    inviwo::LogCentral::getPtr()->registerLogger(new inviwo::FileLogger(basePath));
    inviwo::InviwoApplicationQt inviwoApp("Inviwo v" + IVW_VERSION, basePath, argc, argv);
    inviwoApp.setWindowIcon(QIcon(":/icons/inviwo_light.png"));
    inviwoApp.setAttribute(Qt::AA_NativeWindows);
    QFile styleSheetFile(":/stylesheets/inviwo.qss");
    styleSheetFile.open(QFile::ReadOnly);
    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());
    inviwoApp.setStyleSheet(styleSheet);
    styleSheetFile.close();

    inviwo::InviwoMainWindow mainWin(&inviwoApp);
    // setup core application
    inviwoApp.setMainWindow(&mainWin);
    // initialize and show splash screen
    inviwo::InviwoSplashScreen splashScreen(
        &mainWin, inviwoApp.getCommandLineParser()->getShowSplashScreen());
    inviwoApp.setProgressCallback([&splashScreen](std::string s){splashScreen.showMessage(s);});

    splashScreen.show();
    splashScreen.showMessage("Loading application...");
    
    // Initialize application and register modules
    splashScreen.showMessage("Initializing modules...");
    inviwoApp.initialize(&inviwo::registerAllModules);
    inviwoApp.processEvents();
    // setup main window
    mainWin.initialize();
    inviwoApp.processEvents();
    splashScreen.showMessage("Loading workspace...");
    inviwoApp.processEvents();
    mainWin.showWindow();
    inviwoApp.processEvents();    // Make sure the gui is done loading before loading workspace
    mainWin.openLastWorkspace();  // open last workspace
    splashScreen.finish(&mainWin);

#if defined(REG_INVIWOUNITTESTSMODULE) && defined(IVW_RUN_UNITTEST_ON_STARTUP)
    inviwo::UnitTestsModule::runAllTests();
#endif

    // process last arguments
    if (mainWin.processCommandLineArgs()) {
        return inviwoApp.exec();
    } else {
        mainWin.exitInviwo();
        return 0;
    }
}
示例#9
0
void GameBoard::timerEvent(QTimerEvent *)
{
    encart();
    flameAnim();
    splashScreen();
    movementMario();
    movementPeach();
    movementEncart();
    getModel()->brickOrganisation();
    goldAnim();
    intersectPeachMario();
    shockAnim();
    hurted();
    GameOver();
    Peach();
    view->repaint();
}
/// @brief  Initialises the application.
/// @return Returns true if the initialisation was successful, false otherwise.
bool ServerGraphics::initApplication (void)
{
    // Select and load the relevant resources
    mResourcesCfg = "../../media/resources.cfg";
#ifdef _DEBUG
    mPluginsCfg = "plugins_d.cfg";
#else
    mPluginsCfg = "plugins.cfg";
#endif
    mRoot = new Ogre::Root(mPluginsCfg, "ogre.cfg", "");
    setupResources();
    
    // Configure the renderer and exit if no configuration was provided.
    if (!configureRenderer())
        return false;

    // Create the window and viewport to go in it.
    NameValuePairList windowParameters;
    windowParameters["border"] = "fixed";
    mRoot->initialise(false);
    mWindow = mRoot->createRenderWindow("Collision Domain Server", 640, 480, false, &windowParameters);
    GameCore::mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);

    createCamera();
    createViewports();
    
    // Load the required resources
    // Create the splash screen (preloading its required resources in the process)
    SplashScreen splashScreen(mRoot);
    splashScreen.draw();
    //Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);   // Set default mipmap level
    //loadResources();                    // Load resources

    GameCore::initialise(this); // Initialise other game elements
    GameCore::load(&splashScreen, 0);
    GameCore::mNetworkCore->init(NULL);     // Initialise the server networking

    createScene();                          // Create the scene (in the server's case loading physics meshes)
    createFrameListener();                  // Create the frame listener to be used during rendering

    return true;
}
示例#11
0
文件: main.cpp 项目: brathm/TrollEdit
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("Innovators");
    app.setApplicationName("TrollEdit");
    app.setStartDragDistance(app.startDragDistance() * 2);

    // set splashScreen
    QPixmap pixmap(":/splash");
    QSplashScreen splashScreen(pixmap,Qt::WindowStaysOnTopHint);

    // find the directory of the program
    QFileInfo program(argv[0]);
    QString path = QApplication::applicationDirPath();

    MainWindow w(path);

    w.setWindowOpacity(0);

    splashScreen.show();
 
    w.setWindowIcon (QIcon(":/icon16"));
    w.show();

    QTimer::singleShot(2000, &splashScreen, SLOT(close()));
    QTimer::singleShot(1000, &w, SLOT(wInit()));
    // open all files given as parameters

    //    w.newFile();
    //    w.open("../input/in.c"); // TEMP
    
    // open all files given as parameters
    for (int i = 1; i < argc; i++)
        w.open(argv[i]);

    return app.exec();
}
示例#12
0
int main(){
	setlocale(LC_ALL, "ptb");//Set pt-br locale
	initscr();//Initialize cursor mode
	start_color();//Initialize color mode
	getmaxyx(stdscr,row,col);//Get screen dimensions
	attron(A_BOLD);

	//Configure color pairs
	init_pair(1, COLOR_WHITE, COLOR_BLACK);//Our default
	init_pair(2, COLOR_BLUE, COLOR_BLACK);//For Player 1
	init_pair(3, COLOR_RED, COLOR_BLACK);//For Player 2
	//Set default color pair
	wbkgd(stdscr, COLOR_PAIR(1));
	//Refresh screen to apply
	refresh();

	//Splash screen
	splashScreen();

	//wclear(stdscr);

	//Ready!

	char playAgain = 's';//Answer to the play again question on the end
	//Restart the game while play again answer is positive
	while(playAgain == 's'){
		initializeGameTable();//Initialize game table
		showHeader();//Show header with only title
		requestPlayerNames();//Request players for typing their names
		showHeader();//Show header with the title and players names
		refreshGame();//Show the game table
		//Print a divisor line after a blank line
		printw("\n");
		for(short int i = 0; i < col; i++){
			printw("-");
		}

		/* Here is the game, we'll request a match and refresh the game table while the game is not won or tied (tied is defined by number of matches) */
		//Matches counter
		int matchesCounter = 1;
		//Disable cursor
		curs_set(0);
		//While the game is not won and matches counter is under/equal 9
		while(checkWin() == 0 && matchesCounter <= 9){
			//Request match
			requestMatch();
			//Refresh the game table
			refreshGame();
			//Increase matches counter
			matchesCounter++;
		}

		//Clear line 13
		move(13,0);
		clrtoeol();
		//Check who won, or if the game tied
		if(checkWin() == 1){
			//Player 1 won
			//Increase score
			player1Score++;
			//Show congratulations on player color
			attron(COLOR_PAIR(2));
			mvprintw(13, 0, "Parabéns %s, você ganhou!\n", player1);
			attron(COLOR_PAIR(1));
		}
		if(checkWin() == 2){
			if(!strcmp(player2, "")){
				//PC won
				//Increase score
				player2Score++;
				//Show congratulations on player color
				attron(COLOR_PAIR(3));
				mvprintw(13, 0, "O PC ganhou!\n", player2);
				attron(COLOR_PAIR(1));
			}else{
				//Player2 won
				//Increase score
				player2Score++;
				//Show congratulations on player color
				attron(COLOR_PAIR(3));
				mvprintw(13, 0, "Parabéns %s, você ganhou!\n", player2);
				attron(COLOR_PAIR(1));
			}
		}
		if(checkWin() == 0){
			//Game tied
			mvprintw(13, 0, "Deu velha! O jogo terminou em empate.\n");
		}

		//Refresh scores
		refreshScores();

		//Reset play again var
		playAgain = ' ';
		//Enable cursor
		curs_set(1);
		//Validate play again answer
		while(!(playAgain == 's' | playAgain == 'n')){
			//Clear line 15, removing possible wrong answers from screen
			move(15, 0);
			clrtoeol();
			//Ask user
			printw("Desejam jogar novamente?[s/n] ");
			playAgain = getch();
		}
	}

	
	//Disable cursor
	curs_set(0);
	//Clear screen and show the header
	showHeader();
	//Print the thanks on center
	mvprintw(6, (col-strlen("Obrigado por jogar!"))/2,"Obrigado por jogar!\n");
	//Delay
	refresh(); delay(600);
	//Print the credits
	mvprintw(9, 0, "Desenvolvido por:\n");
	printw("Renan Galeno <*****@*****.**>\n");
	printw("Marcos Antuanny <*****@*****.**>\n");
	printw("Victor Patrick <*****@*****.**>\n");
	printw("\n");
	//Delay
	refresh(); delay(600);
	printw("Este trabalho está licenciado sob uma Licença Creative Commons Atribuição-CompartilhaIgual 4.0 Internacional.\nPara ver uma cópia desta licença, visite http://creativecommons.org/licenses/by-sa/4.0/.\n\n");
	//Delay
	refresh(); delay(1000);
	//Print the press anything to exit message
	printw("Pressione qualquer tecla para sair.");
	getch();


	//End curses mode
	endwin();

	//Return 0, as the program had no errors
	return(0);
}
示例#13
0
void Game::update()
{
   int now;
   int miliseconds;
   now = glutGet(GLUT_ELAPSED_TIME);
   miliseconds =  now - m_lastSong;
   if (miliseconds > 32600){
      Jukebox::PlaySound("./sounds/Song.wav");
      m_lastSong = glutGet(GLUT_ELAPSED_TIME);
   }   
   
   Game::getInstance().keyOperations();
   // Clear color and depth buffers
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

   //clear the screen
   glClearColor(1.0, 1.0, 1.0, 0.0); // Set the clear color to white
   glClear(GL_COLOR_BUFFER_BIT);     // clear the screen

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   // Draw the background
   glEnable(GL_TEXTURE_2D);
   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_REPLACE);
   glBindTexture (GL_TEXTURE_2D, m_backgroundTexture);
   //ImageLoader::rectangle(0,0, m_width, m_height);
   ImageLoader::rectangle(0,0, m_width, m_height);
   glDisable(GL_TEXTURE_2D);
   glFlush();
   
   //********I ADDED THIS*********//
   std::string item = "Item: ";
   std::string amount = "Amount: ";
   int num;

   item += ItemHandler::getInstance().getItem()->getName();
   num =ItemHandler::getInstance().getItem()->getAmount();
   amount += std::to_string(num);
   //std::cout << item << amount << std::endl;
   const char* citem = item.c_str();
   const char* camount = amount.c_str();
      
    
   ImageLoader::RenderString(25, m_height - 20, GLUT_BITMAP_TIMES_ROMAN_24, citem);
   ImageLoader::RenderString(25, m_height - 40, GLUT_BITMAP_TIMES_ROMAN_24, camount);
   
   std::string health = "Health: ";
   int numHealth = Game::getInstance().m_myPlayer.getHealth();
   health += std::to_string(numHealth);
   
   const char* chealth = health.c_str();
   ImageLoader::RenderString(200, m_height - 20, GLUT_BITMAP_TIMES_ROMAN_24, chealth);
   
   //*****************************//
   
   
   if(!Game::c_running)
   {
      return splashScreen();
   }

  
   ItemHandler::getInstance().update();
   m_myPlayer.display();
}
示例#14
0
文件: main.cpp 项目: AHudon/lmms
int main( int argc, char * * argv )
{
	// intialize RNG
	srand( getpid() + time( 0 ) );

	bool core_only = false;
	bool fullscreen = true;
	bool exit_after_import = false;
	QString file_to_load, file_to_save, file_to_import, render_out;

	for( int i = 1; i < argc; ++i )
	{
		if( argc > i && ( ( QString( argv[i] ) == "--render" ||
					QString( argv[i] ) == "-r" ) ||
				( QString( argv[i] ) == "--help" ||
						QString( argv[i] ) == "-h" ) ) )
		{
			core_only = true;
		}
		else if( argc > i && QString( argv[i] ) == "-geometry" )
		{
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

	QCoreApplication * app = core_only ?
			new QCoreApplication( argc, argv ) :
					new QApplication( argc, argv ) ;


	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	ProjectRenderer::OutputSettings os( 44100, false, 160,
						ProjectRenderer::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;


	for( int i = 1; i < argc; ++i )
	{
		if( QString( argv[i] ) == "--version" ||
						QString( argv[i] ) == "-v" )
		{
			printf( "\nLinux MultiMedia Studio %s\n(%s %s, Qt %s, %s)\n\n"
	"Copyright (c) 2004-2014 LMMS developers.\n\n"
	"This program is free software; you can redistribute it and/or\n"
	"modify it under the terms of the GNU General Public\n"
	"License as published by the Free Software Foundation; either\n"
	"version 2 of the License, or (at your option) any later version.\n\n"
	"Try \"%s --help\" for more information.\n\n", LMMS_VERSION, 
				PLATFORM, MACHINE, QT_VERSION_STR, GCC_VERSION,
				argv[0] );

			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--help" ||
						QString( argv[i] ) == "-h" ) )
		{
			printf( "\nLinux MultiMedia Studio %s\n"
	"Copyright (c) 2004-2014 LMMS developers.\n\n"
	"usage: lmms [ -r <project file> ] [ options ]\n"
	"            [ -u <in> <out> ]\n"
	"            [ -d <in> ]\n"
	"            [ -h ]\n"
	"            [ <file to load> ]\n\n"
	"-r, --render <project file>	render given project file\n"
	"-o, --output <file>		render into <file>\n"
	"-f, --output-format <format>	specify format of render-output where\n"
	"				format is either 'wav' or 'ogg'.\n"
	"-s, --samplerate <samplerate>	specify output samplerate in Hz\n"
	"				range: 44100 (default) to 192000\n"
	"-b, --bitrate <bitrate>		specify output bitrate in kHz\n"
	"				default: 160.\n"
	"-i, --interpolation <method>	specify interpolation method\n"
	"				possible values:\n"
	"				   - linear\n"
	"				   - sincfastest (default)\n"
	"				   - sincmedium\n"
	"				   - sincbest\n"
	"-x, --oversampling <value>	specify oversampling\n"
	"				possible values: 1, 2, 4, 8\n"
	"				default: 2\n"
	"-u, --upgrade <in> [out]	upgrade file <in> and save as <out>\n"
	"       standard out is used if no output file is specifed\n"
	"-d, --dump <in>			dump XML of compressed file <in>\n"
	"-v, --version			show version information and exit.\n"
	"-h, --help			show this usage information and exit.\n\n",
							LMMS_VERSION );
			return( EXIT_SUCCESS );
		}
		else if( argc > i+1 && ( QString( argv[i] ) == "--upgrade" ||
						QString( argv[i] ) == "-u" ) )
		{
			QString inFile( argv[i + 1] );
			DataFile dataFile( inFile );
			if (argc > i+2)
			{
				const QString outFile = argv[i + 2];
				dataFile.writeFile( outFile );
			}
			else
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}
			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--dump" ||
						QString( argv[i] ) == "-d" ) )
		{
			QFile f( argv[i + 1] );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );
			return( EXIT_SUCCESS );
		}
		else if( argc > i && ( QString( argv[i] ) == "--render" ||
						QString( argv[i] ) == "-r" ) )
		{
			file_to_load = QString( argv[i + 1] );
			render_out = baseName( file_to_load ) + ".";
			++i;
		}
		else if( argc > i && ( QString( argv[i] ) == "--output" ||
						QString( argv[i] ) == "-o" ) )
		{
			render_out = baseName( QString( argv[i + 1] ) ) + ".";
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--format" ||
						QString( argv[i] ) == "-f" ) )
		{
			const QString ext = QString( argv[i + 1] );
			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--samplerate" ||
						QString( argv[i] ) == "-s" ) )
		{
			sample_rate_t sr = QString( argv[i + 1] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.samplerate = sr;
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--bitrate" ||
						QString( argv[i] ) == "-b" ) )
		{
			int br = QString( argv[i + 1] ).toUInt();
			if( br >= 64 && br <= 384 )
			{
				os.bitrate = br;
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--interpolation" ||
						QString( argv[i] ) == "-i" ) )
		{
			const QString ip = QString( argv[i + 1] );
			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--oversampling" ||
						QString( argv[i] ) == "-x" ) )
		{
			int o = QString( argv[i + 1] ).toUInt();
			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i + 1], argv[0] );
				return( EXIT_FAILURE );
			}
			++i;
		}
		else if( argc > i &&
				( QString( argv[i] ) == "--import" ) )
		{
			file_to_import = argv[i+1];
			++i;
			// exit after import? (only for debugging)
			if( argc > i && QString( argv[i+1] ) == "-e" )
			{
				exit_after_import = true;
			}
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return( EXIT_FAILURE );
			}
			file_to_load = argv[i];
		}
	}


	QString pos = QLocale::system().name().left( 2 );

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR configManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

	configManager::inst()->loadConfigFile();

	if( render_out.isEmpty() )
	{
		// init style and palette
		QApplication::setStyle( new LmmsStyle() );

		// show splash screen
		QSplashScreen splashScreen( embed::getIconPixmap( "splash" ) );
		splashScreen.show();
		splashScreen.showMessage( MainWindow::tr( "Version %1" ).arg( LMMS_VERSION ),
									Qt::AlignRight | Qt::AlignBottom, Qt::white );
		qApp->processEvents();

		// init central engine which handles all components of LMMS
		engine::init();

		splashScreen.hide();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = QDir(configManager::inst()->workingDir()).absoluteFilePath("recover.dataFile");
		if( QFileInfo(recoveryFile).exists() &&
			QMessageBox::question( engine::mainWindow(), MainWindow::tr( "Project recovery" ),
						MainWindow::tr( "It looks like the last session did not end properly. "
										"Do you want to recover the project of this session?" ),
						QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes )
		{
			file_to_load = recoveryFile;
		}

		// we try to load given file
		if( !file_to_load.isEmpty() )
		{
			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
			if( file_to_load == recoveryFile )
			{
				engine::getSong()->createNewProjectFromTemplate( file_to_load );
			}
			else
			{
				engine::getSong()->loadProject( file_to_load );
			}
		}
		else if( !file_to_import.isEmpty() )
		{
			ImportFilter::import( file_to_import, engine::getSong() );
			if( exit_after_import )
			{
				return 0;
			}

			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
		}
		else
		{
			engine::getSong()->createNewProject();

			// [Settel] workaround: showMaximized() doesn't work with
			// FVWM2 unless the window is already visible -> show() first
			engine::mainWindow()->show();
			if( fullscreen )
			{
				engine::mainWindow()->showMaximized();
			}
		}
	}
	else
	{
		// we're going to render our song
		engine::init( false );
		printf( "loading project...\n" );
		engine::getSong()->loadProject( file_to_load );
		printf( "done\n" );

		// create renderer
		ProjectRenderer * r = new ProjectRenderer( qs, os, eff,
			render_out +
				QString( ( eff ==
					ProjectRenderer::WaveFile ) ?
						"wav" : "ogg" ) );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		// start now!
		r->startProcessing();
	}

	const int ret = app->exec();
	delete app;
	return( ret );
}
示例#15
0
void initGraphics(int width, int height, const Graphics::PixelFormat *format) {

	g_system->beginGFXTransaction();

		initCommonGFX();
#ifdef USE_RGB_COLOR
		if (format)
			g_system->initSize(width, height, format);
		else {
			Graphics::PixelFormat bestFormat = g_system->getSupportedFormats().front();
			g_system->initSize(width, height, &bestFormat);
		}
#else
		g_system->initSize(width, height);
#endif

	OSystem::TransactionError gfxError = g_system->endGFXTransaction();

	if (!splash && !GUI::GuiManager::instance()._launched)
		splashScreen();

	if (gfxError == OSystem::kTransactionSuccess)
		return;

	// Error out on size switch failure
	if (gfxError & OSystem::kTransactionSizeChangeFailed) {
		Common::String message;
		message = Common::String::format("Could not switch to resolution: '%dx%d'.", width, height);

		GUIErrorMessage(message);
		error("%s", message.c_str());
	}

	// Just show warnings then these occur:
#ifdef USE_RGB_COLOR
	if (gfxError & OSystem::kTransactionFormatNotSupported) {
		Common::String message = _("Could not initialize color format.");

		GUI::MessageDialog dialog(message);
		dialog.runModal();
	}
#endif

	if (gfxError & OSystem::kTransactionModeSwitchFailed) {
		Common::String message = _("Could not switch to video mode: '");
		message += ConfMan.get("gfx_mode");
		message += "'.";

		GUI::MessageDialog dialog(message);
		dialog.runModal();
	}

	if (gfxError & OSystem::kTransactionStretchModeSwitchFailed) {
		Common::String message = _("Could not switch to stretch mode: '");
		message += ConfMan.get("stretch_mode");
		message += "'.";

		GUI::MessageDialog dialog(message);
		dialog.runModal();
	}

	if (gfxError & OSystem::kTransactionAspectRatioFailed) {
		GUI::MessageDialog dialog(_("Could not apply aspect ratio setting."));
		dialog.runModal();
	}

	if (gfxError & OSystem::kTransactionFullscreenFailed) {
		GUI::MessageDialog dialog(_("Could not apply fullscreen setting."));
		dialog.runModal();
	}

	if (gfxError & OSystem::kTransactionFilteringFailed) {
		GUI::MessageDialog dialog(_("Could not apply filtering setting."));
		dialog.runModal();
	}
}
示例#16
0
int main(int argc, char* argv[])
{
    qInstallMessageHandler(messageHandler);

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

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

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

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

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

    loadStyleSheets(application);
    loadFonts(application);

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

    MainWindow window;
    splashScreen.finish(&window);

    loadConfiguration(application, window, &args);

    window.show();

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

    int returnValue = application.exec();

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

    return returnValue;
}
示例#17
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

	QStringList args = char_array_to_stringlist(argv+1, argc-1);

	Q_INIT_RESOURCE(images);

	rsiface = NULL;

	NotifyQt *notify = NotifyQt::Create();
	createRsIface(*notify);
	createRsControl(*rsiface, *notify);

	/* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if(initResult == RS_INIT_NO_KEYRING)	// happens when we already have accounts, but no pgp key. This is when switching to the openpgp-sdk version.
	{
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		QMessageBox msgBox;
		msgBox.setText(QObject::tr("This version of RetroShare is using OpenPGP-SDK. As a side effect, it's not using the system shared PGP keyring, but has it's own keyring shared by all RetroShare instances. <br><br>You do not appear to have such a keyring, although GPG keys are mentionned by existing RetroShare accounts, probably because you just changed to this new version of the software."));
		msgBox.setInformativeText(QObject::tr("Choose between:<br><ul><li><b>Ok</b> to copy the existing keyring from gnupg (safest bet), or </li><li><b>Close without saving</b> to start fresh with an empty keyring (you will be asked to create a new PGP key to work with RetroShare, or import a previously saved pgp keypair). </li><li><b>Cancel</b> to quit and forge a keyring by yourself (needs some PGP skills)</li></ul>"));
		msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Discard | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.setWindowIcon(QIcon(":/images/rstray3.png"));

		int ret = msgBox.exec();

		if(ret == QMessageBox::Cancel)
			return 0 ;
		if(ret == QMessageBox::Ok)
		{
			if(!RsInit::copyGnuPGKeyrings())
				return 0 ; 

			initResult = RsInit::InitRetroShare(argc, argv);

			displayWarningAboutDSAKeys() ;

		}
		else
			initResult = RS_INIT_OK ;
	}

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		displayWarningAboutDSAKeys();

		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
		mb.setWindowIcon(QIcon(":/images/rstray3.png"));

		switch (initResult) 
		{
			case RS_INIT_AUTH_FAILED:
				std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
				mb.setText(QObject::tr("Inititialize failed. Wrong or missing installation of gpg."));
				break;
			default:
				/* Unexpected return code */
				std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
				mb.setText(QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
				break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromUtf8(RsInit::RsConfigDirectory().c_str()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			StartDialog *sd = NULL;
			bool genCert = false;
			std::list<std::string> accountIds;
			if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0))
			{
				sd = new StartDialog();
				sd->show();

				while(sd -> isVisible())
				{
					rshare.processEvents();
#ifdef WIN32
					Sleep(10);
#else // __LINUX__
					usleep(10000);
#endif
				}

				/* if we're logged in */
				genCert = sd->requestedNewCert();
				delete (sd);
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd;
				gd.exec ();
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			std::string preferredId, gpgId, gpgName, gpgEmail, sslName;
			RsInit::getPreferedAccountId(preferredId);

			if (RsInit::getAccountDetails(preferredId, gpgId, gpgName, gpgEmail, sslName))
			{
				RsInit::SelectGPGAccount(gpgId);
			}

			// true: note auto-login is active
			std::string lockFile;
			int retVal = RsInit::LockAndLoadCertificates(true, lockFile);
			switch(retVal)
			{
				case 0:	break;
				case 1:	QMessageBox::warning(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("Another RetroShare using the same profile is "
												"already running on your system. Please close "
												"that instance first\n Lock file:\n") +
												QString::fromStdString(lockFile));
						return 1;
				case 2:	QMessageBox::critical(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("An unexpected error occurred when Retroshare"
												"tried to acquire the single instance lock\n Lock file:\n") +
												QString::fromStdString(lockFile));
						return 1;
				case 3: QMessageBox::critical(	0,
												QObject::tr("Login Failure"),
												QObject::tr("Maybe password is wrong") );
						return 1;
				default: std::cerr << "StartDialog::loadCertificates() unexpected switch value " << retVal << std::endl;
			}
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	/* recreate global settings object, now with correct path */
	RshareSettings::Create(true);
	Rshare::resetLanguageAndStyle();

	SoundManager::create();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	/* stop Retroshare if startup fails */
	if (!rsicontrol->StartupRetroShare())
	{
		std::cerr << "libretroshare failed to startup!" << std::endl;
		return 1;
	}


	Rshare::initPlugins();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	RsharePeerSettings::Create();

	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);

#ifdef __APPLE__
		/* For OSX, we set the default to "cleanlooks", as the AQUA style hides some input boxes 
		 * only on the first run - as the user might want to change it ;)
		 */
		QString osx_style("cleanlooks");
		Rshare::setStyle(osx_style);
		Settings->setInterfaceStyle(osx_style);
#endif

// This is now disabled - as it doesn't add very much.
// Need to make sure that defaults are sensible!
#ifdef ENABLE_QUICKSTART_WIZARD
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
#endif

	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(linkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->linkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->sharedfilesDialog		,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->sharedfilesDialog		,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                            ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(privateChatChanged(int, int))      ,w                   		,SLOT(privateChatChanged(int, int)     ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->networkDialog    		,SLOT(insertConnect()                  )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w->messagesDialog   		,SLOT(insertMessages()                 )) ;
	QObject::connect(notify,SIGNAL(messagesTagsChanged())             ,w->messagesDialog   		,SLOT(messagesTagsChanged()            )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w                   		,SLOT(updateMessages()                 )) ;
	QObject::connect(notify,SIGNAL(forumsChanged())                   ,w                   		,SLOT(updateForums()                   ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(channelsChanged(int))              ,w                   		,SLOT(updateChannels(int)              ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(downloadCompleteCountChanged(int)) ,w                   		,SLOT(updateTransfers(int)             ));

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->networkDialog,SLOT(updateNewDiscoveryInfo()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);

	notify->enable() ;	// enable notification system after GUI creation, to avoid data races in Qt.

	/* dive into the endless loop */
	int ti = rshare.exec();
	delete w ;

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	ChatDialog::cleanupChat();

	rsicontrol->rsGlobalShutDown();

	delete(soundManager);
	soundManager = NULL;

	Settings->sync();
	delete(Settings);

	return ti ;
}
示例#18
0
int main(int argc, char *argv[])
{
  /* For every Qt graphical application, we need one QApplication instance */
  QApplication app(argc, argv);

  // Set the correct language
  // Translations for Qt
  QTranslator qtTranslator;

  //We get the system's locale
  QString locale = QLocale::system().name();

  qtTranslator.load("qt_" + locale, "/usr/share/qt4/translations",
                    QLibraryInfo::location(QLibraryInfo::TranslationsPath));
  app.installTranslator(&qtTranslator);

  // Translations for QAntenna
  QTranslator myappTranslator;

#ifdef WIN32
  QString transdir=".";
#else
  QString transdir=PREFIX"/share/qantenna";
#endif

  myappTranslator.load("qantenna_" + locale, transdir);
  app.installTranslator(&myappTranslator);

  // The pixmap for the splash screen
  QPixmap pixmap(":/img/splash.png");

  // A splash screen
  QSplashScreen splashScreen(pixmap);
  splashScreen.show();

  // Check whether we have OpenGL support or not
  splashScreen.showMessage(QObject::tr("Checking if there is OpenGL support in this machine"));

  if(!QGLFormat::hasOpenGL())
  {
    qDebug() << QWidget::tr("We don't have OpenGL support");
    QMessageBox::critical(0,"QAntenna - main.cpp",
                          QWidget::tr("There is no OpenGL support in your system.<br>"
                          "Closing QAntenna"));
    return 1;
  }

  // Load QAntenna
  splashScreen.showMessage(QObject::tr("Loading QAntenna"));

  /***************************************************/
  // Check that the necpp command nec2++ is available

  QProcess necppProcess;
  necppProcess.start("nec2++", QStringList() << "-v");

  // Check for successful start + finish of nec2++
  if (necppProcess.waitForStarted() && necppProcess.waitForFinished())
  {
    // nec2++ found!
    necppProcess.close();
  }
  else
  {
    // If either fails, deliver the error
    qDebug() << QWidget::tr("We don't have nec2++");
    QMessageBox::critical(0,"QAntenna - main.cpp",
                          QWidget::tr("nec2++ command is missing!<br>"
                          "The required program necpp must first be installed.<br>"
                          "Closing QAntenna."));
    return 1;
  }
    /***************************************************/

  /* And we need a main window, which must be shown */
  MainWindow mainWin;

  /* We show the window, giving the user the choice to Maximize */
  mainWin.showNormal();

  // And close the splash screen
  splashScreen.finish(&mainWin);

  /* The return value for the OS is returned by app */
  return app.exec();
}
示例#19
0
文件: main.cpp 项目: 00farts/italc-1
// good old main-function... initializes qt-app and starts iTALC
int main( int argc, char * * argv )
{
	QApplication app( argc, argv );

	ItalcCore::init();

	Logger l( "ItalcMaster" );

	app.connect( &app, SIGNAL( lastWindowClosed() ), SLOT( quit() ) );

	app.setStyleSheet(
		"QMenu { border:1px solid black; background-color: white; "
			"background-image:url(:/resources/tray-menu-bg.png); "
			"background-repeat:no-repeat; "
			"background-position: bottom right; }"
		"QMenu::separator { height: 1px; background: rgb(128,128,128); "
					"margin-left: 5px; margin-right: 5px; }"
		"QMenu::item { padding: 2px 32px 2px 20px; "
						"margin:3px; }"
		"QMenu::item:selected { color: white; font-weight:bold; "
			"background-color: rgba(0, 0, 0, 160); "
						"margin:3px; }"
		"QMenu::item:disabled { color: white;  margin:0px; "
			"background-color: rgba(0,0,0,192); font-size:14px;"
			"font-weight:bold; padding: 4px 32px 4px 20px; }" );

	// load translations
	qRegisterMetaType<QModelIndex>( "QModelIndex" );
	qRegisterMetaType<quint16>( "quint16" );


	ItalcCore::role = ItalcCore::RoleTeacher;
/*	if( LocalSystem::parameter( "ivsport" ).toInt() > 0 )
	{
		MasterCore::localDisplayPort =
				LocalSystem::parameter( "ivsport" ).toInt();
	}*/

	// parse arguments
	QStringListIterator arg_it( QCoreApplication::arguments() );
	arg_it.next();
	int screen = -1;
	while( argc > 1 && arg_it.hasNext() )
	{
		const QString & a = arg_it.next();
		if( a == "-rctrl" && arg_it.hasNext() )
		{
			if( !ItalcCore::initAuthentication() )
			{
				ilog_failed( "ItalcCore::initAuthentication()" );
				return -1;
			}

			const QString host = arg_it.next();
			bool view_only = arg_it.hasNext() ?
						arg_it.next().toInt()
					:
						false;
			new RemoteControlWidget( host, view_only );
			return app.exec();
		}
		else if( a == "-screen" && arg_it.hasNext() )
		{
			screen = arg_it.next().toInt();
		}
		else if( a == "-role" )
		{
			if( arg_it.hasNext() )
			{
				const QString role = arg_it.next();
				if( role == "teacher" )
				{
					ItalcCore::role = ItalcCore::RoleTeacher;
				}
				else if( role == "admin" )
				{
					ItalcCore::role = ItalcCore::RoleAdmin;
				}
				else if( role == "supporter" )
				{
					ItalcCore::role = ItalcCore::RoleSupporter;
				}
			}
			else
			{
				printf( "-role needs an argument:\n"
					"	teacher\n"
					"	admin\n"
					"	supporter\n\n" );
				return -1;
			}
		}
/*		else if( a == "-ivsport" && arg_it.hasNext() )
		{
			MasterCore::localDisplayPort = arg_it.next().toInt();
		}*/
	}


	QSplashScreen splashScreen( QPixmap( ":/resources/splash.png" ) );
	splashScreen.show();

	MasterCore::init();

/*	if( !MainWindow::initAuthentication() )
	{
		return -1;
	}*/

	// now create the main-window
	MainWindow mainWindow( screen );

	if( !MasterCore::localDisplay->isConnected() )
	{
		qCritical( "No connection to local ICA - terminating now" );
		if( ItalcCore::config->logLevel() < Logger::LogLevelDebug )
		{
			return -1;
		}
	}

	// hide splash-screen as soon as main-window is shown
	splashScreen.finish( &mainWindow );

	mainWindow.show();

	ilog( Info, "Exec" );

	// let's rock!!
	int ret = app.exec();

	MasterCore::deinit();

	return ret;
}
示例#20
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

  QStringList args = char_array_to_stringlist(argv+1, argc-1);
  
  Q_INIT_RESOURCE(images);

	rsiface = NULL;

	NotifyQt *notify = NotifyQt::Create();
	createRsIface(*notify);
	createRsControl(*rsiface, *notify);

        /* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
		mb.setWindowIcon(QIcon(":/images/rstray3.png"));

		switch (initResult) {
		case RS_INIT_AUTH_FAILED:
			std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
			mb.setText(QObject::tr("Inititialize failed. Wrong or missing installation of gpg."));
			break;
		default:
			/* Unexpected return code */
			std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
			mb.setText(QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
			break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromStdString(RsInit::RsConfigDirectory()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			std::string userName;

			StartDialog *sd = NULL;
			bool genCert = false;
			std::list<std::string> accountIds;
			if (RsInit::getAccountIds(accountIds) && (accountIds.size() > 0))
			{
				sd = new StartDialog();
				sd->show();

				while(sd -> isVisible())
				{
					rshare.processEvents();
#ifdef WIN32
					Sleep(10);
#else // __LINUX__
					usleep(10000);
#endif
				}

				/* if we're logged in */
				genCert = sd->requestedNewCert();
				delete (sd);
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd;
				gd.exec ();
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			std::string preferredId, gpgId, gpgName, gpgEmail, sslName;
			RsInit::getPreferedAccountId(preferredId);

			if (RsInit::getAccountDetails(preferredId, gpgId, gpgName, gpgEmail, sslName))
			{
				RsInit::SelectGPGAccount(gpgId);
			}

			// true: note auto-login is active
                        std::string lockFile;
                        int retVal = RsInit::LockAndLoadCertificates(true, lockFile);
			switch(retVal)
			{
				case 0:	break;
				case 1:	QMessageBox::warning(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("Another RetroShare using the same profile is "
                                                                                                                "already running on your system. Please close "
                                                                                                                "that instance first\n Lock file:\n") +
                                                                                                                QString::fromStdString(lockFile));
						return 1;
				case 2:	QMessageBox::critical(	0,
												QObject::tr("Multiple instances"),
												QObject::tr("An unexpected error occurred when Retroshare"
                                                                                                                     "tried to acquire the single instance lock\n Lock file:\n") +
                                                                                                                     QString::fromStdString(lockFile));
						return 1;
				case 3: QMessageBox::critical(	0,
												QObject::tr("Login Failure"),
												QObject::tr("Maybe password is wrong") );
						return 1;
				default: std::cerr << "StartDialog::loadCertificates() unexpected switch value " << retVal << std::endl;
			}
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	rsicontrol->StartupRetroShare();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	/* recreate global settings object, now with correct path */
	RshareSettings::Create ();
	RsharePeerSettings::Create();

#ifdef MINIMAL_RSGUI
	MessengerWindow::showYourself();

	rshare.setQuitOnLastWindowClosed(true);

	splashScreen.hide();
#else
	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(linkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->linkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPreModChanged(bool))          ,w->sharedfilesDialog		,SLOT(preModDirectories(bool)          )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w->sharedfilesDialog		,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                            ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(friendsChanged())                  ,w->friendsDialog      		,SLOT(insertPeers()                    )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(groupsChanged(int))                ,w->friendsDialog      		,SLOT(groupsChanged(int)               ));
	QObject::connect(notify,SIGNAL(privateChatChanged(int, int))      ,w                   		,SLOT(privateChatChanged(int, int)     ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->networkDialog    		,SLOT(insertConnect()                  )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w->messagesDialog   		,SLOT(insertMessages()                 )) ;
	QObject::connect(notify,SIGNAL(messagesTagsChanged())             ,w->messagesDialog   		,SLOT(messagesTagsChanged()            )) ;
	QObject::connect(notify,SIGNAL(messagesChanged())                 ,w                   		,SLOT(updateMessages()                 )) ;
	QObject::connect(notify,SIGNAL(forumsChanged())                   ,w                   		,SLOT(updateForums()                   ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(channelsChanged(int))              ,w                   		,SLOT(updateChannels(int)              ), Qt::QueuedConnection);
	QObject::connect(notify,SIGNAL(downloadCompleteCountChanged(int)) ,w                   		,SLOT(updateTransfers(int)             ));

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->networkDialog,SLOT(updateNewDiscoveryInfo()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	QObject::connect(w->friendsDialog,SIGNAL(friendsUpdated()),w->networkDialog,SLOT(insertConnect())) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);
#endif // MINIMAL_RSGUI

	/* dive into the endless loop */
	int ti = rshare.exec();
#ifndef MINIMAL_RSGUI
	delete w ;

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	PopupChatDialog::cleanupChat();
#endif // MINIMAL_RSGUI

	rsicontrol->rsGlobalShutDown();

	Settings->sync();
	delete Settings;

	return ti ;
}
示例#21
0
文件: main.c 项目: fabiocody/Snake
/*** MAIN ***/
int main(int argc, const char *argv[]) {
    unsigned int i, j;
    unsigned int end = 0;
    unsigned int foodFlag = 0;
    unsigned int length = 1;
    int score = -1, record = 0, delay = 1000;
    char direction, prevDirection = 'd';
    long duration = 0;
    static struct termios oldt, newt;       // Structs to get all the keystrokes directly to stdin
    struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };        // Struct to timeout getchar
    
    FILE *recordFile = fopen("snake_record.bin", "r+b");
    if (recordFile != NULL) {
        fread(&record, sizeof(int), 1, recordFile);
        fclose(recordFile);
    }
    recordFile = NULL;
    
    srand((unsigned int)time(NULL));
    
    // Initialize grid
    for_i
        for_j
            grid[i][j] = EMPTY;
    for (i = 21; i >= 18; i--, length++)
        grid[10][i] = length;
    
    splashScreen();
    
    // Instructions to get all the keystrokes directly to stdin
    tcgetattr( STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON);
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);
    
    // Game cycle
    while (end == 0) {
        if (foodFlag == 0) {
            generateFood();
            foodFlag = 1;
            score++;
        }
        clearScreen();
        printGrid(score, record);
        do {
            if (poll(&mypoll, 1, delay))
                direction = getchar();
            else
                direction = prevDirection;
        } while (direction != 'w' && direction != 'a' && direction != 's' && direction != 'd' && direction != 'q');
        if (direction == 'q') {
            puts("\n\nEXIT\n");
            exit(EXIT_SUCCESS);
        }
        end = turnSnake(direction, end, &foodFlag);
        prevDirection = direction;
        duration++;
        if ((duration % 30) == 0 && delay > 200)
            delay -= 50;
    }

    puts("\n\nGAME OVER!\n");
    
    if (score > record) {
        recordFile = fopen("snake_record.bin", "wb");
        if (recordFile != NULL) {
            fwrite(&score, sizeof(int), 1, recordFile);
            fclose(recordFile);
        }
    }
    
    // Restore normal mode
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
示例#22
0
文件: main.cpp 项目: acracan/OMEdit
int main(int argc, char *argv[])
{
  /* Do not use the signal handler OR exception filter if user is building a debug version. Perhaps the user wants to use gdb. */
  MMC_INIT();

#ifdef QT_NO_DEBUG
#ifdef WIN32
  SetUnhandledExceptionFilter(exceptionFilter);
#else
  /* Abnormal termination (abort) */
  signal(SIGABRT, signalHandler);
  /* Segmentation violation */
  signal(SIGSEGV, signalHandler);
  /* Illegal instruction */
  signal(SIGILL, signalHandler);
  /* Floating point error */
  signal(SIGFPE, signalHandler);
#endif // #ifdef WIN32
#endif // #ifdef QT_NO_DEBUG
  // if user asks for --help
  for(int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "--help") == 0) {
      printOMEditUsage();
      return 0;
    }
  }
  Q_INIT_RESOURCE(resource_omedit);
  QApplication a(argc, argv);
  // set the stylesheet
  a.setStyleSheet("file:///:/Resources/css/stylesheet.qss");
#if !(QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
  QTextCodec::setCodecForTr(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
#endif
#ifndef WIN32
  QTextCodec::setCodecForLocale(QTextCodec::codecForName(Helper::utf8.toLatin1().data()));
#endif
  a.setAttribute(Qt::AA_DontShowIconsInMenus, false);
  // Localization
  //*a.severin/ add localization
  const char *omhome = getenv("OPENMODELICAHOME");
#ifdef WIN32
  if (!omhome) {
    QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error),
                          GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok);
    a.quit();
    exit(1);
  }
#else /* unix */
  omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME;
#endif
  QSettings *pSettings = OpenModelica::getApplicationSettings();
  QLocale settingsLocale = QLocale(pSettings->value("language").toString());
  settingsLocale = settingsLocale.name() == "C" ? pSettings->value("language").toLocale() : settingsLocale;
  QString locale = settingsLocale.name().isEmpty() ? QLocale::system().name() : settingsLocale.name();
  /* set the default locale of the application so that QSpinBox etc show values according to the locale. */
  QLocale::setDefault(settingsLocale);

  QString translationDirectory = omhome + QString("/share/omedit/nls");
  // install Qt's default translations
  QTranslator qtTranslator;
#ifdef Q_OS_WIN
  qtTranslator.load("qt_" + locale, translationDirectory);
#else
  qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
  a.installTranslator(&qtTranslator);
  // install application translations
  QTranslator translator;
  translator.load("OMEdit_" + locale, translationDirectory);
  a.installTranslator(&translator);
  // Splash Screen
  QPixmap pixmap(":/Resources/icons/omedit_splashscreen.png");
  QSplashScreen splashScreen(pixmap);
  //splashScreen.setMessage();
  splashScreen.show();
  Helper::initHelperVariables();
  /* Force C-style doubles */
  setlocale(LC_NUMERIC, "C");
  // if user has requested to open the file by passing it in argument then,
  bool OMCLogger = false;
  bool debug = false;
  QString fileName = "";
  QStringList fileNames;
  if (a.arguments().size() > 1) {
    for (int i = 1; i < a.arguments().size(); i++) {
      if (strncmp(a.arguments().at(i).toStdString().c_str(), "--OMCLogger=",12) == 0) {
        QString omcLoggerArg = a.arguments().at(i);
        omcLoggerArg.remove("--OMCLogger=");
        if (0 == strcmp("true", omcLoggerArg.toStdString().c_str())) {
          OMCLogger = true;
        } else {
          OMCLogger = false;
        }
      } else if (strncmp(a.arguments().at(i).toStdString().c_str(), "--Debug=",8) == 0) {
        QString debugArg = a.arguments().at(i);
        debugArg.remove("--Debug=");
        if (0 == strcmp("true", debugArg.toStdString().c_str())) {
          debug = true;
        } else {
          debug = false;
        }
      } else {
        fileName = a.arguments().at(i);
        if (!fileName.isEmpty()) {
          // if path is relative make it absolute
          QFileInfo file (fileName);
          if (file.isRelative()) {
            fileName.prepend(QString(QDir::currentPath()).append("/"));
          }
          fileName = fileName.replace("\\", "/");
          fileNames << fileName;
        }
      }
    }
  }
  // MainWindow Initialization
  MainWindow mainwindow(&splashScreen, debug);
  if (mainwindow.getExitApplicationStatus()) {        // if there is some issue in running the application.
    a.quit();
    exit(1);
  }
  // open the files passed as command line arguments
  foreach (QString fileName, fileNames) {
    mainwindow.getLibraryWidget()->openFile(fileName);
  }
示例#23
0
int main(int argc, char *argv[])
{ 
#ifdef WINDOWS_SYS
	// The current directory of the application is changed when using the native dialog on Windows
	// This is a quick fix until libretroshare is using a absolute path in the portable Version
#if QT_VERSION >= QT_VERSION_CHECK (5, 3, 0)
	// Do we need a solution in v0.6?
#endif
#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0) && QT_VERSION < QT_VERSION_CHECK (5, 3, 0)
	typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
	typedef QString (*_qt_filedialog_open_filename_hook)     (QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
	typedef QString (*_qt_filedialog_save_filename_hook)     (QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
	typedef QString (*_qt_filedialog_existing_directory_hook)(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options);

	extern Q_GUI_EXPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook;
	extern Q_GUI_EXPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook;
	extern Q_GUI_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook;
	extern Q_GUI_EXPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook;

	qt_filedialog_open_filename_hook = filedialog_open_filename_hook;
	qt_filedialog_open_filenames_hook = filedialog_open_filenames_hook;
	qt_filedialog_save_filename_hook = filedialog_save_filename_hook;
	qt_filedialog_existing_directory_hook = filedialog_existing_directory_hook;
#endif
#if QT_VERSION < QT_VERSION_CHECK (5, 0, 0)
	extern bool Q_GUI_EXPORT qt_use_native_dialogs;
	qt_use_native_dialogs = false;
#endif

	{
		/* Set the current directory to the application dir,
		   because the start dir with autostart from the registry run key is not the exe dir */
		QApplication app(argc, argv);
		QDir::setCurrent(QCoreApplication::applicationDirPath());
	}
#endif

	QStringList args = char_array_to_stringlist(argv+1, argc-1);

    Q_INIT_RESOURCE(images);
    Q_INIT_RESOURCE(icons);

	// This is needed to allocate rsNotify, so that it can be used to ask for PGP passphrase
	//
	RsControl::earlyInitNotificationSystem() ;

	NotifyQt *notify = NotifyQt::Create();
	rsNotify->registerNotifyClient(notify);

	/* RetroShare Core Objects */
	RsInit::InitRsConfig();
	int initResult = RsInit::InitRetroShare(argc, argv);

	if(initResult == RS_INIT_NO_KEYRING)	// happens when we already have accounts, but no pgp key. This is when switching to the openpgp-sdk version.
	{
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		QMessageBox msgBox;
		msgBox.setText(QObject::tr("This version of RetroShare is using OpenPGP-SDK. As a side effect, it's not using the system shared PGP keyring, but has it's own keyring shared by all RetroShare instances. <br><br>You do not appear to have such a keyring, although PGP keys are mentioned by existing RetroShare accounts, probably because you just changed to this new version of the software."));
		msgBox.setInformativeText(QObject::tr("Choose between:<br><ul><li><b>Ok</b> to copy the existing keyring from gnupg (safest bet), or </li><li><b>Close without saving</b> to start fresh with an empty keyring (you will be asked to create a new PGP key to work with RetroShare, or import a previously saved pgp keypair). </li><li><b>Cancel</b> to quit and forge a keyring by yourself (needs some PGP skills)</li></ul>"));
		msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Discard | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.setWindowIcon(QIcon(":/icons/logo_128.png"));

		int ret = msgBox.exec();

		if(ret == QMessageBox::Cancel)
			return 0 ;
		if(ret == QMessageBox::Ok)
		{
			if(!RsAccounts::CopyGnuPGKeyrings())
				return 0 ; 

			initResult = RsInit::InitRetroShare(argc, argv);

			displayWarningAboutDSAKeys() ;

		}
		else
			initResult = RS_INIT_OK ;
	}

	if (initResult < 0) {
		/* Error occured */
		QApplication dummyApp (argc, argv); // needed for QMessageBox
		/* Translate into the desired language */
		LanguageSupport::translate(LanguageSupport::defaultLanguageCode());

		displayWarningAboutDSAKeys();

		QMessageBox mb(QMessageBox::Critical, QObject::tr("RetroShare"), "", QMessageBox::Ok);
        mb.setWindowIcon(QIcon(":/icons/logo_128.png"));

		switch (initResult) 
		{
			case RS_INIT_AUTH_FAILED:
				std::cerr << "RsInit::InitRetroShare AuthGPG::InitAuth failed" << std::endl;
				mb.setText(QObject::tr("Initialization failed. Wrong or missing installation of PGP."));
				break;
			default:
				/* Unexpected return code */
				std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
				mb.setText(QObject::tr("An unexpected error occurred. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
				break;
		}
		mb.exec();
		return 1;
	}

	/* create global settings object
	   path maybe wrong, when no profile exist
	   in this case it can be use only for default values */
	RshareSettings::Create ();

	/* Setup The GUI Stuff */
	Rshare rshare(args, argc, argv, 
		QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()));

	std::string url = RsInit::getRetroShareLink();
	if (!url.empty()) {
		/* start with RetroShare link */
		EventReceiver eventReceiver;
		if (eventReceiver.sendRetroShareLink(QString::fromStdString(url))) {
			return 0;
		}

		/* Start RetroShare */
	}

	QSplashScreen splashScreen(QPixmap(":/images/logo/logo_splash.png")/* , Qt::WindowStaysOnTopHint*/);

	switch (initResult) {
	case RS_INIT_OK:
		{
			/* Login Dialog */
			/* check for existing Certificate */
			bool genCert = false;
			std::list<RsPeerId> accountIds;
			if (RsAccounts::GetAccountIds(accountIds) && (accountIds.size() > 0))
			{
				StartDialog sd;
				if (sd.exec() == QDialog::Rejected) {
					return 1;
				}

				/* if we're logged in */
				genCert = sd.requestedNewCert();
			}
			else
			{
				genCert = true;
			}

			if (genCert)
			{
				GenCertDialog gd(false);
				if (gd.exec () == QDialog::Rejected) {
					return 1;
				}
			}

			splashScreen.show();
		}
		break;
	case RS_INIT_HAVE_ACCOUNT:
		{
			splashScreen.show();
			splashScreen.showMessage(rshare.translate("SplashScreen", "Load profile"), Qt::AlignHCenter | Qt::AlignBottom);

			RsPeerId preferredId;
			RsAccounts::GetPreferredAccountId(preferredId);

			// true: note auto-login is active
			Rshare::loadCertificate(preferredId, true);
		}
		break;
	default:
		/* Unexpected return code */
		std::cerr << "RsInit::InitRetroShare unexpected return code " << initResult << std::endl;
		QMessageBox::warning(0, QObject::tr("RetroShare"), QObject::tr("An unexpected error occured. Please report 'RsInit::InitRetroShare unexpected return code %1'.").arg(initResult));
		return 1;
	}

	/* recreate global settings object, now with correct path */
	RshareSettings::Create(true);
	Rshare::resetLanguageAndStyle();

	SoundManager::create();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Load configuration"), Qt::AlignHCenter | Qt::AlignBottom);

	/* stop Retroshare if startup fails */
	if (!RsControl::instance()->StartupRetroShare())
	{
		std::cerr << "libretroshare failed to startup!" << std::endl;
		return 1;
	}


	Rshare::initPlugins();

	splashScreen.showMessage(rshare.translate("SplashScreen", "Create interface"), Qt::AlignHCenter | Qt::AlignBottom);

	RsharePeerSettings::Create();

	Emoticons::load();

	if (Settings->value(QString::fromUtf8("FirstRun"), true).toBool()) {
		splashScreen.hide();

		Settings->setValue(QString::fromUtf8("FirstRun"), false);

		SoundManager::initDefault();

#ifdef __APPLE__
		/* For OSX, we set the default to "cleanlooks", as the AQUA style hides some input boxes 
		 * only on the first run - as the user might want to change it ;)
		 */
		QString osx_style("cleanlooks");
		Rshare::setStyle(osx_style);
		Settings->setInterfaceStyle(osx_style);
#endif

// This is now disabled - as it doesn't add very much.
// Need to make sure that defaults are sensible!
#ifdef ENABLE_QUICKSTART_WIZARD
		QuickStartWizard qstartWizard;
		qstartWizard.exec();
#endif

	}

	MainWindow *w = MainWindow::Create ();
	splashScreen.finish(w);

	EventReceiver *eventReceiver = NULL;
	if (Settings->getRetroShareProtocol()) {
		/* Create event receiver */
		eventReceiver = new EventReceiver;
		if (eventReceiver->start()) {
			QObject::connect(eventReceiver, SIGNAL(linkReceived(const QUrl&)), w, SLOT(retroshareLinkActivated(const QUrl&)));
		}
	}

	if (!url.empty()) {
		/* Now use link from the command line, because no RetroShare was running */
		RetroShareLink link(QString::fromStdString(url));
		if (link.valid()) {
			w->retroshareLinkActivated(link.toUrl());
		}
	}

	// I'm using a signal to transfer the hashing info to the mainwindow, because Qt schedules signals properly to
	// avoid clashes between infos from threads.
	//

	qRegisterMetaType<FileDetail>("FileDetail") ;
	qRegisterMetaType<RsPeerId>("RsPeerId") ;

	std::cerr << "connecting signals and slots" << std::endl ;
	QObject::connect(notify,SIGNAL(gotTurtleSearchResult(qulonglong,FileDetail)),w->transfersDialog->searchDialog	,SLOT(updateFiles(qulonglong,FileDetail))) ;
	QObject::connect(notify,SIGNAL(deferredSignatureHandlingRequested()),notify,SLOT(handleSignatureEvent()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(chatLobbyTimeShift(int)),notify,SLOT(handleChatLobbyTimeShift(int)),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(diskFull(int,int))						,w                   		,SLOT(displayDiskSpaceWarning(int,int))) ;
	QObject::connect(notify,SIGNAL(filesPostModChanged(bool))         ,w                         ,SLOT(postModDirectories(bool)         )) ;
	QObject::connect(notify,SIGNAL(transfersChanged())                ,w->transfersDialog  		,SLOT(insertTransfers()                )) ;
	QObject::connect(notify,SIGNAL(publicChatChanged(int))            ,w->friendsDialog      		,SLOT(publicChatChanged(int)           ));
	QObject::connect(notify,SIGNAL(neighboursChanged())               ,w->friendsDialog->networkDialog    		,SLOT(securedUpdateDisplay())) ;

	QObject::connect(notify,SIGNAL(chatStatusChanged(const QString&,const QString&,bool)),w->friendsDialog,SLOT(updatePeerStatusString(const QString&,const QString&,bool)));
	QObject::connect(notify,SIGNAL(ownStatusMessageChanged()),w->friendsDialog,SLOT(loadmypersonalstatus()));

	QObject::connect(notify,SIGNAL(logInfoChanged(const QString&))		,w->friendsDialog->networkDialog,SLOT(setLogInfo(QString))) ;
	QObject::connect(notify,SIGNAL(discInfoChanged())						,w->friendsDialog->networkView,SLOT(update()),Qt::QueuedConnection) ;
	QObject::connect(notify,SIGNAL(errorOccurred(int,int,const QString&)),w,SLOT(displayErrorMessage(int,int,const QString&))) ;

	w->installGroupChatNotifier();

	/* only show window, if not startMinimized */
	if (RsInit::getStartMinimised() || Settings->getStartMinimized())
	{
		splashScreen.close();
	} else {
		w->show();
	}

	/* Startup a Timer to keep the gui's updated */
	QTimer *timer = new QTimer(w);
	timer -> connect(timer, SIGNAL(timeout()), notify, SLOT(UpdateGUI()));
	timer->start(1000);

	notify->enable() ;	// enable notification system after GUI creation, to avoid data races in Qt.

    WebuiPage::checkStartWebui();

	/* dive into the endless loop */
	int ti = rshare.exec();
	delete w ;

    WebuiPage::checkShutdownWebui();

	if (eventReceiver) {
		/* Destroy event receiver */
		delete eventReceiver;
		eventReceiver = NULL;
	}

	/* cleanup */
	ChatDialog::cleanupChat();
#ifdef RS_ENABLE_GXS
	RsGxsUpdateBroadcast::cleanup();
#endif

	RsControl::instance()->rsGlobalShutDown();

	delete(soundManager);
	soundManager = NULL;

	Settings->sync();
	delete(Settings);

	return ti ;
}
示例#24
0
int main(int argc, char** argv) {
    std::string basePath = inviwo::filesystem::findBasePath();

    inviwo::LogCentral::init();
    auto filelogger = std::make_shared<inviwo::FileLogger>(basePath);
    inviwo::LogCentral::getPtr()->registerLogger(filelogger);
    inviwo::InviwoApplicationQt inviwoApp("Inviwo v" + IVW_VERSION, argc, argv);
    inviwoApp.setWindowIcon(QIcon(":/icons/inviwo_light.png"));
    inviwoApp.setAttribute(Qt::AA_NativeWindows);
    QFile styleSheetFile(":/stylesheets/inviwo.qss");
    styleSheetFile.open(QFile::ReadOnly);
    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());
    inviwoApp.setStyleSheet(styleSheet);
    styleSheetFile.close();

    auto& clp = inviwoApp.getCommandLineParser();

    inviwo::InviwoMainWindow mainWin(&inviwoApp);
    // setup core application
    inviwoApp.setMainWindow(&mainWin);
    // initialize and show splash screen
    inviwo::InviwoSplashScreen splashScreen(&mainWin, clp.getShowSplashScreen());
    inviwoApp.setProgressCallback([&splashScreen](std::string s) { splashScreen.showMessage(s); });

    splashScreen.show();
    splashScreen.showMessage("Loading application...");

    // Initialize application and register modules
    splashScreen.showMessage("Initializing modules...");
    inviwoApp.registerModules(&inviwo::registerAllModules);
    inviwoApp.processEvents();

    // Do this after registerModules if some arguments were added
    clp.parse(inviwo::CommandLineParser::Mode::Normal);

    // setup main window
    mainWin.initialize();
    inviwoApp.processEvents();
    splashScreen.showMessage("Loading workspace...");
    inviwoApp.processEvents();
    mainWin.showWindow();
    inviwoApp.processEvents();  // Make sure the gui is done loading before loading workspace

    mainWin.openLastWorkspace(clp.getWorkspacePath());  // open last workspace
    splashScreen.finish(&mainWin);

    inviwoApp.processEvents();
    clp.processCallbacks(); // run any command line callbacks from modules.
    inviwoApp.processEvents();

    inviwo::util::OnScopeExit clearNetwork([&](){
        inviwoApp.getProcessorNetwork()->clear();
    });

    // process last arguments
    if (!clp.getQuitApplicationAfterStartup()) {
        return inviwoApp.exec();
    }
    else {
        mainWin.exitInviwo(false);
        return 0;
    }
}
示例#25
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(resource_omedit);
  // read the second argument if specified by user.
  QString fileName = QString();
  // adding style sheet
  argc++;
  argv[(argc - 1)] = "-stylesheet=:/Resources/css/stylesheet.qss";

  QApplication a(argc, argv);
  QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
  a.setAttribute(Qt::AA_DontShowIconsInMenus, false);
  // Localization
  //*a.severin/ add localization
  const char *omhome = getenv("OPENMODELICAHOME");
#ifdef WIN32
  if (!omhome) {
    QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error),
                          GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok);
    a.quit();
    exit(1);
  }
#else /* unix */
  omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME;
#endif
  QSettings settings(QSettings::IniFormat, QSettings::UserScope, "openmodelica", "omedit");
  QString language = settings.value("language").toString();
  QString translationDirectory = omhome + QString("/share/omedit/nls");
  QString locale = language.isEmpty() ? QLocale::system().name() : language;
  // install Qt's default translations
  QTranslator qtTranslator;
#ifdef Q_OS_WIN
  qtTranslator.load("qt_" + locale, translationDirectory);
#else
  qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
  a.installTranslator(&qtTranslator);
  // install application translations
  QTranslator translator;
  translator.load("OMEdit_" + locale, translationDirectory);
  a.installTranslator(&translator);
  // Splash Screen
  QPixmap pixmap(":/Resources/icons/omeditor_splash.png");
  SplashScreen splashScreen(pixmap);
  splashScreen.setMessage();
  splashScreen.show();
  Helper::initHelperVariables();
  // MainWindow Initialization
  MainWindow mainwindow(&splashScreen);
  if (mainwindow.mExitApplication) {        // if there is some issue in running the application.
    a.quit();
    exit(1);
  }
  bool OMCLogger = false;
  // if user has requested to open the file by passing it in argument then,
  if (a.arguments().size() > 1)
  {
    for (int i = 1; i < a.arguments().size(); i++)
    {
      if (strncmp(a.arguments().at(i).toStdString().c_str(), "--OMCLogger=",12) == 0) {
        QString omcLoggerArg = a.arguments().at(i);
        omcLoggerArg.remove("--OMCLogger=");
        if (0 == strcmp("true", omcLoggerArg.toStdString().c_str()))
          OMCLogger = true;
        else if (0 == strcmp("false", omcLoggerArg.toStdString().c_str()))
          OMCLogger = false;
      }
      fileName = a.arguments().at(i);
      if (!fileName.isEmpty())
      {
        // if path is relative make it absolute
        QFileInfo file (fileName);
        if (file.isRelative())
        {
          fileName.prepend(QString(QDir::currentPath()).append("/"));
        }
        mainwindow.mpProjectTabs->openFile(fileName);
      }
    }
  }
  // hide OMCLogger send custom expression feature if OMCLogger is false
  mainwindow.mpOMCProxy->enableCustomExpression(OMCLogger);
  // finally show the main window
  mainwindow.show();
  // hide the splash screen
  splashScreen.finish(&mainwindow);
  return a.exec();
}