Example #1
0
HRESULT DirectShowIOSource::QueryFilterInfo(FILTER_INFO *pInfo)
{
    if (!pInfo) {
        return E_POINTER;
    } else {
        QString name = m_filterName;

        if (name.length() >= MAX_FILTER_NAME)
            name.truncate(MAX_FILTER_NAME - 1);

        int length = name.toWCharArray(pInfo->achName);
        pInfo->achName[length] = '\0';

        if (m_graph)
            m_graph->AddRef();

        pInfo->pGraph = m_graph;

        return S_OK;
    }
}
HRESULT VideoSurfaceFilter::QueryFilterInfo(FILTER_INFO *pInfo)
{
    if (pInfo) {
        QString name = m_name;

        if (name.length() >= MAX_FILTER_NAME)
            name.truncate(MAX_FILTER_NAME - 1);

        int length = name.toWCharArray(pInfo->achName);
        pInfo->achName[length] = '\0';

        if (m_graph)
            m_graph->AddRef();

        pInfo->pGraph = m_graph;

        return S_OK;
    } else {
        return E_POINTER;
    }
}
Example #3
0
EmbeddedPython::EmbeddedPython()
{
    // Build string list of paths that will
    // comprise the embedded Python's sys.path.
#if defined(__APPLE__)
    // On Mac OS X QCoreApplication::applicationDirPath() points to 
    // whereever Sigil.app/Contents/MacOS/ is located
    // but the python3 dir is in Contents
    QDir execdir(QCoreApplication::applicationDirPath());
    execdir.cdUp();
    QString pyhomepath = execdir.absolutePath();
#else
    QString pyhomepath = QCoreApplication::applicationDirPath();
#endif
    wchar_t *hpath = new wchar_t[pyhomepath.size()+1];
    pyhomepath.toWCharArray(hpath);
    hpath[pyhomepath.size()]=L'\0';

    QString pysyspath = pyhomepath + PYTHON_MAIN_PATH;
    foreach (const QString &src_path, PYTHON_SYS_PATHS) {
        pysyspath = pysyspath + PATH_LIST_DELIM + pyhomepath + PYTHON_MAIN_PATH + src_path;
    }
Example #4
0
/**
  * Return the remaining free space for the given path.
  */
qint64 Global::availableDiskSpace(const QString& path)
{
   Q_ASSERT(!path.isEmpty());

#if defined(Q_OS_WIN32)
   ULARGE_INTEGER space;
   wchar_t buffer[path.size()];

   int l = path.toWCharArray(buffer);
   buffer[l] = 0;

   if (!GetDiskFreeSpaceEx(buffer, &space, NULL, NULL))
      return std::numeric_limits<qint64>::max();
   return space.QuadPart;
#elif defined(Q_OS_LINUX)
   struct statvfs info;
   if (statvfs(path.toUtf8().constData(), &info) == 0)
      return static_cast<qint64>(info.f_bsize) * info.f_bavail;
#endif

   return std::numeric_limits<qint64>::max();
}
Example #5
0
/**
  * @exception DirNotFoundException
  */
bool DirWatcherWin::addDir(const QString& path)
{
    QMutexLocker locker(&this->mutex);

    if (this->dirs.size() > MAXIMUM_WAIT_OBJECTS - MAX_WAIT_CONDITION)
        return false;

    TCHAR pathTCHAR[path.size() + 1];
    path.toWCharArray(pathTCHAR);
    pathTCHAR[path.size()] = 0;

    HANDLE fileHandle = CreateFile(pathTCHAR, // Pointer to the file name.
                                   FILE_LIST_DIRECTORY, // Access (read/write) mode.
                                   FILE_SHARE_READ | FILE_SHARE_WRITE, // Share mode.
                                   NULL, // security descriptor
                                   OPEN_EXISTING, // how to create
                                   FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, // file attributes
                                   NULL // file with attributes to copy
                                  );

    if (fileHandle == INVALID_HANDLE_VALUE)
        throw DirNotFoundException(path);

    HANDLE eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (eventHandle == NULL)
        throw DirNotFoundException(path);

    Dir* dir = new Dir(fileHandle, eventHandle, path);

    if (!this->watch(dir))
    {
        delete dir;
        return false;
    }

    this->dirs << dir;
    return true;
}
void LH_NowPlayingEmulator::sendMessage(bool enabled)
{
    HWND hwnd = ::FindWindowW(L"MsnMsgrUIManager", NULL);
    qDebug() << "window: " << hwnd;
    if(hwnd!=0)
    {
        wchar_t wstr[512];
        QString msg = QString("%1\\0Music\\0%2\\0%1: {1} - {0}\\0%3\\0%4\\0%5\\0WMContentID\\0")
                .arg(setup_player_->value())
                .arg(enabled? 1 : 0)
                .arg(setup_artist_->value())
                .arg(setup_track_->value())
                .arg(setup_album_->value())
                ;
        msg.toWCharArray(wstr);

        COPYDATASTRUCT cd;
        cd.dwData = MSN_MAGIC_NUMBER;
        cd.lpData = wstr;
        cd.cbData = (lstrlenW(wstr) * 2) + 2;

        ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&cd);
    }
}
Example #7
0
//-----------------------------------------------------------------------------
QString Backend::coor(const QString& xy, const QString& text) const
{
	wchar_t *wtext;
	qDebug() << __FUNCTION__;
	mglGraph gr;
	mglParse pr;
	pr.AllowSetSize(true);
	setlocale(LC_CTYPE, "");
	setlocale(LC_NUMERIC, "C");
	wtext = new wchar_t[text.size()+1];
	text.toWCharArray(wtext);
	wtext[text.size()] = 0;
	pr.Execute(&gr,wtext);
	delete[] wtext;
	gr.Finish();

	int x = (int)xy.section(" ",0,0).toDouble();
	int y = (int)xy.section(" ",1,1).toDouble();
	mglPoint p = gr.CalcXYZ(x,y);
	QString res;
	res.sprintf("x = %g, y = %g, z = %g for point (%d, %d)\n", p.x, p.y, p.z, x,y);
	qDebug() << res+"\nask"+xy;
	return res+"\nask"+xy;
}
Example #8
0
void MainWindow::on_btnLinkKey_clicked()
{
    WRITE2LOG("Linking...");
    if(certList.isEmpty() == true)
    {
        WRITE2LOG("Certificate list is empty");
        return;
    }

    if(ui->listCerts->currentIndex().row() == -1)
    {
        QMessageBox::warning(this, "Warning", "Select certificate!");
        return;
    }

    DWORD pcbData = 0;
    if(CertGetCertificateContextProperty(certList[ui->listCerts->currentIndex().row()], CERT_KEY_PROV_INFO_PROP_ID, NULL, &pcbData) != 0)
    {
        int result = QMessageBox::warning(this, "Warning", "This certificate already have private key.\nAre you sure you want to add new key?", QMessageBox::Ok, QMessageBox::Cancel);
        if (result == QMessageBox::Cancel)
        {
            WRITE2LOG("Canceled by user");
            return;
        }
    }

    QDialog* keyInfoDlg = new QDialog(this);
    QLineEdit* lnProvider = new QLineEdit;
    QLineEdit* lnLabel = new QLineEdit;


    QFormLayout* layout = new QFormLayout(keyInfoDlg);
    layout->addRow("CNG Cryptoprovider:", lnProvider);
    layout->addRow("Key name:", lnLabel);


    QDialogButtonBox *btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(btnBox, SIGNAL(accepted()), keyInfoDlg, SLOT(accept()));
    connect(btnBox, SIGNAL(rejected()), keyInfoDlg, SLOT(reject()));
    layout->addRow(btnBox);
    keyInfoDlg->exec();

    if(keyInfoDlg->result() == QDialog::Rejected)
    {
//        delete keyInfoDlg;
//        delete lnProvider;
//        delete lnLabel;
//        delete layout;
//        delete btnBox;
        WRITE2LOG("Canceled by user");
        return;
    }

    if(lnProvider->text().size() == 0 || lnLabel->text().size() == 0 )
    {
        QMessageBox::warning(this, "Warning", "All fields must be filled!", QMessageBox::Ok);
//        delete keyInfoDlg;
//        delete lnProvider;
//        delete lnLabel;
//        delete layout;
//        delete btnBox;
        return;
    }


    QString containerName = lnLabel->text();
    wchar_t* pwszContainerName = new wchar_t[containerName.size()];
    int size = containerName.toWCharArray(pwszContainerName);
    pwszContainerName[size] = 0;

    wchar_t* pwszProvider = new wchar_t[lnProvider->text().size()];
    size = lnProvider->text().toWCharArray(pwszProvider);
    pwszProvider[size] = 0;

    CRYPT_KEY_PROV_INFO kpi;
    ZeroMemory(&kpi, sizeof(kpi));

    kpi.pwszContainerName = pwszContainerName;
    kpi.dwProvType = NULL;
    kpi.pwszProvName = pwszProvider;

    LPCWSTR storage = L"";
    if(ui->rbMYStorage->isChecked() == true)
        storage = L"MY";
    else
        storage = L"ROOT";


    HCERTSTORE hCertStore = CertOpenStore(
           CERT_STORE_PROV_SYSTEM,
           0,
           NULL,
           CERT_SYSTEM_STORE_CURRENT_USER,
           storage);

    int res = CertSetCertificateContextProperty(certList[ui->listCerts->currentIndex().row()], CERT_KEY_PROV_INFO_PROP_ID, 0, &kpi);
    int ret = CertAddCertificateContextToStore(hCertStore, certList[ui->listCerts->currentIndex().row()], CERT_STORE_ADD_ALWAYS, NULL);
    if(res == 1 && ret == 1)
        QMessageBox::information(this, "Information", "Key was associated with certificate successfully. \nCertificate has been added to storage.", QMessageBox::Ok);
    else if (res == 0)
        QMessageBox::warning(this, "Warning", "Failed to associate key with certificate.", QMessageBox::Ok);
    else if (ret == 0)
        QMessageBox::warning(this, "Warning", "Failed to add certificate to store.", QMessageBox::Ok);

    delete keyInfoDlg;
    delete lnProvider;
    delete lnLabel;
    delete layout;
    delete btnBox;
    delete pwszContainerName;
    delete pwszProvider;
}
Example #9
0
// Open the parent directory of the given path with a file manager and select
// (if possible) the item at the given path
void Utils::Misc::openFolderSelect(const QString& absolutePath)
{
    const QString path = Utils::Fs::fromNativePath(absolutePath);
#ifdef Q_OS_WIN
    if (QFileInfo(path).exists()) {
        // Syntax is: explorer /select, "C:\Folder1\Folder2\file_to_select"
        // Dir separators MUST be win-style slashes

        // QProcess::startDetached() has an obscure bug. If the path has
        // no spaces and a comma(and maybe other special characters) it doesn't
        // get wrapped in quotes. So explorer.exe can't find the correct path and
        // displays the default one. If we wrap the path in quotes and pass it to
        // QProcess::startDetached() explorer.exe still shows the default path. In
        // this case QProcess::startDetached() probably puts its own quotes around ours.

        STARTUPINFO startupInfo;
        ::ZeroMemory(&startupInfo, sizeof(startupInfo));
        startupInfo.cb = sizeof(startupInfo);

        PROCESS_INFORMATION processInfo;
        ::ZeroMemory(&processInfo, sizeof(processInfo));

        QString cmd = QString("explorer.exe /select,\"%1\"").arg(Utils::Fs::toNativePath(absolutePath));
        LPWSTR lpCmd = new WCHAR[cmd.size() + 1];
        cmd.toWCharArray(lpCmd);
        lpCmd[cmd.size()] = 0;

        bool ret = ::CreateProcessW(NULL, lpCmd, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
        delete [] lpCmd;

        if (ret) {
            ::CloseHandle(processInfo.hProcess);
            ::CloseHandle(processInfo.hThread);
        }
    }
    else {
        // If the item to select doesn't exist, try to open its parent
        openPath(path.left(path.lastIndexOf("/")));
    }
#elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
    if (QFileInfo(path).exists()) {
        QProcess proc;
        QString output;
        proc.start("xdg-mime", QStringList() << "query" << "default" << "inode/directory");
        proc.waitForFinished();
        output = proc.readLine().simplified();
        if (output == "dolphin.desktop" || output == "org.kde.dolphin.desktop")
            proc.startDetached("dolphin", QStringList() << "--select" << Utils::Fs::toNativePath(path));
        else if (output == "nautilus.desktop" || output == "org.gnome.Nautilus.desktop"
                 || output == "nautilus-folder-handler.desktop")
            proc.startDetached("nautilus", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(path));
        else if (output == "caja-folder-handler.desktop")
            proc.startDetached("caja", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(path));
        else if (output == "nemo.desktop")
            proc.startDetached("nemo", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(path));
        else if (output == "konqueror.desktop" || output == "kfmclient_dir.desktop")
            proc.startDetached("konqueror", QStringList() << "--select" << Utils::Fs::toNativePath(path));
        else
            openPath(path.left(path.lastIndexOf("/")));
    }
    else {
        // If the item to select doesn't exist, try to open its parent
        openPath(path.left(path.lastIndexOf("/")));
    }
#else
    openPath(path.left(path.lastIndexOf("/")));
#endif
}
Example #10
0
void ConfigDialog::accept()
{
	m_accepted = true;

	int windowedValidatorPos = 0;
	QString currentText = ui->windowedResolutionComboBox->currentText();
	if (ui->windowedResolutionComboBox->validator()->validate(
		currentText, windowedValidatorPos
	) == QValidator::Acceptable) {
		QStringList windowedResolutionDimensions = currentText.split("x");
		config.video.windowedWidth = windowedResolutionDimensions[0].trimmed().toInt();
		config.video.windowedHeight = windowedResolutionDimensions[1].trimmed().toInt();
	}

	getFullscreenResolutions(ui->fullScreenResolutionComboBox->currentIndex(), config.video.fullscreenWidth, config.video.fullscreenHeight);
	getFullscreenRefreshRate(ui->fullScreenRefreshRateComboBox->currentIndex(), config.video.fullscreenRefresh);

	config.video.cropMode = ui->cropImageComboBox->currentIndex();
	config.video.cropWidth = ui->cropImageWidthSpinBox->value();
	config.video.cropHeight = ui->cropImageHeightSpinBox->value();

	config.video.multisampling = ui->n64DepthCompareCheckBox->isChecked() ? 0 : pow2(ui->aliasingSlider->value());
	config.texture.maxAnisotropy = ui->anisotropicSlider->value();

	if (ui->blnrStandardRadioButton->isChecked())
		config.texture.bilinearMode = BILINEAR_STANDARD;
	else if (ui->blnr3PointRadioButton->isChecked())
		config.texture.bilinearMode = BILINEAR_3POINT;

	if (ui->pngRadioButton->isChecked())
		config.texture.screenShotFormat = 0;
	else if (ui->jpegRadioButton->isChecked())
		config.texture.screenShotFormat = 1;

	const int lanuageIndex = ui->translationsComboBox->currentIndex();
	if (lanuageIndex == 0) // English
		config.translationFile.clear();
	else {
		QStringList translationFiles;
		_getTranslations(translationFiles);
		config.translationFile = translationFiles[lanuageIndex-1].toLocal8Bit().constData();
	}

	config.video.verticalSync = ui->vSyncCheckBox->isChecked() ? 1 : 0;

	// Emulation settings
	config.generalEmulation.enableLOD = ui->emulateLodCheckBox->isChecked() ? 1 : 0;
	config.generalEmulation.enableNoise = ui->emulateNoiseCheckBox->isChecked() ? 1 : 0;
	config.generalEmulation.enableHWLighting = ui->enableHWLightingCheckBox->isChecked() ? 1 : 0;
	config.generalEmulation.enableShadersStorage = ui->enableShadersStorageCheckBox->isChecked() ? 1 : 0;
	config.generalEmulation.enableCustomSettings = ui->customSettingsCheckBox->isChecked() ? 1 : 0;

	config.gammaCorrection.force = ui->gammaCorrectionCheckBox->isChecked() ? 1 : 0;
	config.gammaCorrection.level = ui->gammaLevelSpinBox->value();

	if (ui->fixTexrectDisableRadioButton->isChecked())
		config.generalEmulation.correctTexrectCoords = Config::tcDisable;
	else if (ui->fixTexrectSmartRadioButton->isChecked())
		config.generalEmulation.correctTexrectCoords = Config::tcSmart;
	else if (ui->fixTexrectForceRadioButton->isChecked())
		config.generalEmulation.correctTexrectCoords = Config::tcForce;

	config.generalEmulation.enableNativeResTexrects = ui->nativeRes2D_checkBox->isChecked() ? 1 : 0;

	config.frameBufferEmulation.enable = ui->frameBufferCheckBox->isChecked() ? 1 : 0;

	config.frameBufferEmulation.bufferSwapMode = ui->frameBufferSwapComboBox->currentIndex();
	config.frameBufferEmulation.copyToRDRAM = ui->copyColorBufferComboBox->currentIndex();
	config.frameBufferEmulation.copyDepthToRDRAM = ui->copyDepthBufferComboBox->currentIndex();
	config.frameBufferEmulation.copyFromRDRAM = ui->RenderFBCheckBox->isChecked() ? 1 : 0;

	config.frameBufferEmulation.N64DepthCompare = ui->n64DepthCompareCheckBox->isChecked() ? 1 : 0;

	if (ui->aspectStretchRadioButton->isChecked())
		config.frameBufferEmulation.aspect = Config::aStretch;
	else if (ui->aspect43RadioButton->isChecked())
		config.frameBufferEmulation.aspect = Config::a43;
	else if (ui->aspect169RadioButton->isChecked())
		config.frameBufferEmulation.aspect = Config::a169;
	else if (ui->aspectAdjustRadioButton->isChecked())
		config.frameBufferEmulation.aspect = Config::aAdjust;

	if (ui->factor0xRadioButton->isChecked())
		config.frameBufferEmulation.nativeResFactor = 0;
	else if (ui->factor1xRadioButton->isChecked())
		config.frameBufferEmulation.nativeResFactor = 1;
	else if (ui->factorXxRadioButton->isChecked())
		config.frameBufferEmulation.nativeResFactor = ui->resolutionFactorSlider->value();

	config.frameBufferEmulation.copyAuxToRDRAM = ui->copyAuxBuffersCheckBox->isChecked() ? 1 : 0;
	config.frameBufferEmulation.fbInfoDisabled = ui->fbInfoEnableCheckBox->isChecked() ? 0 : 1;
	config.frameBufferEmulation.fbInfoReadColorChunk = ui->readColorChunkCheckBox->isChecked() ? 1 : 0;
	config.frameBufferEmulation.fbInfoReadDepthChunk = ui->readDepthChunkCheckBox->isChecked() ? 1 : 0;

	// Texture filter settings
	config.textureFilter.txFilterMode = ui->filterComboBox->currentIndex();
	config.textureFilter.txEnhancementMode = ui->enhancementComboBox->currentIndex();

	config.textureFilter.txCacheSize = ui->textureFilterCacheSpinBox->value() * gc_uMegabyte;
	config.textureFilter.txDeposterize = ui->deposterizeCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txFilterIgnoreBG = ui->ignoreBackgroundsCheckBox->isChecked() ? 1 : 0;

	config.textureFilter.txHiresEnable = ui->texturePackOnCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txHiresFullAlphaChannel = ui->alphaChannelCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txHresAltCRC = ui->alternativeCRCCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txDump = ui->textureDumpCheckBox->isChecked() ? 1 : 0;

	config.textureFilter.txCacheCompression = ui->compressCacheCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txForce16bpp = ui->force16bppCheckBox->isChecked() ? 1 : 0;
	config.textureFilter.txSaveCache = ui->saveTextureCacheCheckBox->isChecked() ? 1 : 0;

	QString txPath = ui->txPathLabel->text();
	if (!txPath.isEmpty())
		config.textureFilter.txPath[txPath.toWCharArray(config.textureFilter.txPath)] = L'\0';
	QString txCachePath = ui->txCachePathLabel->text();
	if (!txPath.isEmpty())
		config.textureFilter.txCachePath[txCachePath.toWCharArray(config.textureFilter.txCachePath)] = L'\0';
	QString txDumpPath = ui->txDumpPathLabel->text();
	if (!txDumpPath.isEmpty())
		config.textureFilter.txDumpPath[txDumpPath.toWCharArray(config.textureFilter.txDumpPath)] = L'\0';

	// OSD settings
	config.font.size = ui->fontSizeSpinBox->value();
#ifdef OS_WINDOWS
	config.font.name = ui->fontLineEdit->text().toLocal8Bit().constData();
#else
	config.font.name = ui->fontLineEdit->text().toStdString();
#endif
	config.font.color[0] = m_color.red();
	config.font.color[1] = m_color.green();
	config.font.color[2] = m_color.blue();
	config.font.color[3] = m_color.alpha();
	config.font.colorf[0] = m_color.redF();
	config.font.colorf[1] = m_color.greenF();
	config.font.colorf[2] = m_color.blueF();
	config.font.colorf[3] = m_color.alphaF();


	if (ui->topLeftPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posTopLeft;
	else if (ui->topPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posTopCenter;
	else if (ui->topRightPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posTopRight;
	else if (ui->bottomLeftPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posBottomLeft;
	else if (ui->bottomPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posBottomCenter;
	else if (ui->bottomRightPushButton->isChecked())
		config.onScreenDisplay.pos = Config::posBottomRight;

	config.onScreenDisplay.fps = ui->fpsCheckBox->isChecked() ? 1 : 0;
	config.onScreenDisplay.vis = ui->visCheckBox->isChecked() ? 1 : 0;
	config.onScreenDisplay.percent = ui->percentCheckBox->isChecked() ? 1 : 0;
	config.onScreenDisplay.internalResolution = ui->internalResolutionCheckBox->isChecked() ? 1 : 0;
	config.onScreenDisplay.renderingResolution = ui->renderingResolutionCheckBox->isChecked() ? 1 : 0;

	config.debug.dumpMode = 0;
	if (ui->dumpLowCheckBox->isChecked())
		config.debug.dumpMode |= DEBUG_LOW;
	if (ui->dumpNormalCheckBox->isChecked())
		config.debug.dumpMode |= DEBUG_NORMAL;
	if (ui->dumpDetailCheckBox->isChecked())
		config.debug.dumpMode |= DEBUG_DETAIL;

	writeSettings(m_strIniPath);

	QDialog::accept();
}
Example #11
0
extern "C" _declspec(dllexport) int main(int argc, char **argv) {
#else
int main(int argc, char **argv) {
#endif
	int res = 0;

	QT_REQUIRE_VERSION(argc, argv, "4.4.0");

#if defined(Q_OS_WIN)
	SetDllDirectory(L"");
#else
#ifndef Q_OS_MAC
	setenv("AVAHI_COMPAT_NOWARN", "1", 1);
#endif
#endif

	// Initialize application object.
	MumbleApplication a(argc, argv);
	a.setApplicationName(QLatin1String("Mumble"));
	a.setOrganizationName(QLatin1String("Mumble"));
	a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net"));
	a.setQuitOnLastWindowClosed(false);

#if QT_VERSION >= 0x050100
	a.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

#if QT_VERSION >= 0x050000 && defined(Q_OS_WIN)
	a.installNativeEventFilter(&a);
#endif

	#ifdef USE_SBCELT
	{
		QDir d(a.applicationVersionRootPath());
		QString helper = d.absoluteFilePath(QString::fromLatin1("sbcelt-helper"));
		setenv("SBCELT_HELPER_BINARY", helper.toUtf8().constData(), 1);
	}
#endif

	Global::g_global_struct = new Global();

	qsrand(QDateTime::currentDateTime().toTime_t());

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
	os_init();
#endif

	bool bAllowMultiple = false;
	bool suppressIdentity = false;
	bool bRpcMode = false;
	QString rpcCommand;
	QUrl url;
	if (a.arguments().count() > 1) {
		QStringList args = a.arguments();
		for (int i = 1; i < args.count(); ++i) {
			if (args.at(i) == QLatin1String("-h") || args.at(i) == QLatin1String("--help")
#if defined(Q_OS_WIN)
				|| args.at(i) == QLatin1String("/?")
#endif
			) {
				QString helpMessage = MainWindow::tr(
					"Usage: mumble [options] [<url>]\n"
					"\n"
					"<url> specifies a URL to connect to after startup instead of showing\n"
					"the connection window, and has the following form:\n"
					"mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/<subchannel>...]][?version=<x.y.z>]\n"
					"\n"
					"The version query parameter has to be set in order to invoke the\n"
					"correct client version. It currently defaults to 1.2.0.\n"
					"\n"
					"Valid options are:\n"
					"  -h, --help    Show this help text and exit.\n"
					"  -m, --multiple\n"
					"                Allow multiple instances of the client to be started.\n"
					"  -n, --noidentity\n"
					"                Suppress loading of identity files (i.e., certificates.)\n"
					"\n"
				);
				QString rpcHelpBanner = MainWindow::tr(
					"Remote controlling Mumble:\n"
					"\n"
				);
				QString rpcHelpMessage = MainWindow::tr(
					"Usage: mumble rpc <action> [options]\n"
					"\n"
					"It is possible to remote control a running instance of Mumble by using\n"
					"the 'mumble rpc' command.\n"
					"\n"
					"Valid actions are:\n"
					"  mute\n"
					"                Mute self\n"
					"  unmute\n"
					"                Unmute self\n"
					"  deaf\n"
					"                Deafen self\n"
					"  undeaf\n"
					"                Undeafen self\n"
					"\n"
				);

				QString helpOutput = helpMessage + rpcHelpBanner + rpcHelpMessage;
				if (bRpcMode) {
					helpOutput = rpcHelpMessage;
				}

#if defined(Q_OS_WIN)
				QMessageBox::information(NULL, MainWindow::tr("Invocation"), helpOutput);
#else
				printf("%s", qPrintable(helpOutput));
#endif
				return 1;
			} else if (args.at(i) == QLatin1String("-m") || args.at(i) == QLatin1String("--multiple")) {
				bAllowMultiple = true;
			} else if (args.at(i) == QLatin1String("-n") || args.at(i) == QLatin1String("--noidentity")) {
				suppressIdentity = true;
				g.s.bSuppressIdentity = true;
			} else if (args.at(i) == QLatin1String("rpc")) {
				bRpcMode = true;
				if (args.count() - 1 > i) {
					rpcCommand = QString(args.at(i + 1));
				}
				else {
					QString rpcError = MainWindow::tr("Error: No RPC command specified");
#if defined(Q_OS_WIN)
					QMessageBox::information(NULL, MainWindow::tr("RPC"), rpcError);
#else
					printf("%s\n", qPrintable(rpcError));
#endif
					return 1;
				}
			} else {
				if (!bRpcMode) {
					QUrl u = QUrl::fromEncoded(args.at(i).toUtf8());
					if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) {
						url = u;
					} else {
						QFile f(args.at(i));
						if (f.exists()) {
							url = QUrl::fromLocalFile(f.fileName());
						}
					}
				}
			}
		}
	}

#ifdef USE_DBUS
#ifdef Q_OS_WIN
	// By default, windbus expects the path to dbus-daemon to be in PATH, and the path
	// should contain bin\\, and the path to the config is hardcoded as ..\etc

	{
		size_t reqSize;
		_wgetenv_s(&reqSize, NULL, 0, L"PATH");
		if (reqSize > 0) {
			STACKVAR(wchar_t, buff, reqSize+1);
			_wgetenv_s(&reqSize, buff, reqSize, L"PATH");
			QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())).arg(QString::fromWCharArray(buff));
			STACKVAR(wchar_t, buffout, path.length() + 1);
			path.toWCharArray(buffout);
			_wputenv_s(L"PATH", buffout);
		}
	}
Example #12
0
int main(int argc, char **argv) {
	int res = 0;

	QT_REQUIRE_VERSION(argc, argv, "4.4.0");

#if defined(Q_OS_WIN)
	SetDllDirectory(L"");
#else
#ifndef Q_OS_MAC
	setenv("AVAHI_COMPAT_NOWARN", "1", 1);
#endif
#endif

	// Initialize application object.
	QAppMumble a(argc, argv);
	a.setApplicationName(QLatin1String("Mumble"));
	a.setOrganizationName(QLatin1String("Mumble"));
	a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net"));
	a.setQuitOnLastWindowClosed(false);

	Global::g_global_struct = new Global();

	qsrand(QDateTime::currentDateTime().toTime_t());

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
	os_init();
#endif

	bool bAllowMultiple = false;
	QUrl url;
	if (a.arguments().count() > 1) {
		QStringList args = a.arguments();
		for (int i = 1; i < args.count(); ++i) {
			if (args.at(i) == QLatin1String("-m")) {
				bAllowMultiple = true;
			} else if (args.at(i) == QLatin1String("-n")) {
				g.s.bSuppressIdentity = true;
			} else {
				QUrl u = QUrl::fromEncoded(args.at(i).toUtf8());
				if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) {
					url = u;
				} else {
					QFile f(args.at(i));
					if (f.exists()) {
						url = QUrl::fromLocalFile(f.fileName());
					}
				}
			}
		}
	}

#ifdef USE_DBUS
#ifdef Q_OS_WIN
	// By default, windbus expects the path to dbus-daemon to be in PATH, and the path
	// should contain bin\\, and the path to the config is hardcoded as ..\etc

	{
		size_t reqSize;
		_wgetenv_s(&reqSize, NULL, 0, L"PATH");
		if (reqSize > 0) {
			STACKVAR(wchar_t, buff, reqSize+1);
			_wgetenv_s(&reqSize, buff, reqSize, L"PATH");
			QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(QString::fromWCharArray(buff));
			STACKVAR(wchar_t, buffout, path.length() + 1);
			path.toWCharArray(buffout);
			_wputenv_s(L"PATH", buffout);
		}
	}
Example #13
0
//Adds dir & its contents to the library
void libraryDialog::addDir2Lib(QDir dir)
{
	dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
	QDirIterator di(dir, QDirIterator::Subdirectories);	

	while(di.hasNext())
	{
		di.next();		
		QString fpath = di.filePath();
		QFileInfo f = di.fileInfo();
		if(isAudioFile(f))//Add this song to the database
		{
			wchar_t wname[250]; //TODO: Dynamic. Need to figure out wchar length from QStr length
			wname[fpath.toWCharArray(wname)] = 0;
			TagLib::FileName fname(wname);
			//We'll store tag information in these:
			QMap<QString, QString> stmap;
			QMap<QString, int> itmap;
			
			TagLib::File* file = NULL;
			//MP3 Means we can check for additional info in ID3v2 tags
			if(f.suffix() == "mp3")
			{				
				TagLib::MPEG::File* fr = new TagLib::MPEG::File(fname, true, TagLib::AudioProperties::ReadStyle::Fast);				
				if(fr->ID3v2Tag())
				{					
					//Somehow this means album artist / band. http://www.id3.org/id3v2.4.0-frames
					TagLib::ID3v2::FrameList l = fr->ID3v2Tag()->frameList("TPE2");
					if(!l.isEmpty())
						stmap["albumartist"] = l.front()->toString().toCString();
				}
				file = dynamic_cast<TagLib::File*>(fr);
			}
			if(file == NULL)
			{
				qDebug() << "ERR: " + fpath;
				continue; //TODO: Error out here
			}
			//Try to get audio properties
			TagLib::AudioProperties* ap = file->audioProperties();			
			
			TagLib::Tag* genTag = file->tag();			
			stmap["name"] = genTag->title().toCString();
			stmap["genre"] = genTag->genre().toCString();
			itmap["year"] = genTag->year();
			itmap["tracknum"] = genTag->track();
			stmap["album"] = genTag->album().toCString();						
			stmap["artist"] = genTag->artist().toCString();			
			if(ap != NULL)
				itmap["length"] = ap->length();
			stmap["path"] = fpath;	
			//Add collected info to db
			DBItem s;
			s.strVals = stmap;
			s.intVals = itmap;

			myparent->dbi->addSong(s);
			delete file;
		}
		else if(f.isDir())
			ui.curDirLbl->setText(fpath);
		//if(top) //If we're the top level of recursion update prog bar
		//	ui.progressBar->setValue(di./siz * 100);		
		qApp->processEvents();
	}
}
Example #14
0
    void GraphAggRenderer::drawString(const QString &text, 
            Point *pos,
            int alignment, 
            Color *color)
    {
        if (text.isEmpty())
            return;
        //qDebug() << QString("%1").arg(__PRETTY_FUNCTION__);

        agg::path_storage &ps = m_data->ps;
        unsigned idx = ps.start_new_path();


        // 绘制文本
        font_manager_type *fman = get_fman();

        double x = pos->x();
        double y = pos->y();

        wchar_t *buffer = new wchar_t[text.size() + 1];
        text.toWCharArray(buffer);
        buffer[text.size()] = NULL;
        //qDebug() << text;
        const wchar_t *p = buffer;//L"this is a deom.";
        while (*p) {
            //qDebug() << QString(*p);

            const agg::glyph_cache* glyph = fman->glyph(*p);
            if (glyph) {
                //qDebug() << QString("good");
                fman->init_embedded_adaptors(glyph, x, y);
                ps.concat_path(fman->path_adaptor());
                /*
                cc_pa_type ccpath(fman->path_adaptor());
                cs_cc_pa_type csccpath(ccpath);
                //ct_cs_cc_pa_type ctpath(csccpath, transform);

                //ras.add_path(ctpath);
                ps.concat_path(csccpath);
                */

                x += glyph->advance_x;
                y += glyph->advance_y;
                //qDebug() << QString("%1,%2").arg(x).arg(y);
            } else {
                //qDebug() << QString("bad");
            }
            ++p;
        }
        delete []buffer;


        // 保存属性
        push_attr();
        m_data->as.add(path_attributes(cur_attr(), idx));

        //保存idx值
        path_attributes attr = cur_attr();
        attr.stroke_flag = true;
        attr.fill_flag = false;
        attr.fill_color = agg::rgba8(color->red(), 
                color->green(), color->blue(), color->alpha());
        attr.index = idx;
        m_data->as[m_data->as.size() -1] = attr;
        pop_attr();

        updateBbox();
    }
Example #15
0
void qtDLGAttach::FillProcessList()
{
	tblProcList->setRowCount(0);

	HANDLE hToolSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
	if( hToolSnapShot != INVALID_HANDLE_VALUE)
	{
		PROCESSENTRY32 pProcessEntry;
		pProcessEntry.dwSize = sizeof(PROCESSENTRY32);

		if(Process32First(hToolSnapShot,&pProcessEntry))
		{
			PTCHAR ProcessFile = (PTCHAR)clsMemManager::CAlloc(MAX_PATH * sizeof(TCHAR));
			do 
			{
				HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,false,pProcessEntry.th32ProcessID);
				if(hProc != NULL)
				{
					tblProcList->insertRow(tblProcList->rowCount());

					// ProcessName		
					tblProcList->setItem(tblProcList->rowCount() - 1,0,
						new QTableWidgetItem(QString().fromWCharArray(pProcessEntry.szExeFile)));

					// PID
					tblProcList->setItem(tblProcList->rowCount() - 1,1,
						new QTableWidgetItem(QString().sprintf("%d",pProcessEntry.th32ProcessID)));

					// Type
					if(clsAPIImport::pIsWow64Process == NULL)
						tblProcList->setItem(tblProcList->rowCount() - 1,2,
							new QTableWidgetItem(QString("x86")));
					else
					{
						BOOL isWoW64 = FALSE;
						clsAPIImport::pIsWow64Process(hProc,&isWoW64);
						if(isWoW64)
						{
							tblProcList->setItem(tblProcList->rowCount() - 1,2,
								new QTableWidgetItem(QString("x86")));
						}
						else
						{
							tblProcList->setItem(tblProcList->rowCount() - 1,2,
								new QTableWidgetItem(QString("x64")));
						}
					}

					// Process Path
					memset(ProcessFile,0,MAX_PATH * sizeof(TCHAR));
					if(GetModuleFileNameEx(hProc,NULL,ProcessFile,MAX_PATH) > 0)
					{
						QString processPath = QString().fromWCharArray(ProcessFile);
						if(processPath.contains("SystemRoot"))
						{
							PTCHAR tempPath = (PTCHAR)clsMemManager::CAlloc(MAX_PATH * sizeof(TCHAR));

							processPath.replace("SystemRoot","%SystemRoot%");
							processPath.toWCharArray(ProcessFile);

							if(ExpandEnvironmentStrings(ProcessFile,tempPath,MAX_PATH))
							{
								processPath = QString().fromWCharArray(tempPath);
								processPath.replace("\\C:\\","C:\\");
							}

							clsMemManager::CFree((LPVOID)tempPath);
						}

						tblProcList->setItem(tblProcList->rowCount() - 1,3,
							new QTableWidgetItem(processPath.replace("/","\\")));
					}
					else
						tblProcList->removeRow(tblProcList->rowCount() - 1);
					//	tblProcList->setItem(tblProcList->rowCount() - 1,3,
					//		new QTableWidgetItem(""));

					CloseHandle(hProc);
				}
			} while (Process32Next(hToolSnapShot,&pProcessEntry));
			clsMemManager::CFree(ProcessFile);
		}

		CloseHandle(hToolSnapShot);
	}
}
Example #16
0
bool PluginLoader::RegisterShellExtDll(QString dllPath, bool bRegister,bool quiet)
{
	if(Debug)
	{
		QString message;
		if(bRegister)
			message+=QString("Try load the dll: %1, and ").arg(dllPath);
		else
			message+=QString("Try unload the dll: %1, and ").arg(dllPath);
		if(quiet)
			message+=QString("don't open the UAC");
		else
			message+=QString("open the UAC if needed");
		QMessageBox::information(NULL,"Debug",message);
	}
	////////////////////////////// First way to load //////////////////////////////
	
	wchar_t arrayArg[65535];
	int size_lenght;
	// first try - load dll and register it manually.
	HRESULT hResult = S_OK;
	// if failed - try by loading extension manually (would fail on vista when running as user)
	hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if(SUCCEEDED(hResult))
	{
		HRESULT (STDAPICALLTYPE *pfn)(void);
		size_lenght=dllPath.toWCharArray(arrayArg);
		HINSTANCE hMod = LoadLibrary(arrayArg);	// load the dll
		if(hMod == NULL)
			hResult = HRESULT_FROM_WIN32(GetLastError());
		if(SUCCEEDED(hResult) && !hMod)
			hResult = E_FAIL;
		if(SUCCEEDED(hResult))
		{
			(FARPROC&)pfn = GetProcAddress(hMod, (bRegister ? "DllRegisterServer" : "DllUnregisterServer"));
			if(pfn == NULL)
				hResult = E_FAIL;
			if(SUCCEEDED(hResult))
				hResult = (*pfn)();

			CoFreeLibrary(hMod);
		}
		CoUninitialize();
		if(SUCCEEDED(hResult) && SCODE_CODE(hResult) != ERROR_ACCESS_DENIED)
			return true;
		else
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,QString("fail by LoadLibrary: %1, error code: %2").arg(dllPath).arg((quint32)hResult));
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,QString("fail by CoInitializeEx: %1, error code: %2").arg(dllPath).arg((quint32)hResult));
	
	////////////////////////////// Second way to load //////////////////////////////
	QStringList arguments;
	if(!Debug)
		arguments.append("/s");
	if(!bRegister)
		arguments.append("/u");
	arguments.append(dllPath);
	QString argumentsString;
	for (int i = 0; i < arguments.size(); ++i) {
		if(argumentsString.isEmpty())
			argumentsString+=arguments.at(i);
		else
			if(i == arguments.size())
				argumentsString+=" \""+arguments.at(i)+"\"";
			else
				argumentsString+=' '+arguments.at(i);
	}
        ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"start: regsvr32 "+argumentsString);
	int result=QProcess::execute("regsvr32",arguments);
	bool ok=false;
	if(result==0)
		ok=true;
	#if ! defined(_M_X64)
	if(result==999 && !changeOfArchDetected)//code of wrong arch for the dll
	{
		changeOfArchDetected=true;
		QStringList temp;
		temp = importantDll;
		secondDll = importantDll;
		importantDll = temp;
		return false;
	}
	#endif
	if(result==5)
	{
		if(!quiet || (!bRegister && correctlyLoaded.contains(dllPath)))
		{
			////////////////////////////// Last way to load //////////////////////////////
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"try it in win32");
			// try with regsvr32, win32 because for admin dialog

			size_lenght=argumentsString.toWCharArray(arrayArg);
			//size_lenght*sizeof(wchar_t)
			wcscpy(arrayArg+size_lenght*sizeof(wchar_t),TEXT("\0"));
			SHELLEXECUTEINFO sei;
			memset(&sei, 0, sizeof(sei));
			sei.cbSize = sizeof(sei);
			sei.fMask = SEE_MASK_UNICODE;
			sei.lpVerb = TEXT("runas");
			sei.lpFile = TEXT("regsvr32.exe");
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"in win32 mode: arrayArg: "+QString::fromWCharArray(arrayArg,size_lenght));
			sei.lpParameters = arrayArg;
			sei.nShow = SW_SHOW;
			ok=ShellExecuteEx(&sei);
		}
		else
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"not try because need be quiet: "+dllPath);
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,QString("regsvr32 terminated with: %1").arg(result));
	correctlyLoaded.remove(dllPath);
	if(!bRegister)
		HardUnloadDLL(dllPath);
	return ok;
}
 WCHAR_Holder(QString s)
     :w(0) {
     w = new WCHAR[s.length()+1];
     s.toWCharArray(w);
     w[s.length()] =0;
 }
