示例#1
0
文件: main.cpp 项目: TJC-AS/trunk
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setOption(QSurfaceFormat::StereoBuffers, true);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

	//The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application
	//DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows)
	QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

	//QT initialiation
	qccApplication app(argc, argv);

	//Locale management
	{
		//Force 'english' locale so as to get a consistent behavior everywhere
		QLocale locale = QLocale(QLocale::English);
		locale.setNumberOptions(QLocale::c().numberOptions());
		QLocale::setDefault(locale);

#ifdef Q_OS_UNIX
		//We reset the numeric locale for POSIX functions
		//See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
		setlocale(LC_NUMERIC, "C");
#endif
	}

#ifdef USE_VLD
	VLDEnable();
#endif

#ifdef Q_OS_MAC	
	// This makes sure that our "working directory" is not within the application bundle
	QDir  appDir = QCoreApplication::applicationDirPath();
	
	if ( appDir.dirName() == "MacOS" )
	{
		appDir.cdUp();
		appDir.cdUp();
		appDir.cdUp();
		
		QDir::setCurrent( appDir.absolutePath() );
	}
#endif
	
	//splash screen
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}
	
	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific case: translation file selection
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine && QString(argv[1]).toUpper() == "-LANG")
	{
		QString langFilename = QString(argv[2]);
		
		//Load translation file
		if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
		{
			qApp->installTranslator(&translator);
		}
		else
		{
			QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
		}
		commandLine = false;
		lastArgumentIndex = 3;
	}

	//command line mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint);
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	ccTimer::Init();
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	int result = 0;

	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}


		if (argc > lastArgumentIndex)
		{
			if (splash)
				splash->close();

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i<argc; ++i)
				filenames << QString(argv[i]);

			mainWindow->addToDB(filenames);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch(...)
		{
			QMessageBox::warning(0, "CC crashed!","Hum, it seems that CC has crashed... Sorry about that :)");
		}
	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
示例#2
0
文件: main.cpp 项目: midzer/LibreCAD
/**
 * Main. Creates Application window.
 */
