Esempio n. 1
0
/**
 * Starts a Cscope build process.
 * @param  conn      A connection object used for reporting progress and data
 * @param  path      The directory to execute under
 * @param  buildArgs Command-line arguments for building the database
 * @throw  Exception
 */
void Cscope::build(Core::Engine::Connection* conn, const QString& path,
                   const QStringList& buildArgs)
{
	// Abort if a process is already running.
	if (state() != QProcess::NotRunning || conn_ != NULL)
		throw Core::Exception("Process already running");

	// TODO: Make the Cscope path configurable.
	QString prog = execPath_;

	// Prepare the argument list.
	QStringList args = buildArgs;
	args << "-b";
	args << "-v";
	setWorkingDirectory(path);

	// Initialise parsing.
	conn_ = conn;
	conn_->setCtrlObject(this);
	setState(buildInitState_);

	// Start the process.
	qDebug() << "Running cscope:" << args << "in" << path;
	start(prog, args);
}
Esempio n. 2
0
void ProcessForker::_launch(const QString& command, const QString& workingDir,
                            const QStringList& env)
{
    for (const auto& var : env)
    {
        // Know Qt bug: QProcess::setProcessEnvironment() does not work with
        // startDetached(). Calling qputenv() directly as a workaround.
        const auto kv = var.split("=");
        if (kv.length() == 2 &&
            !qputenv(kv[0].toLocal8Bit().constData(), kv[1].toLocal8Bit()))
        {
            print_log(LOG_ERROR, LOG_GENERAL, "Setting %s ENV variable failed.",
                      var.toLocal8Bit().constData());
        }
    }

    // forcefully disable touch point compression to ensure every touch point
    // update is received on the QML side (e.g. necessary for the whiteboard).
    // See undocumented QML_NO_TOUCH_COMPRESSION env variable in
    // <qt5-source>/qtdeclarative/src/quick/items/qquickwindow.cpp
    qputenv("QML_NO_TOUCH_COMPRESSION", "1");

    auto process = new QProcess();
    process->setWorkingDirectory(workingDir);
    process->startDetached(command);
}
Esempio n. 3
0
/**
 * Starts a Cscope query process.
 * The process performs a one-time, line-oriented query on the database, without
 * rebuilding it.
 * @param  conn     A connection object used for reporting progress and data
 * @param  path     The directory to execute under
 * @param  type     The type of query to run
 * @param  pattern  The pattern to query
 * @throw  Exception
 */
