Esempio n. 1
0
int MainWindow::getDataMetadata( const int i_CodecInput, const int i_OutputFormat, const QString &s_MetadataIn, QStringList &sl_DataMetadataList, structURL URL[], const int i_NumOfFiles )
{
    int             n                   = 0;

    int             j                   = 0;
    int             i_line              = 0;
    int             stopProgress      = 0;

    int             i_DatePos           = -1;
    int             i_TimePos           = -1;
    int             i_DateTimePos       = -1;
    int             i_ElevationPos      = -1;
    int             i_EventLabelPos     = -1;
    int             i_CampaignLabelPos  = -1;
    int             i_AreaNamePos       = -1;
    int             i_GearNamePos       = -1;
    int             i_LatitudePos       = -1;
    int             i_LongitudePos      = -1;

    QStringList     sl_Input;

    QString         s_Metadata          = "";
    QString         s_EventLabel        = "";
    QString         s_Header            = "";
    QString         s_LatLon            = "";

    bool            b_containsPosition  = false;

    sl_DataMetadataList.clear();

//-----------------------------------------------------------------------------------------------------------------------

    b_containsPosition = getDataMetadataPosition( s_MetadataIn, i_DatePos, i_TimePos, i_DateTimePos, i_ElevationPos, i_EventLabelPos, i_CampaignLabelPos, i_AreaNamePos, i_GearNamePos, i_LatitudePos, i_LongitudePos );

//-----------------------------------------------------------------------------------------------------------------------

    if ( ( n = readFile( s_MetadataIn.section( "\t", _FILENAMEPOS, _FILENAMEPOS ), sl_Input, i_CodecInput ) ) < 1 )
        return( n );

//-----------------------------------------------------------------------------------------------------------------------

    switch ( i_OutputFormat )
    {
      case _FORMAT_KMLFILE:
        initProgress( i_NumOfFiles, s_MetadataIn.section( "\t", _FILENAMEPOS, _FILENAMEPOS ), tr( "Creating Google Earth import file" ), n );
        break;

      case _FORMAT_SHAPE_METADATA:
      case _FORMAT_SHAPE_DATA:
        initProgress( i_NumOfFiles, s_MetadataIn.section( "\t", _FILENAMEPOS, _FILENAMEPOS ), tr( "Creating shapefile" ), n );
        break;

      default:
        initProgress( i_NumOfFiles, s_MetadataIn.section( "\t", _FILENAMEPOS, _FILENAMEPOS ), tr( "Creating file" ), n );
        break;
    }

//-----------------------------------------------------------------------------------------------------------------------

    i_line = s_MetadataIn.section( "\t", _NUMOFHEADERLINESPOS, _NUMOFHEADERLINESPOS ).toInt()-1;

    if ( sl_Input.at( i_line ) == "*/" )
        ++i_line;

    for ( int i=0; i<NumOfSections( sl_Input.at( i_line ) ); ++i )
    {
        s_Header = sl_Input.at( i_line ).section( "\t", i, i );

        if ( ( s_Header.startsWith( "url", Qt::CaseInsensitive ) == true ) || ( s_Header.startsWith( "uri", Qt::CaseInsensitive ) == true ) || ( s_Header.startsWith( "persistent identifier", Qt::CaseInsensitive ) == true ) )
        {
            if ( ++j <= _MAX_NUM_OF_URLS )
            {
                URL[j].position = i;

                if ( s_Header.contains( "@" ) == true )
                    URL[j].TitleURL = s_Header.section( "@", 1, 1 );
                else
                    URL[j].TitleURL = s_Header;
            }
        }
    }

    stopProgress = incProgress( i_NumOfFiles, i_line );

//-----------------------------------------------------------------------------------------------------------------------

    ++i_line;
    parseData( i_line, sl_Input.at( i_line ), s_MetadataIn, i_AreaNamePos, i_CampaignLabelPos, i_EventLabelPos, i_GearNamePos, i_DatePos, i_TimePos, i_DateTimePos, i_LatitudePos, i_LongitudePos, i_ElevationPos, URL, s_Metadata );
    addToMetadataList( s_Metadata, s_EventLabel, s_LatLon, sl_DataMetadataList );

    stopProgress = incProgress( i_NumOfFiles, i_line );

    if ( b_containsPosition == true )
    {
        while ( ( ++i_line < n ) && ( stopProgress != _APPBREAK_ ) )
        {
            parseData( i_line, sl_Input.at( i_line ), s_MetadataIn, i_AreaNamePos, i_CampaignLabelPos, i_EventLabelPos, i_GearNamePos, i_DatePos, i_TimePos, i_DateTimePos, i_LatitudePos, i_LongitudePos, i_ElevationPos, URL, s_Metadata );
            addToMetadataList( s_Metadata, s_EventLabel, s_LatLon, sl_DataMetadataList );

            stopProgress = incProgress( i_NumOfFiles, i_line );
        }
    }

//-----------------------------------------------------------------------------------------------------------------------

    resetProgress( i_NumOfFiles );

    return( _NOERROR_ );
}
Esempio n. 2
0
AboutPlugins::AboutPlugins( Config *_config, QWidget* parent, Qt::WFlags f )
    : KDialog( parent, f ),
    config( _config ),
    currentPlugin( 0 )
{
    setCaption( i18n("About plugins") );
    setWindowIcon( KIcon("preferences-plugin") );
    setButtons( KDialog::Close );
    setButtonFocus( KDialog::Close );

    QWidget *widget = new QWidget( this );
    setMainWidget( widget );
    QHBoxLayout *box = new QHBoxLayout( widget );

    QVBoxLayout *pluginListBox = new QVBoxLayout( widget );
    box->addLayout( pluginListBox );

    QLabel *installedPlugins = new QLabel( i18n("Installed plugins:"), this );
    pluginListBox->addWidget( installedPlugins );

    QListWidget *pluginsList = new QListWidget( this );
    pluginListBox->addWidget( pluginsList );
    connect( pluginsList, SIGNAL(currentTextChanged(const QString&)), this, SLOT(currentPluginChanged(const QString&)) );

    QStringList pluginNames;
    QList<CodecPlugin*> codecPlugins = config->pluginLoader()->getAllCodecPlugins();
    for( int i=0; i<codecPlugins.count(); i++ )
    {
        pluginNames += codecPlugins.at(i)->name();
    }
    pluginNames.sort();
    pluginsList->addItems( pluginNames );

    pluginNames.clear();
    QList<FilterPlugin*> filterPlugins = config->pluginLoader()->getAllFilterPlugins();
    for( int i=0; i<filterPlugins.count(); i++ )
    {
        pluginNames += filterPlugins.at(i)->name();
    }
    pluginNames.sort();
    pluginsList->addItems( pluginNames );

    pluginNames.clear();
    QList<ReplayGainPlugin*> replaygainPlugins = config->pluginLoader()->getAllReplayGainPlugins();
    for( int i=0; i<replaygainPlugins.count(); i++ )
    {
        pluginNames += replaygainPlugins.at(i)->name();
    }
    pluginNames.sort();
    pluginsList->addItems( pluginNames );

    pluginNames.clear();
    QList<RipperPlugin*> ripperPlugins = config->pluginLoader()->getAllRipperPlugins();
    for( int i=0; i<ripperPlugins.count(); i++ )
    {
        pluginNames += ripperPlugins.at(i)->name();
    }
    pluginNames.sort();
    pluginsList->addItems( pluginNames );

    pluginsList->setFixedWidth( 180 );

    box->addSpacing( 10 );

    QVBoxLayout *pluginInfoBox = new QVBoxLayout( widget );
    box->addLayout( pluginInfoBox );

    aboutPluginLabel = new QLabel( this );
    aboutPluginLabel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred );
    aboutPluginLabel->setWordWrap( true );
    aboutPluginLabel->setTextFormat( Qt::RichText );
    pluginInfoBox->addWidget( aboutPluginLabel );
    connect( aboutPluginLabel, SIGNAL(linkActivated(const QString&)), this, SLOT(showProblemInfo(const QString&)) );

    pluginInfoBox->addStretch();

    QHBoxLayout *configurePluginBox = new QHBoxLayout( widget );
    pluginInfoBox->addLayout( configurePluginBox );
    configurePlugin = new KPushButton( KIcon("configure"), "", widget );
    configurePlugin->hide();
    configurePluginBox->addWidget( configurePlugin );
    configurePluginBox->addStretch();
    connect( configurePlugin, SIGNAL(clicked()), this, SLOT(configurePluginClicked()) );

    pluginsList->setCurrentRow(0);
    QListWidgetItem *currentItem = pluginsList->currentItem();
    if( currentItem )
    {
        currentPluginChanged( currentItem->text() );
    }

    setInitialSize( QSize(500,300) );
    KSharedConfig::Ptr conf = KGlobal::config();
    KConfigGroup group = conf->group( "AboutPlugins" );
    restoreDialogSize( group );
}
Esempio n. 3
0
NewX509::NewX509(QWidget *parent)
	:QDialog(parent)
{
	int i;
	eku_nid = *MainWindow::eku_nid;
	dn_nid = *MainWindow::dn_nid;
	aia_nid = *MainWindow::aia_nid;
	attr_nid << NID_pkcs9_unstructuredName << NID_pkcs9_challengePassword;

	QStringList keys;

	setupUi(this);

	/* temporary storage for creating temporary X509V3_CTX */
	ctx_cert = NULL;

	for (i=0; i < dn_nid.count(); i++)
		keys << QString(OBJ_nid2ln(dn_nid[i]));

	extDNlist->setKeys(keys);
	extDNlist->setInfoLabel(extDNinfo);
	connect(extDNlist->itemDelegateForColumn(1),
		SIGNAL(setupLineEdit(const QString &, QLineEdit *)),
		this, SLOT(setupExtDNwidget(const QString &, QLineEdit *)));
	setWindowTitle(XCA_TITLE);

	for (i=0; i<tabWidget->count(); i++) {
		tabnames << tabWidget->tabText(i);
	}

	nsImg->setPixmap(*MainWindow::nsImg);
	serialNr->setValidator(new QRegExpValidator(QRegExp("[0-9a-fA-F]*"), this));
	QStringList strings;

	// are there any useable private keys  ?
	newKeyDone("");

	// any PKCS#10 requests to be used ?
	strings = MainWindow::reqs->getDesc();
	if (strings.isEmpty()) {
		fromReqCB->setDisabled(true);
		fromReqCB->setChecked(false);
	}
	else {
		reqList->insertItems(0, strings);
	}
	on_fromReqCB_clicked();

	// How about signing certificates ?
	strings = MainWindow::certs->getSignerDesc();
	if (strings.isEmpty()) {
		foreignSignRB->setDisabled(true);
	} else {
		certList->insertItems(0, strings);
	}
#ifdef WG_QA_SERIAL
	selfQASignRB = new QRadioButton(signerBox);
	setTabOrder(serialNr, selfQASignRB);
	setTabOrder(selfQASignRB, foreignSignRB);
	selfQASignRB->setText(tr(
			"Create a &self signed certificate with a MD5-hashed QA serial"));
	QBoxLayout *l = (QBoxLayout *)signerBox->layout();
	l->insertWidget(1, selfQASignRB);
#endif
	// set dates to now and now + 1 year
	validNumber->setText("1");
	validRange->setCurrentIndex(2);
	on_applyTime_clicked();

	// settings for the templates ....
	strings.clear();
	strings = MainWindow::temps->getDescPredefs();
	tempList->insertItems(0, strings);

	// setup Extended keyusage
	for (i=0; i < eku_nid.count(); i++)
		ekeyUsage->addItem(OBJ_nid2ln(eku_nid[i]));

	// setup Authority Info Access
	for (i=0; i < aia_nid.count(); i++)
		aiaOid->addItem(OBJ_nid2ln(aia_nid[i]));

	// init the X509 v3 context
	X509V3_set_ctx(&ext_ctx, NULL , NULL, NULL, NULL, 0);
	X509V3_set_ctx_nodb(&ext_ctx);

	QList<QLabel *> nameLabel;
	nameLabel << LcountryName << LstateOrProvinceName << LlocalityName <<
	LorganisationName << LorganisationalUnitName << LcommonName <<
	LemailAddress;

	for(int i=0; i<nameLabel.count(); i++) {
		nameLabel[i]->setText(OBJ_nid2ln(name_nid[i]));
		QString tt = nameLabel[i]->toolTip();
		nameLabel[i]->setToolTip(QString("[%1] %2").
			arg(OBJ_nid2sn(name_nid[i])).arg(tt));
		name_ptr[i] = (QLineEdit *)nameLabel[i]->buddy();
		setupLineEditByNid(name_nid[i], name_ptr[i]);
	}
	// Setup Request Attributes
	if (attrWidget->layout())
		delete attrWidget->layout();
	QGridLayout *attrLayout = new QGridLayout(attrWidget);
	attrLayout->setAlignment(Qt::AlignTop);
	attrLayout->setSpacing(6);
	attrLayout->setMargin(0);
	attr_edit.clear();
	for (i=0; i < attr_nid.count(); i++) {
		QLabel *label;
		QLineEdit *edit;
		int nid = attr_nid[i];
		label = new QLabel(this);
		label->setText(QString(OBJ_nid2ln(nid)));
		label->setToolTip(QString(OBJ_nid2sn(nid)));
		edit = new QLineEdit(this);
		attr_edit << edit;
		attrLayout->addWidget(label, i, 0);
		attrLayout->addWidget(edit, i, 1);
		setupLineEditByNid(nid, edit);
	}
	// last polish
	on_certList_currentIndexChanged(0);
	certList->setDisabled(true);
	tabWidget->setCurrentIndex(0);
	attrWidget->hide();
	pt = none;
	notAfter->setEndDate(true);
}
Esempio n. 4
0
void Recognizer::parseFile(const QString & infileName, const QString & outfileName)
{
    QFile inFile(infileName);
    if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QFile outFile(outfileName);
    if (!outfileName.isEmpty() && !outFile.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    // use textstream instead of direct file reading for prevent
    // problems with different RETURN symbol on different platforms
    // textstream always returns trimmed string
    QTextStream in(&inFile);
    QTextStream out(&outFile);

    QStringList lineList;
    QString line;

    do {
        line = in.readLine();
        lineList.append(line);

        // 4 lines read so starting to process them
        if (lineList.count() == 4) {

            QString accountNumber = decodeValue(lineList);
            ErrorCode code = checkSum(accountNumber);

            // correct errors if possible
            QStringList possibleVariants;
            if (code == ILL || code == ERR) {
                code = errorCorrection(lineList, &possibleVariants);
            }

            QString formattedString;

            // was value corrected or or it's iginal
            if (possibleVariants.size() == 1)
                formattedString.append(possibleVariants[0]);
            else
                formattedString.append(accountNumber);

            // status
            if (code == AMB) {
                formattedString += "  " + errorToString(code) + "  [\'" + possibleVariants.join("\',\'") + "\']";
            } else
                formattedString += "  " + errorToString(code);


            if (outfileName.isEmpty())
                std::cout << formattedString.toStdString() << std::endl;
            else
                out << formattedString << "\n";

            lineList.clear();
            possibleVariants.clear();
        }
    } while(!line.isNull());

    inFile.close();
    if (outFile.isOpen())
        outFile.close();
}
Esempio n. 5
0
int main( int argc, char **argv )
{
    QString defaultContext = "@default";
    MetaTranslator fetchedTor;
    QByteArray codecForTr;
    QByteArray codecForSource;
    QStringList tsFileNames;
    QStringList uiFileNames;

    bool verbose = false;
    bool noObsolete = false;
    bool metSomething = false;
    int numFiles = 0;
    bool standardSyntax = true;
    bool metTsFlag = false;

    int i;

    for ( i = 1; i < argc; i++ ) {
        if ( qstrcmp(argv[i], "-ts") == 0 )
            standardSyntax = false;
    }

    for ( i = 1; i < argc; i++ ) {
        if ( qstrcmp(argv[i], "-help") == 0 ) {
            printUsage();
            return 0;
        } else if ( qstrcmp(argv[i], "-noobsolete") == 0 ) {
            noObsolete = true;
            continue;
        } else if ( qstrcmp(argv[i], "-verbose") == 0 ) {
            verbose = true;
            continue;
        } else if ( qstrcmp(argv[i], "-version") == 0 ) {
            fprintf( stderr, "pylupdate4 version %s\n", QT_VERSION_STR );
            return 0;
        } else if ( qstrcmp(argv[i], "-ts") == 0 ) {
            metTsFlag = true;
            continue;
        }

        numFiles++;

        QString fullText;

        if ( !metTsFlag ) {
            QFile f( argv[i] );
            if ( !f.open(QIODevice::ReadOnly) ) {
#if defined(_MSC_VER) && _MSC_VER >= 1400
                char buf[100];
                strerror_s(buf, sizeof(buf), errno);
                fprintf( stderr, "pylupdate4 error: Cannot open file '%s': %s\n",
                         argv[i], buf );
#else
                fprintf( stderr, "pylupdate4 error: Cannot open file '%s': %s\n",
                         argv[i], strerror(errno) );
#endif
                return 1;
            }

            QTextStream t( &f );
            fullText = t.readAll();
            f.close();
        }

        QString oldDir = QDir::currentPath();
        QDir::setCurrent( QFileInfo(argv[i]).path() );

        if ( standardSyntax ) {
            fetchedTor = MetaTranslator();
            codecForTr.clear();
            codecForSource.clear();
            tsFileNames.clear();
            uiFileNames.clear();

            QMap<QString, QString> tagMap = proFileTagMap( fullText );
            QMap<QString, QString>::Iterator it;

            for ( it = tagMap.begin(); it != tagMap.end(); ++it ) {
                QStringList toks = it.value().split(' ');
                QStringList::Iterator t;

                for ( t = toks.begin(); t != toks.end(); ++t ) {
                    if ( it.key() == "SOURCES" ) {
                        fetchtr_py( (*t).toAscii(), &fetchedTor, defaultContext.toAscii(), true, codecForSource );
                        metSomething = true;
                    } else if ( it.key() == "TRANSLATIONS" ) {
                        tsFileNames.append( *t );
                        metSomething = true;
                    } else if ( it.key() == "CODEC" ||
                                it.key() == "DEFAULTCODEC" ||
                                it.key() == "CODECFORTR" ) {
                        codecForTr = (*t).toLatin1();
                        fetchedTor.setCodecForTr(codecForTr);
                    } else if ( it.key() == "CODECFORSRC" ) {
                        codecForSource = (*t).toLatin1();
                    } else if ( it.key() == "FORMS" ) {
                fetchtr_ui( (*t).toAscii(), &fetchedTor, defaultContext.toAscii(), true);
            }
                }
            }

            updateTsFiles( fetchedTor, tsFileNames, codecForTr, noObsolete, verbose );

            if ( !metSomething ) {
                fprintf( stderr,
                         "pylupdate4 warning: File '%s' does not look like a"
                         " project file\n",
                         argv[i] );
            } else if ( tsFileNames.isEmpty() ) {
                fprintf( stderr,
                         "pylupdate4 warning: Met no 'TRANSLATIONS' entry in"
                         " project file '%s'\n",
                         argv[i] );
            }
        } else {
            if ( metTsFlag ) {
                if ( QString(argv[i]).toLower().endsWith(".ts") ) {
                    QFileInfo fi( argv[i] );
                    if ( !fi.exists() || fi.isWritable() ) {
                        tsFileNames.append( argv[i] );
                    } else {
                        fprintf( stderr,
                                 "pylupdate4 warning: For some reason, I cannot"
                                 " save '%s'\n",
                                 argv[i] );
                    }
        } else {
                    fprintf( stderr,
                             "pylupdate4 error: File '%s' lacks .ts extension\n",
                             argv[i] );
                }
            } else {
                QFileInfo fi(argv[i]);
        if ( fi.suffix() == "py" || fi.suffix() == "pyw" ) {
            fetchtr_py( fi.fileName().toAscii(), &fetchedTor, defaultContext.toAscii(), true, codecForSource );
        } else {
            fetchtr_ui( fi.fileName().toAscii(), &fetchedTor, defaultContext.toAscii(), true);
        }
            }
        }
        QDir::setCurrent( oldDir );
    }

    if ( !standardSyntax )
        updateTsFiles( fetchedTor, tsFileNames, codecForTr, noObsolete, verbose );

    if ( numFiles == 0 ) {
        printUsage();
        return 1;
    }
    return 0;
}
QgsDelimitedTextFile::Status QgsDelimitedTextFile::parseQuoted( QStringList &fields )
{
  fields.clear();

  // Find the first non-blank line to read
  QString buffer;
  Status status = nextLine( buffer, true );
  if ( status != RecordOk ) return status;
  mRecordLineNumber = mLineNumber;

  QString field;        // String in which to accumulate next field
  bool escaped = false; // Next char is escaped
  bool quoted = false;  // In quotes
  QChar quoteChar = 0;  // Actual quote character used to open quotes
  bool started = false; // Non-blank chars in field or quotes started
  bool ended = false;   // Quoted field ended
  int cp = 0;          // Pointer to the next character in the buffer
  int cpmax = buffer.size(); // End of string

  while ( true )
  {
    QChar c = buffer[cp];
    cp++;

    // If end of line then if escaped or buffered then try to get more...
    if ( cp > cpmax )
    {
      if ( quoted || escaped )
      {
        status = nextLine( buffer, false );
        if ( status != RecordOk ) return status;
        field.append( '\n' );
        cp = 0;
        cpmax = buffer.size();
        escaped = false;
        continue;
      }
      break;
    }

    // If escaped, then just append the character
    if ( escaped )
    {
      field.append( c );
      escaped = false;
      continue;
    }

    // Determine if this is a special character - test each class in turn
    // Note that delimiters are not valid as quotes or escape character
    //
    // Somewhat convoluted logic around quote and escape chars is
    // to enforce logic for escape characters that are also quote characters.
    // These escapes can only escape themselves and only in quotes using them
    // as delimiters!

    bool isQuote = false;
    bool isEscape = false;
    bool isDelim = mDelimChars.contains( c );
    if ( ! isDelim )
    {
      bool isQuoteChar = mQuoteChar.contains( c );
      isQuote = quoted ? c == quoteChar : isQuoteChar;
      isEscape = mEscapeChar.contains( c );
      if ( isQuoteChar && isEscape ) isEscape = isQuote;
    }

    // Start or end of quote ...
    if ( isQuote )
    {
      // quote char in quoted field
      if ( quoted )
      {
        // if is also escape and next character is quote, then
        // escape the quote..
        if ( isEscape && buffer[cp] == quoteChar )
        {
          field.append( quoteChar );
          cp++;
        }
        // Otherwise end of quoted field
        else
        {
          quoted = false;
          ended =  true;
        }
      }
      // quote char at start of field .. start of quoted fields
      else if ( ! started )
      {
        field.clear();
        quoteChar = c;
        quoted = true;
        started = true;
      }
      // Cannot have a quote embedded in a field
      else
      {
        fields.clear();
        return RecordInvalid;
      }
    }
    // If escape char, then next char is escaped...
    else if ( isEscape )
    {
      escaped = true;
    }
    // If within quotes, then append to the string
    else if ( quoted )
    {
      field.append( c );
    }
    // If it is a delimiter, then end of field...
    else if ( isDelim )
    {
      if ( mMaxFields <= 0 || fields.size() < mMaxFields )
      {
        // If wasn't quoted, then trim..
        if ( mTrimFields && ! ended ) field = field.trimmed();
        if ( ! field.isEmpty() || ended || ! mDiscardEmptyFields ) fields.append( field );
      }
      // Clear the field
      field.clear();
      started = false;
      ended = false;
    }
    // Whitespace is permitted before the start of a field, or
    // after the end..
    else if ( c.isSpace() )
    {
      if ( ! ended ) field.append( c );
    }
    // Other chars permitted if not after quoted field
    else
    {
      if ( ended )
      {
        fields.clear();
        return RecordInvalid;
      }
      field.append( c );
      started = true;
    }
  }
  // If reached the end of the record, then add the last field...
  if ( started && ( mMaxFields <= 0 || fields.size() < mMaxFields ) )
  {
    if ( mTrimFields && ! ended ) field = field.trimmed();
    if ( ! field.isEmpty() || ended || ! mDiscardEmptyFields ) fields.append( field );
  }
  return RecordOk;
}
Esempio n. 7
0
bool AACEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
	QProcess process;
	QStringList args;
	const QString baseName = QFileInfo(outputFile).fileName();

	switch(m_configRCMode)
	{
	case SettingsModel::VBRMode:
		args << "-q" << QString().sprintf("%.2f", double(qBound(0, m_configBitrate * 5, 100)) / 100.0);
		break;
	case SettingsModel::ABRMode:
		args << "-br" << QString::number(qBound(8, index2bitrate(m_configBitrate), 400) * 1000);
		break;
	case SettingsModel::CBRMode:
		args << "-cbr" << QString::number(qBound(8, index2bitrate(m_configBitrate), 400) * 1000);
		break;
	default:
		THROW("Bad rate-control mode!");
		break;
	}

	if(m_configEnable2Pass && (m_configRCMode == SettingsModel::ABRMode))
	{
		args << "-2pass";
	}
	
	switch(m_configProfile)
	{
	case 1:
		args << "-lc"; //Forces use of LC AAC profile
		break;
	case 2:
		args << "-he"; //Forces use of HE AAC profile
		break;
	case 3:
		args << "-hev2"; //Forces use of HEv2 AAC profile
		break;
	}

	if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);

	args << "-if" << QDir::toNativeSeparators(sourceFile);
	args << "-of" << QDir::toNativeSeparators(outputFile);

	if(!startProcess(process, m_binary_enc, args))
	{
		return false;
	}

	bool bTimeout = false;
	bool bAborted = false;
	int prevProgress = -1;


	QRegExp regExp("Processed\\s+(\\d+)\\s+seconds");
	QRegExp regExp_pass1("First\\s+pass:\\s+processed\\s+(\\d+)\\s+seconds");
	QRegExp regExp_pass2("Second\\s+pass:\\s+processed\\s+(\\d+)\\s+seconds");

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("NeroAacEnc process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(regExp_pass1.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp_pass1.cap(1).toInt(&ok);
				if(ok && (duration > 0))
				{
					int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 50.0);
					if(newProgress > prevProgress)
					{
						emit statusUpdated(newProgress);
						prevProgress = qMin(newProgress + 2, 99);
					}
				}
			}
			else if(regExp_pass2.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp_pass2.cap(1).toInt(&ok);
				if(ok && (duration > 0))
				{
					int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 50.0) + 50;
					if(newProgress > prevProgress)
					{
						emit statusUpdated(newProgress);
						prevProgress = qMin(newProgress + 2, 99);
					}
				}
			}
			else if(regExp.lastIndexIn(text) >= 0)
			{
				bool ok = false;
				int progress = regExp.cap(1).toInt(&ok);
				if(ok && (duration > 0))
				{
					int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 100.0);
					if(newProgress > prevProgress)
					{
						emit statusUpdated(newProgress);
						prevProgress = qMin(newProgress + 2, 99);
					}
				}
			}
			else if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
	
	emit statusUpdated(100);
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}

	emit messageLogged("\n-------------------------------\n");
	
	args.clear();
	args << QDir::toNativeSeparators(outputFile);

	if(!metaInfo.title().isEmpty()) args << QString("-meta:title=%1").arg(cleanTag(metaInfo.title()));
	if(!metaInfo.artist().isEmpty()) args << QString("-meta:artist=%1").arg(cleanTag(metaInfo.artist()));
	if(!metaInfo.album().isEmpty()) args << QString("-meta:album=%1").arg(cleanTag(metaInfo.album()));
	if(!metaInfo.genre().isEmpty()) args << QString("-meta:genre=%1").arg(cleanTag(metaInfo.genre()));
	if(!metaInfo.comment().isEmpty()) args << QString("-meta:comment=%1").arg(cleanTag(metaInfo.comment()));
	if(metaInfo.year()) args << QString("-meta:year=%1").arg(QString::number(metaInfo.year()));
	if(metaInfo.position()) args << QString("-meta:track=%1").arg(QString::number(metaInfo.position()));
	if(!metaInfo.cover().isEmpty()) args << QString("-add-cover:%1:%2").arg("front", metaInfo.cover());
	
	if(!startProcess(process, m_binary_tag, args))
	{
		return false;
	}

	bTimeout = false;

	while(process.state() != QProcess::NotRunning)
	{
		if(*abortFlag)
		{
			process.kill();
			bAborted = true;
			emit messageLogged("\nABORTED BY USER !!!");
			break;
		}
		process.waitForReadyRead(m_processTimeoutInterval);
		if(!process.bytesAvailable() && process.state() == QProcess::Running)
		{
			process.kill();
			qWarning("NeroAacTag process timed out <-- killing!");
			emit messageLogged("\nPROCESS TIMEOUT !!!");
			bTimeout = true;
			break;
		}
		while(process.bytesAvailable() > 0)
		{
			QByteArray line = process.readLine();
			QString text = QString::fromUtf8(line.constData()).simplified();
			if(!text.isEmpty())
			{
				emit messageLogged(text);
			}
		}
	}

	process.waitForFinished();
	if(process.state() != QProcess::NotRunning)
	{
		process.kill();
		process.waitForFinished(-1);
	}
		
	emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));

	if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
	{
		return false;
	}

	return true;
}
Esempio n. 8
0
File: main.cpp Progetto: Afreeca/qt
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
//! [0]
    QStringList fonts;
    fonts << "Arial" << "Helvetica" << "Times" << "Courier";