int main(int argc, char** argv)
{
    RS_DEBUG->setLevel(RS_Debug::D_WARNING);

    QApplication app(argc, argv);
    QCoreApplication::setOrganizationName("LibreCAD");
    QCoreApplication::setApplicationName("/LibreCAD");
    QCoreApplication::setApplicationVersion("master");

    QSplashScreen* splash = new QSplashScreen;

    RS_SETTINGS->beginGroup("Appearance");
    bool show_splash = RS_SETTINGS->readNumEntry("/ShowSplash", 1);
    RS_SETTINGS->endGroup();

    if (show_splash)
    {
        QPixmap pixmap(":/main/splash_librecad.png");
        splash->setPixmap(pixmap);
        splash->setAttribute(Qt::WA_DeleteOnClose);
        splash->show();
        splash->showMessage(QObject::tr("Loading.."),
                            Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
        app.processEvents();
        RS_DEBUG->print("main: splashscreen: OK");
    }

    #if defined(Q_OS_MAC) && QT_VERSION > 0x050000
        //need stylesheet for Qt5 on mac
        app.setStyleSheet(
"QToolButton:checked"
"{"
"    background-color: rgb(160,160,160);"
"    border-style: inset;"
"}"
""
"QToolButton"
"{"
"    background-color: transparent;"
"}"
""
"QToolButton:hover"
"{"
"    background-color: rgb(255,255,255);"
"    border-style: outset;"
"}"
        );
    #endif

    const QString lpDebugSwitch0("-d"),lpDebugSwitch1("--debug") ;
    const QString help0("-h"), help1("--help");
    bool allowOptions=true;
    QList<int> argClean;
    for (int i=0; i<argc; i++)
    {
        QString argstr(argv[i]);
        if(allowOptions&&QString::compare("--", argstr)==0)
        {
            allowOptions=false;
            continue;
        }
        if (allowOptions && (help0.compare(argstr, Qt::CaseInsensitive)==0 ||
                             help1.compare(argstr, Qt::CaseInsensitive)==0 ))
        {
            qDebug()<<"librecad::usage: <options> <dxf file>";
            qDebug()<<"-h, --help\tdisplay this message";
            qDebug()<<"";
            qDebug()<<" --help\tdisplay this message";
            qDebug()<<"-d, --debug <level>";
            RS_DEBUG->print( RS_Debug::D_NOTHING, "possible debug levels:");
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Nothing", RS_Debug::D_NOTHING);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Critical", RS_Debug::D_CRITICAL);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Error", RS_Debug::D_ERROR);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Warning", RS_Debug::D_WARNING);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Notice", RS_Debug::D_NOTICE);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Informational", RS_Debug::D_INFORMATIONAL);
            RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Debugging", RS_Debug::D_DEBUGGING);
            exit(0);
        }
        if ( allowOptions&& (argstr.startsWith(lpDebugSwitch0, Qt::CaseInsensitive) ||
                             argstr.startsWith(lpDebugSwitch1, Qt::CaseInsensitive) ))
        {
            argClean<<i;

            // to control the level of debugging output use --debug with level 0-6, e.g. --debug3
            // for a list of debug levels use --debug?
            // if no level follows, the debugging level is set
            argstr.remove(QRegExp("^"+lpDebugSwitch0));
            argstr.remove(QRegExp("^"+lpDebugSwitch1));
            char level;
            if(argstr.size()==0)
            {
                if(i+1<argc)
                {
                    if(QRegExp("\\d*").exactMatch(argv[i+1]))
                    {
                        ++i;
                        qDebug()<<"reading "<<argv[i]<<" as debugging level";
                        level=argv[i][0];
                        argClean<<i;
                    }
                    else
                        level='3';
                }
                else
                    level='3'; //default to D_WARNING
            }
            else
                level=argstr.toStdString()[0];

            switch(level)
            {
            case '?' :
                RS_DEBUG->print( RS_Debug::D_NOTHING, "possible debug levels:");
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Nothing", RS_Debug::D_NOTHING);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Critical", RS_Debug::D_CRITICAL);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Error", RS_Debug::D_ERROR);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Warning", RS_Debug::D_WARNING);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Notice", RS_Debug::D_NOTICE);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Informational", RS_Debug::D_INFORMATIONAL);
                RS_DEBUG->print( RS_Debug::D_NOTHING, "    %d Debugging", RS_Debug::D_DEBUGGING);
                return 0;

            case '0' + RS_Debug::D_NOTHING :
                RS_DEBUG->setLevel( RS_Debug::D_NOTHING);
                ++i;
                break;

            case '0' + RS_Debug::D_CRITICAL :
                RS_DEBUG->setLevel( RS_Debug::D_CRITICAL);
                ++i;
                break;

            case '0' + RS_Debug::D_ERROR :
                RS_DEBUG->setLevel( RS_Debug::D_ERROR);
                ++i;
                break;

            case '0' + RS_Debug::D_WARNING :
                RS_DEBUG->setLevel( RS_Debug::D_WARNING);
                ++i;
                break;

            case '0' + RS_Debug::D_NOTICE :
                RS_DEBUG->setLevel( RS_Debug::D_NOTICE);
                ++i;
                break;

            case '0' + RS_Debug::D_INFORMATIONAL :
                RS_DEBUG->setLevel( RS_Debug::D_INFORMATIONAL);
                ++i;
                break;

            case '0' + RS_Debug::D_DEBUGGING :
                RS_DEBUG->setLevel( RS_Debug::D_DEBUGGING);
                ++i;
                break;

            default :
                RS_DEBUG->setLevel(RS_Debug::D_DEBUGGING);
                break;
            }
        }
    }
    RS_DEBUG->print("param 0: %s", argv[0]);

    QFileInfo prgInfo( QFile::decodeName(argv[0]) );
    QString prgDir(prgInfo.absolutePath());
    RS_SETTINGS->init(XSTR(QC_COMPANYKEY), XSTR(QC_APPKEY));
    RS_SYSTEM->init(XSTR(QC_APPNAME), XSTR(QC_VERSION), XSTR(QC_APPDIR), prgDir);

    // parse command line arguments that might not need a launched program:
    QStringList fileList = handleArgs(argc, argv, argClean);

    QString lang;
    QString langCmd;
    QString unit;

    RS_SETTINGS->beginGroup("/Defaults");
    #ifndef QC_PREDEFINED_UNIT
        unit = RS_SETTINGS->readEntry("/Unit", "Invalid");
    #else
        unit = RS_SETTINGS->readEntry("/Unit", QC_PREDEFINED_UNIT);
    #endif
    RS_SETTINGS->endGroup();

    // show initial config dialog:
    if (unit=="Invalid")
    {
        RS_DEBUG->print("main: show initial config dialog..");
        QG_DlgInitial di(nullptr);
        QPixmap pxm(":/main/intro_librecad.png");
        di.setPixmap(pxm);
        if (di.exec())
        {
            RS_SETTINGS->beginGroup("/Defaults");
            unit = RS_SETTINGS->readEntry("/Unit", "None");
            RS_SETTINGS->endGroup();
        }
        RS_DEBUG->print("main: show initial config dialog: OK");
    }

    RS_DEBUG->print("main: init fontlist..");
    RS_FONTLIST->init();
    RS_DEBUG->print("main: init fontlist: OK");

    RS_DEBUG->print("main: init patternlist..");
    RS_PATTERNLIST->init();
    RS_DEBUG->print("main: init patternlist: OK");

    RS_DEBUG->print("main: init scriptlist..");
    RS_SCRIPTLIST->init();
    RS_DEBUG->print("main: init scriptlist: OK");

    RS_DEBUG->print("main: loading translation..");
    RS_SETTINGS->beginGroup("/Appearance");
    #ifdef QC_PREDEFINED_LOCALE
        lang = RS_SETTINGS->readEntry("/Language", "");
        if (lang.isEmpty())
        {
            lang=QC_PREDEFINED_LOCALE;
            RS_SETTINGS->writeEntry("/Language", lang);
        }
        langCmd = RS_SETTINGS->readEntry("/LanguageCmd", "");
        if (langCmd.isEmpty())
        {
            langCmd=QC_PREDEFINED_LOCALE;
            RS_SETTINGS->writeEntry("/LanguageCmd", langCmd);
        }
    #else
        lang = RS_SETTINGS->readEntry("/Language", "en");
        langCmd = RS_SETTINGS->readEntry("/LanguageCmd", "en");
    #endif
    RS_SETTINGS->endGroup();

    RS_SYSTEM->loadTranslation(lang, langCmd);
    RS_DEBUG->print("main: loading translation: OK");

    RS_DEBUG->print("main: creating main window..");
    QC_ApplicationWindow appWin;
    RS_DEBUG->print("main: setting caption");
    appWin.setWindowTitle(XSTR(QC_APPNAME));

    RS_DEBUG->print("main: show main window");

    RS_SETTINGS->beginGroup("/Geometry");
    int windowWidth = RS_SETTINGS->readNumEntry("/WindowWidth", 0);
    int windowHeight = RS_SETTINGS->readNumEntry("/WindowHeight", 0);
    int windowX = RS_SETTINGS->readNumEntry("/WindowX", 30);
    int windowY = RS_SETTINGS->readNumEntry("/WindowY", 30);
    RS_SETTINGS->endGroup();

    if (windowWidth != 0)
        appWin.resize(windowWidth, windowHeight);

    appWin.move(windowX, windowY);

    RS_SETTINGS->beginGroup("Defaults");
    bool maximize = RS_SETTINGS->readNumEntry("/Maximize", 0);
    RS_SETTINGS->endGroup();
    if (maximize || windowWidth == 0)
        appWin.showMaximized();
    else
        appWin.show();

    RS_DEBUG->print("main: set focus");
    appWin.setFocus();
    RS_DEBUG->print("main: creating main window: OK");

    if (show_splash)
    {
        RS_DEBUG->print("main: updating splash");
        splash->raise();
        splash->showMessage(QObject::tr("Loading..."),
                Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
        RS_DEBUG->print("main: processing events");
        qApp->processEvents();
        RS_DEBUG->print("main: updating splash: OK");
    }

    // Set LC_NUMERIC so that entering numeric values uses . as the decimal seperator
    setlocale(LC_NUMERIC, "C");

    RS_DEBUG->print("main: loading files..");
    bool files_loaded = false;
    for (QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it )
    {
        if (show_splash)
        {
            splash->showMessage(QObject::tr("Loading File %1..")
                    .arg(QDir::toNativeSeparators(*it)),
            Qt::AlignRight|Qt::AlignBottom, QC_SPLASH_TXTCOL);
            qApp->processEvents();
        }
        appWin.slotFileOpen(*it, RS2::FormatUnknown);
        files_loaded = true;
    }
    RS_DEBUG->print("main: loading files: OK");

    RS_DEBUG->print("main: app.exec()");

    if (!files_loaded)
    {
        appWin.slotFileNewNew();
    }

    if (show_splash)
        splash->finish(&appWin);
    else
        delete splash;

    int return_code = app.exec();

    RS_DEBUG->print("main: exited Qt event loop");

    return return_code;
}
示例#3
0
int main(int argc, char **argv)
{
	//QT initialiation
	qccApplication app(argc, argv);

	//Force 'english' local so as to get a consistent behavior everywhere
	QLocale::setDefault(QLocale::English);

#ifdef Q_OS_LINUX
    // we reset the numeric locale. As suggested in documetation
    // see http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
    // Basically - from doc: - "On Unix/Linux Qt is configured to use the system locale settings by default.
    // This can cause a conflict when using POSIX functions, for instance,
    // when converting between data types such as floats and strings"
    setlocale(LC_NUMERIC,"C");
#endif

#ifdef USE_VLD
	VLDEnable();
#endif

	//splash screen
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	if (!commandLine)
	{
		//OpenGL?
		if (!QGLFormat::hasOpenGL())
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = new QSplashScreen(pixmap,Qt::WindowStaysOnTopHint);
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	ccTimer::Init();
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	int result = 0;

	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc,argv);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->show();
		QApplication::processEvents();

		if (argc > 1)
		{
			if (splash)
				splash->close();

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i=1; i<argc; ++i)
				filenames << QString(argv[i]);

			mainWindow->addToDB(filenames);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch(...)
		{
			QMessageBox::warning(0, "CC crashed!","Hum, it seems that CC has crashed... Sorry about that :)");
		}
	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
示例#4
0
文件: main.cpp 项目: QShen3/QVideo
Q_DECL_EXPORT int main(int argc, char *argv[])
{
#ifdef Q_OS_SYMBIAN
    QApplication::setAttribute((Qt::ApplicationAttribute)11);   //Qt::AA_CaptureMultimediaKeys
#endif
    QApplication app(argc, argv);

    app.setApplicationName("QVideo");
    app.setOrganizationName("QShen");
    app.setApplicationVersion(VER);



    QString locale = QLocale::system().name();
    QTranslator translator;
    if(!translator.load(QString("QVideo_") + locale,":/i18n")){
        qDebug()<<"translator load erro";
    }
    app.installTranslator(&translator);

    Utility utility;
    Settings settings;

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QmlApplicationViewer viewer;

    //viewer.setAttribute(Qt::WA_OpaquePaintEvent);
    //viewer.setAttribute(Qt::WA_NoSystemBackground);
    //viewer.viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    //viewer.viewport()->setAttribute(Qt::WA_NoSystemBackground);
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockPortrait);

    viewer.rootContext()->setContextProperty("utility", &utility);
    viewer.rootContext()->setContextProperty("settings", &settings);

    viewer.rootContext()->setContextProperty("appVersion", app.applicationVersion());

#ifdef Q_OS_SYMBIAN
    QSplashScreen *splash = new QSplashScreen(QPixmap(":/qml/pic/splash_symbian.png"));
    splash->show();
    splash->raise();

    viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml"));
#elif defined(Q_OS_HARMATTAN)
    //QApplication::setGraphicsSystem("native");
    viewer.setSource(QUrl("qrc:/qml/Meego/main.qml"));
#elif defined(Q_WS_SIMULATOR)
    viewer.setSource(QUrl("qrc:/qml/Symbian/main.qml"));
#endif
    viewer.showExpanded();
#else
    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("utility",&utility);
#ifdef Q_OS_WIN32
    engine.load(QUrl(QStringLiteral("qrc:/qml/Win32/main.qml")));
#endif

#endif

#ifdef Q_OS_SYMBIAN
    splash->finish(&viewer);
    splash->deleteLater();
#endif
    return app.exec();
}
示例#5
0
int main(int argc, char **argv)
{
	//See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions
	/** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory
		on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to
		ensure that resource sharing between contexts stays functional as all internal contexts are created
		using the correct version and profile.
	**/
	{
		QSurfaceFormat format = QSurfaceFormat::defaultFormat();
		format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
		format.setOption(QSurfaceFormat::StereoBuffers, true);
		format.setStencilBufferSize(0);
#ifdef CC_GL_WINDOW_USE_QWINDOW
		format.setStereo(true);
#endif
#ifdef Q_OS_MAC
		format.setStereo(false);
		format.setVersion( 2, 1 );
		format.setProfile( QSurfaceFormat::CoreProfile );
#endif
#ifdef QT_DEBUG
		format.setOption(QSurfaceFormat::DebugContext, true);
#endif
		QSurfaceFormat::setDefaultFormat(format);
	}

	//The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application
	//DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows)
	QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);

	//QT initialiation
	qccApplication app(argc, argv);

	//Locale management
	{
		//Force 'english' locale so as to get a consistent behavior everywhere
		QLocale locale = QLocale(QLocale::English);
		locale.setNumberOptions(QLocale::c().numberOptions());
		QLocale::setDefault(locale);

#ifdef Q_OS_UNIX
		//We reset the numeric locale for POSIX functions
		//See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
		setlocale(LC_NUMERIC, "C");
#endif
	}