void Cscope::query(Core::Engine::Connection* conn, const QString& path,
                   QueryType type, const QString& pattern)
{
	// Abort if a process is already running.
	if (state() != QProcess::NotRunning || conn_ != NULL)
		throw Core::Exception("Process already running");

	// Prepare the argument list.
	QStringList args = baseArgs_;
	args << "-d";
	args << "-v";
	args << QString("-L%1").arg(type);
	args << pattern;
	setWorkingDirectory(path);

	// Initialise parsing.
	conn_ = conn;
	conn_->setCtrlObject(this);
	setState(queryProgState_);
	locList_.clear();
	type_ = type;

	// Start the process.
	qDebug() << "Running" << execPath_ << args << "in" << path;
	start(execPath_, args);
}
Esempio n. 4
0
void ScProcess::startLanguage (void)
{
    if (state() != QProcess::NotRunning) {
        statusMessage(tr("Interpreter is already running."));
        return;
    }

    Settings::Manager *settings = Main::settings();
    settings->beginGroup("IDE/interpreter");

    QString workingDirectory = settings->value("runtimeDir").toString();
    QString configFile = settings->value("configFile").toString();

    settings->endGroup();

    QString sclangCommand;
#ifdef Q_OS_MAC
    sclangCommand = standardDirectory(ScResourceDir) + "/../MacOS/sclang";
#else
    sclangCommand = "sclang";
#endif

    QStringList sclangArguments;
    if(!configFile.isEmpty())
        sclangArguments << "-l" << configFile;
    sclangArguments << "-i" << "scqt";

    if(!workingDirectory.isEmpty())
        setWorkingDirectory(workingDirectory);

    QProcess::start(sclangCommand, sclangArguments);
    bool processStarted = QProcess::waitForStarted();
    if (!processStarted)
        emit statusMessage(tr("Failed to start interpreter!"));
}
Esempio n. 5
0
VideoCombiner::VideoCombiner(QObject *parent, const QDir &dir) :
    QProcess(parent)
{
    // Write list file
    QStringList filelist = dir.entryList(QDir::Files, QDir::Name);
    QFile file(dir.filePath("filelist.txt"));
    if (!file.open(QFile::WriteOnly))
    {
        deleteLater();
        return;
    }
    foreach (QString filename, filelist)
        file.write(QString("file '%1'\n").arg(filename).toUtf8());
    file.close();
    // Run FFMPEG
    save_as = dir.absolutePath().section('.', 0, -2) + "(combine)." + dir.absolutePath().section('.', -1);
    QStringList args;
    args << "-f" << "concat" << "-i" << "filelist.txt" << "-c" << "copy" << save_as;
    setWorkingDirectory(dir.absolutePath());
    connect(this, SIGNAL(finished(int)), this, SLOT(onFinished(int)));

#ifdef Q_OS_WIN
    start("ffmpeg.exe", args, QProcess::ReadOnly);
#else
    if (QDir("/usr/share/moonplayer").exists("ffmpeg"))
        start("/usr/share/moonplayer/ffmpeg", args, QProcess::ReadOnly);
    else
        start(QDir::homePath() + "/.moonplayer/ffmpeg", args, QProcess::ReadOnly);
#endif
}
ExtractProcess::ExtractProcess( Project *prj, bool& success, QTextCodec *codec )
 : KProcIO( codec )
{
	success = false;
	// prj mustn't be 0
	if ( !prj ) kdFatal() << "ExtractProcess constructor: prj is null\n";

	setUseShell( true );
	setWorkingDirectory( prj->directory() );
	setComm( KProcess::Stderr );
	enableReadSignals( true );

	// TODO check if cat, tcextract and subtitle2pgm are executable

	*this << "cat";

	uint n = prj->files().count();
	QString file;
	for (uint i = 0; i < n; ++i ) {
		if ( !prj->downloadVob( i, file ) ) return;
		else *this << file;
	}

	*this << "|" << "tcextract" << "-x" << "ps1" << "-t" << "vob" << "-a" << prj->codeLangSelected();
	*this << "|" << "subtitle2pgm" << "-v" << "-P" << "-C" << "1";
	*this << "-c" << prj->coloursString() << "-o" << prj->baseName();

	success = true;
}
Esempio n. 7
0
void MainWindow::readSettings()
{
    QSettings settings;

    move(settings.value("mainWindow/position", pos()).toPoint());
    resize(settings.value("mainWindow/size", size()).toSize());

    setWorkingDirectory(settings.value("workingDirectory", QDir::currentPath()).toString());
}
Esempio n. 8
0
//TODO: add support of URL
void Translator::translateHtml(QString filePath, QDir &docDir)
{
    QFileInfo fileInfo(filePath);
    auto cmd = new QProcess(this);

    QTemporaryFile tmpDoc("document.html");
    cmd->setWorkingDirectory(QDir(DATALOCATION).absoluteFilePath("apertium-all-dev/bin"));
    QStringList args;
    qApp->processEvents();
    //deshtml
#ifdef Q_OS_WIN
    //windows bug with backslash
    //use replace to fix windows bug
    args << "/u" << "/c" << "type" << "\"" + filePath.replace('/', QDir::separator()) + "\""
         << "|" << "apertium-deshtml";
    cmd->setNativeArguments(args.join(' '));
    cmd->start("cmd.exe");
#endif
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    if (!tmpDoc.open()) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    tmpDoc.setTextModeEnabled(true);
    tmpDoc.write(notLinuxTranslate(cmd->readAllStandardOutput()).toUtf8());
    tmpDoc.close();
    //rehtml
    //FIXME: rehtml or rehtml-noent???
    args.clear();
#ifdef Q_OS_WIN
    args << "/u" << "/c" << "type" << "\"" + tmpDoc.fileName().replace('/', QDir::separator()) + "\""
         << "|" << "apertium-rehtml";
    cmd->setNativeArguments(args.join(' '));
    cmd->start("cmd.exe");
#endif
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    QString trFilePath = docDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                 parent->getCurrentSourceLang()
                                                 + "-" + parent->getCurrentTargetLang() + "." + fileInfo.suffix());
    QFile newDoc(trFilePath);
    if (!newDoc.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    newDoc.write(cmd->readAllStandardOutput());
    newDoc.close();
    emit fileTranslated(trFilePath);
    cmd->deleteLater();
    //#else
    //    // cmd->start("ar", QStringList() << "x" << "data.tmp");
    //#endif
}
Esempio n. 9
0
bool MyProcess::launchMe(SCRef runCmd, SCRef buf) {
	arguments = splitArgList(runCmd);
	if (arguments.isEmpty())
		return false;

	setWorkingDirectory(workDir);
	if (!QGit::startProcess(this, arguments, buf, &isWinShell)) {
		sendErrorMsg(true);
		return false;
	}
	return true;
}
Esempio n. 10
0
/**
 * @fn setWorkDirectory
 */
