Exemplo n.º 1
0
void CWizDocumentView::on_syncDatabase_request(const QString& strKbGUID)
{
    MainWindow* mainWindow = qobject_cast<MainWindow *>(m_app.mainWindow());
    mainWindow->quickSyncKb(strKbGUID);
}
Exemplo n.º 2
0
ToolbarMenu::ToolbarMenu(QWidget *parent) : QMenu(parent) {
    MainWindow *w = MainWindow::instance();
    addAction(w->getAction("stopafterthis"));
    addSeparator();
#ifdef APP_SNAPSHOT
    addAction(w->getAction("snapshot"));
#endif
    addAction(w->getAction("findVideoParts"));
    addSeparator();
    addAction(w->getAction("webpage"));
    addAction(w->getAction("videolink"));
    addAction(w->getAction("openInBrowser"));
    addAction(w->getAction("download"));
    addSeparator();
    QWidgetAction *widgetAction = new QWidgetAction(this);
    ShareToolbar *shareToolbar = new ShareToolbar();
    connect(this, &ToolbarMenu::leftMarginChanged, shareToolbar, &ShareToolbar::setLeftMargin);
    widgetAction->setDefaultWidget(shareToolbar);
    addAction(widgetAction);
    addSeparator();

    addAction(w->getAction("compactView"));
    addAction(w->getAction("ontop"));
    addSeparator();

    QToolBar *definitionToolbar = new QToolBar();
    definitionToolbar->setStyleSheet("QToolButton { padding: 0}");
    definitionToolbar->setToolButtonStyle(Qt::ToolButtonTextOnly);
    definitionToolbar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    QActionGroup *definitionGroup = new QActionGroup(this);
    const VideoDefinition &preferredDefinition = YT3::instance().maxVideoDefinition();
    int counter = 0;
    for (auto defName : VideoDefinition::getDefinitionNames()) {
        QAction *a = new QAction(defName);
        a->setCheckable(true);
        a->setChecked(preferredDefinition.getName() == defName);
        connect(a, &QAction::triggered, this, [this, defName] {
            MainWindow::instance()->setDefinitionMode(defName);
            close();
        });
        definitionGroup->addAction(a);
        definitionToolbar->addAction(a);
        if (counter == 0) {
            QWidget *w = definitionToolbar->widgetForAction(a);
            w->setProperty("first", true);
            counter++;
        }
    }
    QWidgetAction *definitionAction = new QWidgetAction(this);
    definitionAction->setDefaultWidget(definitionToolbar);
    addAction(definitionAction);
    addSeparator();

    addAction(w->getAction("clearRecentKeywords"));
#ifndef APP_MAC
    addSeparator();
    addAction(w->getAction("toggleMenu"));
    addSeparator();
    addMenu(w->getMenu("help"));
#endif
}
Exemplo n.º 3
0
void NativeInit(int argc, const char *argv[],
								const char *savegame_directory, const char *external_directory, const char *installID) {
#ifdef ANDROID_NDK_PROFILER
	setenv("CPUPROFILE_FREQUENCY", "500", 1);
	setenv("CPUPROFILE", "/sdcard/gmon.out", 1);
	monstartup("ppsspp_jni.so");
#endif

	InitFastMath(cpu_info.bNEON);

	// Sets both FZ and DefaultNaN on ARM, flipping some ARM implementations into "RunFast" mode for VFP.
	// http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0274h/Babffifj.html
	// Do we need to do this on all threads?
	// Also, the FZ thing may actually be a little bit dangerous, I'm not sure how compliant the MIPS
	// CPU is with denormal handling. Needs testing. Default-NAN should be reasonably safe though.
	FPU_SetFastMode();

	bool skipLogo = false;
	setlocale( LC_ALL, "C" );
	std::string user_data_path = savegame_directory;
	pendingMessages.clear();
#ifdef IOS
	user_data_path += "/";
#endif

	// We want this to be FIRST.
#ifdef USING_QT_UI
	VFSRegister("", new AssetsAssetReader());
#elif defined(BLACKBERRY) || defined(IOS)
	// Packed assets are included in app
	VFSRegister("", new DirectoryAssetReader(external_directory));
#elif defined(__APPLE__) || (defined(__linux__) && !defined(ANDROID))
	VFSRegister("", new DirectoryAssetReader((File::GetExeDirectory() + "assets/").c_str()));
	VFSRegister("", new DirectoryAssetReader((File::GetExeDirectory()).c_str()));
#else
	VFSRegister("", new DirectoryAssetReader("assets/"));
#endif
	VFSRegister("", new DirectoryAssetReader(savegame_directory));

#if defined(MOBILE_DEVICE) || !defined(USING_QT_UI)
	host = new NativeHost();
#endif

#if defined(ANDROID)
	g_Config.internalDataDirectory = savegame_directory;
	// Maybe there should be an option to use internal memory instead, but I think
	// that for most people, using external memory (SDCard/USB Storage) makes the
	// most sense.
	g_Config.memCardDirectory = std::string(external_directory) + "/";
	g_Config.flash0Directory = std::string(external_directory) + "/flash0/";
#elif defined(BLACKBERRY) || defined(__SYMBIAN32__) || defined(MAEMO) || defined(IOS)
	g_Config.memCardDirectory = user_data_path;
	g_Config.flash0Directory = std::string(external_directory) + "/flash0/";
#elif !defined(_WIN32)
	char* config = getenv("XDG_CONFIG_HOME");
	if (!config) {
		config = getenv("HOME");
		strcat(config, "/.config");
	}
	g_Config.memCardDirectory = std::string(config) + "/ppsspp/";
	g_Config.flash0Directory = File::GetExeDirectory() + "/flash0/";
#endif

#ifndef _WIN32
	logger = new AndroidLogger();

	LogManager::Init();
	LogManager *logman = LogManager::GetInstance();

	g_Config.AddSearchPath(user_data_path);
	g_Config.AddSearchPath(g_Config.memCardDirectory + "PSP/SYSTEM/");
	g_Config.SetDefaultPath(g_Config.memCardDirectory + "PSP/SYSTEM/");
	g_Config.Load();
	g_Config.externalDirectory = external_directory;
#endif

#ifdef ANDROID
	// On Android, create a PSP directory tree in the external_directory,
	// to hopefully reduce confusion a bit.
	ILOG("Creating %s", (g_Config.memCardDirectory + "PSP").c_str());
	mkDir((g_Config.memCardDirectory + "PSP").c_str());
	mkDir((g_Config.memCardDirectory + "PSP/SAVEDATA").c_str());
	mkDir((g_Config.memCardDirectory + "PSP/GAME").c_str());
#endif

	const char *fileToLog = 0;
	const char *stateToLoad = 0;

	bool gfxLog = false;
	// Parse command line
	LogTypes::LOG_LEVELS logLevel = LogTypes::LINFO;
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'd':
				// Enable debug logging
				// Note that you must also change the max log level in Log.h.
				logLevel = LogTypes::LDEBUG;
				break;
			case 'g':
				gfxLog = true;
				break;
			case 'j':
				g_Config.bJit = true;
				g_Config.bSaveSettings = false;
				break;
			case 'i':
				g_Config.bJit = false;
				g_Config.bSaveSettings = false;
				break;
			case '-':
				if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log="))
					fileToLog = argv[i] + strlen("--log=");
				if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state="))
					stateToLoad = argv[i] + strlen("--state=");
#if !defined(MOBILE_DEVICE)
				if (!strncmp(argv[i], "--escape-exit", strlen("--escape-exit")))
					g_Config.bPauseExitsEmulator = true;
#endif
				break;
			}
		} else {
			if (boot_filename.empty()) {
				boot_filename = argv[i];
				skipLogo = true;

				FileInfo info;
				if (!getFileInfo(boot_filename.c_str(), &info) || info.exists == false) {
					fprintf(stderr, "File not found: %s\n", boot_filename.c_str());
					exit(1);
				}
			} else {
				fprintf(stderr, "Can only boot one file");
				exit(1);
			}
		}
	}

	if (fileToLog != NULL)
		LogManager::GetInstance()->ChangeFileLog(fileToLog);

#ifndef _WIN32
	if (g_Config.currentDirectory == "") {
#if defined(ANDROID)
		g_Config.currentDirectory = external_directory;
#elif defined(BLACKBERRY) || defined(__SYMBIAN32__) || defined(MAEMO) || defined(IOS) || defined(_WIN32)
		g_Config.currentDirectory = savegame_directory;
#else
		g_Config.currentDirectory = getenv("HOME");
#endif
	}

	for (int i = 0; i < LogTypes::NUMBER_OF_LOGS; i++)
	{
		LogTypes::LOG_TYPE type = (LogTypes::LOG_TYPE)i;
		logman->SetEnable(type, true);
		logman->SetLogLevel(type, gfxLog && i == LogTypes::G3D ? LogTypes::LDEBUG : logLevel);
#ifdef ANDROID
		logman->AddListener(type, logger);
#endif
	}
	// Special hack for G3D as it's very spammy. Need to make a flag for this.
	if (!gfxLog)
		logman->SetLogLevel(LogTypes::G3D, LogTypes::LERROR);
#endif
	// Allow the lang directory to be overridden for testing purposes (e.g. Android, where it's hard to 
	// test new languages without recompiling the entire app, which is a hassle).
	const std::string langOverridePath = g_Config.memCardDirectory + "PSP/SYSTEM/lang/";

	// If we run into the unlikely case that "lang" is actually a file, just use the built-in translations.
	if (!File::Exists(langOverridePath) || !File::IsDirectory(langOverridePath))
		i18nrepo.LoadIni(g_Config.sLanguageIni);
	else
		i18nrepo.LoadIni(g_Config.sLanguageIni, langOverridePath);

	I18NCategory *d = GetI18NCategory("DesktopUI");
	// Note to translators: do not translate this/add this to PPSSPP-lang's files.
	// It's intended to be custom for every user.
	// Only add it to your own personal copies of PPSSPP.
#ifdef _WIN32
	// TODO: Could allow a setting to specify a font file to load?
	// TODO: Make this a constant if we can sanely load the font on other systems?
	AddFontResourceEx(L"assets/Roboto-Condensed.ttf", FR_PRIVATE, NULL);
	g_Config.sFont = d->T("Font", "Roboto");