#ifdef USE_VLD
	VLDEnable();
#endif

#ifdef Q_OS_MAC	
	// This makes sure that our "working directory" is not within the application bundle
	QDir  appDir = QCoreApplication::applicationDirPath();
	
	if ( appDir.dirName() == "MacOS" )
	{
		appDir.cdUp();
		appDir.cdUp();
		appDir.cdUp();
		
		QDir::setCurrent( appDir.absolutePath() );
	}
#endif

	//store the log message until a valid logging instance is registered
	ccLog::EnableMessageBackup(true);
	
	//restore some global parameters
	{
		QSettings settings;
		settings.beginGroup(ccPS::GlobalShift());
		double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble();
		double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble();
		settings.endGroup();

		ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0));
		
		ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord);
		ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag);
	}

	//Command line mode?
	bool commandLine = (argc > 1 && argv[1][0] == '-');
	
	//specific commands
	int lastArgumentIndex = 1;
	QTranslator translator;
	if (commandLine)
	{
		//translation file selection
		if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG")
		{
			QString langFilename = QString(argv[2]);

			//Load translation file
			if (translator.load(langFilename, QCoreApplication::applicationDirPath()))
			{
				qApp->installTranslator(&translator);
			}
			else
			{
				QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename));
			}
			commandLine = false;
			lastArgumentIndex += 2;
		}
	}

	//splash screen
	QSplashScreen* splash = 0;
	QTime splashStartTime;

	//standard mode
	if (!commandLine)
	{
		if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0)
		{
			QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!");
			return EXIT_FAILURE;
		}

		//splash screen
		splashStartTime.start();
		QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png"));
		splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint);
		splash->show();
		QApplication::processEvents();
	}

	//global structures initialization
	FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!)
	ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization
	ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization

	//load the plugins
	tPluginInfoList plugins;
	QStringList dirFilters;
	QStringList pluginPaths;
	{
		QString appPath = QCoreApplication::applicationDirPath();

#if defined(Q_OS_MAC)
		dirFilters << "*.dylib";

		// plugins are in the bundle
		appPath.remove("MacOS");

		pluginPaths += (appPath + "Plugins/ccPlugins");
#if defined(CC_MAC_DEV_PATHS)
		// used for development only - this is the path where the plugins are built
		// this avoids having to install into the application bundle when developing
		pluginPaths += (appPath + "../../../ccPlugins");
#endif
#elif defined(Q_OS_WIN)
		dirFilters << "*.dll";

		//plugins are in bin/plugins
		pluginPaths << (appPath + "/plugins");
#elif defined(Q_OS_LINUX)
		dirFilters << "*.so";

		// Plugins are relative to the bin directory where the executable is found
		QDir  binDir(appPath);

		if (binDir.dirName() == "bin")
		{
			binDir.cdUp();

			pluginPaths << (binDir.absolutePath() + "/lib/cloudcompare/plugins");
		}
		else
		{
			// Choose a reasonable default to look in
			pluginPaths << "/usr/lib/cloudcompare/plugins";
		}
#else
		#warning Need to specify the plugin path for this OS.
#endif

#ifdef Q_OS_MAC
		// Add any app data paths
		// Plugins in these directories take precendence over the included ones
		QStringList appDataPaths = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);

		for (const QString &appDataPath : appDataPaths)
		{
			pluginPaths << (appDataPath + "/plugins");
		}
