Example #1
0
/*!
    Constructs a new IrcSender initialized to \a prefix.
 */
IrcSender::IrcSender(const QString& prefix) : d(new IrcSenderPrivate)
{
    d->dirty = false;
    d->prefix = prefix.trimmed();
}
void AsciiOpenDlg::updateTable()
{
	m_ui->tableWidget->setEnabled(false);
	m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);

	bool hadValidHeader = !m_headerLine.isEmpty();
	m_headerLine.clear();

	if (m_filename.isEmpty())
	{
		m_ui->tableWidget->clear();
		return;
	}
	//we open the file in ASCII mode
	QFile file(m_filename);
	if (!file.open(QFile::ReadOnly))
	{
		m_ui->tableWidget->clear();
		m_columnsValidty.clear();
		return;
	}
	QTextStream stream(&file);

	//we skip first lines (if needed)
	{
		for (unsigned i=0; i<m_skippedLines; ++i)
		{
			QString currentLine = stream.readLine();
			//we keep track of the first line
			if (i == 0)
				m_headerLine = currentLine;
		}
	}

	//if the old setup has less than 3 columns, we forget it
	if (m_columnsCount < 3)
	{
		m_ui->tableWidget->clear();
		m_columnsCount = 0;
	}
	m_ui->tableWidget->setRowCount(DISPLAYED_LINES+1);    //+1 for first line shifting

	unsigned lineCount = 0;			//number of lines read
	unsigned totalChars = 0;		//total read characters (for stats)
	unsigned columnsCount = 0;		//max columns count per line
	unsigned commentLines = 0;		//number of comments line skipped

	std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
	std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
	std::vector<bool> valueIsInteger;	//identifies columns with integer values only
	std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

	QString currentLine = stream.readLine();
	while (lineCount < LINES_READ_FOR_STATS && !currentLine.isNull())
	{
		//we recognize "//" as the beginning of a comment
		if (!currentLine.startsWith("//"))
		{
			QStringList parts = currentLine.trimmed().split(m_separator,QString::SkipEmptyParts);
			unsigned partsCount = static_cast<unsigned>(parts.size());
			if (partsCount > MAX_COLUMNS)
				partsCount = MAX_COLUMNS;

			if (lineCount < DISPLAYED_LINES)
			{
				//do we need to add one or several new columns?
				{
					if (partsCount > columnsCount)
					{
						//we also extend vectors
						for (unsigned i=columnsCount; i<partsCount; ++i)
						{
							valueIsNumber.push_back(true);
							valueIsBelowOne.push_back(true);
							valueIsBelow255.push_back(true);
							valueIsInteger.push_back(true);
						}

						m_ui->tableWidget->setColumnCount(partsCount);
						columnsCount = partsCount;
					}
				}

				//we fill the current row with extracted parts
				{
					for (unsigned i=0; i<partsCount; ++i)
					{
						QTableWidgetItem *newItem = new QTableWidgetItem(parts[i]);

						//test values
						bool isANumber = false;
						double value = parts[i].toDouble(&isANumber);
						if (!isANumber)
						{
							valueIsNumber[i]	= false;
							valueIsBelowOne[i]	= false;
							valueIsInteger[i]	= false;
							valueIsBelow255[i]	= false;
							newItem->setBackground(QBrush(QColor(255,160,160)));
						}
						else
						{
							double intPart, fracPart;
							fracPart = modf(value,&intPart);

							valueIsBelowOne[i]	= valueIsBelowOne[i] && (fabs(value) <= 1.0);
							valueIsInteger[i]	= valueIsInteger[i] && (fracPart == 0.0);
							valueIsBelow255[i]	= valueIsBelow255[i] && (valueIsInteger[i] && (intPart >= 0.0 && value <= 255.0));
						}

						m_ui->tableWidget->setItem(lineCount+1, i, newItem); //+1 for first line shifting
					}
				}
			}

			totalChars += currentLine.size() + 1; //+1 for return char at eol

			++lineCount;
		}
		else
		{
			if (m_skippedLines == 0 && commentLines == 0)
			{
				//if the very first line is a comment, then we force the user to skip it!
				//this way it will be considered as a header
				m_ui->spinBoxSkipLines->setMinimum(1);
				return;
			}
			++commentLines;
		}

		//read next line
		currentLine = stream.readLine();
	}

	file.close();

	//process header line
	if (!m_headerLine.isEmpty())
	{
		m_headerLine = m_headerLine.trimmed();
		int n = 0;
		while (n < m_headerLine.size() && m_headerLine.at(n) == '/')
			++n;
		if (n != 0)
			m_headerLine.remove(0,n);
		m_ui->headerLabel->setText(QString("Header: ")+m_headerLine);
		m_ui->headerLabel->setVisible(true);
	}
	else
	{
		m_ui->headerLabel->setVisible(false);
	}

	m_ui->commentLinesSkippedLabel->setVisible(commentLines != 0);
	if (commentLines)
		m_ui->commentLinesSkippedLabel->setText(QString("+ %1 comment line(s) skipped").arg(commentLines));

	if (lineCount == 0 || columnsCount == 0)
	{
		m_averageLineSize = -1.0;
		m_ui->tableWidget->clear();
		m_columnsValidty.clear();
		return;
	}

	//average line size
	m_averageLineSize = double(totalChars)/double(lineCount);

	//we add a type selector for each column
	QStringList propsText;
	{
		for (unsigned i=0; i<ASCII_OPEN_DLG_TYPES_NUMBER; i++)
			propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);
	}

	//remove unnecessary columns
	{
		while (columnsCount < m_columnsCount)
			m_ui->tableWidget->removeColumn(--m_columnsCount);
		if (m_columnsValidty.size() > columnsCount)
			m_columnsValidty.resize(columnsCount);
		for (unsigned i=lineCount+1; i<=DISPLAYED_LINES; ++i)
			m_ui->tableWidget->removeRow(i);
	}

	//setup table and widgets
	{
		//Icons
		static const QIcon xIcon		(QString::fromUtf8(":/CC/images/typeXCoordinate.png"));
		static const QIcon yIcon		(QString::fromUtf8(":/CC/images/typeYCoordinate.png"));
		static const QIcon zIcon		(QString::fromUtf8(":/CC/images/typeZCoordinate.png"));
		static const QIcon NormIcon		(QString::fromUtf8(":/CC/images/typeNormal.png"));
		static const QIcon RGBIcon		(QString::fromUtf8(":/CC/images/typeRgbCcolor.png"));
		static const QIcon GreyIcon		(QString::fromUtf8(":/CC/images/typeGrayColor.png"));
		static const QIcon ScalarIcon	(QString::fromUtf8(":/CC/images/typeSF.png"));

		int columnWidth = (m_ui->tableWidget->width()*9) / (columnsCount*10);
		columnWidth = std::max(columnWidth,80);

		for (unsigned i=0; i<columnsCount; i++)
		{
			QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0,i));
			QComboBox* _columnHeader = columnHeaderWidget;
			if (!columnHeaderWidget)
			{
				columnHeaderWidget = new QComboBox();
				columnHeaderWidget->addItems(propsText);
				columnHeaderWidget->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_NUMBER);
				columnHeaderWidget->setCurrentIndex(0);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_X,xIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Y,yIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Z,zIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NX,NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NY,NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NZ,NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_R,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_G,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_B,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Rf,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Gf,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Bf,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Grey,GreyIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Scalar,ScalarIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32i,RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32f,RGBIcon);

				connect(columnHeaderWidget, SIGNAL(currentIndexChanged(int)), this, SLOT(columnsTypeHasChanged(int)));
			}

			while (m_columnsValidty.size() <= static_cast<size_t>(i))
				m_columnsValidty.push_back(false);
			assert(m_columnsValidty.size() >= static_cast<size_t>(i));

			if (!_columnHeader)
				m_ui->tableWidget->setCellWidget(0,i,columnHeaderWidget);
			m_ui->tableWidget->setColumnWidth(i,columnWidth);

			//a non-numerical column can't be valid
			if (!valueIsNumber[i])
				m_columnsValidty[i] = false;
		}
	}
 void handleWorkingDirChanged(const QString &wd) {
     m_runConfig->setWorkingDirectory(wd.trimmed());
 }
Example #4
0
void UpdateChecker::runUpdateCheck()
{
	m_networkReply->deleteLater();

	if (m_networkReply->error() != QNetworkReply::NoError)
	{
		Console::addMessage(QCoreApplication::translate("main", "Unable to check for updates: %1").arg(m_networkReply->errorString()), Console::OtherCategory, Console::ErrorLevel);

		deleteLater();

		return;
	}

	QStringList activeChannels(SettingsManager::getValue(SettingsManager::Updates_ActiveChannelsOption).toStringList());
	activeChannels.removeAll(QString());

	const QJsonObject updateData(QJsonDocument::fromJson(m_networkReply->readAll()).object());
	const QJsonArray channels(updateData.value(QLatin1String("channels")).toArray());
	const QString platform(Application::getPlatformIntegration()->getPlatform());
	const int mainVersion(QCoreApplication::applicationVersion().remove(QChar('.')).toInt());
	const int subVersion(QString(OTTER_VERSION_WEEKLY).toInt());
	QList<UpdateInformation> availableUpdates;

	for (int i = 0; i < channels.count(); ++i)
	{
		if (channels.at(i).isObject())
		{
			const QJsonObject object(channels.at(i).toObject());
			const QString identifier(object[QLatin1String("identifier")].toString());
			const QString channelVersion(object[QLatin1String("version")].toString());

			if (activeChannels.contains(identifier, Qt::CaseInsensitive) || (!m_isInBackground && activeChannels.isEmpty()))
			{
				const int channelMainVersion(channelVersion.trimmed().remove(QChar('.')).toInt());

				if (channelMainVersion == 0)
				{
					Console::addMessage(QCoreApplication::translate("main", "Unable to parse version number: %1").arg(channelVersion), Console::OtherCategory, Console::ErrorLevel);

					continue;
				}

				const int channelSubVersion(object[QLatin1String("subVersion")].toString().toInt());

				if (mainVersion < channelMainVersion || (subVersion > 0 && subVersion < channelSubVersion))
				{
					UpdateInformation information;
					information.channel = identifier;
					information.version = channelVersion;
					information.isAvailable = object[QLatin1String("availablePlatforms")].toArray().contains(QJsonValue(platform));
					information.detailsUrl = QUrl(object[QLatin1String("detailsUrl")].toString());
					information.scriptUrl = QUrl(object[QLatin1String("scriptUrl")].toString().replace(QLatin1String("%VERSION%"), channelVersion).replace(QLatin1String("%PLATFORM%"), platform));
					information.fileUrl = QUrl(object[QLatin1String("fileUrl")].toString().replace(QLatin1String("%VERSION%"), channelVersion).replace(QLatin1String("%PLATFORM%"), platform).replace(QLatin1String("%TIMESTAMP%"), QString::number(QDateTime::currentDateTime().toUTC().toTime_t())));

					if (!object[QLatin1String("subVersion")].toString().isEmpty())
					{
						information.version.append(QLatin1Char('#') + object[QLatin1String("subVersion")].toString());
					}

					availableUpdates.append(information);
				}
			}
		}
	}

	SettingsManager::setValue(SettingsManager::Updates_LastCheckOption, QDate::currentDate().toString(Qt::ISODate));

	emit finished(availableUpdates);

	deleteLater();
}
Example #5
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  QString company;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    haveRequireSSL  = false;
  bool    _requireSSL     = false;
  bool    havePasswd      = false;
  bool    cloudOption     = false;
  bool    haveCloud       = false;

  qInstallMsgHandler(xTupleMessageOutput);
  QApplication app(argc, argv);