Example #18
0
// runProcess: Run a command line process (replacement for QProcess which
// does not exist in the bootstrap library).
bool runProcess(const QString &binary, const QStringList &args,
                const QString &workingDirectory,
                unsigned long *exitCode, QByteArray *stdOut, QByteArray *stdErr,
                QString *errorMessage)
{
    if (exitCode)
        *exitCode = 0;

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    STARTUPINFO myInfo;
    GetStartupInfo(&myInfo);
    si.hStdInput = myInfo.hStdInput;
    si.hStdOutput = myInfo.hStdOutput;
    si.hStdError = myInfo.hStdError;

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    const QChar backSlash = QLatin1Char('\\');
    QString nativeWorkingDir = QDir::toNativeSeparators(workingDirectory.isEmpty() ?  QDir::currentPath() : workingDirectory);
    if (!nativeWorkingDir.endsWith(backSlash))
        nativeWorkingDir += backSlash;

    if (stdOut) {
        si.hStdOutput = createInheritableTemporaryFile();
        if (si.hStdOutput == INVALID_HANDLE_VALUE) {
            if (errorMessage)
                *errorMessage = QStringLiteral("Error creating stdout temporary file");
            return false;
        }
        si.dwFlags |= STARTF_USESTDHANDLES;
    }

    if (stdErr) {
        si.hStdError = createInheritableTemporaryFile();
        if (si.hStdError == INVALID_HANDLE_VALUE) {
            if (errorMessage)
                *errorMessage = QStringLiteral("Error creating stderr temporary file");
            return false;
        }
        si.dwFlags |= STARTF_USESTDHANDLES;
    }

    // Create a copy of the command line which CreateProcessW can modify.
    QString commandLine;
    appendToCommandLine(binary, &commandLine);
    foreach (const QString &a, args)
        appendToCommandLine(a, &commandLine);
    if (optVerboseLevel > 1)
        std::wcout << "Running: " << commandLine << '\n';

    QScopedArrayPointer<wchar_t> commandLineW(new wchar_t[commandLine.size() + 1]);
    commandLine.toWCharArray(commandLineW.data());
    commandLineW[commandLine.size()] = 0;
    if (!CreateProcessW(0, commandLineW.data(), 0, 0, /* InheritHandles */ TRUE, 0, 0,
                        (wchar_t *)nativeWorkingDir.utf16(), &si, &pi)) {
        if (stdOut)
            CloseHandle(si.hStdOutput);
        if (stdErr)
            CloseHandle(si.hStdError);
        if (errorMessage)
            *errorMessage = QStringLiteral("CreateProcessW failed: ") + winErrorMessage(GetLastError());
        return false;
    }

    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hThread);
    if (exitCode)
        GetExitCodeProcess(pi.hProcess, exitCode);
    CloseHandle(pi.hProcess);

    if (stdOut)
        readTemporaryProcessFile(si.hStdOutput, stdOut);
    if (stdErr)
        readTemporaryProcessFile(si.hStdError, stdErr);
    return true;
}
Example #19
0
void ConfigDialog::accept()
{
    m_accepted = true;
    const int currentWindowedResolution = ui->windowedResolutionComboBox->currentIndex();
    config.video.windowedWidth = WindowedModes[currentWindowedResolution].width;
    config.video.windowedHeight = WindowedModes[currentWindowedResolution].height;

    getFullscreenResolutions(ui->fullScreenResolutionComboBox->currentIndex(), config.video.fullscreenWidth, config.video.fullscreenHeight);
    getFullscreenRefreshRate(ui->fullScreenRefreshRateComboBox->currentIndex(), config.video.fullscreenRefresh);

    config.video.multisampling = ui->aliasingSlider->value();
    config.texture.maxAnisotropy = ui->anisotropicSlider->value();
    config.texture.maxBytes = ui->cacheSizeSpinBox->value() * gc_uMegabyte;

    if (ui->blnrStandardRadioButton->isChecked())
        config.texture.bilinearMode = BILINEAR_STANDARD;
    else if (ui->blnr3PointRadioButton->isChecked())
        config.texture.bilinearMode = BILINEAR_3POINT;

    if (ui->bmpRadioButton->isChecked())
        config.texture.screenShotFormat = 0;
    else if (ui->jpegRadioButton->isChecked())
        config.texture.screenShotFormat = 1;

    const int lanuageIndex = ui->translationsComboBox->currentIndex();
    if (lanuageIndex == 0) // English
        config.translationFile.clear();
    else {
        QStringList translationFiles;
        _getTranslations(translationFiles);
        config.translationFile = translationFiles[lanuageIndex-1].toLocal8Bit().constData();
    }

    // Emulation settings
    config.generalEmulation.enableLOD = ui->emulateLodCheckBox->isChecked() ? 1 : 0;
    config.generalEmulation.enableNoise = ui->emulateNoiseCheckBox->isChecked() ? 1 : 0;
    config.generalEmulation.enableFog = ui->emulateFogCheckBox->isChecked() ? 1 : 0;
    config.generalEmulation.enableHWLighting = ui->enableHWLightingCheckBox->isChecked() ? 1 : 0;
    config.generalEmulation.enableShadersStorage = ui->enableShadersStorageCheckBox->isChecked() ? 1 : 0;
    config.generalEmulation.enableCustomSettings = ui->customSettingsCheckBox->isChecked() ? 1 : 0;

    config.frameBufferEmulation.bufferSwapMode = ui->bufferSwapComboBox->currentIndex();
    config.frameBufferEmulation.enable = ui->frameBufferGroupBox->isChecked() ? 1 : 0;
    if (ui->copyBufferDisableRadioButton->isChecked())
        config.frameBufferEmulation.copyToRDRAM = Config::ctDisable;
    else if (ui->copyBufferSyncRadioButton->isChecked())
        config.frameBufferEmulation.copyToRDRAM = Config::ctSync;
    else if (ui->copyBufferAsyncRadioButton->isChecked())
        config.frameBufferEmulation.copyToRDRAM = Config::ctAsync;
    config.frameBufferEmulation.copyFromRDRAM = ui->RenderFBCheckBox->isChecked() ? 1 : 0;
    config.frameBufferEmulation.copyDepthToRDRAM = ui->CopyDepthCheckBox->isChecked() ? 1 : 0;
    config.frameBufferEmulation.N64DepthCompare = ui->n64DepthCompareCheckBox->isChecked() ? 1 : 0;
    if (ui->aspectStretchRadioButton->isChecked())
        config.frameBufferEmulation.aspect = Config::aStretch;
    else if (ui->aspect43RadioButton->isChecked())
        config.frameBufferEmulation.aspect = Config::a43;
    else if (ui->aspect169RadioButton->isChecked())
        config.frameBufferEmulation.aspect = Config::a169;
    else if (ui->aspectAdjustRadioButton->isChecked())
        config.frameBufferEmulation.aspect = Config::aAdjust;

    // Texture filter settings
    config.textureFilter.txFilterMode = ui->filterComboBox->currentIndex();
    config.textureFilter.txEnhancementMode = ui->enhancementComboBox->currentIndex();

    config.textureFilter.txCacheSize = ui->textureFilterCacheSpinBox->value() * gc_uMegabyte;
    config.textureFilter.txFilterIgnoreBG = ui->ignoreBackgroundsCheckBox->isChecked() ? 1 : 0;

    config.textureFilter.txHiresEnable = ui->texturePackGroupBox->isChecked() ? 1 : 0;
    config.textureFilter.txHiresFullAlphaChannel = ui->alphaChannelCheckBox->isChecked() ? 1 : 0;
    config.textureFilter.txHresAltCRC = ui->alternativeCRCCheckBox->isChecked() ? 1 : 0;
    config.textureFilter.txDump = ui->textureDumpCheckBox->isChecked() ? 1 : 0;

    config.textureFilter.txCacheCompression = ui->compressCacheCheckBox->isChecked() ? 1 : 0;
    config.textureFilter.txForce16bpp = ui->force16bppCheckBox->isChecked() ? 1 : 0;
    config.textureFilter.txSaveCache = ui->saveTextureCacheCheckBox->isChecked() ? 1 : 0;

    QString txPath = ui->txPathLabel->text();
    if (!txPath.isEmpty())
        config.textureFilter.txPath[txPath.toWCharArray(config.textureFilter.txPath)] = L'\0';

    config.font.size = m_font.pointSize();
    QString fontName = m_font.family() + ".ttf";
#ifdef OS_WINDOWS
    config.font.name = fontName.toLocal8Bit().constData();
#else
    config.font.name = fontName.toStdString();
#endif
    config.font.color[0] = m_color.red();
    config.font.color[1] = m_color.green();
    config.font.color[2] = m_color.blue();
    config.font.color[3] = m_color.alpha();
    config.font.colorf[0] = m_color.redF();
    config.font.colorf[1] = m_color.greenF();
    config.font.colorf[2] = m_color.blueF();
    config.font.colorf[3] = m_color.alphaF();

    // Post filter settings
    config.bloomFilter.enable = ui->bloomGroupBox->isChecked() ? 1 : 0;
    if (ui->bloomStrongRadioButton->isChecked())
        config.bloomFilter.blendMode = 0;
    else if (ui->bloomMildRadioButton->isChecked())
        config.bloomFilter.blendMode = 1;
    else if (ui->bloomLightRadioButton->isChecked())
        config.bloomFilter.blendMode = 2;
    config.bloomFilter.thresholdLevel = ui->bloomThresholdSlider->value();
    config.bloomFilter.blurAmount = ui->blurAmountSlider->value();
    config.bloomFilter.blurStrength = ui->blurStrengthSlider->value();

    config.gammaCorrection.force = ui->forceGammaCorrectionCheckBox->isChecked() ? 1 : 0;
    config.gammaCorrection.level = ui->gammaLevelSpinBox->value();

    writeSettings(m_strIniPath);

    QDialog::accept();
}
Example #20
0
void PythonContext::GlobalInit()
{
  // must happen on the UI thread
  if(qApp->thread() != QThread::currentThread())
  {
    qFatal("PythonContext::GlobalInit MUST be called from the UI thread");
    return;
  }

  // for the exception signal
  qRegisterMetaType<QList<QString>>("QList<QString>");

  PyImport_AppendInittab("_renderdoc", &PyInit_renderdoc);
  PyImport_AppendInittab("_qrenderdoc", &PyInit_qrenderdoc);

#if defined(STATIC_QRENDERDOC)
  // add the location where our libs will be for statically-linked python installs
  {
    QDir bin = QFileInfo(QCoreApplication::applicationFilePath()).absoluteDir();

    QString pylibs = QDir::cleanPath(bin.absoluteFilePath(lit("../share/renderdoc/pylibs")));

    pylibs.toWCharArray(python_home);

    Py_SetPythonHome(python_home);
  }
#endif

  Py_SetProgramName(program_name);

  Py_Initialize();

  PyEval_InitThreads();

  OutputRedirectorType.tp_name = "renderdoc_output_redirector";
  OutputRedirectorType.tp_basicsize = sizeof(OutputRedirector);
  OutputRedirectorType.tp_flags = Py_TPFLAGS_DEFAULT;
  OutputRedirectorType.tp_doc =
      "Output redirector, to be able to catch output to stdout and stderr";
  OutputRedirectorType.tp_new = PyType_GenericNew;
  OutputRedirectorType.tp_dealloc = &PythonContext::outstream_del;
  OutputRedirectorType.tp_methods = OutputRedirector_methods;

  OutputRedirector_methods[0].ml_meth = &PythonContext::outstream_write;
  OutputRedirector_methods[1].ml_meth = &PythonContext::outstream_flush;

  PyObject *main_module = PyImport_AddModule("__main__");

  PyModule_AddObject(main_module, "renderdoc", PyImport_ImportModule("_renderdoc"));
  PyModule_AddObject(main_module, "qrenderdoc", PyImport_ImportModule("_qrenderdoc"));

  main_dict = PyModule_GetDict(main_module);

  // replace sys.stdout and sys.stderr with our own objects. These have a 'this' pointer of NULL,
  // which then indicates they need to forward to a global object

  // import sys
  PyDict_SetItemString(main_dict, "sys", PyImport_ImportModule("sys"));

  PyObject *rlcompleter = PyImport_ImportModule("rlcompleter");

  if(rlcompleter)
  {
    PyDict_SetItemString(main_dict, "rlcompleter", rlcompleter);
  }
  else
  {
    // ignore a failed import
    PyErr_Clear();
  }

  // sysobj = sys
  PyObject *sysobj = PyDict_GetItemString(main_dict, "sys");

  // sysobj.stdout = renderdoc_output_redirector()
  // sysobj.stderr = renderdoc_output_redirector()
  if(PyType_Ready(&OutputRedirectorType) >= 0)
  {
    // for compatibility with earlier versions of python that took a char * instead of const char *
    char noparams[1] = "";

    PyObject *redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stdout", redirector);

    OutputRedirector *output = (OutputRedirector *)redirector;
    output->isStdError = 0;
    output->context = NULL;

    redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stderr", redirector);

    output = (OutputRedirector *)redirector;
    output->isStdError = 1;
    output->context = NULL;
  }

// if we need to append to sys.path to locate PySide2, do that now
#if defined(PYSIDE2_SYS_PATH)
  {
    PyObject *syspath = PyObject_GetAttrString(sysobj, "path");

#ifndef STRINGIZE
#define STRINGIZE2(a) #a
#define STRINGIZE(a) STRINGIZE2(a)
#endif

    PyObject *str = PyUnicode_FromString(STRINGIZE(PYSIDE2_SYS_PATH));

    PyList_Append(syspath, str);

    Py_DecRef(str);
    Py_DecRef(syspath);
  }
#endif

// set up PySide
#if PYSIDE2_ENABLED
  {
    Shiboken::AutoDecRef core(Shiboken::Module::import("PySide2.QtCore"));
    if(!core.isNull())
      SbkPySide2_QtCoreTypes = Shiboken::Module::getTypes(core);
    else
      qCritical() << "Failed to load PySide2.QtCore";

    Shiboken::AutoDecRef gui(Shiboken::Module::import("PySide2.QtGui"));
    if(!gui.isNull())
      SbkPySide2_QtGuiTypes = Shiboken::Module::getTypes(gui);
    else
      qCritical() << "Failed to load PySide2.QtGui";

    Shiboken::AutoDecRef widgets(Shiboken::Module::import("PySide2.QtWidgets"));
    if(!widgets.isNull())
      SbkPySide2_QtWidgetsTypes = Shiboken::Module::getTypes(widgets);
    else
      qCritical() << "Failed to load PySide2.QtWidgets";
  }
#endif

  // release GIL so that python work can now happen on any thread
  PyEval_SaveThread();
}