#endif

	if (!boot_filename.empty() && stateToLoad != NULL)
		SaveState::Load(stateToLoad);

	g_gameInfoCache.Init();

	screenManager = new ScreenManager();
	if (skipLogo) {
		screenManager->switchScreen(new EmuScreen(boot_filename));
	} else {
		screenManager->switchScreen(new LogoScreen());
	}

	std::string sysName = System_GetProperty(SYSPROP_NAME);
	isOuya = KeyMap::IsOuya(sysName);

#if !defined(MOBILE_DEVICE) && defined(USING_QT_UI)
	MainWindow* mainWindow = new MainWindow(0);
	mainWindow->show();
	host = new QtHost(mainWindow);
#endif
}
Exemplo n.º 4
0
void Application::detachView(Session* session)
{
    MainWindow* window = newMainWindow();
    window->createView(session);
    window->show();
}
Exemplo n.º 5
0
int Application::execute()
{
    switch (m_execType)
    {
        case kExecType_Normal:
        case kExecType_ArgFile:
        {
            Q_INIT_RESOURCE(Resource);
            QTranslator translator;
            translator.load(":/root/Resources/lang/linguist_ja.qm");
            installTranslator(&translator);

            MainWindow w;
            w.show();

            if (!m_inputFile.isEmpty())
            {
                w.fileOpen(m_inputFile);
            }

            return this->exec();
        }
        case kExecType_OutputAsm:
        {
            EditData editData;
            { // 入力ファイル読み込み
                Anm2DXml data(false);
                QFile file(m_inputFile);
                if (!file.open(QFile::ReadOnly))
                {
                    qDebug() << trUtf8("ファイルオープン失敗[") << m_inputFile << "]";
                    print_usage();
                    return 1;
                }
                QDomDocument xml;
                xml.setContent(&file);
                data.setFilePath(m_inputFile);
                if (!data.makeFromFile(xml, editData))
                {
                    qDebug() << trUtf8("ファイル読み込み失敗[") << m_inputFile << "]:" << data.getErrorString();
                    print_usage();
                    return 1;
                }
            }
            { // 出力ファイル書き込み
                Anm2DAsm data(false);
                if (!data.makeFromEditData(editData))
                {
                    if (data.getErrorNo() != Anm2DBase::kErrorNo_Cancel)
                    {
                        qDebug() << trUtf8("コンバート失敗[") << m_outputFile << "]:" << data.getErrorString();
                        print_usage();
                    }
                    return 1;
                }

                QFile file(m_outputFile);
                if (!file.open(QFile::WriteOnly))
                {
                    qDebug() << trUtf8("ファイル書き込み失敗[") << m_outputFile << "]:" << data.getErrorString();
                    print_usage();
                    return 1;
                }
                file.write(data.getData().toLatin1());

                QString incFileName = m_outputFile;
                incFileName.replace(QString(".asm"), QString(".inc"));
                Anm2DAsm dataInc(false);
                if (!dataInc.makeFromEditData2Inc(editData, incFileName))
                {
                    if (dataInc.getErrorNo() != Anm2DBase::kErrorNo_Cancel)
                    {
                        qDebug() << trUtf8("コンバート失敗[") << incFileName << "]:" << data.getErrorString();
                        print_usage();
                    }
                    return 1;
                }
                QFile fileInc(incFileName);
                if (!fileInc.open(QFile::WriteOnly))
                {
                    qDebug() << trUtf8("ファイル書き込み失敗[") << incFileName << "]:" << data.getErrorString();
                    return 1;
                }
                fileInc.write(dataInc.getData().toLatin1());
            }
        }
        break;
    }
    return 0;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    if (app.arguments().contains("--debug-output"))
    {
#if QT_VERSION < 0x050000
        qInstallMsgHandler(myMessageOutput);
#else
        qInstallMessageHandler(myMessageOutput);
#endif
    }
#ifdef Q_OS_WIN
    app.addLibraryPath(app.applicationDirPath() + "/plugins");
#endif

#if QT_VERSION < 0x050000
    // gone in Qt5, all source files _MUST_ be utf8-encoded
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif

    QCoreApplication::setOrganizationName("Cockatrice");
    QCoreApplication::setOrganizationDomain("cockatrice.de");
    QCoreApplication::setApplicationName("Cockatrice");

    if (translationPath.isEmpty()) {
#ifdef Q_OS_MAC
        translationPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined(Q_OS_WIN)
        translationPath = app.applicationDirPath() + "/translations";
#endif
    }

    rng = new RNG_SFMT;
    settingsCache = new SettingsCache;
    db = new CardDatabase;

    qtTranslator = new QTranslator;
    translator = new QTranslator;
    installNewTranslator();

    qsrand(QDateTime::currentDateTime().toTime_t());
    
#if QT_VERSION < 0x050000
    const QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
#else
    const QString dataDir = QStandardPaths::standardLocations(QStandardPaths::DataLocation).first();
#endif
    if (!db->getLoadSuccess())
        if (!db->loadCardDatabase(dataDir + "/cards.xml"))
            settingsCache->setCardDatabasePath(dataDir + "/cards.xml");
    if (settingsCache->getTokenDatabasePath().isEmpty())
        settingsCache->setTokenDatabasePath(dataDir + "/tokens.xml");
    if (!QDir(settingsCache->getDeckPath()).exists() || settingsCache->getDeckPath().isEmpty()) {
        QDir().mkpath(dataDir + "/decks");
        settingsCache->setDeckPath(dataDir + "/decks");
    }
    if (!QDir(settingsCache->getReplaysPath()).exists() || settingsCache->getReplaysPath().isEmpty()) {
        QDir().mkpath(dataDir + "/replays");
        settingsCache->setReplaysPath(dataDir + "/replays");
    }
    if (!QDir(settingsCache->getPicsPath()).exists() || settingsCache->getPicsPath().isEmpty()) {
        QDir().mkpath(dataDir + "/pics");
        settingsCache->setPicsPath(dataDir + "/pics");
    }
    if (!QDir().mkpath(settingsCache->getPicsPath() + "/CUSTOM"))
        qDebug() << "Could not create " + settingsCache->getPicsPath().toUtf8() + "/CUSTOM. Will fall back on default card images.";
    if (QDir().mkpath(dataDir + "/customsets"))
    {
        // if the dir exists (or has just been created)
        db->loadCustomCardDatabases(dataDir + "/customsets");
    } else {
        qDebug() << "Could not create " + dataDir + "/customsets folder.";
    }

    if(settingsCache->getSoundPath().isEmpty() || !QDir(settingsCache->getSoundPath()).exists())
    {
        QDir tmpDir;
        
#ifdef Q_OS_MAC
        tmpDir = app.applicationDirPath() + "/../Resources/sounds";
#elif defined(Q_OS_WIN)
         tmpDir = app.applicationDirPath() + "/sounds";
#else // linux
        tmpDir = app.applicationDirPath() + "/../share/cockatrice/sounds/";
#endif
        settingsCache->setSoundPath(tmpDir.canonicalPath());
    }

    if (!settingsValid() || db->getLoadStatus() != Ok) {
        qDebug("main(): invalid settings or load status");
        DlgSettings dlgSettings;
        dlgSettings.show();
        app.exec();
    }

    if (settingsValid()) {
        qDebug("main(): starting main program");
        soundEngine = new SoundEngine;
        qDebug("main(): SoundEngine constructor finished");

        MainWindow ui;
        qDebug("main(): MainWindow constructor finished");

        QIcon icon(":/resources/appicon.svg");
        ui.setWindowIcon(icon);
        
        settingsCache->setClientID(generateClientID());
        qDebug() << "ClientID In Cache: " << settingsCache->getClientID();

        ui.show();
        qDebug("main(): ui.show() finished");

        app.exec();
    }

    qDebug("Event loop finished, terminating...");
    delete db;
    delete settingsCache;
    delete rng;
    PingPixmapGenerator::clear();
    CountryPixmapGenerator::clear();
    UserLevelPixmapGenerator::clear();

    return 0;
}
Exemplo n.º 7
0
void WebInspectorPanel::changeCurrentPage()
{
    MainWindow *w = qobject_cast<MainWindow *>(parent());
    bool enable = w->currentTab()->page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled);
    toggle(enable);
}
Exemplo n.º 8
0
void NativeInit(int argc, const char *argv[], const char *savegame_directory, const char *external_directory, const char *installID)
{
	std::string config_filename;
	Common::EnableCrashingOnCrashes();
	isMessagePending = false;

	std::string user_data_path = savegame_directory;

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(user_data_path.c_str()));

	config_filename = user_data_path + "ppsspp.ini";

	g_Config.Load(config_filename.c_str());

	const char *fileToLog = 0;

	bool hideLog = true;
#ifdef _DEBUG
	hideLog = false;
#endif

	bool gfxLog = false;
	// Parse command line
	LogTypes::LOG_LEVELS logLevel = LogTypes::LINFO;
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'd':
				// Enable debug logging
				logLevel = LogTypes::LDEBUG;
				break;
			case 'g':
				gfxLog = true;
				break;
			case 'j':
				g_Config.bJit = true;
				g_Config.bSaveSettings = false;
				break;
			case 'i':
				g_Config.bJit = false;
				g_Config.bSaveSettings = false;
				break;
			case 'l':
				hideLog = false;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case '-':
				if (!strcmp(argv[i], "--log") && i < argc - 1)
					fileToLog = argv[++i];
				if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log="))
					fileToLog = argv[i] + strlen("--log=");
				if (!strcmp(argv[i], "--state") && i < argc - 1)
					stateToLoad = argv[++i];
				if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state="))
					stateToLoad = argv[i] + strlen("--state=");
				break;
			}
		}
		else if (fileToStart.isNull())
		{
			fileToStart = QString(argv[i]);
			if (!QFile::exists(fileToStart))
			{
				qCritical("File '%s' does not exist!", qPrintable(fileToStart));
				exit(1);
			}
		}
		else
		{
			qCritical("Can only boot one file. Ignoring file '%s'", qPrintable(fileToStart));
		}
	}

	if (g_Config.currentDirectory == "")
	{
		g_Config.currentDirectory = QDir::homePath().toStdString();
	}

	g_Config.memCardDirectory = QDir::homePath().toStdString()+"/.ppsspp/";
	g_Config.flashDirectory = g_Config.memCardDirectory+"/flash0/";

	LogManager::Init();
	if (fileToLog != NULL)
		LogManager::GetInstance()->ChangeFileLog(fileToLog);

	LogManager::GetInstance()->SetLogLevel(LogTypes::G3D, LogTypes::LERROR);

	g_gameInfoCache.Init();