#if QT_VERSION >= 0x040400
  // This is the correct place for this call but on versions less
  // than 4.4 it causes a crash for an unknown reason so it is
  // called later on earlier versions.
  QCoreApplication::addLibraryPath(QString("."));
#endif

#ifndef Q_WS_MACX
  QApplication::setWindowIcon(QIcon(":/images/icon32x32.png"));
#endif

  // Try and load a default translation file and install it
  QTranslator defaultTranslator(&app);
  if (defaultTranslator.load("default.qm", app.applicationDirPath()))
    app.installTranslator(&defaultTranslator);

  app.processEvents();

  if (argc > 1)
  {
    for (int intCounter = 1; intCounter < argc; intCounter++)
    {
      QString argument(argv[intCounter]);

      if (argument.contains("-databaseURL=", Qt::CaseInsensitive))
      {
        haveDatabaseURL = TRUE;
        databaseURL = argument.right(argument.length() - 13);
      }
      else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.contains("-noAuth", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      } 
      else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive))
      {
        haveEnhancedAuth = true;
        _enhancedAuth = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _enhancedAuth = false;
      }
      else if (argument.contains("-requireSSL", Qt::CaseInsensitive))
      {
        haveRequireSSL = true;
        _requireSSL = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          _requireSSL = false;
      }
      else if (argument.contains("-cloud", Qt::CaseInsensitive))
      {
        haveCloud = true;
        cloudOption = true;
        if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive))
          cloudOption = false;
      }
      else if (argument.contains("-company=", Qt::CaseInsensitive))
      {
        company = argument.right(argument.length() - 9);
      }
    }
  }

  _splash = new QSplashScreen();
  _splash->setPixmap(QPixmap(":/images/splashEmpty.png"));

  _evaluation = FALSE;

  if (!loggedIn)
  {
    ParameterList params;
    params.append("copyright", _Copyright);
    params.append("version", _Version);
    params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__));

    if (haveUsername)
      params.append("username", username);

    if (havePasswd)
      params.append("password", passwd);

    if (haveDatabaseURL)
      params.append("databaseURL", databaseURL);

    if (haveEnhancedAuth)
      params.append("enhancedAuth", _enhancedAuth);
    
    if (haveRequireSSL)
      params.append("requireSSL", _requireSSL);

    if (_evaluation)
      params.append("evaluation");

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
      params.append("login");

    if (haveCloud)
      params.append("cloud", cloudOption);

    if (!company.isEmpty())
      params.append("company", company);

    login2 newdlg(0, "", TRUE);
    newdlg.set(params, _splash);

    if(newdlg.result() != QDialog::Accepted)
    {
      if (newdlg.exec() == QDialog::Rejected)
        return -1;
      else
      {
        databaseURL = newdlg._databaseURL;
        username = newdlg.username();
        __password = newdlg.password();
        company = newdlg.company();
        cloudOption = newdlg.useCloud();
      }
    }
  }

  XSqlQuery metric;
  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'Application')" );
  if(!metric.first() || (metric.value("metric_value").toString() == "Standard"))
  {
    // check if the xtmfg package is installed
    metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'");
    if(metric.first())
    {
      _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png"));
      _Name = _Name.arg("Manufacturing");
    }
    else
    {
      _splash->setPixmap(QPixmap(":/images/splashStdEdition.png"));
      _Name = _Name.arg("Standard");
    }

    _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
    metric.exec("SELECT COUNT(*) as _count"
                "  FROM pg_stat_activity"
                " WHERE(datid IN (SELECT datid"
                "                   FROM pg_stat_activity"
                "                  WHERE(procpid=pg_backend_pid())));");
    int cnt = 50000;
    if(metric.first())
      cnt = metric.value("_count").toInt();
    metric.exec("SELECT metric_value"
                "  FROM metric"
                " WHERE(metric_name = 'RegistrationKey');");
    bool checkPass = true;
    QString checkPassReason;
    QString rkey = "";
    if(metric.first())
      rkey = metric.value("metric_value").toString();
    XTupleProductKey pkey(rkey);
    if(pkey.valid() && pkey.version() == 1)
    {
      if(pkey.expiration() < QDate::currentDate())
      {
        checkPass = false;
        checkPassReason = QObject::tr("Your license has expired.");
      }
      else if(pkey.users() != 0 && (pkey.users()+1) < cnt)
      {
        checkPass = false;
        checkPassReason = QObject::tr("You have exceeded the number of allowed concurrent users for your license.");
      }
    }
    else
    {
      checkPass = false;
      checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid.");
    }
    if(!checkPass)
    {
      _splash->hide();
      QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);

      metric.exec("SELECT current_database() AS db,"
                  "       fetchMetricText('DatabaseName') AS dbname,"
                  "       fetchMetricText('remitto_name') AS name;");
      QString db = "";
      QString dbname = "";
      QString name = "";
      if(metric.first())
      {
        db = metric.value("db").toString();
        dbname = metric.value("dbname").toString();
        name = metric.value("name").toString();
      }

      QHttp *http = new QHttp();
      
      QUrl url;
      url.setPath("/api/regviolation.php");
      url.addQueryItem("key", QUrl::toPercentEncoding(rkey));
      url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason));
      url.addQueryItem("name", QUrl::toPercentEncoding(name));
      url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname));
      url.addQueryItem("db", QUrl::toPercentEncoding(db));
      url.addQueryItem("cnt", QString::number(cnt));

      http->setHost("www.xtuple.org");
      http->get(url.toString());
      _splash->show();
    }
  }
  else
  {
    _splash->setPixmap(QPixmap(":/images/splashPostBooks.png"));
    _Name = _Name.arg("PostBooks");
  }

  metric.exec("SELECT metric_value"
           "  FROM metric"
           " WHERE (metric_name = 'ServerVersion')" );
  if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion))
  {
    bool disallowMismatch = false;
    metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')");
    if(metric.first() && (metric.value("metric_value").toString() == "t"))
      disallowMismatch = true;
    
    _splash->hide();
    int result;
    if(disallowMismatch)
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. The system has been configured to disallow "
                    "access in this case.<p>Please contact your systems "
                    "administrator.").arg(_dbVersion),
                 QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
    else
      result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"),
        QObject::tr("<p>The version of the database you are connecting to is "
                    "not the version this client was designed to work against. "
                    "This client was designed to work against the database "
                    "version %1. If you continue some or all functionality may "
                    "not work properly or at all. You may also cause other "
                    "problems on the database.<p>Do you want to continue "
                    "anyway?").arg(_dbVersion),
                 QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
    if(result != QMessageBox::Yes)
      return 0;
    _splash->show();
  }

  _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _metrics = new Metrics();

  _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _preferences = new Preferences(username);

  _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  _privileges = new Privileges();

  // Load the translator and set the locale from the User's preferences
  _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor);
  qApp->processEvents();
  XSqlQuery langq("SELECT * "
                  "FROM usr, locale LEFT OUTER JOIN"
                  "     lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN"
                  "     country ON (locale_country_id=country_id) "
                  "WHERE ( (usr_username=CURRENT_USER)"
                  " AND (usr_locale_id=locale_id) );" );
  if (langq.first())
  {
    QStringList files;
    if (!langq.value("locale_lang_file").toString().isEmpty())
      files << langq.value("locale_lang_file").toString();

    QString langext;
    if (!langq.value("lang_abbr2").toString().isEmpty() && 
        !langq.value("country_abbr").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString() + "_" +
                langq.value("country_abbr").toString().toLower();
    }
    else if (!langq.value("lang_abbr2").toString().isEmpty())
    {
      langext = langq.value("lang_abbr2").toString();
    }

    if(!langext.isEmpty())
    {
      files << "xTuple";
      files << "openrpt";
      files << "reports";

      XSqlQuery pkglist("SELECT pkghead_name"
                        "  FROM pkghead"
                        " WHERE packageIsEnabled(pkghead_name);");
      while(pkglist.next())
        files << pkglist.value("pkghead_name").toString();
    }

    if (files.size() > 0)
    {
      QStringList notfound;
      QTranslator *translator = new QTranslator(&app);
      for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit)
      {
        if (DEBUG)
          qDebug("looking for %s", (*fit).toAscii().data());
        if (translator->load(translationFile(langext, *fit)))
        {
          app.installTranslator(translator);
          qDebug("installed %s", (*fit).toAscii().data());
          translator = new QTranslator(&app);
        }
        else
          notfound << *fit;
      }

      if (! notfound.isEmpty() &&
          !_preferences->boolean("IngoreMissingTranslationFiles"))
        QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"),
                              QObject::tr("<p>The Translation Dictionaries %1 "
                                          "cannot be loaded. Reverting "
                                          "to the default dictionary." )
                                       .arg(notfound.join(QObject::tr(", "))));
    }

    /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or
       lang#, depending on what information is available
     */
    QString langAbbr = langq.value("lang_abbr2").toString();
    QString cntryAbbr = langq.value("country_abbr").toString().toUpper();
    if(cntryAbbr == "UK")
      cntryAbbr = "GB";
    if (! langAbbr.isEmpty() &&
        ! cntryAbbr.isEmpty())
      QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr));
    else if (! langAbbr.isEmpty())
      QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString()));
    else if (langq.value("lang_qt_number").toInt() &&
             langq.value("country_qt_number").toInt())
      QLocale::setDefault(
          QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()),
                  QLocale::Country(langq.value("country_qt_number").toInt())));
    else
      QLocale::setDefault(QLocale::system());

    qDebug("Locale set to language %s and country %s",
           QLocale().languageToString(QLocale().language()).toAscii().data(),
           QLocale().countryToString(QLocale().country()).toAscii().data());

  }
  else if (langq.lastError().type() != QSqlError::NoError)
  {
    systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__);
  }

  qApp->processEvents();
  QString key;

  // TODO: Add code to check a few locations - Hopefully done

  QString keypath;
  QString keyname;
  QString keytogether;
  