void QueuedProcess::setWorkDirectory(const QString &_workDirectory)
{
    qCDebug(LOG_LIB) << "Set working directory to" << _workDirectory;

    m_definitions.workingDirectory
        = _workDirectory.isEmpty()
              ? QStandardPaths::writableLocation(QStandardPaths::StandardLocation::TempLocation)
              : _workDirectory;
    setLogError("");
    setLogOutput("");
    setWorkingDirectory(m_definitions.workingDirectory);
}
Esempio n. 11
0
bool fixWorkingDirectory() {
   std::string executablePath;
   if (!getExecutablePath(executablePath)) {
      return false;
   }

   std::string executableDir;
   if (!getDirectoryFromPath(executablePath, executableDir)) {
      return false;
   }

   return setWorkingDirectory(executableDir);
}
Esempio n. 12
0
EngineConfiguration::EngineConfiguration(const QVariant& variant)
	: m_variants(QStringList() << "standard"),
	  m_whiteEvalPov(false),
	  m_pondering(false),
	  m_validateClaims(true),
	  m_restartMode(RestartAuto)
{
	const QVariantMap map = variant.toMap();

	setName(map["name"].toString());
	setCommand(map["command"].toString());
	setWorkingDirectory(map["workingDirectory"].toString());
	setStderrFile(map["stderrFile"].toString());
	setProtocol(map["protocol"].toString());

	if (map.contains("initStrings"))
		setInitStrings(map["initStrings"].toStringList());
	if (map.contains("whitepov"))
		setWhiteEvalPov(map["whitepov"].toBool());
	if (map.contains("ponder"))
		setPondering(map["ponder"].toBool());

	if (map.contains("restart"))
	{
		const QString val(map["restart"].toString());
		if (val == "auto")
			setRestartMode(RestartAuto);
		else if (val == "on")
			setRestartMode(RestartOn);
		else if (val == "off")
			setRestartMode(RestartOff);
	}

	if (map.contains("validateClaims"))
		setClaimsValidated(map["validateClaims"].toBool());

	if (map.contains("variants"))
		setSupportedVariants(map["variants"].toStringList());

	if (map.contains("options"))
	{
		const QVariantList optionsList = map["options"].toList();
		EngineOption* option = nullptr;

		foreach (const QVariant& optionVariant, optionsList)
		{
			if ((option = EngineOptionFactory::create(optionVariant.toMap())) != nullptr)
				addOption(option);
		}
	}
}
Esempio n. 13
0
/**
 * Executes the back-end process.
 * @param	sName		The name of the process (for error messages)
 * @param	slArgs		A list containing the command-line arguments
 * @param	sWorkDir	(Optional) working directory
 * @param	bBlock		(Optional) true to block, false otherwise
 * @return	true if the process was executed successfully, false otherwise
 */
bool Frontend::run(const QString& sName, const QStringList& slArgs,
		   const QString& incDirs, const QString& srcDirs,
		   const QString& sWorkDir, bool bBlock)
{
	// Cannot start if another controlled process is currently running
	if (QProcess::state() == QProcess::Running) {
		m_sError = i18n("Cannot restart while another process is still "
			"running");
		return false;
	}

	// Reset variables
	m_nRecords = 0;
	m_bKilled = false;

	// Setup the command-line arguments
	clearProgram();

	if (m_bUseShell)
		// Execute inside a shell; join all arguments in a single QString
		setShellCommand(slArgs.join(" "));
	else
		// Or setup args directly
		setProgram(slArgs);

	// Set the working directory, if requested
	if (!sWorkDir.isEmpty())
		setWorkingDirectory(sWorkDir);

	// Set environment variables (INCLUDEDIRS & SOURCEDIRS) if required
	if (! incDirs.isEmpty()) {
		setEnv("INCLUDEDIRS", incDirs);
	}
	if (! srcDirs.isEmpty()) {
		setEnv("SOURCEDIRS", srcDirs);
	}

	// Execute the child process
	setOutputChannelMode( KProcess::SeparateChannels );
	start();
	if (! ( bBlock ? waitForFinished( -1 ) : waitForStarted ( -1 ))) {
		m_sError = sName + i18n(": Failed to start process");
		return false;
	}

	m_sError = i18n("No error");
	return true;
}
Esempio n. 14
0
bool ProRataParameters::setArguments(  int iArgCount,
		char ** cdpArgValues )
{
	int iOption; 

	// Please not print anything if you find unknown parameters.
	opterr = 0;

	// getopt is from the C function, getopt.c
	// getopt.c is a platform-independent implementation of Linux getopt function 
	while( ( iOption = getopt( iArgCount, cdpArgValues, "w:i:") ) != -1 )
	{
		switch (iOption)
		{
			case 'w':
				sWorkingDirectory = optarg;
				break;  
			case 'i':
				sIDFile = optarg;
				break;
			case '?':
				cout << "WARNING: Ignoring unknown input at"
					<< " the command line." << endl;
				break;
		}
	}

	// if the working directory is not given
	// set it to the default, which is assigned in the constructor
	if( !setWorkingDirectory( sWorkingDirectory ) )
		return false;

	// if the ID file name is not given
	// set it to the default, which is assigned in the constructor
	if( !setIDFile( sIDFile ) )
		return false;
		
	// set the configuration file name to the default
	// and read all configurations into memory
	if( !setConfigFile( sConfigFile ) )
		return false;

	return true;
}
Esempio n. 15
0
TermWidgetImpl::TermWidgetImpl(const QString & wdir, const QString & shell, QWidget * parent)
    : QTermWidget(0, parent)
{
    TermWidgetCount++;
    QString name("TermWidget_%1");
    setObjectName(name.arg(TermWidgetCount));

    setFlowControlEnabled(FLOW_CONTROL_ENABLED);
    setFlowControlWarningEnabled(FLOW_CONTROL_WARNING_ENABLED);

    propertiesChanged();

    setHistorySize(5000);

    if (!wdir.isNull())
        setWorkingDirectory(wdir);

    if (shell.isNull())
    {
        if (!Properties::Instance()->shell.isNull())
            setShellProgram(Properties::Instance()->shell);
    }
    else
    {
        qDebug() << "Settings custom shell program:" << shell;
        QStringList parts = shell.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        qDebug() << parts;
        setShellProgram(parts.at(0));
        parts.removeAt(0);
        if (parts.count())
            setArgs(parts);
    }

    setMotionAfterPasting(Properties::Instance()->m_motionAfterPaste);

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(customContextMenuCall(const QPoint &)));

    connect(this, SIGNAL(urlActivated(QUrl)), this, SLOT(activateUrl(const QUrl&)));

    startShellProgram();
}
Esempio n. 16
0
/*!
 * \brief Translating txt files not on Linux.
 *
 * \warning There are some problems with translating of documents
 * on Windows platform. All document translation functions should be rewrited.
 */