#if !defined(USING_GLES2)
	// Start Desktop UI
	MainWindow* mainWindow = new MainWindow();
	mainWindow->show();
#endif
}
Exemplo n.º 9
0
void NativeInit(int argc, const char *argv[], const char *savegame_directory, const char *external_directory, const char *installID)
{
	Common::EnableCrashingOnCrashes();
	isMessagePending = false;

	std::string user_data_path = savegame_directory;
	std::string memcard_path = QDir::homePath().toStdString() + "/.ppsspp/";

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(user_data_path.c_str()));

	g_Config.AddSearchPath(user_data_path);
	g_Config.AddSearchPath(memcard_path + "PSP/SYSTEM/");
	g_Config.SetDefaultPath(g_Config.memCardDirectory + "PSP/SYSTEM/");
	g_Config.Load();

	const char *fileToLog = 0;

	// Parse command line
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
			case 'j':
				g_Config.bJit = true;
				g_Config.bSaveSettings = false;
				break;
			case 'i':
				g_Config.bJit = false;
				g_Config.bSaveSettings = false;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case '-':
				if (!strcmp(argv[i], "--log") && i < argc - 1)
					fileToLog = argv[++i];
				if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log="))
					fileToLog = argv[i] + strlen("--log=");
				if (!strcmp(argv[i], "--state") && i < argc - 1)
					stateToLoad = argv[++i];
				if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state="))
					stateToLoad = argv[i] + strlen("--state=");
				break;
			}
		}
		else if (fileToStart.isNull())
		{
			fileToStart = QString(argv[i]);
			if (!QFile::exists(fileToStart))
			{
				qCritical("File '%s' does not exist!", qPrintable(fileToStart));
				exit(1);
			}
		}
		else
		{
			qCritical("Can only boot one file. Ignoring file '%s'", qPrintable(fileToStart));
		}
	}

	if (g_Config.currentDirectory == "")
	{
		g_Config.currentDirectory = QDir::homePath().toStdString();
	}

	g_Config.memCardDirectory = QDir::homePath().toStdString() + "/.ppsspp/";

#if defined(Q_OS_LINUX) && !defined(ARM)
	std::string program_path = QCoreApplication::applicationDirPath().toStdString();
	if (File::Exists(program_path + "/flash0"))
		g_Config.flash0Directory = program_path + "/flash0/";
	else if (File::Exists(program_path + "/../flash0"))
		g_Config.flash0Directory = program_path + "/../flash0/";
	else
		g_Config.flash0Directory = g_Config.memCardDirectory + "/flash0/";
#else
	g_Config.flash0Directory = g_Config.memCardDirectory + "/flash0/";
#endif

	LogManager::Init();
	if (fileToLog != NULL)
		LogManager::GetInstance()->ChangeFileLog(fileToLog);

	g_gameInfoCache.Init();

#if defined(Q_OS_LINUX) && !defined(ARM)
	// Start Desktop UI
	MainWindow* mainWindow = new MainWindow();
	mainWindow->show();
#endif
}
Exemplo n.º 10
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    string filename = "";

    TLogLevel logLevel = logWARNING;

    try {
        po::options_description desc("Usage: glogg [options] [file]");
        desc.add_options()
            ("help,h", "print out program usage (this message)")
            ("version,v", "print glogg's version information")
            ("debug,d", "output more debug (include multiple times for more verbosity e.g. -dddd")
            ;
        po::options_description desc_hidden("Hidden options");
        // For -dd, -ddd...
        for ( string s = "dd"; s.length() <= 10; s.append("d") )
            desc_hidden.add_options()(s.c_str(), "debug");

        desc_hidden.add_options()
            ("input-file", po::value<string>(), "input file")
            ;

        po::options_description all_options("all options");
        all_options.add(desc).add(desc_hidden);

        po::positional_options_description positional;
        positional.add("input-file", 1);

        int command_line_style = (((po::command_line_style::unix_style ^
                po::command_line_style::allow_guessing) |
                po::command_line_style::allow_long_disguise) ^
                po::command_line_style::allow_sticky);

        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).
                options(all_options).
                positional(positional).
                style(command_line_style).run(),
                vm);
        po::notify(vm);

        if ( vm.count("help") ) {
            desc.print(cout);
            return 0;
        }

        if ( vm.count("version") ) {
            print_version();
            return 0;
        }

        if ( vm.count( "debug" ) ) {
            logLevel = logINFO;
        }

        for ( string s = "dd"; s.length() <= 10; s.append("d") )
            if ( vm.count( s ) )
                logLevel = (TLogLevel) (logWARNING + s.length());

        if ( vm.count("input-file") )
            filename = vm["input-file"].as<string>();
    }
    catch(exception& e) {
        cerr << "Option processing error: " << e.what() << endl;
        return 1;
    }
    catch(...) {
        cerr << "Exception of unknown type!\n";
    }

#if 0
    FILE* file = fopen("glogg.log", "w");
    Output2FILE::Stream() = file;