#ifdef Q_WS_WIN
  keypath = _metrics->value("CCWinEncKey");
#elif defined Q_WS_MACX
  keypath = _metrics->value("CCMacEncKey");
#elif defined Q_WS_X11
  keypath = _metrics->value("CCLinEncKey");
#endif
  
  if (keypath.isEmpty())
    keypath = app.applicationDirPath();

  if (! keypath.endsWith(QDir::separator()))
    keypath += QDir::separator();

  keyname = _metrics->value("CCEncKeyName");
  if (keyname.isEmpty())
  {
    keyname = "xTuple.key";
    keytogether = keypath + keyname;
    QFile kn(keytogether);
    if(!kn.exists())
      keyname = "OpenMFG.key";
  }
  
  keytogether = keypath + keyname;
  
  // qDebug("keytogether: %s", keytogether.toAscii().data());
  QFile keyFile(keytogether);

  if(keyFile.exists())
  {
    if(keyFile.open(QIODevice::ReadOnly))
    {
      key = keyFile.readLine(1024);
      // strip off any newline characters
      key = key.trimmed();
    }
  }

  omfgThis = 0;
  omfgThis = new GUIClient(databaseURL, username);
  omfgThis->_key = key;
  omfgThis->_company = company;
  omfgThis->_useCloud = cloudOption;

// qDebug("Encryption Key: %s", key.toAscii().data() );
  
  if (key.length() > 0) {
	_splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor);
	qApp->processEvents();
	_metricsenc = new Metricsenc(key);
  }
  
  initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace());

// START code for updating the locale settings if they haven't been already
  XSqlQuery lc;
  lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';");
  lc.first();
  if(lc.value(0).toInt() == 0)
  {
    lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');");
    lc.exec("SELECT locale_id from locale;");
    while(lc.next())
    {
      ParameterList params;
      params.append("mode","edit");
      params.append("locale_id", lc.value(0));
      sysLocale lcdlg;
      lcdlg.set(params);
      lcdlg.sSave();
    }
  }