void Translator::translateTxt(QString filePath, QDir &docDir)
{
    QFile f(filePath);
    QFileInfo fileInfo(filePath);
    QTemporaryFile tmpDoc(fileInfo.baseName());
    auto cmd = new QProcess(this);
#ifdef Q_OS_WIN
    cmd->setWorkingDirectory(QDir(DATALOCATION).absoluteFilePath("apertium-all-dev/bin"));
#endif
    qApp->processEvents();
    //destxt
    cmd->start("cmd.exe", QStringList() << "/u" << "/c" << "type" << "\"" + filePath.replace('/',
                                                                                             QDir::separator()) + "\""
               << "|" << "apertium-destxt");
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    if (!tmpDoc.open()) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    tmpDoc.setTextModeEnabled(true);
    tmpDoc.write(notLinuxTranslate(cmd->readAllStandardOutput()).toUtf8());
    //retxt
    cmd->start("cmd.exe", QStringList() << "/u" << "/c" << "type" << "\"" +
               tmpDoc.fileName().replace('/', QDir::separator())
               + "\"" << "|" << "apertium-retxt");
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    QString trFilePath = docDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                 parent->getCurrentSourceLang()
                                                 + "-" + parent->getCurrentTargetLang() + "." + fileInfo.suffix());
    QFile newDoc(trFilePath);
    if (!newDoc.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    newDoc.write(cmd->readAllStandardOutput());
    newDoc.close();
    emit fileTranslated(trFilePath);
    cmd->deleteLater();
}
Esempio n. 17
0
bool DataLoader::start(SCList args, SCRef wd, SCRef buf) {

	if (!isProcExited) {
		dbs("ASSERT in DataLoader::start(), called while processing");
		return false;
	}
	isProcExited = false;
	setWorkingDirectory(wd);

	connect(this, SIGNAL(finished(int, QProcess::ExitStatus)),
	        this, SLOT(on_finished(int, QProcess::ExitStatus)));

	if (!createTemporaryFile() || !QGit::startProcess(this, args, buf)) {
		deleteLater();
		return false;
	}
	loadTime.start();
	guiUpdateTimer.start(GUI_UPDATE_INTERVAL);
	return true;
}
Esempio n. 18
0
void MainWindow::openWorkingDirectoryPrompt()
{
    QFileDialog dialog(this);

    dialog.setFileMode(QFileDialog::Directory);

    qDebug() << workingDirectory;

    dialog.setDirectory(workingDirectory);

    QStringList fileNames;
    if (dialog.exec())
    {
        fileNames = dialog.selectedFiles();

        if (fileNames.size() == 1)
            setWorkingDirectory(fileNames[0]);
    }

}
Esempio n. 19
0
/**
 * Executes the back-end process.
 * @param	sName		The name of the process (for error messages)
 * @param	slArgs		A list containing the command-line arguments
 * @param	sWorkDir	(Optional) working directory
 * @param	bBlock		(Optional) true to block, false otherwise
 * @return	true if the process was executed successfully, false otherwise
 */