#endif

    FILELog::setReportingLevel( logLevel );

    // Register the configuration items
    GetPersistentInfo().migrateAndInit();
    GetPersistentInfo().registerPersistable(
            new SessionInfo, QString( "session" ) );
    GetPersistentInfo().registerPersistable(
            new Configuration, QString( "settings" ) );
    GetPersistentInfo().registerPersistable(
            new FilterSet, QString( "filterSet" ) );
    GetPersistentInfo().registerPersistable(
            new SavedSearches, QString( "savedSearches" ) );
    GetPersistentInfo().registerPersistable(
            new RecentFiles, QString( "recentFiles" ) );

    // FIXME: should be replaced by a two staged init of MainWindow
    GetPersistentInfo().retrieve( QString( "settings" ) );

    std::unique_ptr<Session> session( new Session() );
    MainWindow* mw = new MainWindow( std::move( session ) );

    LOG(logDEBUG) << "MainWindow created.";
    mw->show();
    mw->loadInitialFile( QString::fromStdString( filename ) );
    return app.exec();
}
Exemplo n.º 11
0
void
PadView::DisplayMenu(BPoint where, LaunchButton* button) const
{
	MainWindow* window = dynamic_cast<MainWindow*>(Window());
	if (window == NULL)
		return;

	LaunchButton* nearestButton = button;
	if (!nearestButton) {
		// find the nearest button
		for (int32 i = 0; (nearestButton = ButtonAt(i)); i++) {
			if (nearestButton->Frame().top > where.y)
				break;
		}
	}
	BPopUpMenu* menu = new BPopUpMenu(B_TRANSLATE("launch popup"), false, false);
	// add button
	BMessage* message = new BMessage(MSG_ADD_SLOT);
	message->AddPointer("be:source", (void*)nearestButton);
	BMenuItem* item = new BMenuItem(B_TRANSLATE("Add button here"), message);
	item->SetTarget(window);
	menu->AddItem(item);
	// button options
	if (button) {
		// clear button
		message = new BMessage(MSG_CLEAR_SLOT);
		message->AddPointer("be:source", (void*)button);
		item = new BMenuItem(B_TRANSLATE("Clear button"), message);
		item->SetTarget(window);
		menu->AddItem(item);
		// remove button
		message = new BMessage(MSG_REMOVE_SLOT);
		message->AddPointer("be:source", (void*)button);
		item = new BMenuItem(B_TRANSLATE("Remove button"), message);
		item->SetTarget(window);
		menu->AddItem(item);
		// set button description
		if (button->Ref()) {
			message = new BMessage(MSG_SET_DESCRIPTION);
			message->AddPointer("be:source", (void*)button);
			item = new BMenuItem(B_TRANSLATE("Set description"B_UTF8_ELLIPSIS),
				message);
			item->SetTarget(window);
			menu->AddItem(item);
		}
	}
	menu->AddSeparatorItem();
	// window settings
	BMenu* settingsM = new BMenu(B_TRANSLATE("Settings"));
	settingsM->SetFont(be_plain_font);

	const char* toggleLayoutLabel;
	if (fButtonLayout->Orientation() == B_HORIZONTAL)
		toggleLayoutLabel = B_TRANSLATE("Vertical layout");
	else
		toggleLayoutLabel = B_TRANSLATE("Horizontal layout");
	item = new BMenuItem(toggleLayoutLabel, new BMessage(MSG_TOGGLE_LAYOUT));
	item->SetTarget(this);
	settingsM->AddItem(item);

	BMenu* iconSizeM = new BMenu(B_TRANSLATE("Icon size"));
	for (uint32 i = 0; i < sizeof(kIconSizes) / sizeof(uint32); i++) {
		uint32 iconSize = kIconSizes[i];
		message = new BMessage(MSG_SET_ICON_SIZE);
		message->AddInt32("size", iconSize);
		BString label;
		label << iconSize << " x " << iconSize;
		item = new BMenuItem(label.String(), message);
		item->SetTarget(this);
		item->SetMarked(IconSize() == iconSize);
		iconSizeM->AddItem(item);
	}
	settingsM->AddItem(iconSizeM);

	item = new BMenuItem(B_TRANSLATE("Ignore double-click"),
		new BMessage(MSG_SET_IGNORE_DOUBLECLICK));
	item->SetTarget(this);
	item->SetMarked(IgnoreDoubleClick());
	settingsM->AddItem(item);

	uint32 what = window->Look() == B_BORDERED_WINDOW_LOOK ? MSG_SHOW_BORDER : MSG_HIDE_BORDER;
	item = new BMenuItem(B_TRANSLATE("Show window border"), new BMessage(what));
	item->SetTarget(window);
	item->SetMarked(what == MSG_HIDE_BORDER);
	settingsM->AddItem(item);

	item = new BMenuItem(B_TRANSLATE("Auto-raise"), new BMessage(MSG_TOGGLE_AUTORAISE));
	item->SetTarget(window);
	item->SetMarked(window->AutoRaise());
	settingsM->AddItem(item);

	item = new BMenuItem(B_TRANSLATE("Show on all workspaces"), new BMessage(MSG_SHOW_ON_ALL_WORKSPACES));
	item->SetTarget(window);
	item->SetMarked(window->ShowOnAllWorkspaces());
	settingsM->AddItem(item);

	menu->AddItem(settingsM);

	menu->AddSeparatorItem();

	// pad commands
	BMenu* padM = new BMenu(B_TRANSLATE("Pad"));
	padM->SetFont(be_plain_font);
	// new pad
	item = new BMenuItem(B_TRANSLATE("New"), new BMessage(MSG_ADD_WINDOW));
	item->SetTarget(be_app);
	padM->AddItem(item);
	// new pad
	item = new BMenuItem(B_TRANSLATE("Clone"), new BMessage(MSG_ADD_WINDOW));
	item->SetTarget(window);
	padM->AddItem(item);
	padM->AddSeparatorItem();
	// close
	item = new BMenuItem(B_TRANSLATE("Close"), new BMessage(B_QUIT_REQUESTED));
	item->SetTarget(window);
	padM->AddItem(item);
	menu->AddItem(padM);
	// app commands
	BMenu* appM = new BMenu(B_TRANSLATE_SYSTEM_NAME("LaunchBox"));
	appM->SetFont(be_plain_font);
	// quit
	item = new BMenuItem(B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED));
	item->SetTarget(be_app);
	appM->AddItem(item);
	menu->AddItem(appM);
	// finish popup
	menu->SetAsyncAutoDestruct(true);
	menu->SetFont(be_plain_font);
	where = ConvertToScreen(where);
	BRect mouseRect(where, where);
	mouseRect.InsetBy(-4.0, -4.0);
	menu->Go(where, true, false, mouseRect, true);
}
EditorPluginLoader::EditorPluginLoader(MainWindow& main_window)
	: m_main_window(main_window)
{
	m_global_state = nullptr;
	setWorldEditor(main_window.getWorldEditor());
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
  set_env_vars_if_needed();

  MainApplication app(argc, argv);

#if USING_QT_5
  QCommandLineParser parser;
  parser.setApplicationDescription("Video mapping editor");

  // --help option
  const QCommandLineOption helpOption = parser.addHelpOption();

  // --version option
  const QCommandLineOption versionOption = parser.addVersionOption();

  // --fullscreen option
  QCommandLineOption fullscreenOption(QStringList() << "F" << "fullscreen",
    "Display the output window and make it fullscreen.");
  parser.addOption(fullscreenOption);

  // --file option
  QCommandLineOption fileOption(QStringList() << "f" << "file", "Load project from <file>.", "file", "");
  parser.addOption(fileOption);

  // --reset-settings option
  QCommandLineOption resetSettingsOption(QStringList() << "R" << "reset-settings",
    "Reset MapMap settings, such as GUI properties.");
  parser.addOption(resetSettingsOption);

  // --osc-port option
  QCommandLineOption oscPortOption(QStringList() << "p" << "osc-port", "Use OSC port number <osc-port>.", "osc-port", "");
  parser.addOption(oscPortOption);

  // Positional argument: file
  parser.addPositionalArgument("file", "Load project from that file.");

  parser.process(app);
  if (parser.isSet(versionOption) || parser.isSet(helpOption))
  {
    return 0;
  }
  if (parser.isSet(resetSettingsOption))
  {
    Util::eraseSettings();
  }

#endif // USING_QT_5

  if (! QGLFormat::hasOpenGL())
  {
    qFatal("This system has no OpenGL support.");
    return 1;
  }

  // Create splash screen.
  QPixmap pixmap(":/mapmap-splash");
  QSplashScreen splash(pixmap);

  // Show splash.
  splash.show();

  splash.showMessage("  " + QObject::tr("Initiating program..."),
                     Qt::AlignLeft | Qt::AlignTop, MM::WHITE);

  bool FORCE_FRENCH_LANG = false;
  // set_language_to_french(app);

  // Let splash for at least one second.
  I::sleep(1);

  // Create window.
  MainWindow* win = MainWindow::instance();

  QFontDatabase db;
  Q_ASSERT( QFontDatabase::addApplicationFont(":/base-font") != -1);
  app.setFont(QFont(":/base-font", 10, QFont::Bold));

  // Load stylesheet.
  QFile stylesheet(":/stylesheet");
  stylesheet.open(QFile::ReadOnly);
  app.setStyleSheet(QLatin1String(stylesheet.readAll()));

  //win.setLocale(QLocale("fr"));

#if USING_QT_5
  // read positional argument:
  const QStringList args = parser.positionalArguments();
  QString projectFileValue = QString();

  // there are two ways to specify the project file name.
  // The 2nd overrides the first:

  // read the file option value: (overrides the positional argument)
  projectFileValue = parser.value("file");
  // read the first positional argument:
  if (! args.isEmpty())
  {
    projectFileValue = args.first();
  }

  // finally, load the project file.
  if (projectFileValue != "")
  {
    win->loadFile(projectFileValue);
  }

  QString oscPortNumberValue = parser.value("osc-port");
  if (oscPortNumberValue != "")
  {
    win->setOscPort(oscPortNumberValue);
  }
#endif

  // Terminate splash.
  splash.showMessage("  " + QObject::tr("Done."),
                     Qt::AlignLeft | Qt::AlignTop, MM::WHITE);
  splash.finish(win);
  splash.raise();

  // Launch program.
  win->show();

#if USING_QT_5
  if (parser.isSet(fullscreenOption))
  {
    qDebug() << "TODO: Running in fullscreen mode";
    win->startFullScreen();
  }
#endif

  // Start app.
  int result = app.exec();

  delete win;
  return result;
}
Exemplo n.º 14
0
	foreach(QWidget* widget, topLevelWidgets())
	{
		MainWindow* mainWindow = qobject_cast<MainWindow*>(widget);
		if (mainWindow)
			mainWindow->saveSettings();
	}