//! [0]

//! [1]
    for (int i = 0; i < fonts.size(); ++i)
         cout << fonts.at(i).toLocal8Bit().constData() << endl;
//! [1]

//! [2]
    QStringListIterator javaStyleIterator(fonts);
    while (javaStyleIterator.hasNext())
         cout << javaStyleIterator.next().toLocal8Bit().constData() << endl;
//! [2]

//! [3]
    QStringList::const_iterator constIterator;
    for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd();
           ++constIterator)
        cout << (*constIterator).toLocal8Bit().constData() << endl;
//! [3]

//! [4]
    QString str = fonts.join(",");
     // str == "Arial,Helvetica,Times,Courier"
//! [4]

//! [5] //! [6]
    QStringList list;
//! [5]
    list = str.split(",");
     // list: ["Arial", "Helvetica", "Times", "Courier"]
//! [6]

//! [7]
    QStringList monospacedFonts = fonts.filter(QRegExp("Courier|Fixed"));
//! [7]

//! [8]
    QStringList files;
    files << "$QTDIR/src/moc/moc.y"
          << "$QTDIR/src/moc/moc.l"
          << "$QTDIR/include/qconfig.h";

    files.replaceInStrings("$QTDIR", "/usr/lib/qt");
    // files: [ "/usr/lib/qt/src/moc/moc.y", ...]
//! [8]

    QString str1, str2, str3;
//! [9]
    QStringList longerList = (QStringList() << str1 << str2 << str3);
//! [9]

    list.clear();
//! [10]
    list << "Bill Murray" << "John Doe" << "Bill Clinton";

//! [11]
    QStringList result;
//! [11]
    result = list.filter("Bill");
    // result: ["Bill Murray", "Bill Clinton"]
//! [10]

    result.clear();
//! [12]
    foreach (const QString &str, list) {
        if (str.contains("Bill"))
            result += str;
    }
//! [12]

    list.clear();
//! [13]
    list << "alpha" << "beta" << "gamma" << "epsilon";
    list.replaceInStrings("a", "o");
    // list == ["olpho", "beto", "gommo", "epsilon"]
//! [13]

    list.clear();
//! [14]
    list << "alpha" << "beta" << "gamma" << "epsilon";
    list.replaceInStrings(QRegExp("^a"), "o");
    // list == ["olpha", "beta", "gamma", "epsilon"]
//! [14]

    list.clear();
//! [15]
    list << "Bill Clinton" << "Murray, Bill";
    list.replaceInStrings(QRegExp("^(.*), (.*)$"), "\\2 \\1");
    // list == ["Bill Clinton", "Bill Murray"]