bool Frontend::run(const QString& sName, const QStringList& slArgs, 
	const QString& sWorkDir, bool bBlock)
{
	// Cannot start if another controlled process is currently running
	if (state() == QProcess::Running) {
		m_sError = i18n("Cannot restart while another process is still "
			"running");
		return false;
	}

	// Reset variables
	m_nRecords = 0;
	m_bKilled = false;
	
    clearEnvironment(); // TODO: to check if this call is needed
	// Setup the command-line arguments
	clearProgram();
	*this << slArgs;

	// Set the working directory, if requested
	if (!sWorkDir.isEmpty())
		setWorkingDirectory(sWorkDir);

	// Execute the child process
    bool ret = true;
    if (bBlock) {
        if (execute() < 0)
            ret = false;
    } else {
        start();
    }
    if (!ret) {
		m_sError = sName + i18n(": Failed to start process");
		return false;
	}
	
	m_sError = i18n("No error");
	return true;
}
Esempio n. 20
0
void Translator::translateXlsx(QString filePath, QDir &docDir)
{
    QFileInfo fileInfo(filePath);
    QTemporaryDir dir(docDir.absoluteFilePath(fileInfo.baseName() + ".XXXXXX"));
    auto cmd = new QProcess(this);
    QDir exep (qApp->applicationDirPath());
#ifndef Q_OS_LINUX
    cmd->start(exep.absoluteFilePath("7z"), QStringList() << "t" << fileInfo.absoluteFilePath());
#endif
    cmd->waitForReadyRead();
    QString res = cmd->readAllStandardOutput();
    if (res.contains("ERROR")) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    cmd->waitForFinished();
    cmd->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << fileInfo.absoluteFilePath()
               << "-o" + dir.path());
    cmd->waitForReadyRead();
    cmd->waitForFinished();
    QStringList args;
    //for (QString sheetName : sheetDir.entryList(QStringList() << "sheet*.xml")) {
    QFile sheet (QDir(dir.path() + "/xl").absoluteFilePath("sharedStrings.xml"));
    QTemporaryFile tmpSheet(sheet.fileName());
    cmd->setWorkingDirectory(QDir(DATALOCATION).absoluteFilePath("apertium-all-dev/bin"));

    qApp->processEvents();
    //desxlsx
    args << "/u" << "/c" << "type" << "\"" + sheet.fileName().replace('/', QDir::separator()) + "\""
         << "|" << "apertium-desxlsx";
    cmd->setNativeArguments(args.join(' '));
    args.clear();
    cmd->start("cmd.exe");
    cmd->waitForReadyRead();
    cmd->waitForFinished();
    if (!tmpSheet.open()) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    tmpSheet.setTextModeEnabled(true);
    tmpSheet.write(notLinuxTranslate(cmd->readAllStandardOutput()).toUtf8());
    tmpSheet.close();
    //rexlsx
    args << "/u" << "/c" << "type" << "\"" + tmpSheet.fileName().replace('/', QDir::separator()) + "\""
         << "|" << "apertium-rexlsx";
    cmd->setNativeArguments(args.join(" "));
    args.clear();
    cmd->start("cmd.exe");
    cmd->waitForReadyRead();
    if (!sheet.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    sheet.write(cmd->readAllStandardOutput());
    cmd->waitForFinished();

    sheet.close();
    cmd->setWorkingDirectory(dir.path());
    QString trFilePath = docDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                 parent->getCurrentSourceLang()
                                                 + "-" + parent->getCurrentTargetLang() + "." + fileInfo.suffix());
    QFile(trFilePath).remove();
    args << "a" << "-tzip" << "-y"
         << "\"" + trFilePath + "\""
         << "\"" + dir.path() + "/*\"";
    cmd->setNativeArguments(args.join(' '));
    cmd->start(exep.absoluteFilePath("7z"));
    cmd->waitForFinished();
    emit fileTranslated(trFilePath);
    cmd->deleteLater();
}
Esempio n. 21
0
void Application::start(void)
{
	PROFILE;

    TRACE("Starting application...");

    /* Preferably, the share directory is specified in an environment variable.
	 * We'll set this to our working directory.
	 * XXX: We don't want to write files to the share directory!
	 */
	{
		const char * share;

		share = getenv("ARBARLITH2_SHARE");

		if(!share) {
			setWorkingDirectory(getApplicationDirectory());
		} else {
			setWorkingDirectory(share);
		}
	}

	// Parse the setup files
	loadXmlConfigFiles();

	// Initialize APIs
	startOpenGL();
	startDevIL();

	// Create the effect manager
	EffectManager::GetSingleton().create();

	// Load the font setup file
	loadFonts();

	// Load the key bindings
	TRACE("Loading controller bindings...");
	new Controller();
	TRACE("...Loaded controller bindings");

	// Seed the random number generator
	TRACE("Seeding the random number generator...");
	srand(SDL_GetTicks());
	TRACE("...Seeded the random number generator");

	// Do the splash screen
	{
		TRACE("Doing splash screen...");
		SplashScreen splashScreen;
		splashScreen.doSplash(5000);
		TRACE("...Finished with splash screen");
	}

	// Initialize the wait screen
	new WaitScreen();
	g_WaitScreen.Render();
	TRACE("Wait screen started.");

	// Create the frame timer
	TRACE("Creating the frame timer...");
	fme = new NeHe::Frame();
	TRACE("...Created the frame timer");

	// Create the sound manager
	soundSystem = new SoundSystem();
	soundSystem->create();
	TRACE("Sound system initialized");

	// Prepare handlers for various key press events
	addTask(new ScreenShotTask);
	TRACE("Started screen shot task");

	addTask(new EditorKeyDetector);
	TRACE("Started editor hotkey task");

	addTask(new MenuKeyDetector);
	TRACE("Started menu hotkey task");

	addTask(new SpellMenuKeyDetector);
	TRACE("Started spell-menu hotkey task");

	addTask(new DebugDisplayToggleKeyDetector(*this));
	TRACE("Started debug-info hotkey task");

	addTask(new FPSDisplayToggleKeyDetector);
	TRACE("Started FPS-display hotkey task");


	// Create a task to handle the GUI
	new WidgetManager;
	TRACE("Started the game GUI task");
	g_WaitScreen.Render();

	// Start the profiler system
#ifdef ENABLE_PROFILER
	Profiler::ProfileInit();
	addTask(makePeriodicCallbackTask(500.0f,
                                     &Profiler::ProfileDumpOutputToBuffer));
	TRACE("Started the game profiler task");
	g_WaitScreen.Render();
#endif

	// set up the game states
	TRACE("Creating game state objects...");
	{
		states[GAME_STATE_RUN] = new GameStateRun(*this);
		TRACE("...created GameStateRun...");

		states[GAME_STATE_EDITOR] = new GameStateEditor(*this);
		TRACE("...created GameStateEditor...");

		states[GAME_STATE_MENU] = new GameStateMenu(*this);
		TRACE("...created GameStateMenu...");

		states[GAME_STATE_SPELL_MENU] = new GameStateSpellMenu(*this);
		TRACE("...created GameStateSpellMenu...");

		states[GAME_STATE_CREDITS] = new GameStateCredits(*this);
		TRACE("...created GameStateCredits...");
	}
	TRACE("...finished (Creating game state objects)");

	TRACE("Entering the menu game state...");
	gameState = GAME_STATE_MENU;
	states[GAME_STATE_MENU]->onEnter();
	TRACE("...finished (Entering the menu game state)");

	// Complete
	TRACE("...Finished starting up");
	g_WaitScreen.Render();
}
Esempio n. 22
0
void Action::start()
{
    closeSubCommands();

    if ( m_currentLine + 1 >= m_cmds.size() ) {
        finish();
        return;
    }

    ++m_currentLine;
    const QList<QStringList> &cmds = m_cmds[m_currentLine];

    Q_ASSERT( !cmds.isEmpty() );

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (m_id != -1)
        env.insert("COPYQ_ACTION_ID", QString::number(m_id));
    if ( !m_name.isEmpty() )
        env.insert("COPYQ_ACTION_NAME", m_name);

    for (int i = 0; i < cmds.size(); ++i) {
        auto process = new QProcess(this);
        m_processes.push_back(process);
        process->setProcessEnvironment(env);
        if ( !m_workingDirectoryPath.isEmpty() )
            process->setWorkingDirectory(m_workingDirectoryPath);

        connectProcessError(process, this, &Action::onSubProcessError);
        connect( process, &QProcess::readyReadStandardError,
                 this, &Action::onSubProcessErrorOutput );
    }

    pipeThroughProcesses(m_processes.begin(), m_processes.end());

    QProcess *lastProcess = m_processes.back();
    connect( lastProcess, &QProcess::started,
             this, &Action::onSubProcessStarted );
    connectProcessFinished( lastProcess, this, &Action::onSubProcessFinished );
    connect( lastProcess, &QProcess::readyReadStandardOutput,
             this, &Action::onSubProcessOutput );

    // Writing directly to stdin of a process on Windows can hang the app.
    QProcess *firstProcess = m_processes.front();
    connect( firstProcess, &QProcess::started,
             this, &Action::writeInput, Qt::QueuedConnection );
    connect( firstProcess, &QProcess::bytesWritten,
             this, &Action::onBytesWritten, Qt::QueuedConnection );

    const bool needWrite = !m_input.isEmpty();
    if (m_processes.size() == 1) {
        const auto mode =
                (needWrite && m_readOutput) ? QIODevice::ReadWrite
              : needWrite ? QIODevice::WriteOnly
              : m_readOutput ? QIODevice::ReadOnly
              : QIODevice::NotOpen;
        startProcess(firstProcess, cmds.first(), mode);
    } else {
        auto it = m_processes.begin();
        auto cmdIt = cmds.constBegin();
        startProcess(*it, *cmdIt, needWrite ? QIODevice::ReadWrite : QIODevice::ReadOnly);
        for (++it, ++cmdIt; it != m_processes.end() - 1; ++it, ++cmdIt)
            startProcess(*it, *cmdIt, QIODevice::ReadWrite);
        startProcess(lastProcess, cmds.last(), m_readOutput ? QIODevice::ReadWrite : QIODevice::WriteOnly);
    }
}
void DataSourceView::showContextMenu(const QPoint &point)
{
	QModelIndex i = currentIndex();

	if (!i.isValid())
		return;

	QMenu *menu = new QMenu(this);

	menu->addAction(style()->standardIcon(QStyle::SP_DirOpenIcon), tr("Open"), this, SLOT(indexOpenPath()));
	menu->addAction(QIcon(":/gfx/tab-new.png"), tr("Open in a new tab"), this, SLOT(openInANewTab()));
	menu->addAction(QIcon(":/gfx/gohome.png"), tr("Set as working directory"), this, SLOT(setWorkingDirectory()));
	menu->addAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder), tr("Create directory"), this, SLOT(createDirectory()));

	menu->addSeparator();

	menu->addAction(QIcon(":/gfx/document-edit.png"), tr("Edit"), this, SLOT(editDirectory()));
	menu->addAction(QIcon(":/gfx/list-remove.png"), tr("Delete"), this, SLOT(deleteDirectory()));

	menu->addSeparator();

	m_signalMapper->setMapping(menu->addAction(QIcon(":/gfx/external_programs/ZIMA-PTC-Cleaner.png"), tr("Clean with ZIMA-PTC-Cleaner"), m_signalMapper, SLOT(map())),
	                           ZimaUtils::internalNameForUtility(ZimaUtils::ZimaPtcCleaner));
	m_signalMapper->setMapping(menu->addAction(QIcon(":/gfx/external_programs/ZIMA-CAD-Sync.png"), tr("Sync with ZIMA-CAD-Sync"), m_signalMapper, SLOT(map())),
	                           ZimaUtils::internalNameForUtility(ZimaUtils::ZimaCadSync));
	m_signalMapper->setMapping(menu->addAction(QIcon(":/gfx/external_programs/ZIMA-PS2PDF.png"), tr("Convert postscript to PDF with ZIMA-PS2PDF"), m_signalMapper, SLOT(map())),
	                           ZimaUtils::internalNameForUtility(ZimaUtils::ZimaPs2Pdf));
	m_signalMapper->setMapping(menu->addAction(QIcon(":/gfx/external_programs/ZIMA-STEP-Edit.png"), tr("Edit step files with ZIMA-STEP-Edit"), m_signalMapper, SLOT(map())),
	                           ZimaUtils::internalNameForUtility(ZimaUtils::ZimaStepEdit));

	menu->exec(mapToGlobal(point));
	menu->deleteLater();
}
Esempio n. 24
0
void Translator::translateDocx(QString filePath, QDir &docDir)
{
    QFileInfo fileInfo(filePath);
    QTemporaryDir dir(docDir.absoluteFilePath(fileInfo.baseName() + ".XXXXXX"));
    auto cmd = new QProcess(this);
    QDir exep (qApp->applicationDirPath());
    cmd->start(exep.absoluteFilePath("7z"), QStringList() << "t" << fileInfo.absoluteFilePath());
    cmd->waitForReadyRead();
    if (cmd->readAllStandardOutput().contains("ERROR")) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    cmd->waitForFinished();
    cmd->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << fileInfo.absoluteFilePath()
               << "-o" + dir.path());
    cmd->waitForReadyRead();
    cmd->waitForFinished();

    QTemporaryFile tmpDoc("document.xml");
    QFile doc(dir.path() + "/word/document.xml");
    cmd->setWorkingDirectory(QDir(DATALOCATION).absoluteFilePath("apertium-all-dev/bin"));
    QStringList args;
    qApp->processEvents();
    //deswxml