int main(int argc, char **argv)
{
	int i;
	bool no_filenames = true;
	QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true"));
	QApplication *application = new QApplication(argc, argv);
	QStringList files;
	QStringList importedFiles;
	QStringList arguments = QCoreApplication::arguments();

	bool dedicated_console = arguments.length() > 1 &&
				 (arguments.at(1) == QString("--win32console"));
	subsurface_console_init(dedicated_console);

	const char *default_directory = system_default_directory();
	const char *default_filename = system_default_filename();
	subsurface_mkdir(default_directory);

	for (i = 1; i < arguments.length(); i++) {
		QString a = arguments.at(i);
		if (a.isEmpty())
			continue;
		if (a.at(0) == '-') {
			parse_argument(a.toLocal8Bit().data());
			continue;
		}
		if (imported) {
			importedFiles.push_back(a);
		} else {
			no_filenames = false;
			files.push_back(a);
		}
	}
#if !LIBGIT2_VER_MAJOR && LIBGIT2_VER_MINOR < 22
	git_threads_init();
#else
	git_libgit2_init();
#endif
	setup_system_prefs();
	copy_prefs(&default_prefs, &prefs);
	fill_profile_color();
	parse_xml_init();
	taglist_init_global();
	init_ui();
	if (no_filenames) {
		if (prefs.default_file_behavior == LOCAL_DEFAULT_FILE) {
			QString defaultFile(prefs.default_filename);
			if (!defaultFile.isEmpty())
				files.push_back(QString(prefs.default_filename));
		} else if (prefs.default_file_behavior == CLOUD_DEFAULT_FILE) {
			QString cloudURL;
			if (getCloudURL(cloudURL) == 0)
				files.push_back(cloudURL);
		}
	}
	MainWindow *m = MainWindow::instance();
	m->setLoadedWithFiles(!files.isEmpty() || !importedFiles.isEmpty());
	m->loadFiles(files);
	m->importFiles(importedFiles);
	// in case something has gone wrong make sure we show the error message
	m->showError();

	if (verbose > 0)
		print_files();
	if (!quit)
		run_ui();
	exit_ui();
	taglist_free(g_tag_list);
	parse_xml_exit();
	free((void *)default_directory);
	free((void *)default_filename);
	subsurface_console_exit();
	free_prefs();
	return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
Exemplo n.º 17
0
int main(int argc, char* argv[])
{
    qputenv("QT_STYLE_OVERRIDE", "plastique");

    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;
}
Exemplo n.º 18
0
int main( int argc, char * argv[] )
{
	int result=0;

#ifdef Q_OS_WIN
	hMutex = CreateMutex( NULL, true, L"FreezerSingleProcessMutex");
	if (hMutex == NULL) {
		LOG_5( "Error: Couldn't create mutex, exiting" );
		return false;
	}
	if( GetLastError() == ERROR_ALREADY_EXISTS ) {
		LOG_5( "Error: Another process owns the mutex, exiting" );
		QList<int> pids;
		if( pidsByName( "freezer.exe", &pids ) ) {
			int otherProcessId = pids[0];
			if( otherProcessId == processID() ) {
				if( pids.size() < 2 )
					return false;
				otherProcessId = pids[1];
			}
			LOG_5( "Trying to find window with process pid of " + QString::number( otherProcessId ) );
			EnumWindows( AFEnumWindowsProc, LPARAM(otherProcessId) );
		}
		return false;
	}

	QLibrary excdll( "exchndl.dll" );
	if( !excdll.load() ) {
		qWarning( excdll.errorString().toLatin1().constData() );
	}
	disableWindowsErrorReporting( "assburner.exe" );

#endif

    signal(SIGSEGV, oops_handler);
    signal(SIGABRT, oops_handler);
	QApplication a(argc, argv);

    if( !initConfig( "freezer.ini" ) ) {
#ifndef Q_OS_WIN
        // Fallback if the config file does not exist in the current folder
        if( !initConfig( "/etc/ab/freezer.ini" ) )
#endif
        return -1;
    }

#ifdef Q_OS_WIN
	QString cp = "h:/public/" + getUserName() + "/Blur";
	if( !QDir( cp ).exists() )
		cp = "C:/Documents and Settings/" + getUserName();
	initUserConfig( cp + "/freezer.ini" );
#else
	initUserConfig( QDir::homePath() + "/.freezer" );
#endif

    initStone( argc, argv );
    classes_loader();
    initStoneGui();
	{
		JobList showJobs;
		bool showTime = false;
        QString currentView;
        QStringList loadViewFiles;

		for( int i = 1; i<argc; i++ ){
			QString arg( argv[i] );
			if( arg == "-h" || arg == "--help" )
			{
				LOG_1( QString("Freezer v") + VERSION );
				LOG_1( "Options:" );
				LOG_1( "-current-render" );
				LOG_1( "\tShow the current job that is rendering on this machine\n" );
				LOG_1( "-show-time" );
				LOG_1( "\tOutputs summary of time executed for all sql statement at program close\n" );
				LOG_1( "-user USER" );
				LOG_1( "\tSet the logged in user to USER: Requires Admin Privs" );
				LOG_1( "-current-view VIEWNAME" );
				LOG_1( "\tMake VIEWNAME the active view, once they are all loaded" );
				LOG_1( "-load-view FILE" );
				LOG_1( "\tRead a saved view config from FILE" );
				LOG_1( stoneOptionsHelp() );
				return 0;
			}
			else if( arg.endsWith("-show-time") )
				showTime = true;
			else if( arg.endsWith( "-current-render" ) ) {
				showJobs = Host::currentHost().activeAssignments().jobs();
			}
			else if( arg.endsWith("-user") && (i+1 < argc) ) {
				QString impersonate( argv[++i] );
				if( User::hasPerms( "User", true ) ) // If you can edit users, you can login as anyone
					User::setCurrentUser( impersonate );
			}
            else if( arg.endsWith("-current-view") && (i+1 < argc) ) {
				currentView = QString( argv[++i] );
            }
            else if( arg.endsWith("-load-view") && (i+1 < argc) ) {
                loadViewFiles << QString(argv[++i]);
            }
		}

		// Share the database across threads, each with their own connection
		FreezerCore::setDatabaseForThread( classesDb(), Connection::createFromIni( config(), "Database" ) );
		
		{
            loadPythonPlugins();
			MainWindow m;
			IniConfig & cfg = userConfig();
			cfg.pushSection( "MainWindow" );
			QStringList fg = cfg.readString( "FrameGeometry", "" ).split(',');
			cfg.popSection();
			if( fg.size()==4 ) {
				m.resize( QSize( fg[2].toInt(), fg[3].toInt() ) );
				m.move( QPoint( fg[0].toInt(), fg[1].toInt() ) );
			}
			if( showJobs.size() )
				m.jobPage()->setJobList( showJobs );
            foreach( QString viewFile, loadViewFiles )
                m.loadViewFromFile( viewFile );
            if( !currentView.isEmpty() )
                m.setCurrentView( currentView );
			m.show();
			result = a.exec();
			if( showTime ){
				Database * tm = Database::current();
				LOG_5( 			"                  Sql Time Elapsed" );
				LOG_5(			"|   Select  |   Update  |  Insert  |  Delete  |  Total  |" );
				LOG_5( 			"-----------------------------------------------" );
				LOG_5( QString(	"|     %1    |     %2    |    %3    |    %4    |    %5   |\n")
					.arg( tm->elapsedSqlTime( Table::SqlSelect ) )
					.arg( tm->elapsedSqlTime( Table::SqlUpdate ) )
					.arg( tm->elapsedSqlTime( Table::SqlInsert ) )
					.arg( tm->elapsedSqlTime( Table::SqlDelete ) )
					.arg( tm->elapsedSqlTime() )
				);
				LOG_5( 			"                  Index Time Elapsed" );
				LOG_5(			"|   Added  |   Updated  |  Incoming  |  Deleted  |  Search  |  Total  |" );
				LOG_5( 			"-----------------------------------------------" );
				LOG_5( QString(	"|     %1     |     %2    |    %3    |    %4   |    %5    |   %6    |\n")
					.arg( tm->elapsedIndexTime( Table::IndexAdded ) )
					.arg( tm->elapsedIndexTime( Table::IndexUpdated ) )
					.arg( tm->elapsedIndexTime( Table::IndexIncoming ) )
					.arg( tm->elapsedIndexTime( Table::IndexRemoved ) )
					.arg( tm->elapsedIndexTime( Table::IndexSearch ) )
					.arg( tm->elapsedIndexTime() )
				);
				tm->printStats();
			}
		}
	}
	shutdown();
#ifdef Q_OS_WIN
	CloseHandle( hMutex );
#endif
	return result;
}
Exemplo n.º 19
0
//TODO: wrap this into the MainWindow class... it's weird that it's
//referencing a bunch of MainWindow members but not part of the class
//yet getting passed an app.... yeah.... wtf.
static void gl_draw_grid(App *app, float x0, float x1, float y0, float y1, float win_width, float win_height)
{
    float grid_size = app->get_grid_size();
    float border_count = 5.0f;

    MainWindow *win = app->get_main_window();
    assert(win);

    x0 = (float)((int)(x0 / grid_size)) * grid_size - (border_count * grid_size);
    x1 = (float)((int)(x1 / grid_size)) * grid_size + (border_count * grid_size);

    y0 = (float)((int)(y0 / grid_size)) * grid_size - (border_count * grid_size);
    y1 = (float)((int)(y1 / grid_size)) * grid_size + (border_count * grid_size);

    int x_count = (int)((x1 - x0) / grid_size);
    int y_count = (int)((y1 - y0) / grid_size);

    float density = (x_count) / (win_width);

    float clear_col[4];
    win->get_clear_color(clear_col);

    //fade lines out when they get too dense
    float max_density = 0.15f;
    float min_density = 0.05f;

    float lerp_val = Math::clamp(1.0f - (density - min_density) / (max_density - min_density), 0.0f, 1.0f);
    float line_color[3];
    line_color[0] = Math::lerp(clear_col[0], 0.8f, lerp_val);
    line_color[1] = Math::lerp(clear_col[1], 0.8f, lerp_val);
    line_color[2] = Math::lerp(clear_col[2], 1.0f, lerp_val);


    //TODO: as we zoom in, thicken or darken the main lines and render a new set @ 0.1, 0.2... etc.
    float line_width = 1.0f;//Math::lerp(1.0f, 2.0f, lerp_val);

    if(density > max_density)
    {
        return;
    }

    //ok, draw!
    glLineWidth(line_width);
    glColor3f(line_color[0], line_color[1], line_color[2]);
    glBegin(GL_LINES);

    int i;
    for(i = 0; i < x_count; i++)
    {
        float line_x = x0 + (float)i * grid_size;
        glVertex3f(line_x, y0, 0.0f);
        glVertex3f(line_x, y1, 0.0f);
    }

    for(i = 0; i < y_count; i++)
    {
        float line_y = y0 + (float)i * grid_size;
        glVertex3f(x0, line_y, 0.0f);
        glVertex3f(x1, line_y, 0.0f);
    }

    glEnd();
}
Exemplo n.º 20
0
void CWizUserInfoWidget::on_action_logout_triggered()
{
    MainWindow* window = dynamic_cast<MainWindow*>(m_app.mainWindow());
    window->on_actionLogout_triggered();
}
Exemplo n.º 21
0
void Application::createWindow(Profile::Ptr profile, const QString& directory)
{
    MainWindow* window = newMainWindow();
    window->createSession(profile, directory);
    window->show();
}
Exemplo n.º 22
0
int 
main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    //this is the path within the current directory where GC will look for
    //files to allow USB stick support
    QString localLibraryPath="Library/GoldenCheetah";

    //this is the path that used to be used for all platforms
    //now different platforms will use their own path
    //this path is checked first to make things easier for long-time users
    QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah";

    //these are the new platform-dependent library paths
#if defined(Q_OS_MACX)
    QString libraryPath="Library/GoldenCheetah";
#elif defined(Q_OS_WIN)
    QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "GoldenCheetah";
#else
    // Q_OS_LINUX et al
    QString libraryPath=".goldencheetah";
#endif

    //First check to see if the Library folder exists where the executable is (for USB sticks)
    QDir home = QDir();
    //if it does, create an ini file for settings and cd into the library
    if(home.exists(localLibraryPath))
    {
         home.cd(localLibraryPath);
    }
    //if it does not exist, let QSettings handle storing settings
    //also cd to the home directory and look for libraries
    else
    {
        home = QDir::home();
        //check if this users previously stored files in the old library path
        //if they did, use the existing library
        if (home.exists(oldLibraryPath))
        {
            home.cd(oldLibraryPath);
        }
        //otherwise use the new library path
        else
        {
            //first create the path if it does not exist
            if (!home.exists(libraryPath))
            {
                if (!home.mkpath(libraryPath))
                {
                    qDebug()<<"Failed to create library path\n";
                    assert(false);
                }
            }
            home.cd(libraryPath);
        }
    }
    boost::shared_ptr<QSettings> settings;
    settings = GetApplicationSettings();
    QVariant lastOpened = settings->value(GC_SETTINGS_LAST);
    QVariant unit = settings->value(GC_UNIT);
    double crankLength = settings->value(GC_CRANKLENGTH).toDouble();
    if(crankLength<=0) {
       settings->setValue(GC_CRANKLENGTH,172.5);
    }

    bool anyOpened = false;
    if (lastOpened != QVariant()) {
        QStringList list = lastOpened.toStringList();
        QStringListIterator i(list);
        while (i.hasNext()) {
            QString cyclist = i.next();
            if (home.cd(cyclist)) {
                // used by WkoRideFileReader to store notes
                WKO_HOMEDIR = home.absolutePath();
                MainWindow *main = new MainWindow(home);
                main->show();
                home.cdUp();
                anyOpened = true;
            }
        }
    }
    if (!anyOpened) {
        ChooseCyclistDialog d(home, true);
        d.setModal(true);
        if (d.exec() != QDialog::Accepted)
            return 0;
        home.cd(d.choice());
        if (!home.exists())
            assert(false);
        // used by WkoRideFileReader to store notes
        WKO_HOMEDIR = home.absolutePath();
        MainWindow *main = new MainWindow(home);
        main->show();
    }
    return app.exec();
}
Exemplo n.º 23
0
int Application::newInstance()
{
    static bool firstInstance = true;

    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    // handle session management
    if ((args->count() != 0) || !firstInstance || !isSessionRestored()) {
        // check for arguments to print help or other information to the
        // terminal, quit if such an argument was found
        if (processHelpArgs(args))
            return 0;

        bool openpty = is_use_openpty;


        // create a new window or use an existing one
        MainWindow* window = processWindowArgs(args);

        if (args->isSet("tabs-from-file")) {
            // create new session(s) as described in file
            processTabsFromFileArgs(args, window);
        } else {
            // select profile to use
            Profile::Ptr baseProfile = processProfileSelectArgs(args);

            // process various command-line options which cause a property of the
            // selected profile to be changed
            Profile::Ptr newProfile = processProfileChangeArgs(args, baseProfile);

            // create new session
            Session* session = window->createSession(newProfile, QString(), openpty);

            if (!args->isSet("close")) {
                session->setAutoClose(false);
            }
        }

        // if the background-mode argument is supplied, start the background
        // session ( or bring to the front if it already exists )
        if (args->isSet("background-mode")) {
            startBackgroundMode(window);
        } else {
            // Qt constrains top-level windows which have not been manually
            // resized (via QWidget::resize()) to a maximum of 2/3rds of the
            //  screen size.
            //
            // This means that the terminal display might not get the width/
            // height it asks for.  To work around this, the widget must be
            // manually resized to its sizeHint().
            //
            // This problem only affects the first time the application is run.
            // run. After that KMainWindow will have manually resized the
            // window to its saved size at this point (so the Qt::WA_Resized
            // attribute will be set)
            if (!window->testAttribute(Qt::WA_Resized))
                window->resize(window->sizeHint());

            window->show();
        }
    }

    firstInstance = false;
    args->clear();
    return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
    /*
     * On X11, Tiled uses the 'raster' graphics system by default, because the
     * X11 native graphics system has performance problems with drawing the
     * tile grid.
     */
#ifdef Q_WS_X11
    QApplication::setGraphicsSystem(QLatin1String("raster"));
#endif

    TiledApplication a(argc, argv);

    a.setOrganizationDomain(QLatin1String("mapeditor.org"));
    a.setApplicationName(QLatin1String("Tiled"));
#ifdef BUILD_INFO_VERSION
    a.setApplicationVersion(QLatin1String(AS_STRING(BUILD_INFO_VERSION)));
#else
    a.setApplicationVersion(QLatin1String("0.9.1 + Paul's mods"));
#endif

#ifdef Q_OS_MAC
    a.setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

#if QT_VERSION >= 0x050100
    // Enable support for highres images (added in Qt 5.1, but off by default)
    a.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

#ifndef Q_OS_WIN
    QString baseName = QApplication::style()->objectName();
    if (baseName == QLatin1String("windows")) {
        // Avoid Windows 95 style at all cost
        if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
            baseName = QLatin1String("fusion"); // Qt5
        } else { // Qt4
            // e.g. if we are running on a KDE4 desktop
            QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
            if (desktopEnvironment == "kde")
                baseName = QLatin1String("plastique");
            else
                baseName = QLatin1String("cleanlooks");
        }
        a.setStyle(QStyleFactory::create(baseName));
    }