// END code for updating locale settings

  QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows()));
  if (omfgThis->_singleWindow.isEmpty())
  {
    omfgThis->setAttribute(Qt::WA_DeleteOnClose);
    omfgThis->show();
  }
  // keep this synchronized with GUIClient and user.ui.h
  else if (omfgThis->_singleWindow == "woTimeClock")
  {
    ScriptToolbox sb(0);
    QWidget* newdlg = sb.openWindow("woTimeClock");
    if(newdlg)
    {
      XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg);
      if(mw)
      {
        ParameterList params;
        params.append("captive");
        mw->set(params);
      }
      newdlg->setAttribute(Qt::WA_DeleteOnClose);
      QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit()));
      newdlg->show();
    }
    else
    {
Example #6
0
//! \brief Creates Talkfiles.
//!
TalkGenerator::Status TalkGenerator::process(QList<TalkEntry>* list,int wavtrimth)
{
    QString errStr;
    bool warnings = false;

    //tts
    emit logItem(tr("Starting TTS Engine"),LOGINFO);
    m_tts = TTSBase::getTTS(this,RbSettings::value(RbSettings::Tts).toString());
    if(!m_tts->start(&errStr))
    {
        emit logItem(errStr.trimmed(),LOGERROR);
        emit logItem(tr("Init of TTS engine failed"),LOGERROR);
        emit done(true);
        return eERROR;
    }
    QCoreApplication::processEvents();

    // Encoder
    emit logItem(tr("Starting Encoder Engine"),LOGINFO);
    m_enc = EncBase::getEncoder(this,SystemInfo::value(SystemInfo::CurEncoder).toString());
    if(!m_enc->start())
    {
        emit logItem(tr("Init of Encoder engine failed"),LOGERROR);
        emit done(true);
        m_tts->stop();
        return eERROR;
    }
    QCoreApplication::processEvents();

    emit logProgress(0,0);

    // Voice entries
    emit logItem(tr("Voicing entries..."),LOGINFO);
    Status voiceStatus= voiceList(list,wavtrimth);
    if(voiceStatus == eERROR)
    {
        m_tts->stop();
        m_enc->stop();
        emit done(true);
        return eERROR;
    }
    else if( voiceStatus == eWARNING)
        warnings = true;

    QCoreApplication::processEvents();

    // Encoding Entries
    emit logItem(tr("Encoding files..."),LOGINFO);
    Status encoderStatus = encodeList(list);
    if( encoderStatus == eERROR)
    {
        m_tts->stop();
        m_enc->stop();
        emit done(true);
        return eERROR;
    }
    else if( voiceStatus == eWARNING)
        warnings = true;

    QCoreApplication::processEvents();

    m_tts->stop();
    m_enc->stop();
    emit logProgress(1,1);

    if(warnings)
        return eWARNING;
    return eOK;
}
Example #7
0
QString gtAction::parseColor(const QString &s)
{
	QString ret = CommonStrings::None;
	if (s == CommonStrings::None)
		return ret; // don't want None to become Black or any color
	bool found = false;
	ColorList::Iterator it;
	for (it = m_textFrame->doc()->PageColors.begin(); it != m_textFrame->doc()->PageColors.end(); ++it)
	{
		if (it.key() == s)
		{
			ret = it.key();
			found = true;
		}
	}
	if (!found)
	{
		QColor c;
		if( s.startsWith( "rgb(" ) )
		{
			QString parse = s.trimmed();
			QStringList colors = parse.split(',', QString::SkipEmptyParts);
			QString r = colors[0].right( ( colors[0].length() - 4 ) );
			QString g = colors[1];
			QString b = colors[2].left( ( colors[2].length() - 1 ) );
			if( r.contains( "%" ) )
			{
				r.chop(1);
				r = QString::number( static_cast<int>( ( static_cast<double>( 255 * ScCLocale::toDoubleC(r) ) / 100.0 ) ) );
			}
			if( g.contains( "%" ) )
			{
				g.chop(1);
				g = QString::number( static_cast<int>( ( static_cast<double>( 255 * ScCLocale::toDoubleC(g) ) / 100.0 ) ) );
			}
			if( b.contains( "%" ) )
			{
				b.chop(1);
				b = QString::number( static_cast<int>( ( static_cast<double>( 255 * ScCLocale::toDoubleC(b) ) / 100.0 ) ) );
			}
			c = QColor(r.toInt(), g.toInt(), b.toInt());
		}
		else
		{
			QString rgbColor = s.trimmed();
			if( rgbColor.startsWith( "#" ) )
				c.setNamedColor( rgbColor );
			else
				c = parseColorN( rgbColor );
		}
		found = false;
		for (it = m_textFrame->doc()->PageColors.begin(); it != m_textFrame->doc()->PageColors.end(); ++it)
		{
			if (c == ScColorEngine::getRGBColor(it.value(), m_textFrame->doc()))
			{
				ret = it.key();
				found = true;
			}
		}
		if (!found)
		{
			ScColor tmp;
			tmp.fromQColor(c);
			m_textFrame->doc()->PageColors.insert("FromGetText"+c.name(), tmp);
			m_ScMW->propertiesContentPalette->updateColorList();
			ret = "FromGetText"+c.name();
		}
	}
	return ret;
}
Example #8
0
File: Tv.cpp Project: juriad/tvp
bool Tv::isGeneratorInfoNameValid(QString input) {
  bool ok;
  ok = !input.trimmed().isEmpty();
  return ok;
}
Example #9
0
File: Tv.cpp Project: juriad/tvp
bool Tv::isSourceInfoNameValid(QString input) {
  bool ok;
  ok = !input.trimmed().isEmpty();
  return ok;
}
Example #10
0
// IRIX 6.x
void qt_parseSpoolInterface(QList<QPrinterDescription> *printers)
{
    QDir lp(QLatin1String("/usr/spool/lp/interface"));
    if (!lp.exists())
        return;
    QFileInfoList files = lp.entryInfoList();
    if(files.isEmpty())
        return;

    for (int i = 0; i < files.size(); ++i) {
        QFileInfo printer = files.at(i);

        if (!printer.isFile())
            continue;

        // parse out some information
        QFile configFile(printer.filePath());
        if (!configFile.open(QIODevice::ReadOnly))
            continue;

        QByteArray line;
        line.resize(1025);
        QString namePrinter;
        QString hostName;
        QString hostPrinter;
        QString printerType;

        QString nameKey(QLatin1String("NAME="));
        QString typeKey(QLatin1String("TYPE="));
        QString hostKey(QLatin1String("HOSTNAME="));
        QString hostPrinterKey(QLatin1String("HOSTPRINTER="));

        while (!configFile.atEnd() &&
                (configFile.readLine(line.data(), 1024)) > 0) {
            QString uline = QString::fromLocal8Bit(line);
            if (uline.startsWith(typeKey) ) {
                printerType = uline.mid(nameKey.length());
                printerType = printerType.simplified();
            } else if (uline.startsWith(hostKey)) {
                hostName = uline.mid(hostKey.length());
                hostName = hostName.simplified();
            } else if (uline.startsWith(hostPrinterKey)) {
                hostPrinter = uline.mid(hostPrinterKey.length());
                hostPrinter = hostPrinter.simplified();
            } else if (uline.startsWith(nameKey)) {
                namePrinter = uline.mid(nameKey.length());
                namePrinter = namePrinter.simplified();
            }
        }
        configFile.close();

        printerType = printerType.trimmed();
        if (printerType.indexOf(QLatin1String("postscript"), 0, Qt::CaseInsensitive) < 0)
            continue;

        int ii = 0;
        while ((ii = namePrinter.indexOf(QLatin1Char('"'), ii)) >= 0)
            namePrinter.remove(ii, 1);

        if (hostName.isEmpty() || hostPrinter.isEmpty()) {
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 QLatin1String(""), namePrinter);
        } else {
            QString comment;
            comment = namePrinter;
            comment += QLatin1String(" (");
            comment += hostPrinter;
            comment += QLatin1Char(')');
            qt_perhapsAddPrinter(printers, printer.fileName(),
                                 hostName, comment);
        }
    }
}
Example #11
0
/*!
  Creates a declaration (header file) for the form given in \a e

  \sa createFormImpl()
*/
void Ui3Reader::createFormDecl(const QDomElement &e)
{
    QDomElement body = e;

    QDomElement n;
    QDomNodeList nl;
    int i;
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;
    QString objName = getObjectName(e);

    QStringList typeDefs;

    QMap<QString, CustomInclude> customWidgetIncludes;

    /*
      We are generating a few QImage members that are not strictly
      necessary in some cases. Ideally, we would use requiredImage,
      which is computed elsewhere, to keep the generated .h and .cpp
      files synchronized.
    */

    // at first the images
    QMap<QString, int> customWidgets;
    QStringList forwardDecl;
    QStringList forwardDecl2;
    for (n = e; !n.isNull(); n = n.nextSibling().toElement()) {
        if (n.tagName().toLower() == QLatin1String("customwidgets")) {
            QDomElement n2 = n.firstChild().toElement();
            while (!n2.isNull()) {
                if (n2.tagName().toLower() == QLatin1String("customwidget")) {
                    QDomElement n3 = n2.firstChild().toElement();
                    QString cl;
                    while (!n3.isNull()) {
                        QString tagName = n3.tagName().toLower();
                        if (tagName == QLatin1String("class")) {
                            cl = n3.firstChild().toText().data();
                            if (m_options & CustomWidgetForwardDeclarations)
                                forwardDecl << cl;
                            customWidgets.insert(cl, 0);
                        } else if (tagName == QLatin1String("header")) {
                            CustomInclude ci;
                            ci.header = n3.firstChild().toText().data();
                            ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global"));
                            if (!ci.header.isEmpty())
                                forwardDecl.removeAll(cl);
                            customWidgetIncludes.insert(cl, ci);
                        }
                        n3 = n3.nextSibling().toElement();
                    }
                }
                n2 = n2.nextSibling().toElement();
            }
        }
    }

    // register the object and unify its name
    objName = registerObject(objName);
    QString protector = objName.toUpper() + QLatin1String("_H");
    protector.replace(QLatin1String("::"), QLatin1String("_"));
    out << "#ifndef " << protector << endl;
    out << "#define " << protector << endl;
    out << endl;

    out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers

    QStringList globalIncludes, localIncludes;

    {
        QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass);
        if (it != customWidgetIncludes.end()) {
            if ((*it).location == QLatin1String("global"))
                globalIncludes += (*it).header;
            else
                localIncludes += (*it).header;
        }
    }

    QStringList::ConstIterator it;

    globalIncludes = unique(globalIncludes);
    for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            QString header = fixHeaderName(*it);
            out << "#include <" << header << '>' << endl;
        }
    }
    localIncludes = unique(localIncludes);
    for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            QString header = fixHeaderName(*it);
            out << "#include \"" << header << '\"' << endl;
        }
    }
    out << endl;

    bool dbForm = false;
    registerDatabases(e);
    dbConnections = unique(dbConnections);
    if (dbForms[QLatin1String("(default)")].count())
        dbForm = true;
    bool subDbForms = false;
    for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) {
        if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) {
            if (dbForms[(*it)].count()) {
                subDbForms = true;
                break;
            }
        }
    }

    // some typedefs, maybe
    typeDefs = unique(typeDefs);
    for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) {
        if (!(*it).isEmpty())
            out << "typedef " << *it << ';' << endl;
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward"));
    for (i = 0; i < (int) nl.length(); i++)
        forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data());

    forwardDecl = unique(forwardDecl);
    for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) {
        if (!(*it).isEmpty() && (*it) != objClass) {
            QString forwardName = *it;
            QStringList forwardNamespaces = forwardName.split(QLatin1String("::"));
            forwardName = forwardNamespaces.last();
            forwardNamespaces.removeAt(forwardNamespaces.size()-1);

            QStringList::ConstIterator ns = forwardNamespaces.constBegin();
            while (ns != forwardNamespaces.constEnd()) {
                out << "namespace " << *ns << " {" << endl;
                ++ns;
            }
            out << "class " << forwardName << ';' << endl;
            for (int i = 0; i < (int) forwardNamespaces.count(); i++)
                out << '}' << endl;
        }
    }

    for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) {
        QString fd = *it;
        fd = fd.trimmed();
        if (!fd.endsWith(QLatin1Char(';')))
            fd += QLatin1Char(';');
        out << fd << endl;
    }

    out << endl;

    Driver d;
    d.option().headerProtection = false;
    d.option().copyrightHeader = false;
    d.option().extractImages = m_extractImages;
    d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0;
    d.option().qrcOutputFile = m_qrcOutputFile;
    d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0;
    if (trmacro.size())
        d.option().translateFunction = trmacro;
    DomUI *ui = generateUi4(e);
    d.uic(fileName, ui, &out);
    delete ui;

    createWrapperDeclContents(e);

    out << "#endif // " << protector << endl;
}
void CommandExecutionEngine::execute(Visualization::Item *originator, const QString& command)
{
	deleteLastCommandResult();

	QString trimmed = command.trimmed();

	if ( !doQuotesMatch(command, QUOTE_SYMBOLS, ESCAPE_SYMBOLS) )
	{
		lastCommandResult = new CommandResult(new CommandError("A quoted string expands past the end of the command."));
		lastCommandResult->errors().first()->addResolutionTip("Try inserting a matching quote.");
		return;
	}

	QString navigation = extractNavigationString(trimmed);

	// This is the node where we begin trying to process the command
	Visualization::Item* source = originator;
	// Alter the source node according to the requested navigation location.
	if (!navigation.isEmpty()) source = navigate(originator, navigation);

	// This is the node (source or one of its ancestors) where we manage to process the command.
	Visualization::Item* target = source;

	QStringList tokens = tokenize(trimmed, QUOTE_SYMBOLS, ESCAPE_SYMBOLS);

	bool processed = false;

	while(target != nullptr && !processed)
	{
		GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler());

		if (handler)
		{
			for(int i = 0; i< handler->commands().size(); ++i)
			{
				if ( handler->commands().at(i)->canInterpret(source, target, tokens) )
				{
					lastCommandResult = handler->commands().at(i)->execute(source, target, tokens);

					if (lastCommandResult->code() != CommandResult::CanNotInterpret)
					{
						processed = true;
						break;
					}
					else deleteLastCommandResult();
				}
			}
		}

		if (!processed) target = target->parent();
	}

	// If no item can process this command dispatch it to the SceneItem
	if (!processed && originator != originator->scene()->sceneHandlerItem())
	{
		GenericHandler* handler = dynamic_cast<GenericHandler*> (source->scene()->sceneHandlerItem()->handler());

		if ( handler )
		{
			for (int i = 0; i < handler->commands().size(); ++i)
			{
				if ( handler->commands().at(i)->canInterpret(source, nullptr, tokens) )
				{
					lastCommandResult = handler->commands().at(i)->execute(source, nullptr, tokens);

					if ( lastCommandResult->code() != CommandResult::CanNotInterpret )
					{
						processed = true;
						break;
					}
					else deleteLastCommandResult();
				}
			}
		}
	}

	// If the command is still not processed this is an error
	if (!processed)
	{
		lastCommandResult = new CommandResult(new CommandError("Unknown command '" + command + "' "));
		InteractionBase::log()->add(Logger::Log::LOGWARNING, "Unknown command: " + command);
	}
}
Example #13
0
//using namespace cv;
//*********************************************************************
//* Main entry point to the program.
//*********************************************************************
int main(int argc, char *argv[])
{
    signal(SIGSEGV, fault_handler);   // install our handler

    // Setup the QApplication so we can begin
    Application *a = new Application(argc, argv);
    global.application = a;

    // Setup the QLOG functions for debugging & messages
    QsLogging::Logger& logger = QsLogging::Logger::instance();
    logger.setLoggingLevel(QsLogging::TraceLevel);
//    const QString sLogPath(a->applicationDirPath());

    QsLogging::DestinationPtr debugDestination(
                QsLogging::DestinationFactory::MakeDebugOutputDestination() );
    logger.addDestination(debugDestination.get());

    // Begin setting up the environment
    StartupConfig startupConfig;
    global.argc = argc;
    global.argv = argv;

    startupConfig.accountId = -1;

    for (int i=1; i<=argc; i++) {
        QString parm(argv[i]);
        if (parm == "--help" || parm == "-?") {
            printf("\n\n");
            printf("NixNote command line options:\n");
            printf("  --help or -?                  Show this message\n");
            printf("  --accountId=<id>              Start with specified user account\n");
            printf("  --dontStartMinimized          Override option to start minimized\n");
            printf("  --disableEditing              Disable note editing\n");
            printf("  --disableIndexing             Disable all indexing\n");
            printf("  --openNote=<lid>              Open a specific note on startup\n");
            printf("  --forceSystemTrayAvailable    Force the program to accept that\n");
            printf("                                the desktop supports tray icons.\n");
            printf("  --startMinimized              Force a startup with NixNote minimized\n");
            printf("  --syncAndExit                 Synchronize and exit the program.\n");
            printf("\n\n");
            return 0;
        }
        if (parm.startsWith("--accountId=", Qt::CaseSensitive)) {
            parm = parm.mid(12);
            startupConfig.accountId = parm.toInt();
        }
        if (parm.startsWith("--openNote=", Qt::CaseSensitive)) {
            parm = parm.mid(11);
            startupConfig.startupNoteLid = parm.toInt();
        }
        if (parm == "--disableEditing") {
            startupConfig.disableEditing = true;
        }
        if (parm == "--dontStartMinimized") {
            startupConfig.forceNoStartMinimized = true;
        }
        if (parm == "--startMinimized") {
            startupConfig.forceStartMinimized = true;
        }
        if (parm == "--newNote") {
            startupConfig.startupNewNote = true;
        }
        if (parm == "--syncAndExit") {
            startupConfig.syncAndExit = true;
        }
        if (parm == "--disableIndexing") {
            startupConfig.disableIndexing = true;
        }
        if (parm == "--forceSystemTrayAvailable") {
            startupConfig.forceSystemTrayAvailable = true;
        }
    }

    startupConfig.programDirPath = global.getProgramDirPath() + QDir().separator();
    startupConfig.name = "NixNote";
    global.setup(startupConfig);

    QString logPath = global.fileManager.getLogsDirPath("")+"messages.log";
    QsLogging::DestinationPtr fileDestination(
                 QsLogging::DestinationFactory::MakeFileDestination(logPath) ) ;
    logger.addDestination(fileDestination.get());


    // Show Qt version.  This is useful for debugging
    QLOG_DEBUG() << "Program Home: " << global.fileManager.getProgramDirPath("");
    QLOG_INFO() << "Built on " << __DATE__ << " at " << __TIME__;
    QLOG_INFO() << "Built with Qt" << QT_VERSION_STR << "running on" << qVersion();
    //QLOG_INFO() << "Thrift version: " << PACKAGE_VERSION;



    // Create a shared memory region.  We use this to communicate
    // with any other instance that may be running.  If another instance
    // is found we need to either show that one or kill this one.
    bool memInitNeeded = true;
    if( !global.sharedMemory->create( 512*1024, QSharedMemory::ReadWrite) ) {
        // Attach to it and detach.  This is done in case it crashed.
        global.sharedMemory->attach();
        global.sharedMemory->detach();
        if( !global.sharedMemory->create( 512*1024, QSharedMemory::ReadWrite) ) {
            if (startupConfig.startupNewNote) {
                global.sharedMemory->attach();
                global.sharedMemory->lock();
                void *dataptr = global.sharedMemory->data();
                memcpy(dataptr, "NEW_NOTE", 8);  // Tell the other guy create a new note
                QLOG_INFO() << "Another NixNote was found.  Requesting it to start another note";
                exit(0);  // Exit this one
            }
            if (startupConfig.startupNoteLid > 0) {
                global.sharedMemory->attach();
                global.sharedMemory->lock();
                void *dataptr = global.sharedMemory->data();
                QString msg = "OPEN_NOTE:" +QString::number(startupConfig.startupNoteLid) + " ";
                memcpy(dataptr, msg.toStdString().c_str(), msg.length());  // Tell the other guy to open a note
                QLOG_INFO() << "Another NixNote was found.  Requesting it to open a note";
                exit(0);  // Exit this one
            }
            // If we've gotten this far, we need to either stop this instance or stop the other
            global.settings->beginGroup("Debugging");
            QString startup = global.settings->value("onMultipleInstances", "SHOW_OTHER").toString();
            global.settings->endGroup();
            global.sharedMemory->attach();
            global.sharedMemory->lock();
            void *dataptr = global.sharedMemory->data();
            if (startup == "SHOW_OTHER") {
                memcpy(dataptr, "SHOW_WINDOW", 11);  // Tell the other guy to show himself
                QLOG_INFO() << "Another NixNote was found.  Stopping this instance";
                exit(0);  // Exit this one
            }
            if (startup == "STOP_OTHER") {
                memcpy(dataptr, "IMMEDIATE_SHUTDOWN", 18);  // Tell the other guy to shut down
                memInitNeeded = false;
            }
            global.sharedMemory->unlock();
        }
    }
    if (memInitNeeded) {
        global.sharedMemory->lock();
        memset(global.sharedMemory->data(), 0, global.sharedMemory->size());
        global.sharedMemory->unlock();
    }



    // Save the clipboard
    global.clipboard = QApplication::clipboard();

    NixNote *w = new NixNote();
    w->setAttribute(Qt::WA_QuitOnClose);
    bool show = true;
    if (global.syncAndExit)
        show = false;
    if (global.minimizeToTray() && global.startMinimized)
        show = false;
    if (show)
        w->show();
    else
        w->hide();
    if (global.startMinimized)
        w->showMinimized();

    // Setup the proxy
    QNetworkProxy proxy;
    proxy.setType(QNetworkProxy::HttpProxy);
    if (global.isProxyEnabled()) {
        QString host = global.getProxyHost();
        int port = global.getProxyPort();
        QString user = global.getProxyUserid();
        QString password = global.getProxyPassword();

        if (host.trimmed() != "")
            proxy.setHostName(host.trimmed());
        if (port > 0)
            proxy.setPort(port);
        if (user.trimmed() != "")
            proxy.setUser(user.trimmed());
        if (password.trimmed() != "")
            proxy.setPassword(password.trimmed());

        QNetworkProxy::setApplicationProxy(proxy);
    }

    int rc = a->exec();
    QLOG_DEBUG() << "Unlocking memory";
    global.sharedMemory->unlock();
    QLOG_DEBUG() << "Deleting NixNote instance";
    delete w;
    QLOG_DEBUG() << "Quitting application instance";
    a->exit(rc);
    QLOG_DEBUG() << "Deleting application instance";
    delete a;
    QLOG_DEBUG() << "Exiting: RC=" << rc;
    exit(rc);
    return rc;
}
Example #14
0
void ParserHafasBinary::parseSearchJourney(QNetworkReply *networkReply)
{
    lastJourneyResultList = new JourneyResultList();
    journeyDetailInlineData.clear();

    QByteArray tmpBuffer = networkReply->readAll();
    QByteArray buffer = gzipDecompress(tmpBuffer);

    /*
    QFile file("f://out.txt");
    file.open(QIODevice::WriteOnly);
    file.write(buffer);
    file.close();
*/

    QDataStream hafasData(buffer);
    hafasData.setByteOrder(QDataStream::LittleEndian);

    qint16 hafasVersion;
    hafasData >> hafasVersion;

    if (hafasVersion != 5 && hafasVersion != 6) {
        qWarning()<<"Wrong version of hafas binary data";
        emit errorOccured(tr("An error ocurred with the backend"));
        return;
    }

    qDebug()<<"Binary-Data Version: "<<hafasVersion;

    //Basic data offsets
    qint32 serviceDaysTablePtr;
    qint32 stringTablePtr;
    qint32 stationTablePtr;
    qint32 commentTablePtr;
    qint32 extensionHeaderPtr;
    qint32 extensionHeaderLength;
    qint16 errorCode;

    hafasData.device()->seek(0x20);
    hafasData >> serviceDaysTablePtr;
    hafasData >> stringTablePtr;
    hafasData.device()->seek(0x36);
    hafasData >> stationTablePtr;
    hafasData >> commentTablePtr;
    hafasData.device()->seek(0x46);
    hafasData >> extensionHeaderPtr;
    hafasData.device()->seek(extensionHeaderPtr);
    hafasData >> extensionHeaderLength;
    hafasData.device()->seek(extensionHeaderPtr + 16);
    hafasData >> errorCode;

    //Debug data offsets
    qDebug()<<serviceDaysTablePtr<<stringTablePtr;
    qDebug()<<stationTablePtr<<commentTablePtr;
    qDebug()<<extensionHeaderPtr<<extensionHeaderLength;
    qDebug()<<errorCode;

    //Read strings
    hafasData.device()->seek(stringTablePtr);
    QMap<int, QString> strings;
    QString tmpString;
    for (int num = 0; num < (serviceDaysTablePtr - stringTablePtr); num++) {
        qint8 c;
        hafasData>>c;
        if (c == 0) {
            strings.insert((num - tmpString.length()), tmpString.trimmed());
            tmpString.clear();
        } else {
            tmpString.append((char)c);
        }
    }

    //Looks ok, parsing
    if (errorCode == 0) {
        hafasData.device()->seek(extensionHeaderPtr + 0x8);
        qint16 seqNr;
        qint16 requestIdPtr;
        qint16 encodingPtr;
        qint32 connectionDetailsPtr;
        qint32 attrsOffset;
        qint16 ldPtr;
        hafasData >> seqNr;
        hafasData >> requestIdPtr;
        hafasData >> connectionDetailsPtr;
        hafasData.device()->seek(hafasData.device()->pos() + 16);
        hafasData >> encodingPtr;
        hafasData >> ldPtr;
        hafasData >> attrsOffset;
        QString encoding = strings[encodingPtr];
        QString requestId = strings[requestIdPtr];
        QString ld = strings[ldPtr];

        qint32 connectionAttrsPtr;
        if (extensionHeaderLength >= 0x30) {
            if (extensionHeaderLength < 0x32) {
                qWarning()<<"too short: " + extensionHeaderLength;
                return;
            }
            hafasData.device()->seek(extensionHeaderPtr + 0x2c);
            hafasData >> connectionAttrsPtr;
        } else {
Example #15
0
static QStringList fontPath()
{
    if (qt_fontpath)
        return *qt_fontpath;

    // append qsettings fontpath
    QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
    settings.beginGroup(QLatin1String("Qt"));

    QStringList fontpath;

    int npaths;
    char** font_path;
    font_path = XGetFontPath(X11->display, &npaths);
    bool xfsconfig_read = false;
    for (int i=0; i<npaths; i++) {
        // If we're using xfs, append font paths from /etc/X11/fs/config
        // can't hurt, and chances are we'll get all fonts that way.
        if (((font_path[i])[0] != '/') && !xfsconfig_read) {
            // We're using xfs -> read its config
            bool finished = false;
            QFile f(QLatin1String("/etc/X11/fs/config"));
            if (!f.exists())
                f.setFileName(QLatin1String("/usr/X11R6/lib/X11/fs/config"));
            if (!f.exists())
                f.setFileName(QLatin1String("/usr/X11/lib/X11/fs/config"));
            if (f.exists()) {
                f.open(QIODevice::ReadOnly);
                while (f.error()==QFile::NoError && !finished) {
                    QString fs = QString::fromLocal8Bit(f.readLine(1024));
                    fs=fs.trimmed();
                    if (fs.left(9)==QLatin1String("catalogue") && fs.contains(QLatin1Char('='))) {
                        fs = fs.mid(fs.indexOf(QLatin1Char('=')) + 1).trimmed();
                        bool end = false;
                        while (f.error()==QFile::NoError && !end) {
                            if (fs[int(fs.length())-1] == QLatin1Char(','))
                                fs = fs.left(fs.length()-1);
                            else
                                end = true;

                            fs = fs.left(fs.indexOf(QLatin1String(":unscaled")));
                            if (fs[0] != QLatin1Char('#'))
                                fontpath += fs;
                            fs = QLatin1String(f.readLine(1024));
                            fs = fs.trimmed();
                            if (fs.isEmpty())
                                end = true;
                        }
                        finished = true;
                    }
                }
                f.close();
            }
            xfsconfig_read = true;
        } else {
            QString fs = QString::fromLocal8Bit(font_path[i]);
            fontpath += fs.left(fs.indexOf(QLatin1String(":unscaled")));
        }
    }
    XFreeFontPath(font_path);

    // append qsettings fontpath
    QStringList fp = settings.value(QLatin1String("fontPath")).toStringList();
    if (!fp.isEmpty())
        fontpath += fp;

    qt_fontpath = new QStringList(fontpath);
    return fontpath;
}
Example #16
0
void Util::commandPostProcess( const QString& errorMsg){
    if ( errorMsg.trimmed().length() > 0 ){
        ErrorManager* errorMan = Util::findSingletonObject<ErrorManager>();
        errorMan->registerWarning( errorMsg );
    }
}
Example #17
0
double ScrSpinBox::valueFromText ( const QString & text ) const
{
	//Get all our units strings
//CB: Replaced by new CommonStrings versions
// 	QString trStrPT=unitGetStrFromIndex(SC_PT);
// 	QString trStrMM=unitGetStrFromIndex(SC_MM);
// 	QString trStrIN=unitGetStrFromIndex(SC_IN);
// 	QString trStrP =unitGetStrFromIndex(SC_P);
// 	QString trStrCM=unitGetStrFromIndex(SC_CM);
// 	QString trStrC =unitGetStrFromIndex(SC_C);
// 	QString strPT=unitGetUntranslatedStrFromIndex(SC_PT);
// 	QString strMM=unitGetUntranslatedStrFromIndex(SC_MM);
// 	QString strIN=unitGetUntranslatedStrFromIndex(SC_IN);
// 	QString strP =unitGetUntranslatedStrFromIndex(SC_P);
// 	QString strCM=unitGetUntranslatedStrFromIndex(SC_CM);
// 	QString strC =unitGetUntranslatedStrFromIndex(SC_C);
	//Get a copy for use
	QString ts = text.trimmed();
	//Find our suffix
	QString su(unitGetStrFromIndex(m_unitIndex));
	//Replace our pica XpY.Z format with (X*12+Y.Z)pt
	if (CommonStrings::trStrP.localeAwareCompare(CommonStrings::strP)!=0)
		ts.replace(CommonStrings::trStrP, CommonStrings::strP);
	QRegExp rxP;
	if (m_unitIndex==SC_PICAS)
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"?(\\d+\\.?\\d*)?\\b");
	else
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"(\\d+\\.?\\d*)?\\b");
	int posP = 0;
	while (posP >= 0)
	{
// 		qDebug() << "#";
		posP = rxP.indexIn(ts, posP);
		if (posP >= 0)
		{
// 			qDebug() << rxP.cap(1);
// 			qDebug() << rxP.cap(2);
			QString replacement = QString("%1%2").arg(rxP.cap(1).toDouble()*(static_cast<double>(unitGetBaseFromIndex(SC_PICAS))) + rxP.cap(2).toDouble()).arg(CommonStrings::strPT);
			ts.replace(posP, rxP.cap(0).length(), replacement);
// 			qDebug() << ts;
		}
	}
// 	qDebug() << "##" << ts;
	
	ts.replace(",", ".");
	ts.replace("%", "");
	ts.replace("°", "");
	ts.replace(FinishTag, "");
	ts = ts.trimmed();

	if (ts.endsWith(su))
		ts = ts.left(ts.length()-su.length());
	int pos = ts.length();
	while (pos > 0)
	{
		pos = ts.lastIndexOf(".", pos);
		if (pos >= 0) 
		{
			if (pos < static_cast<int>(ts.length()))
			{
				if (!ts[pos+1].isDigit())
					ts.insert(pos+1, "0 ");
			}
			pos--;
		}
	}
	if (ts.endsWith("."))
		ts.append("0");
	//CB FParser doesn't handle unicode well/at all.
	//So, instead of just getting the translated strings and
	//sticking them in as variables in the parser, if they are
	//not the same as the untranslated version, then we replace them.
	//We lose the ability for now to have some strings in languages 
	//that might use them in variables.
	//To return to previous functionality, remove the follow replacement ifs,
	//S&R in the trStr* assignments trStrPT->strPT and remove the current str* ones. 
	//IE, send the translated strings through to the regexp.
	if (CommonStrings::trStrPT.localeAwareCompare(CommonStrings::strPT)!=0)
		ts.replace(CommonStrings::trStrPT, CommonStrings::strPT);
	if (CommonStrings::trStrMM.localeAwareCompare(CommonStrings::strMM)!=0)
		ts.replace(CommonStrings::trStrMM, CommonStrings::strMM);
	if (CommonStrings::trStrIN.localeAwareCompare(CommonStrings::strIN)!=0)
		ts.replace(CommonStrings::trStrIN, CommonStrings::strIN);
	if (CommonStrings::trStrCM.localeAwareCompare(CommonStrings::strCM)!=0)
		ts.replace(CommonStrings::trStrCM, CommonStrings::strCM);
	if (CommonStrings::trStrC.localeAwareCompare(CommonStrings::trStrC)!=0)
		ts.replace(CommonStrings::trStrC, CommonStrings::strC);
	//Replace in our typed text all of the units strings with *unitstring
	QRegExp rx("\\b(\\d+)\\s*("+CommonStrings::strPT+"|"+CommonStrings::strMM+"|"+CommonStrings::strC+"|"+CommonStrings::strCM+"|"+CommonStrings::strIN+")\\b");
	pos = 0;
	while (pos >= 0) {
		pos = rx.indexIn(ts, pos);
		if (pos >= 0) {
			QString replacement = rx.cap(1) + "*" + rx.cap(2);
			ts.replace(pos, rx.cap(0).length(), replacement);
		}
	}

	//Add in the fparser constants using our unit strings, and the conversion factors.
	FunctionParser fp;
// 	setFPConstants(fp);
	fp.AddConstant(CommonStrings::strPT.toStdString(), value2value(1.0, SC_PT, m_unitIndex));
	fp.AddConstant(CommonStrings::strMM.toStdString(), value2value(1.0, SC_MM, m_unitIndex));
	fp.AddConstant(CommonStrings::strIN.toStdString(), value2value(1.0, SC_IN, m_unitIndex));
	fp.AddConstant(CommonStrings::strP.toStdString(), value2value(1.0, SC_P, m_unitIndex));
	fp.AddConstant(CommonStrings::strCM.toStdString(), value2value(1.0, SC_CM, m_unitIndex));
	fp.AddConstant(CommonStrings::strC.toStdString(), value2value(1.0, SC_C, m_unitIndex));

	fp.AddConstant("old", value());
	if (m_constants)
	{
		QMap<QString, double>::ConstIterator itend = m_constants->constEnd();
		QMap<QString, double>::ConstIterator it = m_constants->constBegin();
		while(it != itend)
		{
			fp.AddConstant(it.key().toStdString(), it.value() * unitGetRatioFromIndex(m_unitIndex));
			++it;
		}
	}
	
	int ret = fp.Parse(ts.toStdString(), "", true);
//	qDebug() << "fp return =" << ret;
	if (ret >= 0)
		return 0;
	double erg = fp.Eval(NULL);
//	qDebug() << "fp value =" << erg;
	return erg;
}
void SettingsManager::NewConfig(QString host, QString db_name, QString port, QString newuser){
    using namespace std;

    QString name;
    bool isMale;

    // only show name/gender check if the app is in firstrun mode. Otherwise, use existing values in buffer.
    if(Buffer::firstrun){
        name=FullName();
        isMale=GenderCheck();
    }
    else{
        name=Buffer::full_name;
        isMale=Buffer::is_male;
    }

    QCoreApplication::setOrganizationName("Will Kraft");
    QCoreApplication::setApplicationName("robojournal");

    QString config_path=QDir::homePath()+ QDir::separator() + ".robojournal"+ QDir::separator() + "robojournal.ini";
    QSettings settings(config_path,QSettings::IniFormat);

    QString folderpath=QDir::homePath()+ QDir::separator() + ".robojournal"+ QDir::separator();

    settings.beginGroup("Backend");
    settings.setValue("default_host", host.trimmed());
    settings.setValue("default_db", db_name.trimmed());
    settings.setValue("default_user", newuser.trimmed());
    settings.setValue("db_type", "MySQL");
    settings.setValue("port", port);
    settings.setValue("entry_range", 4);
    settings.endGroup();

    settings.beginGroup("Behavior");
    settings.setValue("toolbar_location", 1);
    settings.setValue("allow_root_login", false);
    settings.setValue("show_all_entries", true);
    settings.setValue("always_use_defaults", true);
    settings.setValue("show_warnings", true);
    settings.setValue("sort_by_day", false);
    settings.setValue("alternate_colors", true);
    settings.setValue("use_time", true);
    settings.setValue("show_title", true);
    settings.setValue("use_24_hour_clock", false);
    settings.setValue("set_date_format", 1);
    settings.setValue("enable_rich_text", false);
    settings.setValue("use_dow", true);


    if((!Buffer::show_icon_labels) && (!Buffer::firstrun)){
       settings.setValue("enable_toolbar_button_text", false);
    }
    else{
       settings.setValue("enable_toolbar_button_text", true);
    }

    settings.setValue("autoload_recent_entry", true);
    settings.setValue("ssl_support", false);
    settings.setValue("display_year_indicator", false);
    settings.setValue("use_highlights", true);
    settings.setValue("trim_whitespace", true);
    settings.setValue("smart_quotes", true);
    settings.setValue("html_hyphens", true);
    settings.setValue("use_spellcheck", false);
    settings.setValue("default_show_errors", false);

    // Bugfix: Keep dictionary and AFF blank in new configurations.
    settings.setValue("spellcheck_dictionary", "");
    settings.setValue("spellcheck_dictionary_aff", "");

    settings.setValue("misc_processing",true);
    settings.setValue("name_in_titlebar", true);
    settings.setValue("show_untagged_reminder", true);
    settings.endGroup();

    settings.beginGroup("Appearance");
    settings.setValue("background_image", "");
    settings.setValue("use_background", false);
    settings.setValue("use_theme", false);
    settings.setValue("use_theme_editor",false);
    settings.setValue("tile_background", true);
    settings.setValue("background_tree", false);
    settings.setValue("background_fixed", true);
    settings.setValue("font_color", "#000000");
    settings.setValue("font_face", "");
    settings.setValue("font_size", 16);
    settings.setValue("datebox_override", false);
    settings.setValue("highlight_color", 0);
    settings.setValue("entry_node_icon", 0);
    settings.endGroup();

    settings.beginGroup("Export");
    settings.setValue("rounded_corners", true);
    settings.setValue("system_colors", false);
    settings.setValue("include_tags", true);
    settings.setValue("header_font", "Verdana");
    settings.setValue("body_font", "Times New Roman");
    settings.setValue("header_use_em", true);
    settings.setValue("body_use_em", true);
    settings.setValue("header_font_size", 3);
    settings.setValue("body_font_size", 1.2);
    settings.endGroup();

    settings.beginGroup("User");
    settings.setValue("user_gender_male", isMale);
    settings.setValue("user_full_name", name.trimmed());

    // bugfix 12/8/12: Do not set full name to true if no name was given.
    if(name.isEmpty()){
        settings.setValue("use_full_name", false);
    }
    else{
       settings.setValue("use_full_name", true);
    }

    settings.endGroup();


    // Save the settings
    settings.sync();

    // Clear Firstrun flag
    Buffer::firstrun=false;

    // Bugfix 12/8/12:
    // Install dictionaries now so they are available immediately after firstrun is finished.
    InstallDictionaries();

    // Firstrun is now finished, allow the program to load normally by reading new config.
    LoadConfig();
}
Example #19
0
void MainWindow::preProcessFile(QString filepath)
{
    QFile file(filepath);
    if (file.open(QFile::ReadOnly))
    {
        posList.clear();

        float totalLineCount = 0;
        QTextStream code(&file);
        while ((code.atEnd() == false))
        {
            totalLineCount++;
            code.readLine();
        }
        if (totalLineCount == 0)
            totalLineCount = 1;

        code.seek(0);

        double x = 0;
        double y = 0;
        double i = 0;
        double j = 0;
        bool arc = false;
        bool cw = false;
        bool mm = true;
        int index = 0;
        int g = 0;

        bool zeroInsert = false;
        do
        {
            QString strline = code.readLine();

            index++;

            GCode::trimToEnd(strline, '(');
            GCode::trimToEnd(strline, ';');
            GCode::trimToEnd(strline, '%');

            strline = strline.trimmed();

            if (strline.size() == 0)
            {}//ignore comments
            else
            {
                strline = strline.toUpper();
                strline.replace("M6", "M06");
                strline.replace(QRegExp("([A-Z])"), " \\1");
                strline.replace(QRegExp("\\s+"), " ");
                //if (strline.contains("G", Qt::CaseInsensitive))
                {
                    if (processGCode(strline, x, y, i, j, arc, cw, mm, g))
                    {
                        if (!zeroInsert)
                        {
                            // insert 0,0 position
                            posList.append(PosItem(0, 0, 0, 0, false, false, mm, 0));
                            zeroInsert = true;
                        }
                        posList.append(PosItem(x, y, i, j, arc, cw, mm, index));

                        //printf("Got G command:%s (%f,%f)\n", strline.toLocal8Bit().constData(), x, y);
                    }
                }
            }
        } while (code.atEnd() == false);

        file.close();

        emit setItems(posList);
    }
    else
        printf("Can't open file\n");
}
Example #20
0
void UEFITool::replace(const UINT8 mode)
{
    QModelIndex index = ui->structureTreeView->selectionModel()->currentIndex();
    if (!index.isValid())
        return;

    TreeModel* model = ffsEngine->treeModel();
    QString path;
    if (model->type(index) == Types::Region) {
        if (mode == REPLACE_MODE_AS_IS) {
            path = QFileDialog::getOpenFileName(this, tr("Select region file to replace selected object"), currentDir, "Region files (*.rgn *.bin);;All files (*)");
        }
        else
            return;
    }
    else if (model->type(index) == Types::Volume) {
        if (mode == REPLACE_MODE_AS_IS) {
            path = QFileDialog::getOpenFileName(this, tr("Select volume file to replace selected object"), currentDir, "Volume files (*.vol *.bin);;All files (*)");
        }
        else if (mode == REPLACE_MODE_BODY) {
            path = QFileDialog::getOpenFileName(this, tr("Select volume body file to replace body"), currentDir, "Volume body files (*.vbd *.bin);;All files (*)");
        }
        else
            return;
    }
    else if (model->type(index) == Types::File) {
        if (mode == REPLACE_MODE_AS_IS) {
            path = QFileDialog::getOpenFileName(this, tr("Select FFS file to replace selected object"), currentDir, "FFS files (*.ffs *.bin);;All files (*)");
        }
        else if (mode == REPLACE_MODE_BODY) {
            if (model->subtype(index) == EFI_FV_FILETYPE_ALL || model->subtype(index) == EFI_FV_FILETYPE_RAW)
                path = QFileDialog::getOpenFileName(this, tr("Select raw file to replace body"), currentDir, "Raw files (*.raw *.bin);;All files (*)");
            else if (model->subtype(index) == EFI_FV_FILETYPE_PAD) // Pad file body can't be replaced
                //!TODO: handle non-empty pad files
                return;
            else
                path = QFileDialog::getOpenFileName(this, tr("Select FFS file body to replace body"), currentDir, "FFS file body files (*.fbd *.bin);;All files (*)");
        }
        else
            return;
    }
    else if (model->type(index) == Types::Section) {
        if (mode == REPLACE_MODE_AS_IS) {
            path = QFileDialog::getOpenFileName(this, tr("Select section file to replace selected object"), currentDir, "Section files (*.sct *.bin);;All files (*)");
        }
        else if (mode == REPLACE_MODE_BODY) {
            if (model->subtype(index) == EFI_SECTION_COMPRESSION || model->subtype(index) == EFI_SECTION_GUID_DEFINED || model->subtype(index) == EFI_SECTION_DISPOSABLE)
                path = QFileDialog::getOpenFileName(this, tr("Select FFS file body file to replace body"), currentDir, "FFS file body files (*.fbd *.bin);;All files (*)");
            else if (model->subtype(index) == EFI_SECTION_FIRMWARE_VOLUME_IMAGE)
                path = QFileDialog::getOpenFileName(this, tr("Select volume file to replace body"), currentDir, "Volume files (*.vol *.bin);;All files (*)");
            else if (model->subtype(index) == EFI_SECTION_RAW)
                path = QFileDialog::getOpenFileName(this, tr("Select raw file to replace body"), currentDir, "Raw files (*.raw *.bin);;All files (*)");
            else
                path = QFileDialog::getOpenFileName(this, tr("Select file to replace body"), currentDir, "Binary files (*.bin);;All files (*)");
        }
        else
            return;
    }
    else
        return;

    if (path.trimmed().isEmpty())
        return;

    QFileInfo fileInfo = QFileInfo(path);
    if (!fileInfo.exists()) {
        ui->statusBar->showMessage(tr("Please select existing file"));
        return;
    }

    QFile inputFile;
    inputFile.setFileName(path);

    if (!inputFile.open(QFile::ReadOnly)) {
        QMessageBox::critical(this, tr("Replacing failed"), tr("Can't open input file for reading"), QMessageBox::Ok);
        return;
    }

    QByteArray buffer = inputFile.readAll();
    inputFile.close();

    UINT8 result = ffsEngine->replace(index, buffer, mode);
    if (result) {
        QMessageBox::critical(this, tr("Replacing failed"), errorMessage(result), QMessageBox::Ok);
        return;
    }
    ui->actionSaveImageFile->setEnabled(true);
}
Example #21
0
void RBlock::setName(const QString& n) {
    name = n.trimmed();
}
Example #22
0
void UEFITool::extract(const UINT8 mode)
{
    QModelIndex index = ui->structureTreeView->selectionModel()->currentIndex();
    if (!index.isValid())
        return;

    TreeModel* model = ffsEngine->treeModel();
    UINT8 type = model->type(index);

    QString path;
    if (mode == EXTRACT_MODE_AS_IS) {
        switch (type) {
        case Types::Capsule:
            path = QFileDialog::getSaveFileName(this, tr("Save capsule to file"), currentDir, "Capsule files (*.cap *.bin);;All files (*)");
            break;
        case Types::Image:
            path = QFileDialog::getSaveFileName(this, tr("Save image to file"), currentDir, "Image files (*.rom *.bin);;All files (*)");
            break;
        case Types::Region:
            path = QFileDialog::getSaveFileName(this, tr("Save region to file"), currentDir, "Region files (*.rgn *.bin);;All files (*)");
            break;
        case Types::Padding:
            path = QFileDialog::getSaveFileName(this, tr("Save padding to file"), currentDir, "Padding files (*.pad *.bin);;All files (*)");
            break;
        case Types::Volume:
            path = QFileDialog::getSaveFileName(this, tr("Save volume to file"), currentDir, "Volume files (*.vol *.bin);;All files (*)");
            break;
        case Types::File:
            path = QFileDialog::getSaveFileName(this, tr("Save FFS file to file"), currentDir, "FFS files (*.ffs *.bin);;All files (*)");
            break;
        case Types::Section:
            path = QFileDialog::getSaveFileName(this, tr("Save section file to file"), currentDir, "Section files (*.sct *.bin);;All files (*)");
            break;
        default:
            path = QFileDialog::getSaveFileName(this, tr("Save object to file"), currentDir, "Binary files (*.bin);;All files (*)");
        }
    }
    else if (mode == EXTRACT_MODE_BODY) {
        switch (type) {
        case Types::Capsule:
            path = QFileDialog::getSaveFileName(this, tr("Save capsule body to image file"), currentDir, "Image files (*.rom *.bin);;All files (*)");
            break;
        case Types::Volume: 
            path = QFileDialog::getSaveFileName(this, tr("Save volume body to file"), currentDir, "Volume body files (*.vbd *.bin);;All files (*)");
            break;
        case Types::File: {
            if (model->subtype(index) == EFI_FV_FILETYPE_ALL || model->subtype(index) == EFI_FV_FILETYPE_RAW)
                path = QFileDialog::getSaveFileName(this, tr("Save FFS file body to raw file"), currentDir, "Raw files (*.raw *.bin);;All files (*)");
            else
                path = QFileDialog::getSaveFileName(this, tr("Save FFS file body to file"), currentDir, "FFS file body files (*.fbd *.bin);;All files (*)");
        }
            break;
        case Types::Section: {
            if (model->subtype(index) == EFI_SECTION_COMPRESSION || model->subtype(index) == EFI_SECTION_GUID_DEFINED || model->subtype(index) == EFI_SECTION_DISPOSABLE)
                path = QFileDialog::getSaveFileName(this, tr("Save encapsulation section body to FFS body file"), currentDir, "FFS file body files (*.fbd *.bin);;All files (*)");
            else if (model->subtype(index) == EFI_SECTION_FIRMWARE_VOLUME_IMAGE)
                path = QFileDialog::getSaveFileName(this, tr("Save section body to volume file"), currentDir, "Volume files (*.vol *.bin);;All files (*)");
            else if (model->subtype(index) == EFI_SECTION_RAW)
                path = QFileDialog::getSaveFileName(this, tr("Save section body to raw file"), currentDir, "Raw files (*.raw *.bin);;All files (*)");
            else
                path = QFileDialog::getSaveFileName(this, tr("Save section body to file"), currentDir, "Binary files (*.bin);;All files (*)");
        }
            break;
        default:
            path = QFileDialog::getSaveFileName(this, tr("Save object to file"), currentDir, "Binary files (*.bin);;All files (*)");
        }
    }
    else
        path = QFileDialog::getSaveFileName(this, tr("Save object to file"), currentDir, "Binary files (*.bin);;All files (*)");

    if (path.trimmed().isEmpty())
        return;

    QByteArray extracted;
    UINT8 result = ffsEngine->extract(index, extracted, mode);
    if (result) {
        QMessageBox::critical(this, tr("Extraction failed"), errorMessage(result), QMessageBox::Ok);
        return;
    }

    QFile outputFile;
    outputFile.setFileName(path);
    if (!outputFile.open(QFile::WriteOnly)) {
        QMessageBox::critical(this, tr("Extraction failed"), tr("Can't open output file for rewriting"), QMessageBox::Ok);
        return;
    }
    outputFile.resize(0);
    outputFile.write(extracted);
    outputFile.close();
}
Example #23
0
void SopoMygga::addTopicMatch(QString topic, int topic_d) {
    m_topics.insert(topic.trimmed(), topic_d);
}
Example #24
0
 foreach (const QString& v, f) {
     fmts.append(v.trimmed());
 }
Example #25
0
UDSEntry Adb::getEntry(const QString &lineFull) {
	if(lineFull.trimmed() == opendir_failed) {
		// FIXME: der string da oben wird wohl bei jedem android device anders sein ...
		QString errorMessage=ERR_ACCESS_DENIED+"|error entering directory";
		throw errorMessage;
	}
	UDSEntry entry;
	QString perm, owner, group, size, filename;
	time_t mtime;
	this->splitLsLine(lineFull, perm, owner, group, size, mtime, filename);

	// this->error( ERR_CANNOT_ENTER_DIRECTORY, path);
	entry.insert( KIO::UDSEntry::UDS_NAME, filename );
	entry.insert( KIO::UDSEntry::UDS_SIZE, size.toInt() );
	entry.insert( KIO::UDSEntry::UDS_MODIFICATION_TIME, mtime );
	// entry.insert( KIO::UDSEntry::UDS_ACCESS, 0664 );
	// entry.insert( KIO::UDSEntry::UDS_USER, 1000 );
	// entry.insert( KIO::UDSEntry::UDS_GROUP, 1000 );
	// entry.insert ( UDSEntry::UDS_NAME, QLatin1String ( "Adb:///" ) );
	if(perm[0] == 'd') {
		qDebug() << "directory";
		entry.insert ( UDSEntry::UDS_FILE_TYPE, S_IFDIR );
		entry.insert ( UDSEntry::UDS_MIME_TYPE, QLatin1String ( "inode/directory" ) );
		entry.insert ( UDSEntry::UDS_ICON_NAME, QLatin1String ( "drive-removable-media" ) );
	} else if(perm[0] == 'l') {
		QRegExp linkRegex("->\\s*(.*)\\s*$",Qt::CaseSensitive,QRegExp::RegExp2);
		if (linkRegex.indexIn(lineFull) > 0) {
			QStringList list = linkRegex.capturedTexts();
			// das sollt nur [2] sein FIXME error handling
			QString link = list[1];
			entry.insert( UDSEntry::UDS_LINK_DEST, link );
			QStringList arguments;
			arguments << "shell";
			arguments << ( "[ -d " + link + " ] && echo -n true" ) ;
			QByteArray read_stdout, read_stderr;
			int rc=this->exec(arguments, read_stdout, read_stderr);
			if(rc != 0) {
				QString errorMessage=ERR_COULD_NOT_READ+"|error calling adb "+read_stderr;
				throw errorMessage;
			}
			qDebug() << "link: ["+link+"]";
			qDebug() << "check sagt: " << read_stdout << "\n" << read_stderr;
			if(read_stdout == "true") {
				qDebug() << "softlink isDirectory";
				entry.insert( KIO::UDSEntry::UDS_GUESSED_MIME_TYPE, QString::fromLatin1( "inode/directory" ) );
			}
			// FIXME: sollt ma da 
			// void SlaveBase::redirection	(	const QUrl & 	_url	)	
			// aufrufen???
		} else {
			qDebug() << "regex match failed for >>>"<<lineFull<< "<<<";
			QString errorMessage = ERR_CANNOT_ENTER_DIRECTORY + "|error getting softlink target for "+lineFull+" [regex match failed]";
			throw errorMessage;
		}
	} else {
		qDebug() << "file";
		entry.insert ( UDSEntry::UDS_FILE_TYPE, S_IFREG);
	}
	entry.insert ( UDSEntry::UDS_ACCESS, S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH );
	return entry;
}
Example #26
0
bool HttpServer::registerRoute(const QString& method, const QString& actionName, const QString& path, Visibility visibility)
{
  return registerRoute(Utils::fromString(method.trimmed().toUpper()), actionName, path, visibility);
}
 void handleArgumentsChanged(const QString &arguments) {
     m_runConfig->setArguments(arguments.trimmed());
 }
Example #28
0
bool HttpServer::initialize()
{
  if(m_IsInitialized)
  {
    LOG_DEBUG("Already initialized");
    return false;
  }

  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  if(env.contains(QTTP_HOME_ENV_VAR))
  {
    QDir::setCurrent(env.value(QTTP_HOME_ENV_VAR));
    LOG_DEBUG("Working directory from $" << QTTP_HOME_ENV_VAR << QDir::currentPath());
  }
  else
  {
    // Just a quirk for mac, but I wonder if we can apply to all in general.
    #ifdef Q_OS_MAC
    QDir::setCurrent(qApp->applicationDirPath());
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #else
    LOG_DEBUG("Working directory" << QDir::currentPath());
    #endif
  }

  QCoreApplication* app = QCoreApplication::instance();
  Q_ASSERT(app);

  m_CmdLineParser.addOptions({
    {{"i", "ip"},
     QCoreApplication::translate("main", "ip of the target interface"),
     QCoreApplication::translate("main", "ip")},
    {{"p", "port"},
     QCoreApplication::translate("main", "port to listen on"),
     QCoreApplication::translate("main", "port")},
    {{"m", "meta"},
     QCoreApplication::translate("main", "appends metadata to responses")},
    {{"c", "config"},
     QCoreApplication::translate("main", "absolute path to the global config file (json)"),
     QCoreApplication::translate("main", "config")},
    {{"r", "routes"},
     QCoreApplication::translate("main", "absolute path to the routes config file (json)"),
     QCoreApplication::translate("main", "routes")},
    {{"d", "dir"},
     QCoreApplication::translate("main", "absolute path to the config directory, don't combine with -c or -r args"),
     QCoreApplication::translate("main", "dir")},
    {{"w", "www"},
     QCoreApplication::translate("main", "absolute path to the www folder to serve http files"),
     QCoreApplication::translate("main", "www")},
    {{"s", "swagger"},
     QCoreApplication::translate("main", "exposes swagger-api json responses for the path /swagger/")},
  });

  m_CmdLineParser.addHelpOption();
  m_CmdLineParser.process(*app);

  if(env.contains(CONFIG_DIRECTORY_ENV_VAR))
  {
    QString var = env.value(CONFIG_DIRECTORY_ENV_VAR);
    if(!var.isNull() && !var.trimmed().isEmpty())
    {
      LOG_INFO("Processing ENVIRONMENT VARIABLE [" << var << "]");
      initConfigDirectory(var);
    }
    else
    {
      LOG_WARN("Invalid ENVIRONMENT VARIABLE [" << CONFIG_DIRECTORY_ENV_VAR << "]");
    }
  }

  QJsonValue d = m_CmdLineParser.value("d");
  if(d.isString() && !d.isNull() && !d.toString().trimmed().isEmpty())
  {
    initConfigDirectory(d.toString());
  }
  else
  {
    QJsonValue c = m_CmdLineParser.value("c");
    if(c.isString() && !c.isNull() && !c.toString().trimmed().isEmpty())
    {
      initGlobal(c.toString());
    }
    else
    {
      initGlobal(GLOBAL_CONFIG_FILE_PATH);
    }

    QJsonValue r = m_CmdLineParser.value("r");
    if(r.isString() && !r.isNull() && !r.toString().trimmed().isEmpty())
    {
      initRoutes(r.toString());
    }
    else
    {
      initRoutes(ROUTES_CONFIG_FILE_PATH);
    }
  }

  if(!m_SendRequestMetadata)
  {
    m_SendRequestMetadata = m_CmdLineParser.isSet("m");
    LOG_DEBUG("CmdLine meta-data" << m_SendRequestMetadata);
  }

  if(!m_IsSwaggerEnabled)
  {
    initSwagger(m_CmdLineParser.isSet("s"));
    LOG_DEBUG("CmdLine swagger" << m_IsSwaggerEnabled);
  }

  QJsonValue i = m_CmdLineParser.value("i");
  if((i.isString() || i.isDouble()) && !i.toString().trimmed().isEmpty())
  {
    QString ip = i.toString();
    m_GlobalConfig["bindIp"] = ip;
    LOG_DEBUG("CmdLine ip" << ip);
  }

  QJsonValue p = m_CmdLineParser.value("p");
  if((p.isString() || p.isDouble()) && !p.toString().trimmed().isEmpty())
  {
    qint32 port = p.toInt();
    m_GlobalConfig["bindPort"] = port;
    LOG_DEBUG("CmdLine port" << port);
  }

  QJsonValue w = m_CmdLineParser.value("w");
  if(w.isString() && !w.isNull() && !w.toString().trimmed().isEmpty())
  {
    initHttpDirectory(w.toString());
    LOG_DEBUG("CmdLine www/web/http-files" << w);
  }

  m_IsInitialized = true;

  return true;
}
Example #29
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
Example #30
0
bool StringHandler::unparseBool(QString value)
{
  value = value.trimmed();
  return value == "true";
}