//! [15]
}
Esempio n. 9
0
int main( int argc, char** argv )
{
	QString defaultContext = "@default";
	MetaTranslator fetchedTor;
	QCString codec;
	QStringList tsFileNames;

	bool verbose = FALSE;
	bool noObsolete = FALSE;
	bool metSomething = FALSE;
	int numFiles = 0;
	bool standardSyntax = TRUE;
	bool metTsFlag = FALSE;

	int i;

	for ( i = 1; i < argc; i++ )
	{
		if ( qstrcmp( argv[i], "-ts" ) == 0 )
			standardSyntax = FALSE;
	}

	for ( i = 1; i < argc; i++ )
	{
		if ( qstrcmp( argv[i], "-help" ) == 0 )
		{
			printUsage();
			return 0;
		}
		else if ( qstrcmp( argv[i], "-noobsolete" ) == 0 )
		{
			noObsolete = TRUE;
			continue;
		}
		else if ( qstrcmp( argv[i], "-verbose" ) == 0 )
		{
			verbose = TRUE;
			continue;
		}
		else if ( qstrcmp( argv[i], "-version" ) == 0 )
		{
			fprintf( stderr, "lupdate version %s\n", QT_VERSION_STR );
			return 0;
		}
		else if ( qstrcmp( argv[i], "-ts" ) == 0 )
		{
			metTsFlag = TRUE;
			continue;
		}

		numFiles++;

		QString fullText;

		if ( !metTsFlag )
		{
			QFile f( argv[i] );
			if ( !f.open( IO_ReadOnly ) )
			{
				fprintf( stderr, "lupdate error: Cannot open file '%s': %s\n", argv[i], strerror( errno ) );
				return 1;
			}

			QTextStream t( &f );
			fullText = t.read();
			f.close();
		}

		QString oldDir = QDir::currentDirPath();
		QDir::setCurrent( QFileInfo( argv[i] ).dirPath() );

		if ( standardSyntax )
		{
			fetchedTor = MetaTranslator();
			codec.truncate( 0 );
			tsFileNames.clear();

			QMap<QString, QString> tagMap = proFileTagMap( fullText );
			QMap<QString, QString>::Iterator it;

			for ( it = tagMap.begin(); it != tagMap.end(); ++it )
			{
				QStringList toks = QStringList::split( ' ', it.data() );
				QStringList::Iterator t;

				for ( t = toks.begin(); t != toks.end(); ++t )
				{
					if ( it.key() == "HEADERS" || it.key() == "SOURCES" )
					{
						fetchtr_cpp( *t, &fetchedTor, defaultContext, TRUE );
						metSomething = TRUE;
					}
					else if ( it.key() == "INTERFACES" || it.key() == "FORMS" )
					{
						fetchtr_ui( *t, &fetchedTor, defaultContext, TRUE );
						fetchtr_cpp( *t + ".h", &fetchedTor, defaultContext, FALSE );
						metSomething = TRUE;
					}
					else if ( it.key() == "TRANSLATIONS" )
					{
						tsFileNames.append( *t );
						metSomething = TRUE;
					}
					else if ( it.key() == "CODEC" || it.key() == "DEFAULTCODEC" )
					{
						codec = ( *t ).latin1();
					}
					else if ( it.key() == "WPDEFINITIONS" )
					{
						lookForDefinitions( *t, "*.xml", &fetchedTor, &fetchtr_xml );
					}
					else if ( it.key() == "WPSCRIPTS" )
					{
						lookForDefinitions( *t, "*.py", &fetchedTor, &fetchtr_py );
					}
				}
			}
			
			updateTsFiles( fetchedTor, tsFileNames, codec, noObsolete, verbose );

			if ( !metSomething )
			{
				fprintf( stderr, "lupdate warning: File '%s' does not look like a"
			 " project file\n", argv[i] );
			}
			else if ( tsFileNames.isEmpty() )
			{
				fprintf( stderr, "lupdate warning: Met no 'TRANSLATIONS' entry in"
			 " project file '%s'\n", argv[i] );
			}
		}
		else
		{
			if ( metTsFlag )
			{
				if ( QString( argv[i] ).lower().endsWith( ".ts" ) )
				{
					QFileInfo fi( argv[i] );
					if ( !fi.exists() || fi.isWritable() )
					{
						tsFileNames.append( argv[i] );
					}
					else
					{
						fprintf( stderr, "lupdate warning: For some reason, I cannot"
				 " save '%s'\n", argv[i] );
					}
				}
				else
				{
					fprintf( stderr, "lupdate error: File '%s' lacks .ts extension\n", argv[i] );
				}
			}
			else
			{
				QFileInfo fi( argv[i] );
				if ( QString( argv[i] ).lower().endsWith( ".ui" ) )
				{
					fetchtr_ui( fi.fileName(), &fetchedTor, defaultContext, TRUE );
					fetchtr_cpp( QString( fi.fileName() ) + ".h", &fetchedTor, defaultContext, FALSE );
				}
				else if ( QString( argv[i] ).lower().endsWith( ".xml" ) )
				{
					fetchtr_xml( fi.fileName(), &fetchedTor, 0, TRUE );
				}
				else if ( QString( argv[i] ).lower().endsWith( ".py" ) )
				{
					fetchtr_py( fi.fileName(), &fetchedTor, 0, TRUE );
				}
				else
				{
					fetchtr_cpp( fi.fileName(), &fetchedTor, defaultContext, TRUE );
				}
			}
		}
		QDir::setCurrent( oldDir );
	}

	if ( !standardSyntax )
		updateTsFiles( fetchedTor, tsFileNames, codec, noObsolete, verbose );

	if ( numFiles == 0 )
	{
		printUsage();
		return 1;
	}
	return 0;
}
Esempio n. 10
0
void DbPlugin::getIndexHistory (BarData *barData, QDateTime &startDate)
{
  QString s = "List";
  QString s2;
  getData(s, s2);
  QStringList l = QStringList::split(":", s2, FALSE);
  if (! l.count())
    return;
    
  QDict<Bar> lookup;
  lookup.setAutoDelete(TRUE);
  int loop;
  int count = 0;
  for (loop = 0; loop < (int) l.count(); loop = loop + 2)
  {
    float weight = l[loop + 1].toFloat();
    if (weight == 0)
      weight = 1;

    loadIndexData(l[loop], lookup, startDate, weight, barRange, barLength);
    count++;
  }

  l.clear();
  QDictIterator<Bar> it(lookup);
  for (; it.current(); ++it)
  {
    Bar *r = it.current();
    if (r->getOI() == count)
    {
      r->setOpen(r->getOpen() / count);
      r->setHigh(r->getHigh() / count);
      r->setLow(r->getLow() / count);
      r->setClose(r->getClose() / count);
      
      if (r->getOpen() > r->getHigh())
        r->setHigh(r->getOpen());
      if (r->getOpen() < r->getLow())
        r->setLow(r->getOpen());

      if (r->getClose() > r->getHigh())
        r->setHigh(r->getClose());
      if (r->getClose() < r->getLow())
        r->setLow(r->getClose());

      r->getDateTimeString(FALSE, s);
      l.append(s);
    }
    else
      lookup.remove(it.currentKey());
  }

  l.sort();
  for (loop = l.count() - 1; loop > -1; loop--)
  {
    Bar *r = lookup.find(l[loop]);
    if (r)
    {
      QDateTime dt;
      r->getDate(dt);
      Bar tr;
      tr.setDate(dt);
      tr.setOpen(r->getOpen());
      tr.setHigh(r->getHigh());
      tr.setLow(r->getLow());
      tr.setClose(r->getClose());
      barData->prepend(tr);
    }
  }
}
Esempio n. 11
0
KateConfigDialog::KateConfigDialog(KateMainWindow *parent, Kate::View *view)
    : KDialogBase(KDialogBase::TreeList, i18n("Configure"), KDialogBase::Ok | KDialogBase::Apply | KDialogBase::Cancel | KDialogBase::Help,
                  KDialogBase::Ok, parent, "configdialog")
{
    KConfig *config = KateApp::self()->config();

    KWin::setIcons(winId(), KateApp::self()->icon(), KateApp::self()->miniIcon());

    actionButton(KDialogBase::Apply)->setEnabled(false);

    mainWindow = parent;

    setMinimumSize(600, 400);

    v = view;

    pluginPages.setAutoDelete(false);
    editorPages.setAutoDelete(false);

    QStringList path;

    setShowIconsInTreeList(true);

    path.clear();
    path << i18n("Application");
    setFolderIcon(path, SmallIcon("kate", KIcon::SizeSmall));

    path.clear();

    // BEGIN General page
    path << i18n("Application") << i18n("General");
    QFrame *frGeneral = addPage(path, i18n("General Options"), BarIcon("gohome", KIcon::SizeSmall));

    QVBoxLayout *lo = new QVBoxLayout(frGeneral);
    lo->setSpacing(KDialog::spacingHint());
    config->setGroup("General");

    // GROUP with the one below: "Appearance"
    QButtonGroup *bgStartup = new QButtonGroup(1, Qt::Horizontal, i18n("&Appearance"), frGeneral);
    lo->addWidget(bgStartup);

    // show full path in title
    config->setGroup("General");
    cb_fullPath = new QCheckBox(i18n("&Show full path in title"), bgStartup);
    cb_fullPath->setChecked(mainWindow->viewManager()->getShowFullPath());
    QWhatsThis::add(cb_fullPath, i18n("If this option is checked, the full document path will be shown in the window caption."));
    connect(cb_fullPath, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));


    // GROUP with the one below: "Behavior"
    bgStartup = new QButtonGroup(1, Qt::Horizontal, i18n("&Behavior"), frGeneral);
    lo->addWidget(bgStartup);

    // sync the konsole ?
    cb_syncKonsole = new QCheckBox(bgStartup);
    cb_syncKonsole->setText(i18n("Sync &terminal emulator with active document"));
    cb_syncKonsole->setChecked(parent->syncKonsole);
    QWhatsThis::add(cb_syncKonsole, i18n("If this is checked, the built in Konsole will <code>cd</code> to the directory "
                                         "of the active document when started and whenever the active document changes, "
                                         "if the document is a local file."));
    connect(cb_syncKonsole, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    // modified files notification
    cb_modNotifications = new QCheckBox(i18n("Wa&rn about files modified by foreign processes"), bgStartup);
    cb_modNotifications->setChecked(parent->modNotification);
    QWhatsThis::add(cb_modNotifications, i18n("If enabled, when Kate receives focus you will be asked what to do with "
                                              "files that have been modified on the hard disk. If not enabled, you will "
                                              "be asked what to do with a file that has been modified on the hard disk only "
                                              "when that file gains focus inside Kate."));
    connect(cb_modNotifications, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    // GROUP with the one below: "Meta-informations"
    bgStartup = new QButtonGroup(1, Qt::Horizontal, i18n("Meta-Information"), frGeneral);
    lo->addWidget(bgStartup);

    // save meta infos
    cb_saveMetaInfos = new QCheckBox(bgStartup);
    cb_saveMetaInfos->setText(i18n("Keep &meta-information past sessions"));
    cb_saveMetaInfos->setChecked(KateDocManager::self()->getSaveMetaInfos());
    QWhatsThis::add(cb_saveMetaInfos, i18n("Check this if you want document configuration like for example "
                                           "bookmarks to be saved past editor sessions. The configuration will be "
                                           "restored if the document has not changed when reopened."));
    connect(cb_saveMetaInfos, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    // meta infos days
    QHBox *hbDmf = new QHBox(bgStartup);
    hbDmf->setEnabled(KateDocManager::self()->getSaveMetaInfos());
    QLabel *lDmf = new QLabel(i18n("&Delete unused meta-information after:"), hbDmf);
    sb_daysMetaInfos = new QSpinBox(0, 180, 1, hbDmf);
    sb_daysMetaInfos->setSpecialValueText(i18n("(never)"));
    sb_daysMetaInfos->setSuffix(i18n(" day(s)"));
    sb_daysMetaInfos->setValue(KateDocManager::self()->getDaysMetaInfos());
    lDmf->setBuddy(sb_daysMetaInfos);
    connect(cb_saveMetaInfos, SIGNAL(toggled(bool)), hbDmf, SLOT(setEnabled(bool)));
    connect(sb_daysMetaInfos, SIGNAL(valueChanged(int)), this, SLOT(slotChanged()));

    lo->addStretch(1); // :-] works correct without autoadd
    // END General page

    path.clear();

    // BEGIN Session page
    path << i18n("Application") << i18n("Sessions");
    QFrame *frSessions = addPage(path, i18n("Session Management"), BarIcon("history", KIcon::SizeSmall));

    lo = new QVBoxLayout(frSessions);
    lo->setSpacing(KDialog::spacingHint());

    // GROUP with the one below: "Startup"
    bgStartup = new QButtonGroup(1, Qt::Horizontal, i18n("Elements of Sessions"), frSessions);
    lo->addWidget(bgStartup);

    // restore view  config
    cb_restoreVC = new QCheckBox(bgStartup);
    cb_restoreVC->setText(i18n("Include &window configuration"));
    config->setGroup("General");
    cb_restoreVC->setChecked(config->readBoolEntry("Restore Window Configuration", true));
    QWhatsThis::add(cb_restoreVC, i18n("Check this if you want all your views and frames restored each time you open Kate"));
    connect(cb_restoreVC, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    QRadioButton *rb1, *rb2, *rb3;

    sessions_start = new QButtonGroup(1, Qt::Horizontal, i18n("Behavior on Application Startup"), frSessions);
    lo->add(sessions_start);

    sessions_start->setRadioButtonExclusive(true);
    sessions_start->insert(rb1 = new QRadioButton(i18n("&Start new session"), sessions_start), 0);
    sessions_start->insert(rb2 = new QRadioButton(i18n("&Load last-used session"), sessions_start), 1);
    sessions_start->insert(rb3 = new QRadioButton(i18n("&Manually choose a session"), sessions_start), 2);

    config->setGroup("General");
    QString sesStart(config->readEntry("Startup Session", "manual"));
    if(sesStart == "new")
        sessions_start->setButton(0);
    else if(sesStart == "last")
        sessions_start->setButton(1);
    else
        sessions_start->setButton(2);

    connect(rb1, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));
    connect(rb2, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));
    connect(rb3, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    sessions_exit = new QButtonGroup(1, Qt::Horizontal, i18n("Behavior on Application Exit or Session Switch"), frSessions);
    lo->add(sessions_exit);

    sessions_exit->setRadioButtonExclusive(true);
    sessions_exit->insert(rb1 = new QRadioButton(i18n("&Do not save session"), sessions_exit), 0);
    sessions_exit->insert(rb2 = new QRadioButton(i18n("&Save session"), sessions_exit), 1);
    sessions_exit->insert(rb3 = new QRadioButton(i18n("&Ask user"), sessions_exit), 2);

    config->setGroup("General");
    QString sesExit(config->readEntry("Session Exit", "save"));
    if(sesExit == "discard")
        sessions_exit->setButton(0);
    else if(sesExit == "save")
        sessions_exit->setButton(1);
    else
        sessions_exit->setButton(2);

    connect(rb1, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));
    connect(rb2, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));
    connect(rb3, SIGNAL(toggled(bool)), this, SLOT(slotChanged()));

    lo->addStretch(1); // :-] works correct without autoadd
    // END Session page

    path.clear();

    // file selector page
    path << i18n("Application") << i18n("File Selector");

    QVBox *page = addVBoxPage(path, i18n("File Selector Settings"), BarIcon("fileopen", KIcon::SizeSmall));
    fileSelConfigPage = new KFSConfigPage(page, "file selector config page", mainWindow->fileselector);
    connect(fileSelConfigPage, SIGNAL(changed()), this, SLOT(slotChanged()));
    path.clear();

    path << i18n("Application") << i18n("Document List");
    page = addVBoxPage(path, i18n("Document List Settings"), BarIcon("view_text", KIcon::SizeSmall));
    filelistConfigPage = new KFLConfigPage(page, "file list config page", mainWindow->filelist);
    connect(filelistConfigPage, SIGNAL(changed()), this, SLOT(slotChanged()));
    path.clear();

    path << i18n("Application") << i18n("Plugins");
    /*QVBox **/ page = addVBoxPage(path, i18n("Plugin Manager"), BarIcon("connect_established", KIcon::SizeSmall));
    KateConfigPluginPage *configPluginPage = new KateConfigPluginPage(page, this);
    connect(configPluginPage, SIGNAL(changed()), this, SLOT(slotChanged()));

    // Tools->External Tools menu
    path.clear();
    path << i18n("Application") << i18n("External Tools");
    page = addVBoxPage(path, i18n("External Tools"), BarIcon("configure", KIcon::SizeSmall));
    configExternalToolsPage = new KateExternalToolsConfigWidget(page, "external tools config page");
    connect(configExternalToolsPage, SIGNAL(changed()), this, SLOT(slotChanged()));

    // editor widgets from kwrite/kwdialog
    path.clear();
    path << i18n("Editor");
    setFolderIcon(path, SmallIcon("edit", KIcon::SizeSmall));

    for(uint i = 0; i < KTextEditor::configInterfaceExtension(v->document())->configPages(); i++)
    {
        path.clear();
        path << i18n("Editor") << KTextEditor::configInterfaceExtension(v->document())->configPageName(i);
        /*QVBox **/ page = addVBoxPage(path, KTextEditor::configInterfaceExtension(v->document())->configPageFullName(i),
                                       KTextEditor::configInterfaceExtension(v->document())->configPagePixmap(i, KIcon::SizeSmall));

        KTextEditor::ConfigPage *cPage = KTextEditor::configInterfaceExtension(v->document())->configPage(i, page);
        connect(cPage, SIGNAL(changed()), this, SLOT(slotChanged()));
        editorPages.append(cPage);
    }

    KatePluginList &pluginList(KatePluginManager::self()->pluginList());
    for(unsigned int i = 0; i < pluginList.size(); ++i)
    {
        if(pluginList[i].load && Kate::pluginConfigInterfaceExtension(pluginList[i].plugin))
            addPluginPage(pluginList[i].plugin);
    }

    enableButtonSeparator(true);
    dataChanged = false;
    unfoldTreeList();
}
Esempio n. 12
0
BarcodeGenerator::BarcodeGenerator(QWidget* parent, const char* name)
	: QDialog(parent),
	  paintBarcodeTimer(NULL)
{
	ui.setupUi(this);
	setObjectName(name);
	setModal(true);

	connect(&thread, SIGNAL(renderedImage(QString)),this, SLOT(updatePreview(QString)));

	/*
	 *  We extract the barcode information from the BWIPP metadata which looks like this:
	 *
	 *  % --BEGIN ENCODER gs1-128--
	 *  % --REQUIRES preamble raiseerror renlinear code128--
	 *  % --DESC: GS1-128
	 *  % --EXAM: (01)95012345678903(3103)000123
	 *  % --EXOP: includetext
	 *  % --RNDR: renlinear
	 *
	 */

	QFile f(ScPaths::instance().shareDir() + QString("/plugins/barcode.ps"));
	if(!f.open(QIODevice::ReadOnly))
	{
		qDebug()<<"Barcodegenerator unable to open "<<f.fileName();
		return;
	}
	QTextStream ts(&f);
	QString bwipp = ts.readAll();
	f.close();

	QRegExp rx(
		"[\\r\\n]+% --BEGIN (RESOURCE|RENDERER|ENCODER) ([\\w-]+)--[\\r\\n]+"
		"(.*[\\r\\n]+)?"
		"(%%BeginResource.*[\\r\\n]+)"
		"% --END \\1 \\2--[\\r\\n]+");
	rx.setMinimal(true);
	int pos = 0;
	while ( (pos = rx.indexIn(bwipp, pos)) != -1 )
	{
		int len=rx.matchedLength();
		QString restype=rx.cap(1);
	 	QString resname=rx.cap(2);
	 	QString reshead=rx.cap(3);
	 	QString resbody=rx.cap(4);

	 	resbodys[resname]=resbody;

	 	if (restype=="ENCODER")
		{
			QRegExp rxhead(
				"% --REQUIRES (.*)--[\\r\\n]+"
				"% --DESC:(.*)[\\r\\n]+"
				"% --EXAM:(.*)[\\r\\n]+"
				"% --EXOP:(.*)[\\r\\n]+"
				"% --RNDR:(.*)[\\r\\n]+"
			);
			rxhead.indexIn(reshead);
			resreqs[resname]=rxhead.cap(1).trimmed();
			resdescs[resname]=rxhead.cap(2).trimmed();
			resexams[resname]=rxhead.cap(3).trimmed();
			resexops[resname]=rxhead.cap(4).trimmed();
			resrndrs[resname]=rxhead.cap(5).trimmed();
			encoderlist.append(resname);
	 	}
		pos+=len;
	}

	foreach (const QString& enc, encoderlist)
		map[resdescs[enc]] = BarcodeType(enc, resexams[enc], resexops[enc]);

	/*
	 *  Ultimately all of this static data about the capabilities of each barcode
	 *  encoder will be replaced by data read from the barcode.ps metadata, when 
	 *  such data exists...
	 *
	 */ 

	// Content for the version and ecc combos
	resvers["qrcode"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40";
	resecls["qrcode"]="L,Q,M,H";
	resvers["gs1qrcode"]=resvers["qrcode"];
	resecls["gs1qrcode"]=resecls["qrcode"];
	resvers["hibcqrcode"]=resvers["qrcode"];
	resecls["hibcqrcode"]=resecls["qrcode"];
	resvers["microqrcode"]="M1,M2,M3,M4";
	resecls["microqrcode"]="L,Q,M,H";
	resvers["datamatrix"]="10x10,12x12,14x14,16x16,18x18,20x20,22x22,24x24,26x26,32x32,36x36,40x40,44x44,48x48,52x52,64x64,72x72,80x80,88x88,96x96,104x104,120x120,132x132,144x144,8x18,8x32,12x26,12x36,16x36,16x48";
	resecls["datamatrix"]="";
	resvers["gs1datamatrix"]=resvers["datamatrix"];
	resecls["gs1datamatrix"]=resvers["datamatrix"];
	resvers["hibcdatamatrix"]=resvers["datamatrix"];
	resecls["hibcdatamatrix"]=resecls["datamatrix"];
	resvers["azteccode"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32";
	resvlbl["azteccode"]="Layers";
	resecls["azteccode"]="5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95";
	resvers["azteccodecompact"]="1,2,3,4";
	resvlbl["azteccodecompact"]=resvlbl["azteccode"];
	resecls["azteccodecompact"]=resecls["azteccode"];
	resvers["pdf417"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
	resvlbl["pdf417"]="Columns";
	resecls["pdf417"]="1,2,3,4,5";
	resvers["pdf417compact"]=resvers["pdf417"];
	resvlbl["pdf417compact"]=resvlbl["pdf417"];
	resecls["pdf417compact"]=resecls["pdf417"];
	resvers["hibcpdf417"]=resvers["pdf417"];
	resvlbl["hibcpdf417"]=resvlbl["pdf417"];
	resecls["hibcpdf417"]=resecls["pdf417"];
	resvers["micropdf417"]="1x11,1x14,1x17,1x20,1x24,1x28,2x8,2x11,2x14,2x17,2x20,2x23,2x26,3x6,3x8,3x10,3x12,3x15,3x20,3x26,3x32,3x38,3x44,4x4,4x6,4x8,4x10,4x12,4x15,4x20,4x26,4x32,4x38,4x44";
	resecls["micropdf417"]="";
	resvers["hibcmicropdf417"]=resvers["micropdf417"];
	resecls["hibcmicropdf417"]=resecls["micropdf417"];
	resvers["hanxin"]="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84";
	resecls["hanxin"]="L1,L2,L3,L4";


	// Which options checkboxes are enabled for each encoder
	QStringList includetextAvail=encoderlist;
	foreach (const QString& enc, includetextAvail)
		resincludetextAvail[enc]=true; 

	QStringList guardwhitespaceAvail;
	guardwhitespaceAvail << "ean13" << "ean8" << "isbn" << "ismn" << "issn" << "ean13composite" << "ean8composite";
	foreach (const QString& enc, guardwhitespaceAvail)
		resguardwhitespaceAvail[enc]=true; 

	QStringList includecheckAvail;
	includecheckAvail << "bc412" << "channelcode" << "code11" << "code2of5" << "coop2of5" << "datalogic2of5"
					  << "iata2of5" << "industrial2of5" << "matrix2of5" << "code39" << "code39ext"
					  << "code93" << "code93ext" << "interleaved2of5" << "msi" << "rationalizedCodabar";
	foreach (const QString& enc, includecheckAvail)
		resincludecheckAvail[enc]=true; 

	QStringList includecheckintextAvail;
	includecheckintextAvail << "bc412" << "code11" << "code2of5" << "coop2of5" << "datalogic2of5" << "iata2of5"
							<< "industrial2of5" << "matrix2of5" << "code39" << "code39ext" << "interleaved2of5"
							<< "japanpost" << "msi" << "planet" << "plessey" << "postnet" << "rationalizedCodabar" << "royalmail";
	foreach (const QString& enc, includecheckintextAvail)
		resincludecheckintextAvail[enc]=true; 

	QStringList parseAvail;
	parseAvail << "azteccode" << "azteccodecompact" << "codablockf" << "hibccodablockf" << "code128" << "hibccode128" << "code16k" << "code39ext" << "code49"
			   << "code93ext" << "codeone" << "datamatrix" << "hibcdatamatrix" << "maxicode" << "micropdf417" << "hibcmicropdf417" << "pdf417" << "hibcpdf417"
			   << "pdf417compact" << "posicode" << "qrcode" << "hibcqrcode" << "microqrcode" << "telepen" << "hanxin";
	foreach (const QString& enc, parseAvail)
		resparseAvail[enc]=true; 

	QStringList parsefncAvail;
	parsefncAvail << "codablockf" << "code128" << "code16k" << "code49" << "code93" << "codeone"
				  << "datamatrix" << "posicode" << "qrcode" << "microqrcode";
	foreach (const QString& enc, parsefncAvail)
		resparsefncAvail[enc]=true; 

	// Building up the bcFamilyCombo grouping the formats for readablity
	ui.bcFamilyCombo->addItem(tr("Select a barcode family")); // to prevent 1st gs call
	ui.bcFamilyCombo->insertSeparator(999);

	// Building up the bcCombo grouping the formats for readablity
	ui.bcCombo->addItem(tr("Select a barcode format")); // to prevent 1st gs call
	ui.bcCombo->insertSeparator(999);

	QString familyName;
	QStringList bcNames;
	bcNames << "EAN-13" << "EAN-8" << "UPC-A" << "UPC-E" << "ISBN" << "ISMN" << "ISSN";
	familyName = tr("Point of Sale");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "GS1-14" << "GS1 Data Matrix" << "GS1 QR Code" << "GS1-128" << "ITF-14" << "SSCC-18";
	familyName = tr("Supply Chain");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "QR Code" << "Micro QR Code" << "Data Matrix" << "Aztec Code" << "Compact Aztec Code"
			<< "Aztec Runes" << "PDF417" << "Compact PDF417" << "MicroPDF417" << "Han Xin Code";
	familyName = tr("Two-dimensional symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Code 128" << "Code 39" << "Code 39 Extended" << "Code 93" << "Code 93 Extended"
			<< "Interleaved 2 of 5 (ITF)";
	familyName = tr("One-dimensional symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "GS1 DataBar Omnidirectional" << "GS1 DataBar Stacked Omnidirectional"
			<< "GS1 DataBar Expanded" << "GS1 DataBar Expanded Stacked" << "GS1 DataBar Truncated"
			<< "GS1 DataBar Stacked" << "GS1 DataBar Limited";
	familyName = tr("GS1 DataBar family");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "AusPost 4 State Customer Code" << "Deutsche Post Identcode" << "Deutsche Post Leitcode"
			<< "Japan Post 4 State Customer Code" << "Royal Dutch TPG Post KIX"
			<< "Royal Mail 4 State Customer Code" << "USPS Intelligent Mail" << "USPS PLANET" << "USPS POSTNET";
	familyName = tr("Postal symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Italian Pharmacode" << "Pharmaceutical Binary Code" << "Two-track Pharmacode"
			<< "Pharmazentralnummer (PZN)" << "HIBC Codablock F" << "HIBC Code 128" << "HIBC Code 39"
			<< "HIBC Data Matrix" << "HIBC MicroPDF417" << "HIBC PDF417" << "HIBC QR Code";
	familyName = tr("Pharmaceutical symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "Code 11" << "Codabar" << "Code 25" << "COOP 2 of 5" << "Datalogic 2 of 5" << "IATA 2 of 5"
			<< "Industrial 2 of 5" << "Matrix 2 of 5" << "MSI Modified Plessey" << "Plessey UK"
			<< "PosiCode" << "Telepen" << "Telepen Numeric"<< "Code 16K" << "Codablock F" << "Code 49"
			<< "Code One";
	familyName = tr("Less-used symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	bcNames.clear();
	bcNames << "EAN-13 Composite" << "EAN-8 Composite" << "UPC-A Composite" << "UPC-E Composite"
			<< "GS1 DataBar Omnidirectional Composite" << "GS1 DataBar Stacked Omnidirectional Composite"
			<< "GS1 DataBar Expanded Composite" << "GS1 DataBar Expanded Stacked Composite"
			<< "GS1 DataBar Truncated Composite" << "GS1 DataBar Stacked Composite"
			<< "GS1 DataBar Limited Composite" << "GS1-128 Composite";
	familyName = tr("GS1 Composite symbols");
	familyList.append(familyName);
	familyItems.insert(familyName, bcNames);

	ui.bcFamilyCombo->addItems(familyList);

	/*
	 *  End of the hard-coded data 
	 *
	 */

	guiColor = ui.codeEdit->palette().color(QPalette::Window);

	ui.okButton->setText(CommonStrings::tr_OK);
	ui.cancelButton->setText(CommonStrings::tr_Cancel);
	ui.resetButton->setIcon(IconManager::instance()->loadIcon("u_undo16.png"));

	if (ScCore->primaryMainWindow()->doc->PageColors.contains("Black"))
	{
		lnColor = ScCore->primaryMainWindow()->doc->PageColors["Black"];
		txtColor = ScCore->primaryMainWindow()->doc->PageColors["Black"];
		ui.linesLabel->setToolTip("Black");
		ui.txtLabel->setToolTip("Black");
	}
	else
	{
		ui.linesLabel->setToolTip("n.a.");
		ui.txtLabel->setToolTip("n.a.");
	}
	if (ScCore->primaryMainWindow()->doc->PageColors.contains("White"))
	{
		bgColor = ScCore->primaryMainWindow()->doc->PageColors["White"];
		ui.bgLabel->setToolTip("White");
	}
	else
		ui.bgLabel->setToolTip("n.a.");

	paintColorSample(ui.linesLabel, lnColor);
	paintColorSample(ui.txtLabel, txtColor);
	paintColorSample(ui.bgLabel, bgColor);

	paintBarcodeTimer=new QTimer(this);
	paintBarcodeTimer->setSingleShot(true);
	connect(paintBarcodeTimer, SIGNAL(timeout()), this, SLOT(paintBarcode()));

	connect(ui.bcFamilyCombo, SIGNAL(activated(QString)), this, SLOT(bcFamilyComboChanged()));
	connect(ui.bcCombo, SIGNAL(activated(QString)), this, SLOT(bcComboChanged()));
	connect(ui.bgColorButton, SIGNAL(clicked()), this, SLOT(bgColorButton_pressed()));
	connect(ui.lnColorButton, SIGNAL(clicked()), this, SLOT(lnColorButton_pressed()));
	connect(ui.txtColorButton, SIGNAL(clicked()), this, SLOT(txtColorButton_pressed()));
	connect(ui.okButton, SIGNAL(clicked()), this, SLOT(okButton_pressed()));
	connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(cancelButton_pressed()));
	connect(ui.codeEdit, SIGNAL(textChanged(QString)), this, SLOT(codeEdit_textChanged(QString)));
	connect(ui.resetButton, SIGNAL(clicked()), this, SLOT(resetButton_clicked()));
	bcComboChanged();

}
Esempio n. 13
0
SummaryView::SummaryView(SummaryViewPrivate* d, QWidget* parent)
	:QWidget(parent)
    , d_ptr(d)
{
	setWindowIcon(QIcon(":/Icons/Logo.png"));
	if(QMetaType::type("Waterfall")==QMetaType::UnknownType)
		qRegisterMetaType<Waterfall>("Waterfall");
	setWindowTitle("Stress Scenario");
	setMinimumSize(1024,768);
	QStringList HeadersStrings;
	d->MainWidget=new QTabWidget(this);

    d->StructureTable = new QTableWidget(this);
	HeadersStrings 
		<< "Bond"
		<< "Pro rata Group"
		<< "Currency"
		<< "Original Amount"
		<< "Current Amount"
		<< "Bond Factor"
		<< "Implied CE"
		<< "Reference Rate"
		<< "Coupon"
		<< "Price"
		<< "IRR"
		<< "WAL"
		<< "DM"
		<< "Loss"
	;
    d->StructureTable->setRowCount(0);
    d->StructureTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    d->StructureTable->setColumnCount(HeadersStrings.size());
    d->StructureTable->setHorizontalHeaderLabels(HeadersStrings);
    d->StructureTable->verticalHeader()->setVisible(false);
    d->StructureTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->StructureTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    d->StructureTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    d->StructureTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    d->MainWidget->addTab(d->StructureTable, "Structure");

    d->WatStructView = new WaterfallViewer(this);
    d->MainWidget->addTab(d->WatStructView, "Waterfall Structure");

    d->MtgTable = new QTableWidget(this);
    d->MtgTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    d->MtgTable->setColumnCount(8);
    d->MtgTable->setRowCount(0);
	HeadersStrings.clear();
	HeadersStrings 
			<< "Date"
			<< "Outstanding"
			<< "Interest"
			<< "Principal"
			<< "Prepayments"
			<< "Accrued Interest"
			<< "Loss on Principal"
			<< "Loss on Interests";
    d->MtgTable->setHorizontalHeaderLabels(HeadersStrings);
    d->MtgTable->verticalHeader()->setVisible(false);
    d->MtgTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->MtgTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    d->MtgTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    d->MainWidget->addTab(d->MtgTable, "Mortgages Results");

	QWidget* TranchesWidget=new QWidget(this);
	QHBoxLayout* TranchesLay=new QHBoxLayout(TranchesWidget);
    d->TranchesArea = new QStackedWidget(TranchesWidget);
    d->TranchesList = new QListWidget(TranchesWidget);
    d->TranchesList->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding);
    connect(d->TranchesList, &QListWidget::currentRowChanged, d->TranchesArea, &QStackedWidget::setCurrentIndex);
    TranchesLay->addWidget(d->TranchesList);
    TranchesLay->addWidget(d->TranchesArea);
    d->MainWidget->addTab(TranchesWidget, "Tranches Results");

	QWidget* CallTranchesWidget=new QWidget(this);
	QHBoxLayout* CallTranchesLay=new QHBoxLayout(CallTranchesWidget);
    d->CallTranchesArea = new QStackedWidget(CallTranchesWidget);
    d->CallTranchesList = new QListWidget(CallTranchesWidget);
    d->CallTranchesList->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding);
    connect(d->CallTranchesList, &QListWidget::currentRowChanged, d->CallTranchesArea, &QStackedWidget::setCurrentIndex);
    CallTranchesLay->addWidget(d->CallTranchesList);
    CallTranchesLay->addWidget(d->CallTranchesArea);
    d->MainWidget->addTab(CallTranchesWidget, "Call Tranches Results");
	
    d->ExpensesTable = new QTableWidget(this);
    d->ExpensesTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
	//ExpensesTable->setColumnCount(6);
    d->ExpensesTable->setRowCount(0);
	HeadersStrings.clear();
	/*HeadersStrings
		<< "Date"
		<< "Senior Expenses"
		<< "Senior Fees"
		<< "Junior Fees"
		<< "Annualized Excess Spread"
		<< "WA Cost of Funding";
	ExpensesTable->setHorizontalHeaderLabels(HeadersStrings);*/
    d->ExpensesTable->verticalHeader()->setVisible(false);
    d->ExpensesTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->ExpensesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    d->ExpensesTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    d->MainWidget->addTab(d->ExpensesTable, "Waterfall Infos");

    d->ReinvestmentsTable = new QTableWidget(this);
    d->ReinvestmentsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
	HeadersStrings.clear();
	HeadersStrings
		<< "Date"
		<< "Funds Reinvested"
	;
    d->ReinvestmentsTable->setRowCount(0);
    d->ReinvestmentsTable->setColumnCount(2);
    d->ReinvestmentsTable->setHorizontalHeaderLabels(HeadersStrings);
    d->ReinvestmentsTable->verticalHeader()->setVisible(false);
    d->ReinvestmentsTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->ReinvestmentsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    d->ReinvestmentsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    d->MainWidget->addTab(d->ReinvestmentsTable, "Reinvestments");

    d->GICTable = new QTableWidget(this);
    d->GICTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
	HeadersStrings.clear();
	HeadersStrings
		<< "Date"
		<< "Interest On Revenues Cash"
		<< "Interest On Principal Cash"
		<< "Interest On Reserve Funds"
		<< "Interest On Re-investable Cash"
		;
    d->GICTable->setRowCount(0);
    d->GICTable->setColumnCount(5);
    d->GICTable->setHorizontalHeaderLabels(HeadersStrings);
    d->GICTable->verticalHeader()->setVisible(false);
    d->GICTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->GICTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    d->GICTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    d->MainWidget->addTab(d->GICTable, "GIC");

    d->ChartPlotter = new ChartsWidget(this);
    d->MainWidget->addTab(d->ChartPlotter, "Charts");

	QHBoxLayout* mainLay=new QHBoxLayout(this);
    mainLay->addWidget(d->MainWidget);
	//connect(MainWidget,SIGNAL(currentChanged(int)),this,SLOT(AdjustTableSizes()));
}
Esempio n. 14
0
/**
 * Set up the constants
 *
 */
void Analyzer::setupConstants()
{
    if (luaL_loadfile(L, qPrintable(scriptName)) || lua_pcall(L, 0, 0, 0))
    {
        throw "Error loading script \"" + scriptName + "\"";
    }

    // get extensions
    lua_getglobal (L, EXTENSIONS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        extensions.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    // get language name
    lua_getglobal (L, LANGUAGE_FIELD);
    langName = QString(lua_tostring(L, -1));
    lua_pop(L, 1);

    // get grammars
    lua_getglobal (L, MAIN_GRAMMAR_FIELD);
    mainGrammar = QString(lua_tostring(L, -1));
    lua_pop(L, 1);

    if (mainGrammar.isEmpty())
        throw "No main grammar specified in script \"" + scriptName + "\"";

    lua_getglobal (L, SUB_GRAMMARS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        subGrammars[QString(lua_tostring(L, -2))] = QString(lua_tostring(L, -1));
        lua_pop(L, 1);
    }

    // get paired tokens (e.g BEGIN/END, {/}, </>)
    lua_getglobal (L, PAIRED_TOKENS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        pairedTokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    // get selectable tokens (can be selected and moved)
    lua_getglobal (L, SELECTABLE_TOKENS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        selectableTokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    // get multi-text tokens (can contain more lines of text)
    lua_getglobal (L, MULTI_TEXT_TOKENS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        multiTextTokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    // get floating tokens
    lua_getglobal (L, FLOATING_TOKENS_FIELD);
    lua_pushnil(L);
    while (lua_next(L, -2) != 0)
    {
        floatingTokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    // get multiline comment support
    lua_getglobal (L, MULTILINE_SUPPORT_FIELD);
    multilineSupport = QString(lua_tostring(L, -1));
    lua_pop(L, 1);

    QStringList tokens;

    // get line tokens
    lua_getglobal (L, LINE_COMMENT_TOKENS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        tokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    commentTokens["line"] = tokens;
    tokens.clear();

    // get multiline tokens
    lua_getglobal (L, MULTILINE_COMMENT_TOKENS_FIELD);
    lua_pushnil(L);

    while (lua_next(L, -2) != 0)
    {
        tokens.append(QString(lua_tostring(L, -1)));
        lua_pop(L, 1);
    }

    commentTokens["multiline"] = tokens;
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/icon/train"));

//------------------------------* Drag and Drop *--------------------------------------
    this->setAcceptDrops(true);
    ui->tabWidget->setAcceptDrops(false);
//----------------------------------* config *-----------------------------------------
    visitorMode = false;
    if(visitorMode == true)
        this->setWindowTitle(QString::fromLocal8Bit("车票管理系统(访客模式)"));
    else
        this->setWindowTitle(QString::fromLocal8Bit("车票管理系统(管理员模式)"));
    this->configInfo << "admin"
                     << "admin"
                     << "C:\\Users\\Magnolias\\Desktop\\trainExport.txt"
                     << "C:\\Users\\Magnolias\\Desktop\\ticketExport.txt"
                     << "C:\\Users\\Magnolias\\Desktop\\train.txt"
                     << "C:\\Users\\Magnolias\\Desktop\\ticket.txt"
                     << "true"
                     << "false";

    QFile configFile("train.conf");
    if(configFile.exists())
    {
        bool flag = true;
        if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            flag = false;
        }
        if(flag == true)
        {
            this->configInfo.clear();
            QTextStream in(&configFile);
            while(!in.atEnd())
                this->configInfo << in.readLine();
            configFile.close();
        }
    }

    if(this->configInfo.at(6) == "true")
        trainRoutes.setAutoExport(true);
    else
        trainRoutes.setAutoExport(false);
    if(this->configInfo.at(7) == "true")
        trainRoutes.setAutoImport(true);
    else
        trainRoutes.setAutoImport(false);
    trainRoutes.setTrainExportPath (this->configInfo.at(2));
    trainRoutes.setTicketExportPath(this->configInfo.at(3));
    trainRoutes.setTrainImportPath (this->configInfo.at(4));
    trainRoutes.setTicketImportPath(this->configInfo.at(5));

//--------------------------------* signal-slots *----------------------------------------
    connect(ui->importButton,    &QPushButton::clicked, this, &MainWindow::importDialog);
    connect(ui->exportButton,    &QPushButton::clicked, this, &MainWindow::exportDialog);
    connect(ui->refreshButton,   &QPushButton::clicked, this, &MainWindow::refreshTable);
    connect(ui->removeButton,    &QPushButton::clicked, this, &MainWindow::deleteRoute);
    connect(ui->sellButton,      &QPushButton::clicked, this, &MainWindow::sellTicketDialog);
    connect(ui->refundButton,    &QPushButton::clicked, this, &MainWindow::refundTicketDialog);
    connect(ui->addButton,       &QPushButton::clicked, this, &MainWindow::addTrainDialog);
    connect(ui->modifyButton,    &QPushButton::clicked, this, &MainWindow::modifyTrainDialog);
    connect(ui->queryButton,     &QPushButton::clicked, this, &MainWindow::queryDialog);
    connect(ui->routeQueryButton,&QPushButton::clicked, this, &MainWindow::openRouteQueryDialog);

//-----------------------------------* menu *--------------------------------------------
    QMenu *fileMenu   = ui->menuBar->addMenu(QString::fromLocal8Bit("文件"));
    QMenu *configMenu = ui->menuBar->addMenu(QString::fromLocal8Bit("选项"));
    QMenu *helpMenu   = ui->menuBar->addMenu(QString::fromLocal8Bit("帮助"));

    QAction *configAction = new QAction(QIcon(":/icon/config.png"), QString::fromLocal8Bit("首选项"), this);
    connect(configAction, &QAction::triggered, this, &MainWindow::configDialog);
    configMenu->addAction(configAction);

    QAction *exportAction = new QAction(QIcon(":/icon/export.png"), QString::fromLocal8Bit("导出车次"), this);
    connect(exportAction, &QAction::triggered, this, &MainWindow::saveToFile);
    fileMenu->addAction(exportAction);

    QAction *ticketsExportAction = new QAction(QIcon(":/icon/export.png"), QString::fromLocal8Bit("导出票价"), this);
    connect(ticketsExportAction, &QAction::triggered, this, &MainWindow::ticketsSaveToFile);
    fileMenu->addAction(ticketsExportAction);

    QAction *importAction = new QAction(QIcon(":/icon/import.png"), QString::fromLocal8Bit("导入"), this);
    connect(importAction, &QAction::triggered, this, &MainWindow::importDialog);
    fileMenu->addAction(importAction);

    QAction *onlineImportAction = new QAction(QIcon(":/icon/import.png"), QString::fromLocal8Bit("从网络导入"), this);
    connect(onlineImportAction, &QAction::triggered, this, &MainWindow::onlineLoadingDialog);
    fileMenu->addAction(onlineImportAction);

    QAction *emptyAction = new QAction(QIcon(":/icon/refresh.png"), QString::fromLocal8Bit("清空"), this);
    connect(emptyAction, &QAction::triggered, this, &MainWindow::removeAll);
    fileMenu->addAction(emptyAction);

    QAction *helpAction = new QAction(QIcon(":/icon/help.png"), QString::fromLocal8Bit("用户手册"), this);
    connect(helpAction, &QAction::triggered, this, &MainWindow::helpDialog);
    helpMenu->addAction(helpAction);
//-----------------------------------* table *-----------------------------------
    //train Table initialize
    trainTable = new QTableWidget(this);
    trainTable->setColumnCount(9);
    trainTable->setRowCount(0);

    connect(trainTable, &QTableWidget::cellDoubleClicked, this, &MainWindow::modifyTrainDialog);

    QStringList headers;
    headers << QString::fromLocal8Bit("班次号")
            << QString::fromLocal8Bit("始发站")
            << QString::fromLocal8Bit("终点站")
            << QString::fromLocal8Bit("发车时间")
            << QString::fromLocal8Bit("行车时间")
            << QString::fromLocal8Bit("票价")
            << QString::fromLocal8Bit("额定载客量")
            << QString::fromLocal8Bit("余票数")
            << QString::fromLocal8Bit("路线/余票");
    trainTable->setHorizontalHeaderLabels(headers);
    trainTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // uneditable
    trainTable->setSelectionBehavior(QAbstractItemView::SelectRows);//select entire row
    trainTable->verticalHeader()->setVisible(false); //hide vertical header
    trainTable->setSelectionMode(QAbstractItemView::SingleSelection);//single selection
    //table width
    trainTable->resizeColumnsToContents();
    trainTable->resizeRowsToContents();
    trainTable->setColumnWidth(0, 65);
    trainTable->setColumnWidth(1, 75);
    trainTable->setColumnWidth(2, 75);
    trainTable->setColumnWidth(3, 140);
    trainTable->setColumnWidth(5, 60);
    trainTable->setColumnWidth(8, 115);

    //ticket table init
    ticketTable = new QTableWidget(this);
    ticketTable->setColumnCount(8);
    ticketTable->setRowCount(0);
    ticketTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // uneditable
    ticketTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ticketTable->setSelectionMode(QAbstractItemView::SingleSelection); //single selection
    ticketTable->verticalHeader()->setVisible(false);//hide vertical header
    //table header
    headers.clear();
    headers << QString::fromLocal8Bit("订单号")
            << QString::fromLocal8Bit("购票人")
            << QString::fromLocal8Bit("车次号")
            << QString::fromLocal8Bit("始发站")
            << QString::fromLocal8Bit("终点站")
            << QString::fromLocal8Bit("票价")
            << QString::fromLocal8Bit("票数")
            << QString::fromLocal8Bit("总价");
    ticketTable->setHorizontalHeaderLabels(headers);
    //table width
    ticketTable->resizeColumnsToContents();
    ticketTable->resizeRowsToContents();
    ticketTable->setColumnWidth(0,100 * 1.27);
    ticketTable->setColumnWidth(1, 72 * 1.27);
    ticketTable->setColumnWidth(2, 68 * 1.27);
    ticketTable->setColumnWidth(3, 78 * 1.27);
    ticketTable->setColumnWidth(4, 78 * 1.27);
    ticketTable->setColumnWidth(5, 62 * 1.27);
    ticketTable->setColumnWidth(6, 60 * 1.27);
    ticketTable->setColumnWidth(7, 70 * 1.27);

    //add table
    ui->tabWidget->addTab(trainTable, QString::fromLocal8Bit("火车"));
    ui->tabWidget->addTab(ticketTable, QString::fromLocal8Bit("订单"));

//----------------------------------* time label *------------------------------------

    timeLabel = new QLabel(this);
    QVBoxLayout *timeLayout = new QVBoxLayout(this);
    timeLayout->addWidget(timeLabel);
    ui->groupBox->setLayout(timeLayout);
    QTimer *timer = new QTimer(this);
    connect(timer,
            &QTimer::timeout,
            [&](){timeLabel->setText("  " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));});
    timer->start(1000);
}
Esempio n. 16
0
File: ppplog.cpp Progetto: KDE/kppp
void PPPL_AnalyseLog(QStringList &list, QStringList &result) {
  QString msg;
  const char *rmsg = "Remote message: ";

  result.clear();

  // setup the analysis database
  struct {
    const char *regexp;
    const char *answer;
  } hints[] = {
    {"Receive serial link is not 8-bit clean",
     I18N_NOOP("You have launched pppd before the remote server " \
	  "was ready to establish a PPP connection.\n"
	  "Please use the terminal-based login to verify") },

    {"Serial line is looped back",
     I18N_NOOP("You have not started the PPP software on the peer system.") },

    {"AP authentication failed",
     I18N_NOOP("Check that you supplied the correct username and password.")} ,

    {"is locked by pid",
     I18N_NOOP("You should not pass 'lock' as an argument to pppd. "
	  "Check /etc/ppp/options and ~/.ppprc") },

    {"CP: timeout sending",
     I18N_NOOP("The remote system does not seem to answer to\n"
	  "configuration request. Contact your provider.") },

    {"unrecognized option",
     I18N_NOOP("You have passed an invalid option to pppd. See 'man pppd' "
          "for a complete list of valid arguments.") },

    // terminator
    {0,0}
  };


  // scan the log for keywords and try to offer any help
  for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
  {
    // look for remote message
    int pos = (*it).indexOf(rmsg);
    if (pos != -1)
    {
      QString str = (*it);
      str.remove(0, pos + strlen(rmsg));
      if(!str.isEmpty()) {
        msg = i18n("Notice that the remote system has sent the following"
                         " message:\n\"%1\"\nThis may give you a hint why the"
                         " connection has failed.", str);
        result.append(msg);
      }
    }

    // check in the hint database
    for(uint k = 0; hints[k].regexp != 0; k++) {
      QRegExp rx(hints[k].regexp);
      QString l(*it);
      if(l.contains(rx)) {
	result.append(i18n(hints[k].answer));
	break;
      }
    }
  }

  if (result.isEmpty())
    result.append(i18n("Unable to provide help."));
}
// Refresh plugin listing.
void qtractorPluginSelectForm::refresh (void)
{
	m_ui.PluginListView->clear();

	qtractorPluginFactory *pPluginFactory
		= qtractorPluginFactory::getInstance();
	if (pPluginFactory == NULL)
		return;

	// FIXME: Should this be a global (singleton) registry?
	if (pPluginFactory->types().isEmpty()) {
		// Tell the world we'll take some time...
		QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
		const bool bRescan = m_ui.PluginRescanPushButton->isVisible();
		if (bRescan) m_ui.PluginRescanPushButton->hide();
		m_ui.DialogButtonBox->button(QDialogButtonBox::Cancel)->setEnabled(false);
		m_ui.PluginScanProgressBar->show();
		pPluginFactory->scan();
		m_ui.PluginScanProgressBar->hide();
		m_ui.DialogButtonBox->button(QDialogButtonBox::Cancel)->setEnabled(true);
		if (bRescan) m_ui.PluginRescanPushButton->show();
		// We're formerly done.
		QApplication::restoreOverrideCursor();
	}

	if (m_pPluginList == NULL) {
		stabilize();
		return;
	}

	const unsigned short iChannels = m_pPluginList->channels();
	const bool bMidi = m_pPluginList->isMidi();

	QString sSearch = m_ui.PluginSearchComboBox->currentText().simplified();
	const QRegExp rx(sSearch.replace(QRegExp("[\\s]+"), ".*"), Qt::CaseInsensitive);

	QStringList cols;
	QList<QTreeWidgetItem *> items;
	QListIterator<qtractorPluginType *> type_iter(pPluginFactory->types());
	while (type_iter.hasNext()) {
		qtractorPluginType *pType = type_iter.next();
		const QString& sFilename = pType->filename();
		const QString& sName = pType->name();
		if (rx.isEmpty()
			|| rx.indexIn(sName) >= 0
			|| rx.indexIn(sFilename) >= 0) {
			// Try primary instantiation...
			const int iAudioIns    = pType->audioIns();
			const int iAudioOuts   = pType->audioOuts();
			const int iMidiIns     = pType->midiIns();
			const int iMidiOuts    = pType->midiOuts();
			const int iControlIns  = pType->controlIns();
			const int iControlOuts = pType->controlOuts();
			// All that to check whether it will get properly instantiated.
			const unsigned short iInstances
				= pType->instances(iChannels, bMidi);
			cols.clear();
			cols << sName;
			cols << QString("%1:%2").arg(iAudioIns).arg(iAudioOuts);
			cols << QString("%1:%2").arg(iMidiIns).arg(iMidiOuts);
			cols << QString("%1:%2").arg(iControlIns).arg(iControlOuts);
			QStringList modes;
			if (pType->isEditor())
				modes << tr("GUI");
			if (pType->isConfigure())
				modes << tr("EXT");
			if (pType->isRealtime())
				modes << tr("RT");
			if (modes.isEmpty())
				cols << "-";
			else
				cols << modes.join(",");
			cols << sFilename;
			cols << QString::number(pType->index());
			cols << QString::number(iInstances);
			cols << qtractorPluginType::textFromHint(pType->typeHint());
			QTreeWidgetItem *pItem = new QTreeWidgetItem(cols);
			if (iInstances < 1) {
				pItem->setFlags(pItem->flags() & ~Qt::ItemIsSelectable);
				const int iColumnCount = m_ui.PluginListView->columnCount();
				const QPalette& pal = m_ui.PluginListView->palette();
				const QColor& rgbForeground
					= pal.color(QPalette::Disabled, QPalette::WindowText);
				for (int i = 0; i < iColumnCount; ++i)
					pItem->setForeground(i, rgbForeground);
			}
			pItem->setTextAlignment(1, Qt::AlignHCenter);	// Audio
			pItem->setTextAlignment(2, Qt::AlignHCenter);	// MIDI
			pItem->setTextAlignment(3, Qt::AlignHCenter);	// Controls
			pItem->setTextAlignment(4, Qt::AlignHCenter);	// Modes
			items.append(pItem);
		}
	}
	m_ui.PluginListView->addTopLevelItems(items);

	QHeaderView *pHeader = m_ui.PluginListView->header();
	m_ui.PluginListView->sortItems(
		pHeader->sortIndicatorSection(),
		pHeader->sortIndicatorOrder());

	m_ui.PluginResetToolButton->setEnabled(!rx.isEmpty());

	stabilize();
}
Esempio n. 18
0
File: ppplog.cpp Progetto: KDE/kppp
int PPPL_MakeLog(QStringList &list) {
  int pid = -1, newpid;
  char buffer[1024], *p;
  const char *pidp;
  int fd;

  fd = Requester::rq->openSysLog();
  if(fd < 0) {
    list.append(i18n("Cannot open any of the following logfiles:"));
    const char * const * logFile = &kppp_syslog[0];
    while(*logFile) {
      list.append(*logFile);
      logFile++;
    }
    return 1;
  }

  FILE *f = fdopen(fd, "r");
  while(fgets(buffer, sizeof(buffer), f) != 0) {
    // pppd line ?
    p = (char *)strstr(buffer, "pppd[");
    if(p == 0)
      continue;
    pidp = p += strlen("pppd[");
    while(*p && isdigit(*p))
      p++;
    if(*p != ']')
      continue;

    /* find out pid of pppd */
    sscanf(pidp, "%d", &newpid);
    if(newpid != pid) {
      pid = newpid;
      list.clear();
    }
    if(buffer[strlen(buffer)-1] == '\n')
      buffer[strlen(buffer)-1] = '\0';
    list.append(buffer);
  }
  fclose(f);

  if(list.isEmpty())
    return 2;

  /* clear security related info */

  const char *keyword[] = {"name = \"",
		    "user=\"",
		    "password=\"",
		    0};

  for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
  {
    QByteArray tmp = (*it).toLocal8Bit();
    for(int j = 0; keyword[j] != 0; j++) {
      char *p;

      if( (p = (char *)strstr(tmp.data(), keyword[j])) != 0) {
	p += strlen(keyword[j]);
	while(*p && *p != '"')
	  *p++ = 'X';
      }
    }

  }

  return 0;
}
Esempio n. 19
0
/**
 * @brief TimerWindow::updateTimeData 同步时间到数据库
 */
void TimerWindow::updateTimeData()
{
    qDebug()<<"\nupdateTimeData()";
    User &user = User::getInstance();
    //未登录时,直接返回
    if(!user.isLogined()){
        qDebug()<<"not login";
        return;
    }
    QString u_id = QString::number(user.getUserId());

#ifdef USE_DB_HELPER
    int result;
    //获取当前时间
    QString date;
//    result = db.getNowDate(date);
//    if(result != db.e_result::excuteSueecss){
//        emit signalSetStatus(tr("Get time error!code:") + QString::number(result),true);
//        return;
//    }

    QString sql;
    QStringList params;
    nowDate = QDate::fromString(date, "yyyy-MM-dd");
//    qDebug()<<"lastDate"<<lastDate.toString("yyyy-MM-dd");
//    qDebug()<<"nowDate"<<nowDate.toString("yyyy-MM-dd");
    if(lastDate == nowDate){
        qDebug()<<"lastDate == nowDate";

        //更新时间
        sql = "UPDATE times SET times = ? WHERE user_id = ? AND date = ?";
        params.append(QString::number(todayTime));
        params.append(u_id);
        params.append(date);
//        result = db.excuteSqlTran(sql, params);
//        if(result != db.e_result::excuteSueecss){
//            emit signalSetStatus(tr("Update time error!code:")+QString::number(result),true);
//            return;
//        }
    }else{
        qDebug()<<"lastDate != nowDate";
        //如果lastDate不存在
//        if(!db.existDate(u_id, lastDate.toString("yyyy-MM-dd"))){
//            //插入lastDate
//            sql = "INSERT INTO times(user_id, date) VALUES(?, ?)";
//            params.clear();
//            params.append(u_id);
//            params.append(lastDate.toString("yyyy-MM-dd"));
//            result = db.excuteSqlTran(sql, params);
////            qDebug()<<"insert " + QString::number(result);
//            if(result != db.e_result::excuteSueecss){
//                emit signalSetStatus(tr("Insert last error!code:")+QString::number(result),true);
//                return;
//            }
//        }

        //更新lastDate的时间
        sql = "UPDATE times SET times = ? WHERE user_id = ? AND date = ?";
        params.clear();
        params.append(QString::number(todayTime));
        params.append(u_id);
        params.append(date);
//        result = db.excuteSqlTran(sql, params);
//        qDebug()<<"update " + QString::number(result);
//        if(result != db.e_result::excuteSueecss){
//            emit signalSetStatus(tr("Update last error!code:")+QString::number(result),true);
//            return;
//        }

        //如果nowDate不存在
//        if(!db.existDate(u_id, nowDate.toString("yyyy-MM-dd"))){
//            //插入nowDate的时间
//            sql = "INSERT INTO times(user_id, date) VALUES(?, ?)";
//            params.clear();
//            params.append(u_id);
//            params.append(date);
//            result = db.excuteSqlTran(sql, params);

//    //        qDebug()<<"insert2 " + QString::number(result);
////            if(result != db.e_result::excuteSueecss){
////                emit signalSetStatus(tr("Update error!code:")+QString::number(result),true);
////                return;
////            }
//        }else{
//            //某日已有时间数据在数据库,而该日又重装了计时器则会进入这里(很少遇到),
//            //因为重装后lastDate默认为1970-01-01,导致nowDate != lastDate。
//            //这里应该要获取用户该日和该周时间,与现在计时器的时间相加再更
//            //新到数据库!但这里不打算这样做,而是直接不要这个更新周期所得的时间(也不多)。
//            //所以什么都不处理。
//        }

//        if(lastDate != nowDate){
//            //更新注册表lastDate
//            settings.beginGroup("UserInfo");
//            settings.setValue("lastDate",date);
//            settings.endGroup();
//        }

        lastDate = nowDate;
        todayTime = 0;

    }
#else
    //获取当前时间
    //lastDate == nowDate
        //更新时间
    //lastDate != nowDate
        //lastDate不存在
            //插入lastDate
        //更新lastDate
        //nowDate不存在
            //插入nowDate
        //更新注册表lastDate
#endif

    qDebug()<<"end updateTimeData()";
}
Esempio n. 20
0
AbstractCommand::ReturnCodes Record::record()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot(CheckFileSystem);

    if (m_mode != Unset)
        m_all = m_mode == AllChanges;
    const bool needHunks = !m_all || m_patchName.isEmpty();

    ChangeSet changeSet;
    changeSet.fillFromCurrentChanges(rebasedArguments(), needHunks);

    changeSet.waitForFinishFirstFile();
    bool shouldDoRecord = changeSet.count() > 0;
    if (!shouldDoRecord) {
        Logger::warn() << "No changes!" << endl;
        return Ok;
    }

    QString email = m_author;
    if (email.isEmpty())
        email = getenv("EMAIL");
    QStringList environment;
    if (! email.isEmpty()) {
        QRegExp re("(.*) <([@\\S]+)>");
        if (re.exactMatch(email)) { // meaning its an email AND name
            environment << "GIT_AUTHOR_NAME="+ re.cap(1);
            environment << "GIT_COMMITTER_NAME="+ re.cap(1);
            environment << "GIT_AUTHOR_EMAIL="+ re.cap(2);
            environment << "GIT_COMMITTER_EMAIL="+ re.cap(2);
        }
        else if (m_author.isEmpty()) { // if its an account or shell wide option; just use the git defs.
            environment << "GIT_AUTHOR_EMAIL="+ email;
            environment << "GIT_COMMITTER_EMAIL="+ email;
        }
        else {
            Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
            return InvalidOptions;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // then do interview
        HunksCursor cursor(changeSet);
        cursor.setConfiguration(m_config);
        Interview interview(cursor, name());
        interview.setUsePager(shouldUsePager());
        if (! interview.start()) {
            Logger::warn() << "Cancelled." << endl;
            return UserCancelled;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // check if there is anything selected
        shouldDoRecord = changeSet.hasAcceptedChanges();
        if (! shouldDoRecord) {
            Logger::warn() << "Ok, if you don't want to record anything, that's fine!" <<endl;
            return UserCancelled;
        }
    }
    if (dryRun())
        return Ok;

    if ((m_editComment || m_patchName.isEmpty()) && getenv("EDITOR")) {
        class Deleter : public QObject {
        public:
            Deleter() : commitMessage(0) { }
            ~Deleter() {
                if (commitMessage)
                    commitMessage->remove();
            }
            QFile *commitMessage;
        };
        Deleter parent;
        QFile *commitMessage;
        int i = 0;
        do {
            commitMessage = new QFile(QString("vng-record-%1").arg(i++), &parent);
        } while (commitMessage->exists());
        parent.commitMessage = commitMessage; // make sure the file is removed from FS.
        if (! commitMessage->open(QIODevice::WriteOnly)) {
            Logger::error() << "Vng failed. Could not create a temporary file for the record message '"
                << commitMessage->fileName() << "`\n";
            return WriteError;
        }
        const char * defaultCommitMessage1 = "\n***END OF DESCRIPTION***"; // we will look for this string later
        const char * defaultCommitMessage2 = "\nPlace the long patch description above the ***END OF DESCRIPTION*** marker.\n\nThis patch contains the following changes:\n\n";
        if (! m_patchName.isEmpty())
            commitMessage->write(m_patchName);
        else
            commitMessage->write("\n", 1);
        commitMessage->write(defaultCommitMessage1, strlen(defaultCommitMessage1));
        commitMessage->write(defaultCommitMessage2, strlen(defaultCommitMessage2));
        QBuffer buffer;
        changeSet.writeDiff(buffer, m_all ? ChangeSet::AllHunks : ChangeSet::UserSelection);
        ChangeSet actualChanges;
        actualChanges.fillFromDiffFile(buffer);
        QTextStream out (commitMessage);
        for (int i=0; i < actualChanges.count(); ++i) {
            File file = actualChanges.file(i);
            file.outputWhatsChanged(out, m_config, true, false);
        }
        for (int i=0; i < changeSet.count(); ++i) {
            File file = changeSet.file(i);
            if (file.isBinary() && (m_all || file.binaryChangeAcceptance() == Vng::Accepted))
                out << "M " << QString::fromLocal8Bit(file.fileName());
            else if (file.fileName().isEmpty() && (m_all || file.renameAcceptance() == Vng::Accepted))
                out << "D " << QString::fromLocal8Bit(file.oldFileName());
        }
        out.flush();

        commitMessage->close();
        QDateTime modification = QFileInfo(*commitMessage).lastModified();
        QString command = QString("%1 %2").arg(getenv("EDITOR")).arg(commitMessage->fileName());
        int rc = system(command.toAscii().data());
        if (rc != 0) {
            // this will keep patchName empty and we fall through to the interview.
            Logger::warn() << "Vng-Warning: Could not start editor '" << getenv("EDITOR") << "`\n";
            Logger::warn().flush();
        }
        else if (modification == QFileInfo(*commitMessage).lastModified()) {
            Logger::warn() << "unchanged, won't record\n";
            return UserCancelled;
        }
        else {
            // get data until the separator line.
            commitMessage->open(QIODevice::ReadOnly);
            m_patchName = commitMessage->readAll();
            commitMessage->close();
            int cuttoff = m_patchName.indexOf(defaultCommitMessage1);
            if (cuttoff > 0)
                m_patchName.truncate(cuttoff);
            for (int i = m_patchName.length()-1; i >= 0; --i) {
                if (m_patchName[i] == '\n' || m_patchName[i] == '\r' || m_patchName[i] == ' ')
                    m_patchName.resize(i); // shrink
                else break;
            }
        }
    }
    if (m_patchName.isEmpty())
        m_patchName = Interview::ask("What is the patch name? ").toUtf8();

    ReturnCodes rc = addFilesPerAcceptance(changeSet, m_all);
    if (rc != Ok)
        return rc;

    QProcess git;
    QStringList arguments;
    arguments << "write-tree";
    GitRunner runner(git, arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git write-tree failed!, aborting record\n";
        return rc;
    }
    char buf[1024];
    Vng::readLine(&git, buf, sizeof(buf));
    QString tree(buf);
    git.waitForFinished(); // patiently wait for it to finish..
    Logger::debug() << "The tree got git ref; " << tree;
    Logger::debug().flush(); // flush since we do an ask next

    arguments.clear();
    git.setEnvironment(environment);

    arguments << "commit-tree" << tree.left(40);
    if (!m_config.isEmptyRepo())
        arguments << "-p" << "HEAD" ;

    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilReadyForWrite);
    if (rc != Ok) {
        Logger::error() << "Git commit-tree failed!, aborting record\n";
        return rc;
    }
    git.write(m_patchName);
    git.write("\n");
    git.closeWriteChannel();
    Vng::readLine(&git, buf, sizeof(buf));
    QString commit(buf);
    Logger::debug() << "commit is ref; " << commit;
    git.waitForFinished(); // patiently wait for it to finish..
    if (commit.isEmpty()) {
        Logger::error() << "Git update-ref failed to produce a reference!, aborting record\n";
        return GitFailed;
    }
    m_sha1 = commit.left(40);

    arguments.clear();
    arguments << "update-ref" << "HEAD" << m_sha1;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilFinished);
    if (rc != Ok) {
        Logger::error() << "Git update-ref failed!, aborting record\n";
        return rc;
    }

    // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
    // we have to re-add those files.
    arguments.clear();
    arguments << "update-index" << "--add";
    for (int i=0; i < changeSet.count(); ++i) {
        File file = changeSet.file(i);
        if (! file.oldFileName().isEmpty())
            continue; // not a new added file.
        if (file.renameAcceptance() == Vng::Rejected)
            arguments.append(file.fileName());
    }
    if (arguments.count() > 2) {
        runner.setArguments(arguments);
        runner.start(GitRunner::WaitUntilFinished);
    }

    int endOfLine = m_patchName.indexOf('\n');
    if (endOfLine > 0)
        m_patchName.truncate(endOfLine);
    Logger::warn() << "Finished recording patch `" << m_patchName << "'" << endl;
    return Ok;
}
Esempio n. 21
0
QgsAbout::QgsAbout()
    : QDialog( NULL, Qt::WindowSystemMenuHint )  // Modeless dialog with close button only
#else
QgsAbout::QgsAbout()
    : QDialog( NULL )  // Normal dialog in non Mac-OS
#endif
{
  setupUi( this );
  init();
}

QgsAbout::~QgsAbout()
{
}

void QgsAbout::init()
{
  setPluginInfo();

  // set the 60x60 icon pixmap
  QPixmap icon( QgsApplication::iconsPath() + "qgis-icon-60x60.png" );
  qgisIcon->setPixmap( icon );

  //read the authors file to populate the svn committers list
  QStringList lines;

  //
  // Load the authors (svn committers) list
  //
  QFile file( QgsApplication::authorsFilePath() );
  if ( file.open( QIODevice::ReadOnly ) )
  {
    QTextStream stream( &file );
    // Always use UTF-8
    stream.setCodec( "UTF-8" );
    QString line;
    while ( !stream.atEnd() )
    {
      line = stream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( line.left( 1 ) == "#" ) continue;
      QStringList myTokens = line.split( "\t", QString::SkipEmptyParts );
      lines << myTokens[0];
    }
    file.close();
    lstDevelopers->clear();
    lstDevelopers->insertItems( 0, lines );

    if ( lstDevelopers->count() > 0 )
    {
      lstDevelopers->setCurrentRow( 0 );
    }
  }

  lines.clear();
  //
  // Now load up the contributors list
  //
  QFile file2( QgsApplication::contributorsFilePath() );
  printf( "Reading contributors file %s.............................................\n",
          file2.fileName().toLocal8Bit().constData() );
  if ( file2.open( QIODevice::ReadOnly ) )
  {
    QTextStream stream( &file2 );
    // Always use UTF-8
    stream.setCodec( "UTF-8" );
    QString line;
    while ( !stream.atEnd() )
    {
      line = stream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( line.left( 1 ) == "#" ) continue;
      lines += line;
    }
    file2.close();
    lstContributors->clear();
    lstContributors->insertItems( 0, lines );
    if ( lstContributors->count() > 0 )
    {
      lstContributors->setCurrentRow( 0 );
    }
  }


  // read the SPONSORS file and populate the text widget
  QFile sponsorFile( QgsApplication::sponsorsFilePath() );
#ifdef QGISDEBUG
  printf( "Reading sponsors file %s.............................................\n",
          sponsorFile.fileName().toLocal8Bit().constData() );
#endif
  if ( sponsorFile.open( QIODevice::ReadOnly ) )
  {
    QString sponsorHTML = ""
                          + tr( "<p>QGIS sponsorship programme:"
                                "contribute to QGIS development</p>" )
                          + "<hr>"
                          "<table width='100%'>"
                          "<tr><th>" + tr( "Name" ) + "</th>"
                          "<th>" + tr( "Website" ) + "</th></tr>";
    QString website;
    QTextStream sponsorStream( &sponsorFile );
    // Always use UTF-8
    sponsorStream.setCodec( "UTF-8" );
    QString sline;
    while ( !sponsorStream.atEnd() )
    {
      sline = sponsorStream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( sline.left( 1 ) == "#" ) continue;
      QStringList myTokens = sline.split( "|", QString::SkipEmptyParts );
      if ( myTokens.size() == 0 )
      {
        continue;
      }
      else if ( myTokens.size() > 1 )
      {
        website = "<a href=\"" + myTokens[1].remove( ' ' ) + "\">" + myTokens[1] + "</a>";
      }
      else
      {
        website = "&nbsp;";
      }
      sponsorHTML += "<tr>";
      sponsorHTML += "<td>" + myTokens[0] + "</td><td>" + website + "</td>";
      // close the row
      sponsorHTML += "</tr>";
    }
    sponsorHTML += "</table>";

    QString myStyle = QgsApplication::reportStyleSheet();
    txtSponsors->clear();
    txtSponsors->document()->setDefaultStyleSheet( myStyle );
    txtSponsors->setHtml( sponsorHTML );
    QgsDebugMsg( QString( "sponsorHTML:%1" ).arg( sponsorHTML.toAscii().constData() ) );
    QgsDebugMsg( QString( "txtSponsors:%1" ).arg( txtSponsors->toHtml().toAscii().constData() ) );
  }

  // read the DONORS file and populate the text widget
  QFile donorsFile( QgsApplication::donorsFilePath() );
#ifdef QGISDEBUG
  printf( "Reading donors file %s.............................................\n",
          donorsFile.fileName().toLocal8Bit().constData() );
#endif
  if ( donorsFile.open( QIODevice::ReadOnly ) )
  {
    QString donorsHTML = ""
                         + tr( "<p>For a list of individuals and institutions who have contributed "
                               "money to fund QGIS development and other project costs see "
                               "<a href=\"http://qgis.org/en/sponsorship/donors.html\">"
                               "http://qgis.org/en/sponsorship/donors.html</a></p>" );
    /*QString website;
    QTextStream donorsStream( &donorsFile );
    // Always use UTF-8
    donorsStream.setCodec( "UTF-8" );
    QString sline;
    while ( !donorsStream.atEnd() )
    {
      sline = donorsStream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( sline.left( 1 ) == "#" ) continue;
      QStringList myTokens = sline.split( "|", QString::SkipEmptyParts );
      if ( myTokens.size() > 1 )
      {
        website = "<a href=\"" + myTokens[1].remove( ' ' ) + "\">" + myTokens[1] + "</a>";
      }
      else
      {
        website = "&nbsp;";
      }
      donorsHTML += "<tr>";
      donorsHTML += "<td>" + myTokens[0] + "</td><td>" + website + "</td>";
      // close the row
      donorsHTML += "</tr>";
    }
    donorsHTML += "</table>";*/

    QString myStyle = QgsApplication::reportStyleSheet();
    txtDonors->clear();
    txtDonors->document()->setDefaultStyleSheet( myStyle );
    txtDonors->setHtml( donorsHTML );
    QgsDebugMsg( QString( "donorsHTML:%1" ).arg( donorsHTML.toAscii().constData() ) );
    QgsDebugMsg( QString( "txtDonors:%1" ).arg( txtDonors->toHtml().toAscii().constData() ) );
  }

  // read the TRANSLATORS file and populate the text widget
  QFile translatorFile( QgsApplication::translatorsFilePath() );
#ifdef QGISDEBUG
  printf( "Reading translators file %s.............................................\n",
          translatorFile.fileName().toLocal8Bit().constData() );
#endif
  if ( translatorFile.open( QIODevice::ReadOnly ) )
  {
    QString translatorHTML = ""
                             + tr( "<p>The following have contributed to QGIS"
                                   " by translating the user interface or documentation</p>" )
                             + "<hr>"
                             "<table width='100%'>"
                             "<tr><th>" + tr( "Language" ) + "</th>"
                             "<th>" + tr( "Names" ) + "</th></tr>";
    QString website;
    QTextStream translatorStream( &translatorFile );
    // Always use UTF-8
    translatorStream.setCodec( "UTF-8" );
    QString sline;
    while ( !translatorStream.atEnd() )
    {
      sline = translatorStream.readLine(); // line of text excluding '\n'
      //ignore the line if it starts with a hash....
      if ( sline.left( 1 ) == "#" ) continue;
      QStringList myTokens = sline.split( "|", QString::SkipEmptyParts );
      if ( myTokens.size() > 1 )
      {
        website = myTokens[1];
      }
      else
      {
        website = "&nbsp;";
      }
      translatorHTML += "<tr>";
      translatorHTML += "<td>" + myTokens[0] + "</td><td>" + website + "</td>";
      // close the row
      translatorHTML += "</tr>";
    }
    translatorHTML += "</table>";

    QString myStyle = QgsApplication::reportStyleSheet();
    txtTranslators->clear();
    txtTranslators->document()->setDefaultStyleSheet( myStyle );
    txtTranslators->setHtml( translatorHTML );
    QgsDebugMsg( QString( "translatorHTML:%1" ).arg( translatorHTML.toAscii().constData() ) );
    QgsDebugMsg( QString( "txtTranslators:%1" ).arg( txtTranslators->toHtml().toAscii().constData() ) );
  }
}
Esempio n. 22
0
void KStandardDirs::addKDEDefaults()
{
    QStringList kdedirList;

    // begin KDEDIRS
    QString kdedirs = readEnvPath("KDEDIRS");
    if (!kdedirs.isEmpty())
    {
        tokenize(kdedirList, kdedirs, QChar(KPATH_SEPARATOR));
    }
    else
    {
        QString kdedir = readEnvPath("KDEDIR");
        if (!kdedir.isEmpty())
        {
           kdedir = KShell::tildeExpand(kdedir);
           kdedirList.append(kdedir);
        }
    }

#ifndef Q_OS_WIN //no default KDEDIR on win32 defined
    kdedirList.append(KDEDIR);
#endif

#ifdef __KDE_EXECPREFIX
    QString execPrefix(__KDE_EXECPREFIX);
    if (execPrefix!="NONE")
       kdedirList.append(execPrefix);
#endif
#ifdef __linux__
    const QString linuxExecPrefix = executablePrefix();
    if ( !linuxExecPrefix.isEmpty() )
       kdedirList.append( linuxExecPrefix );
#endif

    // We treat root differently to prevent a "su" shell messing up the
    // file permissions in the user's home directory.
    QString localKdeDir = readEnvPath(getuid() ? "KDEHOME" : "KDEROOTHOME");
    if (!localKdeDir.isEmpty())
    {
       if (localKdeDir[localKdeDir.length()-1] != '/')
          localKdeDir += '/';
    }
    else
    {
       localKdeDir =  QDir::homeDirPath() + "/.kde/";
    }

    if (localKdeDir != "-/")
    {
        localKdeDir = KShell::tildeExpand(localKdeDir);
        addPrefix(localKdeDir);
    }

	QStringList::ConstIterator end(kdedirList.end());
    for (QStringList::ConstIterator it = kdedirList.begin();
	 it != end; ++it)
    {
        QString dir = KShell::tildeExpand(*it);
	addPrefix(dir);
    }
    // end KDEDIRS

    // begin XDG_CONFIG_XXX
    QStringList xdgdirList;
    QString xdgdirs = readEnvPath("XDG_CONFIG_DIRS");
    if (!xdgdirs.isEmpty())
    {
	tokenize(xdgdirList, xdgdirs, QChar(KPATH_SEPARATOR));
    }
    else
    {
	xdgdirList.clear();
        xdgdirList.append("/etc/xdg");
#ifdef Q_WS_WIN
        xdgdirList.append(kfsstnd_defaultprefix() + "/etc/xdg");
#else
        xdgdirList.append(KDESYSCONFDIR "/xdg");
#endif
    }

    QString localXdgDir = readEnvPath("XDG_CONFIG_HOME");
    if (!localXdgDir.isEmpty())
    {
       if (localXdgDir[localXdgDir.length()-1] != '/')
          localXdgDir += '/';
    }
    else
    {
       localXdgDir =  QDir::homeDirPath() + "/.config/";
    }

    localXdgDir = KShell::tildeExpand(localXdgDir);
    addXdgConfigPrefix(localXdgDir);

    for (QStringList::ConstIterator it = xdgdirList.begin();
	 it != xdgdirList.end(); ++it)
    {
        QString dir = KShell::tildeExpand(*it);
	addXdgConfigPrefix(dir);
    }
    // end XDG_CONFIG_XXX

    // begin XDG_DATA_XXX
    xdgdirs = readEnvPath("XDG_DATA_DIRS");
    if (!xdgdirs.isEmpty())
    {
	tokenize(xdgdirList, xdgdirs, QChar(KPATH_SEPARATOR));
    }
    else
    {
	xdgdirList.clear();
        for (QStringList::ConstIterator it = kdedirList.begin();
           it != kdedirList.end(); ++it)
        {
           QString dir = *it;
           if (dir[dir.length()-1] != '/')
             dir += '/';
           xdgdirList.append(dir+"share/");
        }

        xdgdirList.append("/usr/local/share/");
        xdgdirList.append("/usr/share/");
    }

    localXdgDir = readEnvPath("XDG_DATA_HOME");
    if (!localXdgDir.isEmpty())
    {
       if (localXdgDir[localXdgDir.length()-1] != '/')
          localXdgDir += '/';
    }
    else
    {
       localXdgDir = QDir::homeDirPath() + "/.local/share/";
    }

    localXdgDir = KShell::tildeExpand(localXdgDir);
    addXdgDataPrefix(localXdgDir);

    for (QStringList::ConstIterator it = xdgdirList.begin();
	 it != xdgdirList.end(); ++it)
    {
        QString dir = KShell::tildeExpand(*it);
	addXdgDataPrefix(dir);
    }
    // end XDG_DATA_XXX


    uint index = 0;
    while (types[index] != 0) {
	addResourceType(types[index], kde_default(types[index]));
	index++;
    }

    addResourceDir("home", QDir::homeDirPath());
}
Esempio n. 23
0
void MainWindow::on_BTN_START_clicked()
{
    ui->BTN_START->setEnabled(false);
    ui->BTN_ADD->setEnabled(true);

    if (m_pScheAlgo)
    {
        delete m_pScheAlgo;
        m_pScheAlgo = nullptr;
    }
    QStringList header;

    header << "" << "" << "" << "" << "";
    ui->TABLE_RUN->setHorizontalHeaderLabels(header);
    ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
    header << "" << "" << "";
    ui->TABLE_FINISH->setHorizontalHeaderLabels(header);
    header.clear();

    header << "进程名" << "需要运行时间(s)" << "到达时间" << "已运行时间(S)";
    ui->TABLE_RUN->setHorizontalHeaderLabels(header);
    ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
    ui->TABLE_FINISH->setHorizontalHeaderLabels(header);
    if (ui->FCFS->isChecked())
    {
        m_pScheAlgo = new FCFS;
        m_Status = STATUS_FCFS;
    }
    else if (ui->LEVEL->isChecked())
    {
        m_pScheAlgo = new LEVEL;
        m_Status = STATUS_LEVEL;
        QStringList header;
        header << "" << "" << "" << "" << "";
        ui->TABLE_RUN->setHorizontalHeaderLabels(header);
        ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
        header << "" << "" << "";
        ui->TABLE_FINISH->setHorizontalHeaderLabels(header);
        header.clear();
        header << "进程名" << "需要运行时间(s)" << "到达时间" << "已运行时间(S)" << "优先级";
        ui->TABLE_RUN->setHorizontalHeaderLabels(header);
        ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
        ui->TABLE_FINISH->setHorizontalHeaderLabels(header);
    }
    else if(ui->RR->isChecked())
    {
        m_pScheAlgo = new RR(ui->lineEdit->text().toInt());
        m_Status = STATUS_RR;
    }
    else if(ui->SJF->isChecked())
    {
        m_pScheAlgo = new SJF;
        m_Status = STATUS_SJF;
    }
    else if(ui->HRRN->isChecked())
    {
        m_pScheAlgo = new HRRN;
        m_Status = STATUS_HRRN;
        QStringList header;
        header << "" << "" << "" << "" << "" ;
        ui->TABLE_RUN->setHorizontalHeaderLabels(header);
        ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
        header << "" << "" << "";
        ui->TABLE_FINISH->setHorizontalHeaderLabels(header);
        header.clear();
        header << "进程名" << "需要运行时间(s)" << "到达时间" << "已运行时间(S)" << "已等待时间(S)";
        ui->TABLE_RUN->setHorizontalHeaderLabels(header);
        ui->TABLE_WAIT->setHorizontalHeaderLabels(header);
        header << "完成时刻" << "周转时间(S)" << "带权周转时间(S)";
        ui->TABLE_FINISH->setHorizontalHeaderLabels(header);

    }

    m_pScheAlgo->AddWidget(this);

    m_Timer->start(1000);
}
Esempio n. 24
0
void QueryDB::execQuery( const QString& db_path , const QString& query , QueryResult& q_result )
{
    sqlite3 *db;
    sqlite3_stmt *stmt;
    int rc = 0 ;
    int col, cols;

    q_result.clear();
    rc = sqlite3_open( db_path.toAscii().data() , &db );
    if( rc )
    {
        return ;
    }

    rc = sqlite3_prepare_v2( db, query.toUtf8().data() , -1, &stmt, 0);
    if( rc )
    {
        return ;
    }

    cols = sqlite3_column_count(stmt);
    for( col=0; col<cols; col++)
    {
        char *sql_buffer = NULL ;
        sql_buffer = (char*)sqlite3_column_name( stmt, col ) ;
        QString name = QString::fromUtf8( (const char*)sql_buffer ) ;

        q_result.appendColumnName( name , col );
    }

    QStringList row ;
    cols = sqlite3_column_count(stmt);
    // execute the statement

    do
    {
        rc = sqlite3_step(stmt);
        switch( rc ){
        case SQLITE_DONE:
            break;
        case SQLITE_ROW:
            row.clear();
            // print results for this row
            for( col=0; col<cols; col++)
            {
                const unsigned char *sql_buffer = NULL ;
                sql_buffer = sqlite3_column_text( stmt, col ) ;

                row.append( QString::fromUtf8( (const char*)sql_buffer ) ) ;
            }
            q_result.appendResultRow( row ) ;
            break;
        default:
            break;
        }
    } while ( rc == SQLITE_ROW ) ;

    // finalize the statement to release resources
    sqlite3_finalize(stmt);
    sqlite3_close( db ) ;
}
Esempio n. 25
0
void AboutPlugins::currentPluginChanged( const QString& pluginName )
{
    currentPlugin = config->pluginLoader()->backendPluginByName( pluginName );
    if( !currentPlugin )
    {
        aboutPluginLabel->setText( "" );
        return;
    }

    QStringList info;
    info += i18n("About plugin %1:",pluginName);

    info += i18n("Plugin type: %1",currentPlugin->type());

    QMap<QString,QString> binaries = currentPlugin->binaries;
    QStringList binariesString;
    if( binaries.count() > 0 )
    {
        binariesString += i18n("Backend binaries:");
    }
    for( int i=0; i<binaries.count(); i++ )
    {
        if( !binaries.values().at(i).isEmpty() )
            binariesString += i18n("%1 (found at: %2)",binaries.keys().at(i),"<span style=\"color:green\">" + binaries.values().at(i) + "</span>");
        else
            binariesString += "<span style=\"color:red\">" + i18n("%1 (not found)",binaries.keys().at(i)) + "</span>";
    }
    info += binariesString.join("<br>");

    problemInfos.clear();
    if( currentPlugin->type() == "codec" )
    {
        CodecPlugin *codecPlugin = (CodecPlugin*)currentPlugin;

        QStringList codecsString;
        QMap<QString,bool> encodeCodecs;
        QMap<QString,bool> decodeCodecs;
        QList<ConversionPipeTrunk> codecTable = codecPlugin->codecTable();
        for( int i=0; i<codecTable.count(); i++ )
        {
            if( codecTable.at(i).codecTo != "wav" && ( !encodeCodecs.contains(codecTable.at(i).codecTo) || !encodeCodecs[codecTable.at(i).codecTo] ) )
                encodeCodecs[codecTable.at(i).codecTo] = codecTable.at(i).enabled;

            if( codecTable.at(i).codecFrom != "wav" && ( !decodeCodecs.contains(codecTable.at(i).codecFrom) || !decodeCodecs[codecTable.at(i).codecFrom] ) )
                decodeCodecs[codecTable.at(i).codecFrom] = codecTable.at(i).enabled;
        }
        codecsString += i18n("Supported codecs:");
        QStringList list;
        for( int i=0; i<encodeCodecs.count(); i++ )
        {
            const QString codecName = encodeCodecs.keys().at(i);
            problemInfos["encode-"+codecName] = i18n("Currently deactivated.") + "\n\n" + config->pluginLoader()->pluginEncodeProblems( pluginName, codecName );
            list += encodeCodecs.values().at(i) ? "<span style=\"color:green\">" + codecName + "</span>" : "<a style=\"color:red\" href=\"encode-"+codecName+"\">" + codecName + "</a>";
        }
        codecsString += i18n("Encode: %1",list.join(", "));
        list.clear();
        for( int i=0; i<decodeCodecs.count(); i++ )
        {
            const QString codecName = decodeCodecs.keys().at(i);
            problemInfos["decode-"+codecName] = i18n("Currently deactivated.") + "\n\n" + config->pluginLoader()->pluginDecodeProblems( pluginName, codecName );
            list += decodeCodecs.values().at(i) ? "<span style=\"color:green\">" + codecName + "</span>" : "<a style=\"color:red\" href=\"decode-"+codecName+"\">" + codecName + "</a>";
        }
        codecsString += i18n("Decode: %1",list.join(", "));
        info += codecsString.join("<br>");
    }
    else if( currentPlugin->type() == "filter" )
    {
        CodecPlugin *codecPlugin = (CodecPlugin*)currentPlugin;

        QStringList codecsString;
        QMap<QString,bool> encodeCodecs;
        QMap<QString,bool> decodeCodecs;
        QList<ConversionPipeTrunk> codecTable = codecPlugin->codecTable();
        for( int i=0; i<codecTable.count(); i++ )
        {
            if( codecTable.at(i).codecTo != "wav" && ( !encodeCodecs.contains(codecTable.at(i).codecTo) || !encodeCodecs[codecTable.at(i).codecTo] ) )
                encodeCodecs[codecTable.at(i).codecTo] = codecTable.at(i).enabled;

            if( codecTable.at(i).codecFrom != "wav" && ( !decodeCodecs.contains(codecTable.at(i).codecFrom) || !decodeCodecs[codecTable.at(i).codecFrom] ) )
                decodeCodecs[codecTable.at(i).codecFrom] = codecTable.at(i).enabled;
        }
        codecsString += i18n("Supported codecs:");
        QStringList list;
        for( int i=0; i<encodeCodecs.count(); i++ )
        {
            const QString codecName = encodeCodecs.keys().at(i);
            problemInfos["encode-"+codecName] = i18n("Currently deactivated.") + "\n\n" + config->pluginLoader()->pluginEncodeProblems( pluginName, codecName );
            list += encodeCodecs.values().at(i) ? "<span style=\"color:green\">" + codecName + "</span>" : "<a style=\"color:red\" href=\"encode-"+codecName+"\">" + codecName + "</a>";
        }
        codecsString += i18n("Encode: %1",list.join(", "));
        list.clear();
        for( int i=0; i<decodeCodecs.count(); i++ )
        {
            const QString codecName = decodeCodecs.keys().at(i);
            problemInfos["decode-"+codecName] = i18n("Currently deactivated.") + "\n\n" + config->pluginLoader()->pluginDecodeProblems( pluginName, codecName );
            list += decodeCodecs.values().at(i) ? "<span style=\"color:green\">" + codecName + "</span>" : "<a style=\"color:red\" href=\"decode-"+codecName+"\">" + codecName + "</a>";
        }
        codecsString += i18n("Decode: %1",list.join(", "));
        info += codecsString.join("<br>");
    }
    else if( currentPlugin->type() == "replaygain" )
    {
        ReplayGainPlugin *replaygainPlugin = (ReplayGainPlugin*)currentPlugin;

        QStringList codecs;
        QList<ReplayGainPipe> codecTable = replaygainPlugin->codecTable();
        for( int i=0; i<codecTable.count(); i++ )
        {
            const QString codecName = codecTable.at(i).codecName;
            problemInfos["replaygain-"+codecName] = i18n("Currently deactivated.") + "\n\n" + config->pluginLoader()->pluginReplayGainProblems( pluginName, codecName );
            codecs += codecTable.at(i).enabled ? "<span style=\"color:green\">" + codecName + "</span>" : "<a style=\"color:red\" href=\"replaygain-"+codecName+"\">" + codecName + "</a>";
        }
        info += QString( i18n("Supported codecs:") + "<br>" + codecs.join(", ") );
    }
    else if( currentPlugin->type() == "ripper" )
    {
    }

    aboutPluginLabel->setText( info.join("<br><br>") );

    if( currentPlugin->isConfigSupported(BackendPlugin::General,"") )
    {
        configurePlugin->setText( i18n("Configure %1 ...",currentPlugin->name()) );
        configurePlugin->show();
    }
    else
    {
        configurePlugin->hide();
    }
}
Esempio n. 26
0
File: main.cpp Progetto: dtbinh/vmt
int main(/*int argc, char *argv[]*/)
{
    const QString suffix = QString("_b%1_d%2").arg(BEST_N).arg(DILATION);
    const QDir testFolder("/home/emredog/LIRIS-data/test/");
    const QDir bboxMainFolder("/home/emredog/Documents/ADSC_NUS_Harl_result_code_v2/HumanDetectionResults/");

    QStringList filters;

    //get video folders:
    //QStringList vidFolders = testFolder.entryList(filters, QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
    QStringList bboxFolders = bboxMainFolder.entryList(filters, QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);

    filters.clear();
    filters << "*.txt";
    //for each video
    for (int i=0; i<bboxFolders.length(); i++)
    {
        QFile trackFile(testFolder.absoluteFilePath(bboxFolders[i].left(7).append(suffix).append(".track")));
        if (!trackFile.open(QIODevice::Truncate | QIODevice::WriteOnly))
                continue;

        QTextStream out(&trackFile);
        //write frame number

        //QDir vidFolder(testFolder.absoluteFilePath(vidFolders[i]));
        QDir bboxFolder(bboxMainFolder.absoluteFilePath(bboxFolders[i]));

        QStringList bboxFilesForAVideo = bboxFolder.entryList(filters, QDir::Files, QDir::Name);

        for (int frameNr=0; frameNr<bboxFilesForAVideo.length(); frameNr++)
        {
            QList<Rect> bestBBoxes = getBestBoundingBox(bboxFolder.absoluteFilePath(bboxFilesForAVideo[frameNr]), 3);

            if (bestBBoxes.isEmpty())
            {
                continue;
            }
            else if (bestBBoxes.length() == 1) //only one rectangle, dilate it:
            {
                if (bestBBoxes[0].width > 0) //valid rectangle?
                {
                    Rect dilated = dilateRectangle(bestBBoxes[0], DILATION);
                    out << frameNr+1 << " "
                        << dilated.x << " "
                        << dilated.y << " "
                        << dilated.width << " "
                        << dilated.height << "\n";
                }
            }
            else //more than one rectangles, create a new rectangle that contains all bounding boxes
            {
                int topLeftMinX = INT_MAX, topLeftMinY = INT_MAX, botRightMaxX = INT_MIN, botRightMaxy = INT_MIN;
                //get topmost-leftmost point and bottommost-rightmost point of all available bounding boxes
                foreach(Rect rect, bestBBoxes)
                {
                    if (rect.tl().x < topLeftMinX) topLeftMinX = rect.tl().x;
                    if (rect.tl().y < topLeftMinY) topLeftMinY = rect.tl().y;
                    if (rect.br().x > botRightMaxX) botRightMaxX = rect.br().x;
                    if (rect.br().x > botRightMaxy) botRightMaxy = rect.br().y;
                }

                Rect containerRect(Point(topLeftMinX, topLeftMinY), Point(botRightMaxX, botRightMaxy));
                Rect dilated = dilateRectangle(containerRect, DILATION);
                out << frameNr+1 << " "
                    << containerRect.x << " "
                    << containerRect.y << " "
                    << containerRect.width << " "
                    << containerRect.height << "\n";
            }
        }

        out.flush();
        trackFile.close();
    }
}
bool QgsCoordinateTransformContext::readXml( const QDomElement &element, const QgsReadWriteContext &, QStringList &missingTransforms )
{
  d.detach();
  d->mLock.lockForWrite();

  d->mSourceDestDatumTransforms.clear();
#if 0
  d->mSourceDatumTransforms.clear();
  d->mDestDatumTransforms.clear();
#endif

  const QDomNodeList contextNodes = element.elementsByTagName( QStringLiteral( "transformContext" ) );
  if ( contextNodes.count() < 1 )
  {
    d->mLock.unlock();
    return true;
  }

  missingTransforms.clear();
  bool result = true;

  const QDomElement contextElem = contextNodes.at( 0 ).toElement();

  // src/dest transforms
  const QDomNodeList srcDestNodes = contextElem.elementsByTagName( QStringLiteral( "srcDest" ) );
  for ( int i = 0; i < srcDestNodes.size(); ++i )
  {
    const QDomElement transformElem = srcDestNodes.at( i ).toElement();
    QString key1 = transformElem.attribute( QStringLiteral( "source" ) );
    QString key2 = transformElem.attribute( QStringLiteral( "dest" ) );

    QString value1 = transformElem.attribute( QStringLiteral( "sourceTransform" ) );
    QString value2 = transformElem.attribute( QStringLiteral( "destTransform" ) );

    Q_NOWARN_DEPRECATED_PUSH
    int datumId1 = -1;
    int datumId2 = -1;
    //warn if value1 or value2 is non-empty, yet no matching transform was found
    if ( !value1.isEmpty() )
    {
      datumId1 = QgsDatumTransform::projStringToDatumTransformId( value1 );
      if ( datumId1 < 0 )
      {
        result = false;
        missingTransforms << value1;
      }
    }
    if ( !value2.isEmpty() )
    {
      datumId2 = QgsDatumTransform::projStringToDatumTransformId( value2 );
      if ( datumId2 < 0 )
      {
        result = false;
        missingTransforms << value2;
      }
    }
    Q_NOWARN_DEPRECATED_POP

    d->mSourceDestDatumTransforms.insert( qMakePair( key1, key2 ), QgsDatumTransform::TransformPair( datumId1, datumId2 ) );
  }

#if 0
  // src transforms
  const QDomNodeList srcNodes = contextElem.elementsByTagName( QStringLiteral( "source" ) );
  for ( int i = 0; i < srcNodes .size(); ++i )
  {
    const QDomElement transformElem = srcNodes.at( i ).toElement();
    QString key = transformElem.attribute( QStringLiteral( "crs" ) );
    QString value = transformElem.attribute( QStringLiteral( "transform" ) );
    if ( value.isEmpty() )
      continue;

    int datumId = QgsCoordinateTransform::projStringToDatumTransformId( value );
    //TODO - throw warning if datumId is -1
    d->mSourceDatumTransforms.insert( key, datumId );
  }

  // dest transforms
  const QDomNodeList destNodes = contextElem.elementsByTagName( QStringLiteral( "dest" ) );
  for ( int i = 0; i < destNodes.size(); ++i )
  {
    const QDomElement transformElem = destNodes.at( i ).toElement();
    QString key = transformElem.attribute( QStringLiteral( "crs" ) );
    QString value = transformElem.attribute( QStringLiteral( "transform" ) );
    if ( value.isEmpty() )
      continue;

    int datumId = QgsCoordinateTransform::projStringToDatumTransformId( value );
    //TODO - throw warning if datumId is -1
    d->mDestDatumTransforms.insert( key, datumId );
  }
#endif

  d->mLock.unlock();
  return result;
}
Esempio n. 28
0
/**
 * Add entries to a variable. Will just add the variables to the existing line, removing duplicates
 * Will preserve += constructs and make sure that the variable only has one copy of the value across
 * all += constructs
 * @param fileName
 * @param variables key=value string of entries to add
 * @param add true= add these key,value pairs, false = remove. You can have empty values for an add - the whole line is
 * removed. For adding, we will not add an empty line.
 */
void AutoProjectTool::addRemoveMakefileam(const QString &fileName, QMap<QString, QString> variables,  bool add)
{
	// input file reading
	QFile fin(fileName);
	if (!fin.open(IO_ReadOnly))
	{
		return ;
	}
	QTextStream ins(&fin);

	// output file writing.
	QFile fout(fileName + "#");
	if (!fout.open(IO_WriteOnly))
	{
		fin.close();
		return ;
	}
	QTextStream outs(&fout);

	// variables
	QRegExp re("^(#kdevelop:[ \t]*)?([A-Za-z][@A-Za-z0-9_]*)[ \t]*([:\\+]?=)[ \t]*(.*)$");

	// build key=map of values to add
	// map can be empty.we never add an empty key, but do remove empty keys from the file..
	QDict< QMap<QString, bool> > interest;
	for (QMap<QString, QString>::Iterator it0 = variables.begin(); it0 != variables.end(); ++it0)
	{
		kdDebug(9020) << "key (" << add<<"): " << it0.key() << "="<< it0.data() << endl;

		QMap<QString, bool>* set = new QMap<QString, bool>();
		if (!it0.data().stripWhiteSpace().isEmpty())
		{
			QStringList variableList = QStringList::split(' ', it0.data());

			for (uint i = 0; i < variableList.count(); i++)
			{
				set->insert(variableList[i], true);
			}
		}
		interest.insert(it0.key(), set);
	}

	bool multiLine = false;
	QString lastLhs;
	QStringList lastRhs;
	QMap<QString, QString> seenLhs;
	while (!fin.atEnd())
	{
		QString s = ins.readLine();
		if (re.exactMatch(s))
		{
			QString lhs = re.cap(2);
			QMap<QString, bool>* ourRhs = interest.find(lhs);

			if (!ourRhs)
			{
				// not interested in this line at all
				// write it out as is..
				outs << s << endl;
			}
			else
			{
				// we are interested in this line..
				QString rhs = re.cap(4).stripWhiteSpace();
				if (rhs[ rhs.length() - 1 ] == '\\')
				{
					// save it for when we have the whole line..
					multiLine = true;
					lastLhs = lhs;
					rhs.setLength(rhs.length() - 1);
					lastRhs += QStringList::split(" ", rhs);
				}
				else
				{
					// deal with it now.

					QStringList bits = QStringList::split(" ", rhs);
					if (add)
					{
						// we are adding our interested values to this line and writing it

						// add this line to we we want to add to remove duplicates.
						for (uint index = 0; index < bits.size(); index++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(bits[index]);
							if (findEntry == ourRhs->end())
							{
								// we haven't seen it, so add it, so we don't add it again later..
								ourRhs->insert(bits[index], true);
							}
							// else we have this value in our 'to add list' , it is either already been
							// added, so we don't want to add it again, or it hasn't been added, in which
							// case we will do so soon. so we can ignore this now..
						}
						// now write the line out if it is not going to be empty.
						QString newLine(lhs);
						if (seenLhs.find(lhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lhs] = "";
						}
						else
						{
							newLine += " += ";
						}

						int len = newLine.length();
						bool added = false;
						QValueList<QString> keys = ourRhs->keys();
						for (uint count = 0; count < keys.size(); count++)
						{
							// if out entry is true, add it..
							if ((*ourRhs)[keys[count]])
							{
								added = true;
								len += keys[count].length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += keys[count];
								newLine += ' ';
								// set our value so we don't add it again.
								(*ourRhs)[keys[count]] = false;
							}
						}
						// only print it out if there was a value to add..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
					else
					{
						// we are removing our interested values from this line

						// special case - no values, remove the line..
						if (!ourRhs->empty())
						{
							// check if any of these values are down to remove.
							QString newLine(lhs);
							if (seenLhs.find(lhs) == seenLhs.end())
							{
								newLine += " = ";
								seenLhs[lhs] = "";
							}
							else
							{
								newLine += " += ";
							}

							int len = newLine.length();
							bool added = false;
							for (QStringList::Iterator posIter = bits.begin(); posIter != bits.end();posIter++)
							{
								QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
								if (findEntry == ourRhs->end())
								{
									// we do not want to remove it..
									added = true;
									len += (*posIter).length() + 1;
									if (len > 80)
									{
										newLine += "\\\n\t";
										len = 8;
									}
									newLine += (*posIter);
									newLine += ' ';
								}
								// else we have this value in our 'to remove list', so don't add it.
							}
							// only print it out if there was a value on it..
							if (added)
							{
								newLine.setLength(newLine.length() - 1);
								outs << newLine << endl;
							}
						}
					}//if (add)
				}//if ( rhs[ rhs.length() - 1 ] == '\\'  )
			}//if ( found == interest.end())
		}
		else if (multiLine)
		{
			s = s.stripWhiteSpace();
			// we are only here if were interested in this line..
			if (s[s.length()-1] == '\\')
			{
				s.setLength(s.length() - 1);
				// still more multi line we wait for..
			}
			else
			{
				// end of the multi line..
				multiLine = false;
			}
			lastRhs += QStringList::split(" ", s);

			if (!multiLine)
			{
				// now we have to deal with this multiLine value..
				// ourRhs will always be a value, as we only get multiLine if we're interested in it..
				QMap<QString, bool>* ourRhs = interest.find(lastLhs);

				if (add)
				{
					// we are adding our interested values to this line and writing it

					// add this line to we we want to add to remove duplicates.
					for (uint index = 0; index < lastRhs.size(); index++)
					{
						QMap<QString, bool>::iterator findEntry = ourRhs->find(lastRhs[index]);
						if (findEntry == ourRhs->end())
						{
							// we haven't seen it, so add it, so we don't add it again later..
							ourRhs->insert(lastRhs[index], true);
						}
						// else we have this value in our 'to add list' , it is either already been
						// added, so we don't want to add it again, or it hasn't been added, in which
						// case we will do so soon. so we can ignore this now..
					}
					// now write the line out if it is not going to be empty.
					QString newLine(lastLhs);
					if (seenLhs.find(lastLhs) == seenLhs.end())
					{
						newLine += " = ";
						seenLhs[lastLhs] = "";
					}
					else
					{
						newLine += " += ";
					}

					int len = newLine.length();
					bool added = false;
					QValueList<QString> keys = ourRhs->keys();
					for (uint count = 0; count < keys.size(); count++)
					{
						// if out entry is true, add it..
						if ((*ourRhs)[keys[count]])
						{
							added = true;
							len += keys[count].length() + 1;
							if (len > 80)
							{
								newLine += "\\\n\t";
								len = 8;
							}
							newLine += keys[count];
							newLine += ' ';
							// set our value so we don't add it again.
							(*ourRhs)[keys[count]] = false;
						}
					}
					// only print it out if there was a value to add..
					if (added)
					{
						newLine.setLength(newLine.length() - 1);
						outs << newLine << endl;
					}
				}
				else
				{
					// we are removing our interested values from this line
					// special case - no values, remove the line..
					if (!ourRhs->empty())
					{
						// check if any of these values are down to remove.
						QString newLine(lastLhs);
						if (seenLhs.find(lastLhs) == seenLhs.end())
						{
							newLine += " = ";
							seenLhs[lastLhs] = "";
						}
						else
						{
							newLine += " += ";
						}
						int len = newLine.length();
						bool added = false;
						for (QStringList::Iterator posIter = lastRhs.begin(); posIter != lastRhs.end();posIter++)
						{
							QMap<QString, bool>::iterator findEntry = ourRhs->find(*posIter);
							if (findEntry == ourRhs->end())
							{
								// we do not want to remove it..
								added = true;
								len += (*posIter).length() + 1;
								if (len > 80)
								{
									newLine += "\\\n\t";
									len = 8;
								}
								newLine += (*posIter);
								newLine += ' ';
							}
							// else we have this value in our 'to remove list', so don't add it.
						}
						// only print it out if there was a value on it..
						if (added)
						{
							newLine.setLength(newLine.length() - 1);
							outs << newLine << endl;
						}
					}
				}

				lastLhs.setLength(0);
				lastRhs.clear();
			}
		}
		else
		{
			// can write this line out..
			// not a match, not a multi line,
			outs << s << endl;
		}
	}

	if (add)
	{
		QDictIterator<QMap<QString, bool> > it(interest);
		for (; it.current(); ++it)
		{
			QString lhs = it.currentKey();
			QMap<QString, bool>* ourRhs = it.current();

			QString newLine(lhs);
			if (seenLhs.find(lhs) == seenLhs.end())
			{
				newLine += " = ";
				seenLhs[lastLhs] = "";
			}
			else
			{
				newLine += " += ";
			}
			int len = newLine.length();
			bool added = false;
			QValueList<QString> keys = ourRhs->keys();
			for (uint count = 0; count < keys.size(); count++)
			{
				if ((*ourRhs)[keys[count]])
				{
					added = true;
					len += keys[count].length() + 1;
					if (len > 80)
					{
						newLine += "\\\n\t";
						len = 8;
					}
					newLine += keys[count];
					newLine += ' ';
					// set our value so we don't add it again.
					(*ourRhs)[keys[count]] = false;
				}
			}
			// only print it out if there was a value to add..
			if (added)
			{
				newLine.setLength(newLine.length() - 1);
				outs << newLine << endl;
			}
		}
	}
	interest.setAutoDelete(true);
	interest.clear();

	fin.close();
	fout.close();

	QDir().rename(fileName + "#", fileName);
}
Esempio n. 29
0
static void parseClass(const QString& name, const QString& in)
      {
      Class cl;
      cl.name = name;

      QStringList sl = in.split("\n");
      QStringList methodDescription;

      QRegExp re("@P ([^\\s]+)\\s+([^\\s]+)(.*)");

      // matches Q_INVOKABLE void mops(int a);   // comment
      QRegExp re1("Q_INVOKABLE +([^ ]+) +([^;]+); */*(.*)");
      QRegExp re2("Q_INVOKABLE +([^ ]+) +([^\\{]+)\\{");
      QRegExp re3("Q_INVOKABLE +([^ ]+) +(\\w+\\([^\\)]*\\))\\s+const\\s*([^\\{]*)\\{");

      QRegExp reD("//@ (.*)");
      QRegExp re4 ("class +(\\w+) *: *public +(\\w+) *\\{");
      QRegExp re4b("class +(\\w+) *: *public +(\\w+), *public");

      Q_ASSERT(re1.isValid() && re2.isValid() && re3.isValid());

      bool parseClassDescription = true;

      foreach(const QString& s, sl) {
            if (re.indexIn(s, 0) != -1) {             //@P
                  parseClassDescription = false;
                  Prop p;
                  p.name        = re.cap(1);
                  p.type        = re.cap(2);
                  p.description = re.cap(3);
                  cl.props.append(p);
                  }
            else if (re2.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re2.cap(1);
                  p.name        = re2.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if (re1.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re1.cap(1);
                  p.name        = re1.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if (re3.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  Proc p;
                  p.type        = re3.cap(1);
                  p.name        = re3.cap(2);
                  p.description = methodDescription;
                  methodDescription.clear();
                  cl.procs.append(p);
                  }
            else if ((reD.indexIn(s, 0) != -1)) {
                  if (parseClassDescription)
                        cl.description.append(reD.cap(1));
                  else
                        methodDescription.append(reD.cap(1));
                  }
            else if (s.startsWith("///")) {
                  QString ss = s.mid(3);
                  if (parseClassDescription)
                        cl.description.append(ss);
                  else
                        methodDescription.append(ss);
                  }
            else if (re4.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  QString parent = re4.cap(2).simplified();
                  if (name == re4.cap(1).simplified()) {
                        cl.parent = parent;
                        }
                  else {
                        printf("?<%s>!=<%s> derived from <%s>\n",
                           qPrintable(name), qPrintable(re4.cap(1).simplified()), qPrintable(parent));
                        }
                  }
            else if (re4b.indexIn(s, 0) != -1) {
                  parseClassDescription = false;
                  QString parent = re4b.cap(2).simplified();
                  if (name == re4b.cap(1).simplified()) {
                        cl.parent = parent;
                        }
                  else {
                        printf("?<%s>!=<%s> derived from <%s>\n",
                           qPrintable(name), qPrintable(re4b.cap(1).simplified()), qPrintable(parent));
                        }
                  }
            }
      classes.append(cl);
      }
Esempio n. 30
0
MythSocket *RemoteFile::openSocket(bool control)
{
    QUrl qurl(path);
    QString dir;

    QString host = qurl.host();
    int port = qurl.port();

    dir = qurl.path();

    if (qurl.hasQuery())
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
        dir += "?" + QUrl::fromPercentEncoding(
                   qurl.query(QUrl::FullyEncoded).toLocal8Bit());
#else
        dir += "?" + QUrl::fromPercentEncoding(qurl.encodedQuery());
#endif

    if (qurl.hasFragment())
        dir += "#" + qurl.fragment();

    QString sgroup = qurl.userName();

    MythSocket *lsock = new MythSocket();
    QString stype = (control) ? "control socket" : "file data socket";

    QString loc = QString("RemoteFile::openSocket(%1): ").arg(stype);

    if (port <= 0)
    {
        port = GetMythDB()->GetSettingOnHost("BackendServerPort", host).toInt();

        // if we still have no port use the default
        if (port <= 0)
            port = 6543;
    }

    if (!lsock->ConnectToHost(host, port))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Could not connect to server %1:%2") .arg(host).arg(port));
        lsock->DecrRef();
        return NULL;
    }

    QString hostname = GetMythDB()->GetHostName();

    QStringList strlist;

#ifndef IGNORE_PROTO_VER_MISMATCH
    if (!gCoreContext->CheckProtoVersion(lsock))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Failed validation to server %1:%2").arg(host).arg(port));
        lsock->DecrRef();
        return NULL;
    }
#endif

    if (control)
    {
        strlist.append(QString("ANN Playback %1 %2").arg(hostname).arg(false));
        if (!lsock->SendReceiveStringList(strlist))
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Could not read string list from server %1:%2")
                .arg(host).arg(port));
            lsock->DecrRef();
            return NULL;
        }
    }
    else
    {
        strlist.push_back(QString("ANN FileTransfer %1 %2 %3 %4")
                          .arg(hostname).arg(writemode)
                          .arg(usereadahead).arg(timeout_ms));
        strlist << QString("%1").arg(dir);
        strlist << sgroup;

        QStringList::const_iterator it = possibleauxfiles.begin();
        for (; it != possibleauxfiles.end(); ++it)
            strlist << *it;

        if (!lsock->SendReceiveStringList(strlist))
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Did not get proper response from %1:%2")
                .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }

        if (strlist.size() >= 3)
        {
            it = strlist.begin();
            ++it;
            recordernum = (*it).toInt();
            ++it;
            filesize = (*(it)).toLongLong();
            ++it;
            for (; it != strlist.end(); ++it)
                auxfiles << *it;
        }
        else if (0 < strlist.size() && strlist.size() < 3 &&
                 strlist[0] != "ERROR")
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Did not get proper response from %1:%2")
                .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }
    }

    if (strlist.empty() || strlist[0] == "ERROR")
    {
        lsock->DecrRef();
        lsock = NULL;
        if (strlist.empty())
        {
            LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket, timeout");
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket" +
                ((strlist.size() >= 2) ?
                 QString(", error was %1").arg(strlist[1]) :
                 QString(", remote error")));
        }
    }

    return lsock;
}