#endif

    LanguageManager *languageManager = LanguageManager::instance();
    languageManager->installTranslators();

    CommandLineHandler commandLine;

    if (!commandLine.parse(QCoreApplication::arguments()))
        return 0;
    if (commandLine.quit)
        return 0;
    if (commandLine.disableOpenGL)
        Preferences::instance()->setUseOpenGL(false);

    PluginManager::instance()->loadPlugins();

    MainWindow w;
    w.show();

    QObject::connect(&a, SIGNAL(fileOpenRequest(QString)),
                     &w, SLOT(openFile(QString)));

    if (!commandLine.filesToOpen().isEmpty()) {
        foreach (const QString &fileName, commandLine.filesToOpen())
            w.openFile(fileName);
    } else {
Exemplo n.º 25
0
int main(int argc, char *argv[])
{

#if defined(WIN32)
    // We create a console. This is inherited by console processes created by the localhost broker. 
    // It is useful because new processes can receive ctrl+brk signals and shutdown cleanly.
    // This console is not actually needed for printing so we hide it.  In principle we could 
    // redirect the output of all processes to this console, in practice this would be end up 
    // soon in a big mess.
   AllocConsole();
   HWND hwnd = GetConsoleWindow();
   HWND hide = FindWindowA("ConsoleWindowClass",NULL);
   ShowWindow(hide, 0);
#endif
    QApplication a(argc, argv);

    // Setup resource finder

    yarp::os::ResourceFinder rf;
    rf.setVerbose(false);
    rf.setDefaultContext("yarpmanager");
    rf.setDefaultConfigFile(DEF_CONFIG_FILE);
    rf.configure(argc, argv);

    yarp::os::Network yarp;
    yarp.setVerbosity(-1);

    yarp::os::Property config;
    config.fromString(rf.toString());

    if(config.check("help")){
        qDebug("%s",HELP_MESSAGE);
        return 0;
    }

    /**
    *  preparing default options
    */

    std::string inifile=rf.findFile("from").c_str();
    std::string inipath="";
    size_t lastSlash=inifile.rfind("/");
    if (lastSlash!=std::string::npos){
        inipath=inifile.substr(0, lastSlash+1);
    }else{
        lastSlash=inifile.rfind("\\");
        if (lastSlash!=std::string::npos){
            inipath=inifile.substr(0, lastSlash+1);
        }
    }

    if(!config.check("ymanagerini_dir")){
        config.put("ymanagerini_dir", inipath.c_str());
    }

    yarp::os::Bottle appPaths;
    if(!config.check("apppath")){
        appPaths= rf.findPaths("applications");

        yarp::os::ResourceFinderOptions findRobotScripts;
        findRobotScripts.searchLocations=yarp::os::ResourceFinderOptions::Robot;
        yarp::os::Bottle appPaths2=rf.findPaths("scripts", findRobotScripts);
//        yarp::os::Bottle appPaths2=rf.findPaths("scripts");
//        std::cout << "app path : " << appPaths.toString()<< std::endl;
        QString appPathsStr="";
        for (int ind=0; ind < appPaths.size(); ++ind){
            appPathsStr += (appPaths.get(ind).asString() + ";").c_str();
        }
        for (int ind=0; ind < appPaths2.size(); ++ind){
            appPathsStr += (appPaths2.get(ind).asString() + ";").c_str();
        }
        config.put("apppath", appPathsStr.toLatin1().data());
    }

    if(!config.check("modpath")){
       appPaths=rf.findPaths("modules");
       //std::cout << "mod path : " << appPaths.toString()<< std::endl;
       QString modPathsStr="";
       for (int ind=0; ind < appPaths.size(); ++ind){
           modPathsStr += (appPaths.get(ind).asString() + ";").c_str();
       }
       config.put("modpath", modPathsStr.toLatin1().data());
    }

    if(!config.check("respath")){
       appPaths=rf.findPaths("resources");
       //std::cout << "res path : " << appPaths.toString()<< std::endl;
       QString resPathsStr="";
       for (int ind=0; ind < appPaths.size(); ++ind){
           resPathsStr += (appPaths.get(ind).asString() + ";").c_str();
       }
       config.put("respath", resPathsStr.toLatin1().data());
    }

    if(!config.check("templpath")){
       appPaths=rf.findPaths("templates/applications");
      // std::cout << "templ path : " << appPaths.toString()<< std::endl;
       QString templPathsStr="";
       for (int ind=0; ind < appPaths.size(); ++ind){
            templPathsStr += (appPaths.get(ind).asString() + ";").c_str();
       }
       config.put("templpath", templPathsStr.toLatin1().data());

    }

    if(!config.check("load_subfolders")){
        config.put("load_subfolders", "no");
    }

    if(!config.check("watchdog")){
        config.put("watchdog", "no");
    }

    if(!config.check("module_failure")){
        config.put("module_failure", "prompt");
    }

    if(!config.check("connection_failure")){
        config.put("connection_failure", "prompt");
    }

    if(!config.check("auto_connect")){
        config.put("auto_connect", "no");
    }

    if(!config.check("auto_dependency")){
        config.put("auto_dependency", "no");
    }

#if defined(WIN32)
    //setup signal handler for windows
//    ACE_OS::signal(SIGINT, (ACE_SignalHandler) onSignal);
//    ACE_OS::signal(SIGBREAK, (ACE_SignalHandler) onSignal);
//    ACE_OS::signal(SIGTERM, (ACE_SignalHandler) onSignal);

#else
    // Set up the structure to specify the new action.
//     struct sigaction new_action, old_action;
//     new_action.sa_handler = onSignal;
//     sigemptyset (&new_action.sa_mask);
//     new_action.sa_flags = 0;
//     sigaction (SIGINT, NULL, &old_action);
//     if (old_action.sa_handler != SIG_IGN)
//         sigaction (SIGINT, &new_action, NULL);
//     sigaction (SIGHUP, NULL, &old_action);
//     if (old_action.sa_handler != SIG_IGN)
//         sigaction (SIGHUP, &new_action, NULL);
//     sigaction (SIGTERM, NULL, &old_action);
//     if (old_action.sa_handler != SIG_IGN)
//         sigaction (SIGTERM, &new_action, NULL);
#endif

    MainWindow w;
    w.init(config);
    w.show();

    return a.exec();
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);

#ifdef __WINDOWS__
	// Start up Winsock2
	{
		WSADATA wsaData;
		WSAStartup(MAKEWORD(2,2),&wsaData);
	}
#endif

	{
		QFile qss(":css/stylesheet.css");
		qss.open(QFile::ReadOnly);
		QString style(qss.readAll());
		a.setStyleSheet(style);
	}

#ifdef __APPLE__
	// If service isn't installed, download and install it
	if (!QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
		// InstallDialog is an alternative main window. It will re-launch the app
		// when done.
		InstallDialog id;
		id.setStyleSheet(a.styleSheet());
		id.show();
		return a.exec();
	}

	{
		// Put QSettings here because this is one of the writable directories allowed
		// in Apple's app store sandbox specs. We might end up in app store someday.
		QString zt1AppSupport(QDir::homePath() + "/Library/Application Support/ZeroTier/One");
		QDir::root().mkpath(zt1AppSupport);
		settings = new QSettings(zt1AppSupport + "/ui.ini",QSettings::IniFormat);
	}
#else // on non-Apple boxen put it in the standard place using the default format
	settings = new QSettings("ZeroTier Networks","ZeroTier One");
#endif

	if (!settings->value("acceptedLicenseV1",false).toBool()) {
		LicenseDialog ld;
		ld.setStyleSheet(a.styleSheet());
		ld.exec();
	}

#if defined(__WINDOWS__) && !defined(DISABLE_WINDOWS_SERVICE_MANAGEMENT)
	{
		bool winSvcInstalled = false;
		while (!startWindowsService()) {
			if (winSvcInstalled) {
				// Service was installed and subsequently failed to start again, so
				// something is wrong!
				QMessageBox::critical((QWidget *)0,"Service Not Available","Unable to locate or start ZeroTier One service. There may be a problem with the installation. Try installing from the .msi file again or e-mail [email protected] if you cannot install. (Error: service failed to start)",QMessageBox::Ok);
				return 1;
			}

#ifdef _WIN64
			BOOL is64Bit = TRUE;
#else
			BOOL is64Bit = FALSE;
			IsWow64Process(GetCurrentProcess(),&is64Bit);
#endif
			std::string exe(ZeroTier::ZT_DEFAULTS.defaultHomePath + "\\zerotier-one_");
			exe.append((is64Bit == TRUE) ? "x64.exe" : "x86.exe");

			if (QFile::exists(exe.c_str())) {
				STARTUPINFOA si;
				PROCESS_INFORMATION pi;
				memset(&si,0,sizeof(si));
				memset(&pi,0,sizeof(pi));
				if (CreateProcessA(NULL,const_cast <LPSTR>((exe + " -I").c_str()),NULL,NULL,FALSE,CREATE_NO_WINDOW|CREATE_NEW_PROCESS_GROUP,NULL,NULL,&si,&pi)) {
					WaitForSingleObject(pi.hProcess,INFINITE);
					CloseHandle(pi.hProcess);
					CloseHandle(pi.hThread);
					winSvcInstalled = true;
				}
			}

			if (!winSvcInstalled) {
				// Service failed to install -- installation problem like missing .exe
				QMessageBox::critical((QWidget *)0,"Service Not Available","Unable to locate or start ZeroTier One service. There may be a problem with the installation. Try installing from the .msi file again or e-mail [email protected] if you cannot install. (Error: service not installed)",QMessageBox::Ok);
				return 1;
			}
		}
	}
#endif

	MainWindow w;
	w.show();
	return a.exec();
}
Exemplo n.º 27
0
int main(int argc, char* argv[])
{
	QApplication app(argc, argv);
	app.setOrganizationName("Graphem");
	app.setApplicationName("Graphem");

	QCA::Initializer crypto_init;
	InputWidget *input = new InputWidget();

	WindowMode mode = CONFIG;
	int tries = 0; //ignored if mode != ASK

	for(int i = 1; i < argc; i++) {
		if(argv[i] == QString("--help")) {
			printHelp(argv[0]);
			return 0;
		} else if(argv[i] == QString("--ask")) {
			mode = ASK;
		} else if(argv[i] == QString("--lock")) {
			mode = LOCK;
		} else if(argv[i] == QString("--tries")) {
			if(i+1 >= argc)
				break; //parameter not found

			tries = QString(argv[i+1]).toInt();
			i++;
		} else if(argv[i] == QString("-v") or argv[i] == QString("--verbose")) {
			input->auth()->setVerbose(true);

		}

#ifndef NO_DEBUG
		else if(argv[i] == QString("--print-data")) {
			QObject::connect(input, SIGNAL(dataReady()),
				input, SLOT(printData()));
		} else if(argv[i] == QString("--print-pattern")) {
			input->auth()->setPrintPattern(true);
		}
#endif

		else {
			std::cerr << "Unknown command line option '" << argv[i] << "'\n";
			printHelp(argv[0]);
			return 1;
		}
	}

	if(mode == CONFIG) { //show main window
		MainWindow *main = new MainWindow(input);
		//main->setWindowIcon(QIcon("icon.png"));
		main->setWindowTitle(GRAPHEM_VERSION);
		main->show();
	} else {
		if(!input->hashLoaded()) {
			std::cerr << "Couldn't load key pattern! Please start Graphem without any arguments to create one.\n";
			return 1;
		}

		QObject::connect(input->auth(), SIGNAL(passed()),
			input, SLOT(quit()));

		//input->setWindowIcon(QIcon("icon.png"));

		if(mode == ASK) {
			input->setWindowTitle(QObject::tr("%1 - Press ESC to cancel").arg(GRAPHEM_VERSION));
			new QShortcut(QKeySequence("Esc"), input, SLOT(exit()));
			input->auth()->setTries(tries);
			input->showMaximized();
		} else { //mode == LOCK
			input->setWindowTitle(GRAPHEM_VERSION);
			input->setGrab(true);

			//for full screen, we strip WM decorations and resize the window manually
			input->setWindowFlags(Qt::X11BypassWindowManagerHint);
			input->setVisible(true);
			QDesktopWidget dw;
			input->setGeometry(dw.screenGeometry());
		}
	}

	return app.exec();
}
Exemplo n.º 28
0
void File_v2::loadChart(QXmlStreamReader *stream)
{
    MainWindow *mw = mMainWindow;
    CrochetTab *tab = 0;
    QString tabName = "", defaultSt = "";

    while(!(stream->isEndElement() && stream->name() == "chart")) {
        stream->readNext();
        QString tag = stream->name().toString();

        if(tag == "name") {
            tabName = stream->readElementText();

        } else if(tag == "style") {
            int style = stream->readElementText().toInt();
            tab = mw->createTab((Scene::ChartStyle)style);

            mParent->mTabWidget->addTab(tab, "");
            mParent->mTabWidget->widget(mParent->mTabWidget->indexOf(tab))->hide();
        } else if(tag == "defaultSt") {
            defaultSt = stream->readElementText();
            tab->scene()->mDefaultStitch = defaultSt;

        } else if(tag == "chartCenter") {
            qreal x = stream->attributes().value("x").toString().toDouble();
            qreal y = stream->attributes().value("y").toString().toDouble();

            stream->readElementText();
            tab->blockSignals(true);
            tab->setShowChartCenter(true);
            tab->scene()->mCenterSymbol->setPos(x, y);
            tab->blockSignals(false);

        } else if(tag == "grid") {
            loadGrid(stream, tab->scene());

        } else if(tag == "rowSpacing") {
            qreal width = stream->attributes().value("width").toString().toDouble();
            qreal height = stream->attributes().value("height").toString().toDouble();
            tab->scene()->mDefaultSize.setHeight(height);
            tab->scene()->mDefaultSize.setWidth(width);

            stream->readElementText(); //move to the next tag.
        } else if(tag == "cell") {
            loadCell(tab, stream);

        } else if(tag == "indicator") {
            loadIndicator(tab, stream);
		
        } else if(tag == "chartimage") {
            loadChartImage(tab, stream);
		
        } else if(tag == "group") {
            stream->readElementText().toInt();
            //create an empty group for future use.
            QList<QGraphicsItem*> items;
            tab->scene()->group(items);

        } else if(tag == "guidelines") {
            QString type = stream->attributes().value("type").toString();
            int rows = stream->attributes().value("rows").toString().toInt();
            int columns = stream->attributes().value("columns").toString().toInt();
            int cellHeight = stream->attributes().value("cellHeight").toString().toInt();
            int cellWidth = stream->attributes().value("cellWidth").toString().toInt();

            tab->scene()->mGuidelines.setType(type);
            tab->scene()->mGuidelines.setColumns(columns);
            tab->scene()->mGuidelines.setRows(rows);
            tab->scene()->mGuidelines.setCellWidth(cellWidth);
            tab->scene()->mGuidelines.setCellHeight(cellHeight);

            stream->readElementText(); //move to the next tag
            tab->scene()->updateGuidelines();
            emit tab->updateGuidelines(tab->scene()->guidelines());

        } else if (tag == "chartLayer") {
			QString name = stream->attributes().value("name").toString();
			unsigned int uid = stream->attributes().value("uid").toString().toUInt();
			bool visible = stream->attributes().value("visible").toString().toInt();
			tab->scene()->addLayer(name, uid);
			tab->scene()->getLayer(uid)->setVisible(visible);
			tab->scene()->selectLayer(uid);
            stream->readElementText(); //move to the next tag.
		} else if (tag == "size") {
			qreal x = stream->attributes().value("x").toString().toDouble();
			qreal y = stream->attributes().value("y").toString().toDouble();
			qreal width = stream->attributes().value("width").toString().toDouble();
			qreal height = stream->attributes().value("height").toString().toDouble();
			
			QRectF size = QRectF(x, y, width, height);
			tab->scene()->setSceneRect(size);
			
			stream->readElementText();
		} else {
            qWarning() << "loadChart Unknown tag:" << tag;
        }
    }
	
	//refresh the layers so the visibility and selectability of items is correct
	tab->scene()->refreshLayers();
		
    tab->updateRows();
    int index = mParent->mTabWidget->indexOf(tab);
    mParent->mTabWidget->setTabText(index, tabName);
    mParent->mTabWidget->widget(mParent->mTabWidget->indexOf(tab))->show();
    tab->scene()->updateSceneRect();
    if(tab->scene()->hasChartCenter()) {
        tab->view()->centerOn(tab->scene()->mCenterSymbol->sceneBoundingRect().center());
    } else {
        tab->view()->centerOn(tab->scene()->itemsBoundingRect().center());
    }
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
    // start application
    QString str = QString("\n\n%1: Field").
            arg(QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss.zzz"));

    QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
    QDir("/").mkpath(location);
    appendToFile(location, str);

    // register message handler
    // TODO: qInstallMsgHandler(logOutput);

    ArgosApplication a(argc, argv);
    // QApplication a(argc, argv);

#ifdef VERSION_BETA
    bool beta = true;
#else
    bool beta = false;
#endif

    a.setWindowIcon(icon("field"));
    a.setApplicationVersion(versionString(VERSION_MAJOR, VERSION_MINOR, VERSION_SUB, VERSION_GIT, VERSION_YEAR, VERSION_MONTH, VERSION_DAY, beta));
    a.setOrganizationName("hpfem.org");
    a.setOrganizationDomain("hpfem.org");
    a.setApplicationName("Field");

#ifdef Q_WS_MAC
    // don't show icons in menu
    a.setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif

    // parameters
    QStringList args = QCoreApplication::arguments();
    if (args.count() == 2)
    {
        if (args.contains( "--help") || args.contains("/help"))
        {
            cout << "field [fileName (*.fld; *.py) | -run fileName (*.py) | --help | --verbose]" << endl;
            exit(0);
            return 0;
        }
    }

    QSettings settings;

    // first run
    if (settings.value("General/GUIStyle").value<QString>().isEmpty())
    {
        QString styleName = "";
        QStringList styles = QStyleFactory::keys();

#ifdef Q_WS_X11
        // kde 3
        if (getenv("KDE_FULL_SESSION") != NULL)
            styleName = "Plastique";
        // kde 4
        if (getenv("KDE_SESSION_VERSION") != NULL)
        {
            if (styles.contains("Oxygen"))
                styleName = "Oxygen";
            else
                styleName = "Plastique";
        }
        // gtk+
        if (styleName == "")
            styleName = "GTK+";
#endif

#ifdef Q_WS_WIN
        if (styles.contains("WindowsVista"))
            styleName = "WindowsVista";
        else if (styles.contains("WindowsXP"))
            styleName = "WindowsXP";
        else
            styleName = "Windows";
#endif


#ifdef Q_WS_MAC
        styleName = "Aqua";
#endif

        settings.setValue("General/GUIStyle", styleName);
    }

    // setting gui style
    setGUIStyle(settings.value("General/GUIStyle").value<QString>());

    // language
    QString locale = settings.value("General/Language", QLocale::system().name()).value<QString>();
    setLanguage(locale);

    // init indicator (ubuntu - unity, windows - overlay icon, macosx - ???)
    Indicator::init();

    MainWindow w;
    w.show();

    return a.exec();
}
Exemplo n.º 30
0
CWizDocumentView::CWizDocumentView(CWizExplorerApp& app, QWidget* parent)
    : INoteView(parent)
    , m_app(app)
    , m_userSettings(app.userSettings())
    , m_dbMgr(app.databaseManager())
    #ifdef USEWEBENGINE
    , m_web(new CWizDocumentWebEngine(app, this))
    , m_comments(new QWebEngineView(this))
    #else
    , m_web(new CWizDocumentWebView(app, this))
    , m_commentWidget(new CWizLocalProgressWebView(app.mainWindow()))
    #endif
    , m_title(new TitleBar(app, this))
    , m_passwordView(new CWizUserCipherForm(app, this))
    , m_viewMode(app.userSettings().noteViewMode())
    , m_transitionView(new CWizDocumentTransitionView(this))
    , m_bLocked(false)
    , m_bEditingMode(false)
    , m_noteLoaded(false)
    , m_editStatusSyncThread(new CWizDocumentEditStatusSyncThread(this))
    //, m_editStatusCheckThread(new CWizDocumentStatusCheckThread(this))
    , m_editStatus(0)
{
    m_title->setEditor(m_web);

    QVBoxLayout* layoutDoc = new QVBoxLayout();
    layoutDoc->setContentsMargins(0, 0, 0, 0);
    layoutDoc->setSpacing(0);

    m_docView = new QWidget(this);
    m_docView->setLayout(layoutDoc);

    m_tab = new QStackedWidget(this);
    //
    m_passwordView->setGeometry(this->geometry());
    connect(m_passwordView, SIGNAL(cipherCheckRequest()), SLOT(onCipherCheckRequest()));
    //
    m_msgWidget = new QWidget(this);
    QVBoxLayout* layoutMsg = new QVBoxLayout();
    m_msgWidget->setLayout(layoutMsg);
    m_msgLabel = new QLabel(m_msgWidget);
    m_msgLabel->setAlignment(Qt::AlignCenter);
    m_msgLabel->setWordWrap(true);
    layoutMsg->addWidget(m_msgLabel);
    //
    m_tab->addWidget(m_docView);
    m_tab->addWidget(m_passwordView);
    m_tab->addWidget(m_msgWidget);
    m_tab->setCurrentWidget(m_docView);

    m_splitter = new CWizSplitter(this);
    m_splitter->addWidget(m_web);
    m_splitter->addWidget(m_commentWidget);
    m_web->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    m_comments = m_commentWidget->web();
    QWebPage *commentPage = new QWebPage(m_comments);
    commentPage->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    m_comments->setPage(commentPage);
    m_comments->history()->setMaximumItemCount(0);
    m_comments->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    m_comments->settings()->globalSettings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    m_comments->settings()->globalSettings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);
    m_comments->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    m_comments->setAcceptDrops(false);
    connect(m_comments, SIGNAL(loadFinished(bool)), m_title, SLOT(onCommentPageLoaded(bool)));
    connect(m_comments, SIGNAL(linkClicked(QUrl)), m_web, SLOT(onEditorLinkClicked(QUrl)));
    connect(m_comments->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            SLOT(on_comment_populateJavaScriptWindowObject()));

    m_commentWidget->hide();

    layoutDoc->addWidget(m_title);
    layoutDoc->addWidget(m_splitter);
    layoutDoc->setStretchFactor(m_title, 0);
    layoutDoc->setStretchFactor(m_splitter, 1);

#ifdef USEWEBENGINE
    QLineEdit *commandLine = new QLineEdit(this);
    layoutDoc->addWidget(commandLine);
    connect(commandLine, SIGNAL(returnPressed()), SLOT(on_command_request()));
#endif

    QVBoxLayout* layoutMain = new QVBoxLayout(this);
    layoutMain->setContentsMargins(0, 0, 0, 0);
    setLayout(layoutMain);
    layoutMain->addWidget(m_tab);

    //
    layoutMain->addWidget(m_transitionView);
    m_transitionView->hide();

    MainWindow* mainWindow = qobject_cast<MainWindow *>(m_app.mainWindow());
    m_downloaderHost = mainWindow->downloaderHost();
    connect(m_downloaderHost, SIGNAL(downloadDone(const WIZOBJECTDATA&, bool)),
            SLOT(on_download_finished(const WIZOBJECTDATA&, bool)));

    connect(&m_dbMgr, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), \
            SLOT(on_document_modified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentDataModified(const WIZDOCUMENTDATA&)),
            SLOT(on_document_data_modified(const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentCreated(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_created(const WIZDOCUMENTATTACHMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentDeleted(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_deleted(const WIZDOCUMENTATTACHMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(documentUploaded(QString,QString)), \
            m_editStatusSyncThread, SLOT(documentUploaded(QString,QString)));

    connect(Core::ICore::instance(), SIGNAL(viewNoteRequested(Core::INoteView*,const WIZDOCUMENTDATA&)),
            SLOT(onViewNoteRequested(Core::INoteView*,const WIZDOCUMENTDATA&)));

    connect(Core::ICore::instance(), SIGNAL(viewNoteLoaded(Core::INoteView*,WIZDOCUMENTDATA,bool)),
            SLOT(onViewNoteLoaded(Core::INoteView*,const WIZDOCUMENTDATA&,bool)));

    connect(Core::ICore::instance(), SIGNAL(closeNoteRequested(Core::INoteView*)),
            SLOT(onCloseNoteRequested(Core::INoteView*)));

    connect(m_web, SIGNAL(focusIn()), SLOT(on_webView_focus_changed()));

    connect(m_title, SIGNAL(notifyBar_link_clicked(QString)), SLOT(on_notifyBar_link_clicked(QString)));
    connect(m_title, SIGNAL(loadComment_request(QString)), SLOT(on_loadComment_request(QString)), Qt::QueuedConnection);

//    connect(m_editStatusCheckThread, SIGNAL(checkFinished(QString,QStringList)),
//            SLOT(on_checkEditStatus_finished(QString,QStringList)));
//    connect(m_editStatusCheckThread, SIGNAL(checkDocumentChangedFinished(QString,bool)),
//            SLOT(on_checkDocumentChanged_finished(QString,bool)));
//    connect(m_editStatusCheckThread, SIGNAL(checkTimeOut(QString)),
//            SLOT(on_checkEditStatus_timeout(QString)));

    //
    m_editStatusSyncThread->start(QThread::IdlePriority);
//    m_editStatusCheckThread->start(QThread::IdlePriority);

    m_editStatusChecker = new CWizDocumentStatusChecker();
    connect(this, SIGNAL(checkDocumentEditStatusRequest(QString,QString)), m_editStatusChecker,
            SLOT(checkEditStatus(QString,QString)));
    connect(this, SIGNAL(stopCheckDocumentEditStatusRequest(QString,QString)),
            m_editStatusChecker, SLOT(stopCheckStatus(QString,QString)));
    connect(m_editStatusChecker, SIGNAL(checkEditStatusFinished(QString,bool)), \
            SLOT(on_checkEditStatus_finished(QString,bool)));
    connect(m_editStatusChecker, SIGNAL(checkTimeOut(QString)), \
            SLOT(on_checkEditStatus_timeout(QString)));
    connect(m_editStatusChecker, SIGNAL(documentEditingByOthers(QString,QStringList)), \
            SLOT(on_documentEditingByOthers(QString,QStringList)));
    connect(m_editStatusChecker, SIGNAL(checkDocumentChangedFinished(QString,bool)), \
            SLOT(on_checkDocumentChanged_finished(QString,bool)));

    QThread* checkThread = new QThread(this);
    connect(checkThread, SIGNAL(started()), m_editStatusChecker, SLOT(initialise()));
    connect(checkThread, SIGNAL(finished()), m_editStatusChecker, SLOT(clearTimers()));
    m_editStatusChecker->moveToThread(checkThread);
    checkThread->start();
}