#endif
	}

	ccPlugins::LoadPlugins(plugins, pluginPaths, dirFilters);
	
	int result = 0;

	//command line mode
	if (commandLine)
	{
		//command line processing (no GUI)
		result = ccCommandLineParser::Parse(argc, argv);
	}
	else
	{
		//main window init.
		MainWindow* mainWindow = MainWindow::TheInstance();
		if (!mainWindow)
		{
			QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!");
			return EXIT_FAILURE;
		}
		mainWindow->dispatchPlugins(plugins, pluginPaths);
		mainWindow->show();
		QApplication::processEvents();

		//show current Global Shift parameters in Console
		{
			ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2")
				.arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0)
				.arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0));
		}

		if (argc > lastArgumentIndex)
		{
			if (splash)
				splash->close();

			//any additional argument is assumed to be a filename --> we try to load it/them
			QStringList filenames;
			for (int i = lastArgumentIndex; i < argc; ++i)
			{
				QString arg(argv[i]);
				//special command: auto start a plugin
				if (arg.startsWith(":start-plugin:"))
				{
					QString pluginName = arg.mid(14);
					QString pluginNameUpper = pluginName.toUpper();
					//look for this plugin
					bool found = false;
					for (const tPluginInfo &plugin : plugins)
					{
						if (plugin.object->getName().replace(' ', '_').toUpper() == pluginNameUpper)
						{
							found = true;
							bool success = plugin.object->start();
							if (!success)
							{
								ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin.object->getName()));
							}
							break;
						}
					}

					if (!found)
					{
						ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' ')));
					}
				}
				else
				{
					filenames << arg;
				}
			}

			mainWindow->addToDB(filenames);
		}
		
		if (splash)
		{
			//we want the splash screen to be visible a minimum amount of time (1000 ms.)
			while (splashStartTime.elapsed() < 1000)
			{
				splash->raise();
				QApplication::processEvents(); //to let the system breath!
			}

			splash->close();
			QApplication::processEvents();

			delete splash;
			splash = 0;
		}

		//let's rock!
		try
		{
			result = app.exec();
		}
		catch (...)
		{
			QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)");
		}

		//release the plugins
		for (tPluginInfo &plugin : plugins)
		{
			plugin.object->stop(); //just in case
			if (!plugin.qObject->parent())
			{
				delete plugin.object;
				plugin.object = 0;
				plugin.qObject = 0;
			}
		}

	}

	//release global structures
	MainWindow::DestroyInstance();
	FileIOFilter::UnregisterAll();