#ifdef Q_OS_WIN
    //windows bug with backslash
    //use replace to fix windows bug
    args << "/u" << "/c" << "type" << "\"" + doc.fileName().replace('/', QDir::separator()) + "\""
         << "|" << "apertium-deswxml";
    cmd->setNativeArguments(args.join(' '));
    cmd->start("cmd.exe");
#endif
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    if (!tmpDoc.open()) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    tmpDoc.setTextModeEnabled(true);
    tmpDoc.write(notLinuxTranslate(cmd->readAllStandardOutput()).toUtf8());
    tmpDoc.close();
    //rewxml
    args.clear();
#ifdef Q_OS_WIN
    args << "/u" << "/c" << "type" << "\"" + tmpDoc.fileName().replace('/', QDir::separator()) + "\""
         << "|" << "apertium-rewxml";
    cmd->setNativeArguments(args.join(' '));
    cmd->start("cmd.exe");
#endif
    cmd->waitForFinished();
    cmd->waitForReadyRead();
    if (!doc.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
        emit fileTranslateRejected();
        cmd->deleteLater();
        return;
    }
    doc.write(cmd->readAllStandardOutput());
    doc.close();
    cmd->setWorkingDirectory(dir.path());
    QString trFilePath = docDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                 parent->getCurrentSourceLang()
                                                 + "-" + parent->getCurrentTargetLang() + "." + fileInfo.suffix());
    cmd->start(exep.absoluteFilePath("7z"), QStringList() << "a" << "-tzip" << "-y"
               << trFilePath << dir.path() + "/*");
    cmd->waitForFinished();
    emit fileTranslated(trFilePath);
    cmd->deleteLater();
}
Esempio n. 25
0
TermWidgetImpl::TermWidgetImpl(const QString & wdir, const QString & shell, QWidget * parent)
    : QTermWidget(0, parent)
{
    TermWidgetCount++;
    QString name("TermWidget_%1");
    setObjectName(name.arg(TermWidgetCount));

    setFlowControlEnabled(FLOW_CONTROL_ENABLED);
    setFlowControlWarningEnabled(FLOW_CONTROL_WARNING_ENABLED);

    propertiesChanged();

    setHistorySize(5000);

    if (!wdir.isNull())
        setWorkingDirectory(wdir);

    if (shell.isNull())
    {
        if (!Properties::Instance()->shell.isNull())
            setShellProgram(Properties::Instance()->shell);
    }
    else
    {
        qDebug() << "Settings custom shell program:" << shell;
        QStringList parts = shell.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        qDebug() << parts;
        setShellProgram(parts.at(0));
        parts.removeAt(0);
        if (parts.count())
            setArgs(parts);
    }

    setMotionAfterPasting(Properties::Instance()->m_motionAfterPaste);
    
    actionMap[COPY_SELECTION] = new QAction(QIcon(":/icons/edit-copy.png"), tr(COPY_SELECTION), this);
    connect(actionMap[COPY_SELECTION], SIGNAL(triggered()), this, SLOT(copyClipboard()));
    addAction(actionMap[COPY_SELECTION]);

    actionMap[PASTE_CLIPBOARD] = new QAction(QIcon(":/icons/edit-paste.png"), tr(PASTE_CLIPBOARD), this);
    connect(actionMap[PASTE_CLIPBOARD], SIGNAL(triggered()), this, SLOT(pasteClipboard()));
    addAction(actionMap[PASTE_CLIPBOARD]);

    actionMap[PASTE_SELECTION] = new QAction(QIcon(":/icons/edit-paste.png"), tr(PASTE_SELECTION), this);
    connect(actionMap[PASTE_SELECTION], SIGNAL(triggered()), this, SLOT(pasteSelection()));
    addAction(actionMap[PASTE_SELECTION]);

    actionMap[ZOOM_IN] = new QAction(QIcon(":/icons/zoom-in.png"), tr(ZOOM_IN), this);
    connect(actionMap[ZOOM_IN], SIGNAL(triggered()), this, SLOT(zoomIn()));
    addAction(actionMap[ZOOM_IN]);

    actionMap[ZOOM_OUT] = new QAction(QIcon(":/icons/zoom-out.png"), tr(ZOOM_OUT), this);
    connect(actionMap[ZOOM_OUT], SIGNAL(triggered()), this, SLOT(zoomOut()));
    addAction(actionMap[ZOOM_OUT]);

    actionMap[ZOOM_RESET] = new QAction(QIcon(":/icons/zoom-out.png"), tr(ZOOM_RESET), this);
    connect(actionMap[ZOOM_RESET], SIGNAL(triggered()), this, SLOT(zoomReset()));
    addAction(actionMap[ZOOM_RESET]);

    QAction *act = new QAction(this);
    act->setSeparator(true);
    addAction(act);

    actionMap[CLEAR_TERMINAL] = new QAction(tr(CLEAR_TERMINAL), this);
    connect(actionMap[CLEAR_TERMINAL], SIGNAL(triggered()), this, SLOT(clear()));
    addAction(actionMap[CLEAR_TERMINAL]);

    actionMap[SPLIT_HORIZONTAL] = new QAction(tr(SPLIT_HORIZONTAL), this);
    connect(actionMap[SPLIT_HORIZONTAL], SIGNAL(triggered()), this, SLOT(act_splitHorizontal()));
    addAction(actionMap[SPLIT_HORIZONTAL]);

    actionMap[SPLIT_VERTICAL] = new QAction(tr(SPLIT_VERTICAL), this);
    connect(actionMap[SPLIT_VERTICAL], SIGNAL(triggered()), this, SLOT(act_splitVertical()));
    addAction(actionMap[SPLIT_VERTICAL]);

    actionMap[SUB_COLLAPSE] = new QAction(tr(SUB_COLLAPSE), this);
    connect(actionMap[SUB_COLLAPSE], SIGNAL(triggered()), this, SLOT(act_splitCollapse()));
    addAction(actionMap[SUB_COLLAPSE]);

    //act = new QAction(this);
    //act->setSeparator(true);
    //addAction(act);
    //
    //act = new QAction(tr("&Rename session..."), this);
    //act->setShortcut(Properties::Instance()->shortcuts[RENAME_SESSION]);
    //connect(act, SIGNAL(triggered()), this, SIGNAL(renameSession()));
    //addAction(act);

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(customContextMenuCall(const QPoint &)));

    updateShortcuts();

    //setKeyBindings("linux");
    startShellProgram();
}