#ifdef CC_TRACK_ALIVE_SHARED_OBJECTS
	//for debug purposes
	unsigned alive = CCShareable::GetAliveCount();
	if (alive > 1)
	{
		printf("Error: some shared objects (%u) have not been released on program end!",alive);
		system("PAUSE");
	}
#endif

	return result;
}
示例#6
0
文件: main.cpp 项目: ydxt25/ithome-1
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));
    //qDebug()<<QString::fromUtf8("主线程地址是:")<<QThread::currentThread();
#if defined(Q_OS_SYMBIAN)||defined(Q_WS_SIMULATOR)
    QPixmap pixmap(":/Image/Symbian.png");
    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();
    splash->raise();
#endif

#ifndef QT_NO_DEBUG
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::HttpProxy);
    proxy.setHostName("localhost");
    proxy.setPort(8888);
    QNetworkProxy::setApplicationProxy(proxy);
#endif
    //int width=QApplication::desktop()->width();
    //int height=QApplication::desktop()->height();
    app->setApplicationName (QString::fromUtf8("IT之家"));
    app->setOrganizationName ("Stars");
    app->setApplicationVersion ("1.2.2");
    Settings *setting=new Settings;
    Utility *unility=new Utility;
    Cache *cacheContent=new Cache(setting);
    //qmlRegisterType<MyXmlListModel>("myXmlListModel",1,0,"MyXmlListModel");
    //qmlRegisterType<MyXmlRole>("myXmlListModel", 1, 0, "MyXmlRole");

    QmlApplicationViewer viewer;
    
    MyNetworkAccessManagerFactory *network = new MyNetworkAccessManagerFactory();
    viewer.engine()->setNetworkAccessManagerFactory(network);
    
    viewer.rootContext ()->setContextProperty ("cacheContent",cacheContent);
    viewer.rootContext()->setContextProperty("settings",setting);
    viewer.rootContext()->setContextProperty("utility",unility);
    
    QWebSettings::globalSettings ()->setAttribute (QWebSettings::LocalContentCanAccessRemoteUrls,true);
    QWebSettings::globalSettings ()->setAttribute (QWebSettings::SpatialNavigationEnabled,true);
    QWebSettings::globalSettings ()->setAttribute (QWebSettings::SpatialNavigationEnabled, true);
#if defined(Q_OS_SYMBIAN)||defined(Q_WS_SIMULATOR)
#if defined(Q_OS_S60V5)//判断qt的版本
    qWarning("build symbian s60v5");
    viewer.setMainQmlFile(QLatin1String("qml/symbian-v5/main.qml"));
    if(setting->getValue("night_mode",false).toBool())
        unility->setCss("./qml/symbian-v5/theme_black.css",viewer.width()-20);//设置默认的css
    else
        unility->setCss("./qml/symbian-v5/theme_white.css",viewer.width()-20);
#elif defined(Q_OS_S60V3)
    qWarning("build symbian s60v3");
    viewer.setMainQmlFile(QLatin1String("qml/symbian-v3/main.qml"));
    if(setting->getValue("night_mode",false).toBool())
        unility->setCss("./qml/symbian-v3/theme_black.css",viewer.width()-20);//设置默认的css
    else
        unility->setCss("./qml/symbian-v3/theme_white.css",viewer.width()-20);
#else
    qWarning("build symbian anna or simulator");
    viewer.setMainQmlFile(QLatin1String("qml/symbian-anna/main.qml"));
    if(setting->getValue("night_mode",false).toBool())
        unility->setCss("./qml/symbian-anna/theme_black.css",viewer.width()-20);//设置默认的css
    else
        unility->setCss("./qml/symbian-anna/theme_white.css",viewer.width()-20);
#endif
    viewer.showExpanded();
    splash->finish(&viewer);
    splash->deleteLater();
#elif defined(Q_OS_HARMATTAN)
    qWarning("build meego");
    viewer.setMainQmlFile(QLatin1String("qml/meego/main.qml"));
    if(setting->getValue("night_mode",false).toBool())
        unility->setCss("/opt/ithome/qml/meego/theme_black.css",460);//设置默认的css
    else
        unility->setCss("/opt/ithome/qml/meego/theme_white.css",460);
    viewer.showExpanded();
#endif
    return app->exec();
}