Example #1
0
  ControlNet * CnetEditorWidget::filteredNetwork() const {
    ControlNet * filteredCnet = new ControlNet(*m_controlNet);

    QList<AbstractTreeItem *> networkItems = m_pointModel->getItems(0, -1,
        AbstractTreeModel::MeasureItems | AbstractTreeModel::PointItems, true);

    // Iterate through our copy of the cnet, deleting anything that doesn't
    //   exactly match our networkItems.
    for (int pointIndex = filteredCnet->GetNumPoints() - 1;
         pointIndex >= 0;
         pointIndex--) {
      if (networkItems.isEmpty()) {
        ControlPoint *cp = filteredCnet->GetPoint(pointIndex);
        cp->SetEditLock(false);

        for (int measureIndex = 0;
             measureIndex < cp->GetNumMeasures();
             measureIndex++) {
          cp->GetMeasure(measureIndex)->SetEditLock(false);
        }

        filteredCnet->DeletePoint(cp);
      }
      else if (networkItems.last()->getPointerType() ==
               AbstractTreeItem::Point) {
        ControlPoint *networkItemsCp =
            (ControlPoint *)networkItems.last()->getPointer();
        ControlPoint *cp = filteredCnet->GetPoint(pointIndex);
        if (cp->GetId() != networkItemsCp->GetId()) {
          cp->SetEditLock(false);

          for (int measureIndex = 0;
               measureIndex < cp->GetNumMeasures();
               measureIndex++) {
            cp->GetMeasure(measureIndex)->SetEditLock(false);
          }

          filteredCnet->DeletePoint(cp);
        }
        else {
          networkItems.removeLast();
        }
      }
      else if (networkItems.last()->getPointerType() ==
               AbstractTreeItem::Measure) {
        ControlPoint *cp = filteredCnet->GetPoint(pointIndex);
        ControlMeasure *networkItemsCm =
            (ControlMeasure *)networkItems.last()->getPointer();

        if (cp->GetId() != networkItemsCm->Parent()->GetId()) {
          cp->SetEditLock(false);

          for (int measureIndex = 0;
               measureIndex < cp->GetNumMeasures();
               measureIndex++) {
            cp->GetMeasure(measureIndex)->SetEditLock(false);
          }

          filteredCnet->DeletePoint(cp);
        }
        else {
          // Our CP stays, figure out which CMs stay.
          for (int measureIndex = cp->GetNumMeasures() - 1;
               networkItemsCm && measureIndex >= 0;
               measureIndex--) {
            ControlMeasure *cm = cp->GetMeasure(measureIndex);
            if (cm->GetCubeSerialNumber() !=
                networkItemsCm->GetCubeSerialNumber()) {
              cm->SetEditLock(false);
              cp->Delete(cm);
            }
            else {
              networkItems.removeLast();
              networkItemsCm = NULL;

              if (networkItems.last()->getPointerType() ==
                       AbstractTreeItem::Measure) {
                networkItemsCm =
                    (ControlMeasure *)networkItems.last()->getPointer();
              }
            }
          }

          // We still need to verify the copied CP at this index... although
          //   nothing should go wrong, we know things do go wrong so do
          //   the verify instead of just tossing the last networkItems item.
          pointIndex++;
        }
      }
    }

    return filteredCnet;
  }
Example #2
0
void RadialMap::Widget::dragEnterEvent(QDragEnterEvent *e)
{
    QList<QUrl> uriList = KUrlMimeData::urlsFromMimeData(e->mimeData());
    e->setAccepted(!uriList.isEmpty());
}
Example #3
0
void QgsGml::endElement( const XML_Char* el )
{
    QString elementName( QString::fromUtf8( el ) );
    ParseMode theParseMode( mParseModeStack.isEmpty() ? none : mParseModeStack.top() );
    QStringList splitName =  elementName.split( NS_SEPARATOR );
    QString localName = splitName.last();
    QString ns = splitName.size() > 1 ? splitName.first() : "";

    if (( theParseMode == coordinate && elementName == GML_NAMESPACE + NS_SEPARATOR + "coordinates" )
            || ( theParseMode == posList && (
                     elementName == GML_NAMESPACE + NS_SEPARATOR + "pos"
                     || elementName == GML_NAMESPACE + NS_SEPARATOR + "posList" ) ) )
    {
        mParseModeStack.pop();
    }
    else if ( theParseMode == attribute && localName == mAttributeName ) //add a thematic attribute to the feature
    {
        mParseModeStack.pop();

        setAttribute( mAttributeName, mStringCash );
    }
    else if ( theParseMode == geometry && localName == mGeometryAttribute )
    {
        mParseModeStack.pop();
    }
    else if ( theParseMode == boundingBox && elementName == GML_NAMESPACE + NS_SEPARATOR + "boundedBy" )
    {
        //create bounding box from mStringCash
        if ( createBBoxFromCoordinateString( mCurrentExtent, mStringCash ) != 0 )
        {
            QgsDebugMsg( "creation of bounding box failed" );
        }

        mParseModeStack.pop();
    }
    else if ( theParseMode == feature && localName == mTypeName )
    {
        Q_ASSERT( mCurrentFeature );
        if ( mCurrentWKBSize > 0 )
        {
            QgsGeometry *g = new QgsGeometry();
            g->fromWkb( mCurrentWKB, mCurrentWKBSize );
            mCurrentFeature->setGeometry( g );
            mCurrentWKB = QgsWkbPtr( nullptr, 0 );
        }
        else if ( !mCurrentExtent.isEmpty() )
        {
            mCurrentFeature->setGeometry( QgsGeometry::fromRect( mCurrentExtent ) );
        }
        else
        {
            mCurrentFeature->setGeometry( nullptr );
        }
        mCurrentFeature->setValid( true );

        mFeatures.insert( mCurrentFeature->id(), mCurrentFeature );
        if ( !mCurrentFeatureId.isEmpty() )
        {
            mIdMap.insert( mCurrentFeature->id(), mCurrentFeatureId );
        }
        mCurrentFeature = nullptr;
        ++mFeatureCount;
        mParseModeStack.pop();
    }
    else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "Point" )
    {
        QList<QgsPoint> pointList;
        if ( pointsFromString( pointList, mStringCash ) != 0 )
        {
            //error
        }

        if ( pointList.isEmpty() )
            return;  // error

        if ( theParseMode == QgsGml::geometry )
        {
            //directly add WKB point to the feature
            if ( getPointWKB( mCurrentWKB, *( pointList.constBegin() ) ) != 0 )
            {
                //error
            }

            if ( *mWkbType != QGis::WKBMultiPoint ) //keep multitype in case of geometry type mix
            {
                *mWkbType = QGis::WKBPoint;
            }
        }
        else //multipoint, add WKB as fragment
        {
            QgsWkbPtr wkbPtr( nullptr, 0 );
            if ( getPointWKB( wkbPtr, *( pointList.constBegin() ) ) != 0 )
            {
                //error
            }
            if ( !mCurrentWKBFragments.isEmpty() )
            {
                mCurrentWKBFragments.last().push_back( wkbPtr );
            }
            else
            {
                QgsDebugMsg( "No wkb fragments" );
                delete [] wkbPtr;
            }
        }
    }
    else if ( elementName == GML_NAMESPACE + NS_SEPARATOR + "LineString" )
    {
        //add WKB point to the feature

        QList<QgsPoint> pointList;
        if ( pointsFromString( pointList, mStringCash ) != 0 )
        {
            //error
        }
        if ( theParseMode == QgsGml::geometry )
        {
            if ( getLineWKB( mCurrentWKB, pointList ) != 0 )
            {
                //error
            }

            if ( *mWkbType != QGis::WKBMultiLineString )//keep multitype in case of geometry type mix
            {
                *mWkbType = QGis::WKBLineString;
            }
        }
        else //multiline, add WKB as fragment
        {
            QgsWkbPtr wkbPtr( nullptr, 0 );
            if ( getLineWKB( wkbPtr, pointList ) != 0 )
            {
                //error
            }
            if ( !mCurrentWKBFragments.isEmpty() )
            {
                mCurrentWKBFragments.last().push_back( wkbPtr );
            }
            else
            {
                QgsDebugMsg( "no wkb fragments" );
                delete [] wkbPtr;
            }
        }
    }
    else if (( theParseMode == geometry || theParseMode == multiPolygon ) && elementName == GML_NAMESPACE + NS_SEPARATOR + "LinearRing" )
    {
        QList<QgsPoint> pointList;
        if ( pointsFromString( pointList, mStringCash ) != 0 )
        {
            //error
        }

        QgsWkbPtr wkbPtr( nullptr, 0 );
        if ( getRingWKB( wkbPtr, pointList ) != 0 )
        {
            //error
        }

        if ( !mCurrentWKBFragments.isEmpty() )
        {
            mCurrentWKBFragments.last().push_back( wkbPtr );
        }
        else
        {
            delete[] wkbPtr;
            QgsDebugMsg( "no wkb fragments" );
        }
    }
    else if (( theParseMode == geometry || theParseMode == multiPolygon ) && elementName == GML_NAMESPACE + NS_SEPARATOR + "Polygon" )
    {
        if ( *mWkbType != QGis::WKBMultiPolygon )//keep multitype in case of geometry type mix
        {
            *mWkbType = QGis::WKBPolygon;
        }

        if ( theParseMode == geometry )
        {
            createPolygonFromFragments();
        }
    }
    else if ( theParseMode == multiPoint && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPoint" )
    {
        *mWkbType = QGis::WKBMultiPoint;
        mParseModeStack.pop();
        createMultiPointFromFragments();
    }
    else if ( theParseMode == multiLine && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiLineString" )
    {
        *mWkbType = QGis::WKBMultiLineString;
        mParseModeStack.pop();
        createMultiLineFromFragments();
    }
    else if ( theParseMode == multiPolygon && elementName == GML_NAMESPACE + NS_SEPARATOR + "MultiPolygon" )
    {
        *mWkbType = QGis::WKBMultiPolygon;
        mParseModeStack.pop();
        createMultiPolygonFromFragments();
    }
}
Example #4
0
void tags::Tags::initGenres()
{
    if (genreList.isEmpty())
    {
        // the official weird, unsorted, incomplete list of genres for ID3 tags
        genreList << "Blues"
                  << "Classic Rock"
                  << "Country"
                  << "Dance"
                  << "Disco"
                  << "Funk"
                  << "Grunge"
                  << "Hip-Hop"
                  << "Jazz"
                  << "Metal"
                  << "New Age"
                  << "Oldies"
                  << "Other"
                  << "Pop"
                  << "R&B"
                  << "Rap"
                  << "Reggae"
                  << "Rock"
                  << "Techno"
                  << "Industrial"

                  << "Alternative"
                  << "Ska"
                  << "Death Metal"
                  << "Pranks"
                  << "Soundtrack"
                  << "Euro-Techno"
                  << "Ambient"
                  << "Trip-Hop"
                  << "Vocal"
                  << "Jazz + Funk"
                  << "Fusion"
                  << "Trance"
                  << "Classical"
                  << "Instrumental"
                  << "Acid"
                  << "House"
                  << "Game"
                  << "Sound Clip"
                  << "Gospel"
                  << "Noise"

                  << "Alt Rock"
                  << "Bass"
                  << "Soul"
                  << "Punk"
                  << "Space"
                  << "Meditative"
                  << "Instrumental Pop"
                  << "Instrumental Rock"
                  << "Ethnic"
                  << "Gothic"
                  << "Darkwave"
                  << "Techno-Industrial"
                  << "Electronic"
                  << "Pop-Folk"
                  << "Eurodance"
                  << "Dream"
                  << "Southern Rock"
                  << "Comedy"
                  << "Cult"
                  << "Gangsta Rap"

                  << "Top 40"
                  << "Christian Rap"
                  << "Pop / Funk"
                  << "Jungle"
                  << "Native American"
                  << "Cabaret"
                  << "New Wave"
                  << "Psychedelic"
                  << "Rave"
                  << "Showtunes"
                  << "Trailer"
                  << "Lo-Fi"
                  << "Tribal"
                  << "Acid Punk"
                  << "Acid Jazz"
                  << "Polka"
                  << "Retro"
                  << "Musical"
                  << "Rock'n Roll"
                  << "Hard Rock"

                  << "Folk"
                  << "Folk / Rock"
                  << "National Folk"
                  << "Swing"
                  << "Fast-Fusion"
                  << "Bebop"
                  << "Latin"
                  << "Revival"
                  << "Celtic"
                  << "Bluegrass"
                  << "Avantgarde"
                  << "Gothic Rock"
                  << "Progressive Rock"
                  << "Psychedelic Rock"
                  << "Symphonic Rock"
                  << "Slow Rock"
                  << "Big Band"
                  << "Chorus"
                  << "Easy Listening"
                  << "Acoustic"

                  << "Humour"
                  << "Speech"
                  << "Chanson"
                  << "Opera"
                  << "Chamber Music"
                  << "Sonata"
                  << "Symphony"
                  << "Booty Bass"
                  << "Primus"
                  << "Porn Groove"
                  << "Satire"
                  << "Slow Jam"
                  << "Club"
                  << "Tango"
                  << "Samba"
                  << "Folklore"
                  << "Ballad"
                  << "Power Ballad"
                  << "Rhythmic Soul"
                  << "Freestyle"

                  << "Duet"
                  << "Punk Rock"
                  << "Drum Solo"
                  << "A Capella"
                  << "Euro-House"
                  << "Dance Hall"
                  << "Goa"
                  << "Drum & Bass"
                  << "Club-House"
                  << "Hardcore"
                  << "Terror"
                  << "Indie"
                  << "BritPop"
                  << "Negerpunk"
                  << "Polsk Punk"
                  << "Beat"
                  << "Christian Gangsta Rap"
                  << "Heavy Metal"
                  << "Black Metal"
                  << "Crossover"

                  << "Contemporary Christian"
                  << "Christian Rock"
                  << "Merengue"
                  << "Salsa"
                  << "Thrash Metal"
                  << "Anime"
                  << "JPop"
                  << "Synthpop";

        while (genreList.length() < 256)
            genreList << "Unknown";

    }
}
Example #5
0
void SendCoinsDialog::on_sendButton_clicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate())
            {
                recipients.append(entry->getValue());
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    // Format confirmation message
    QStringList formatted;
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        // generate bold amount string
        QString amount = "<b>" + BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
        amount.append("</b>");
        // generate monospace address string
        QString address = "<span style='font-family: monospace;'>" + rcp.address;
        address.append("</span>");

        QString recipientElement;

        if (rcp.authenticatedMerchant.isEmpty())
        {
            if(rcp.label.length() > 0) // label with address
            {
                recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
                recipientElement.append(QString(" (%1)").arg(address));
            }
            else // just address
            {
                recipientElement = tr("%1 to %2").arg(amount, address);
            }
        }
        else // just merchant
        {
            recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
        }

        formatted.append(recipientElement);
    }
    /* Update our model of the wallet incrementally, to synchronize our model of the wallet
       with that of the core.

       Call with transaction that was added, removed or changed.
     */
    void updateWallet(const uint256 &hash, int status)
    {
        qDebug() << "TransactionTablePriv::updateWallet : " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
        {
            LOCK2(cs_main, wallet->cs_wallet);

            // Find transaction in wallet
            std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
            bool inWallet = mi != wallet->mapWallet.end();

            // Find bounds of this transaction in model
            QList<TransactionRecord>::iterator lower = qLowerBound(
                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
            QList<TransactionRecord>::iterator upper = qUpperBound(
                cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
            int lowerIndex = (lower - cachedWallet.begin());
            int upperIndex = (upper - cachedWallet.begin());
            bool inModel = (lower != upper);

            // Determine whether to show transaction or not
            bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));

            if(status == CT_UPDATED)
            {
                if(showTransaction && !inModel)
                    status = CT_NEW; /* Not in model, but want to show, treat as new */
                if(!showTransaction && inModel)
                    status = CT_DELETED; /* In model, but want to hide, treat as deleted */
            }

            qDebug() << "   inWallet=" + QString::number(inWallet) + " inModel=" + QString::number(inModel) +
                        " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) +
                        " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status);

            switch(status)
            {
            case CT_NEW:
                if(inModel)
                {
                    qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model";
                    break;
                }
                if(!inWallet)
                {
                    qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet";
                    break;
                }
                if(showTransaction)
                {
                    // Added -- insert at the right position
                    QList<TransactionRecord> toInsert =
                            TransactionRecord::decomposeTransaction(wallet, mi->second);
                    if(!toInsert.isEmpty()) /* only if something to insert */
                    {
                        parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1);
                        int insert_idx = lowerIndex;
                        foreach(const TransactionRecord &rec, toInsert)
                        {
                            cachedWallet.insert(insert_idx, rec);
                            insert_idx += 1;
                        }
                        parent->endInsertRows();
                    }
                }
                break;
            case CT_DELETED:
                if(!inModel)
                {
                    qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model";
                    break;
                }
                // Removed -- remove entire transaction from table
                parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
                cachedWallet.erase(lower, upper);
                parent->endRemoveRows();
                break;
            case CT_UPDATED:
                // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
                // visible transactions.
                break;
            }
bool QgsAtlasComposition::prepareForFeature( const int featureI, const bool updateMaps )
{
  if ( !mCoverageLayer )
  {
    return false;
  }

  if ( mFeatureIds.isEmpty() )
  {
    emit statusMsgChanged( tr( "No matching atlas features" ) );
    return false;
  }

  if ( featureI >= mFeatureIds.size() )
  {
    return false;
  }

  mCurrentFeatureNo = featureI;

  // retrieve the next feature, based on its id
  mCoverageLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeatureIds[ featureI ].first ) ).nextFeature( mCurrentFeature );

  QgsExpressionContext expressionContext = createExpressionContext();

  // generate filename for current feature
  if ( !evalFeatureFilename( expressionContext ) )
  {
    //error evaluating filename
    return false;
  }

  mGeometryCache.clear();
  emit featureChanged( &mCurrentFeature );
  emit statusMsgChanged( QString( tr( "Atlas feature %1 of %2" ) ).arg( featureI + 1 ).arg( mFeatureIds.size() ) );

  if ( !mCurrentFeature.isValid() )
  {
    //bad feature
    return true;
  }

  if ( !updateMaps )
  {
    //nothing more to do
    return true;
  }

  //update composer maps

  //build a list of atlas-enabled composer maps
  QList<QgsComposerMap*> maps;
  QList<QgsComposerMap*> atlasMaps;
  mComposition->composerItems( maps );
  if ( maps.isEmpty() )
  {
    return true;
  }
  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
  {
    QgsComposerMap* currentMap = ( *mit );
    if ( !currentMap->atlasDriven() )
    {
      continue;
    }
    atlasMaps << currentMap;
  }

  if ( !atlasMaps.isEmpty() )
  {
    //clear the transformed bounds of the previous feature
    mTransformedFeatureBounds = QgsRectangle();

    // compute extent of current feature in the map CRS. This should be set on a per-atlas map basis,
    // but given that it's not currently possible to have maps with different CRSes we can just
    // calculate it once based on the first atlas maps' CRS.
    computeExtent( atlasMaps[0] );
  }

  for ( QList<QgsComposerMap*>::iterator mit = maps.begin(); mit != maps.end(); ++mit )
  {
    if (( *mit )->atlasDriven() )
    {
      // map is atlas driven, so update it's bounds (causes a redraw)
      prepareMap( *mit );
    }
    else
    {
      // map is not atlas driven, so manually force a redraw (to reflect possibly atlas
      // dependent symbology)
      ( *mit )->cache();
    }
  }

  return true;
}
Example #8
0
void AudioPortConfig::addOutRoute()/*{{{*/
{
	QListWidgetItem* dstItem = newDstList->currentItem();
	QListWidgetItem* tItem = tracksList->currentItem();
	if (!_selected || dstItem == 0)
		return;

	RouteList* rl = _selected->outRoutes();
	int chan = 0;

	if (_selected->type() == Track::AUDIO_OUTPUT)
	{
		if(!tItem)
			return;
		int row = tracksList->row(tItem);
		QList<QListWidgetItem*> found = tracksList->findItems(tItem->text(), Qt::MatchExactly);
		if(found.isEmpty())
			return;
		for(int i = 0; i < found.size(); ++i)
		{
			QListWidgetItem* item = found.at(i);
			chan = i;
			int r = tracksList->row(item);
			if(r == row)
				break;
		}

		Route srcRoute(_selected, chan);
		Route dstRoute(dstItem->text(), true, -1, Route::JACK_ROUTE);
		dstRoute.channel = chan;

		// check if route src->dst exists:
		iRoute irl = rl->begin();
		for (; irl != rl->end(); ++irl)
		{
			if (*irl == dstRoute)
				break;
		}
		audio->msgAddRoute(srcRoute, dstRoute);
		audio->msgUpdateSoloStates();
		song->update(SC_ROUTE);
		//new QTreeWidgetItem(routeList, QStringList() << srcRoute.name() << dstRoute.name());
		btnConnectOut->setEnabled(false);
		return;
	}
	else
	{
		Route srcRoute(_selected, chan, _selected->channels());
		Route dstRoute(dstItem->text(), true, -1);

		audio->msgAddRoute(srcRoute, dstRoute);
		audio->msgUpdateSoloStates();
		song->update(SC_ROUTE);
		//new QTreeWidgetItem(routeList, QStringList() << srcRoute.name() << dstRoute.name());
		btnConnectOut->setEnabled(false);
	}
	/*
	audio->msgAddRoute(Route(srcItem->text(), false, -1), Route(dstItem->text(), true, -1));
	audio->msgUpdateSoloStates();
	//song->update(SC_SOLO);
	song->update(SC_ROUTE);
	new QTreeWidgetItem(routeList, QStringList() << srcItem->text() << dstItem->text());
	connectButton->setEnabled(false);
	*/
}/*}}}*/
Example #9
0
bool SessionsManager::saveSession(const QString &path, const QString &title, MainWindow *window, bool isClean)
{
	if (m_isPrivate && path.isEmpty())
	{
		return false;
	}

	QList<MainWindow*> windows;

	if (window)
	{
		windows.append(window);
	}
	else
	{
		windows = Application::getInstance()->getWindows();
	}

	if (windows.isEmpty())
	{
		return false;
	}

	QDir().mkpath(m_profilePath + QLatin1String("/sessions/"));

	QSaveFile file(getSessionPath(path));

	if (!file.open(QIODevice::WriteOnly))
	{
		return false;
	}

	const QString defaultSearchEngine = SettingsManager::getValue(QLatin1String("Search/DefaultSearchEngine")).toString();
	const QString defaultUserAgent = SettingsManager::getValue(QLatin1String("Network/UserAgent")).toString();
	QTextStream stream(&file);
	stream.setCodec("UTF-8");
	stream << QLatin1String("[Session]\n");
	stream << Utils::formatConfigurationEntry(QLatin1String("title"), (title.isEmpty() ? m_sessionTitle : title), true);

	if (!isClean)
	{
		stream << QLatin1String("clean=false\n");
	}

	stream << QLatin1String("windows=") << windows.count() << QLatin1Char('\n');
	stream << QLatin1String("index=1\n\n");

	for (int i = 0; i < windows.count(); ++i)
	{
		const SessionMainWindow sessionEntry = windows.at(i)->getWindowsManager()->getSession();

		stream << QStringLiteral("[%1/Properties]\n").arg(i + 1);
		stream << Utils::formatConfigurationEntry(QLatin1String("geometry"), windows.at(i)->saveGeometry().toBase64(), true);
		stream << QLatin1String("groups=0\n");
		stream << QLatin1String("windows=") << sessionEntry.windows.count() << QLatin1Char('\n');
		stream << QLatin1String("index=") << (sessionEntry.index + 1) << QLatin1String("\n\n");

		for (int j = 0; j < sessionEntry.windows.count(); ++j)
		{
			stream << QStringLiteral("[%1/%2/Properties]\n").arg(i + 1).arg(j + 1);

			if (sessionEntry.windows.at(j).state == NormalWindowState)
			{
				stream << Utils::formatConfigurationEntry(QLatin1String("geometry"), QStringLiteral("%1,%2,%3,%4").arg(sessionEntry.windows.at(j).geometry.x()).arg(sessionEntry.windows.at(j).geometry.y()).arg(sessionEntry.windows.at(j).geometry.width()).arg(sessionEntry.windows.at(j).geometry.height()), true);
			}
			else
			{
				stream << Utils::formatConfigurationEntry(QLatin1String("state"), ((sessionEntry.windows.at(j).state == MaximizedWindowState) ? QLatin1String("maximized") : QLatin1String("minimized")));
			}

			if (sessionEntry.windows.at(j).overrides.value(QLatin1String("Search/DefaultSearchEngine"), QString()).toString() != defaultSearchEngine)
			{
				stream << Utils::formatConfigurationEntry(QLatin1String("searchEngine"), sessionEntry.windows.at(j).overrides[QLatin1String("Search/DefaultSearchEngine")].toString());
			}

			if (sessionEntry.windows.at(j).overrides.value(QLatin1String("Network/UserAgent"), QString()).toString() != defaultUserAgent)
			{
				stream << Utils::formatConfigurationEntry(QLatin1String("userAgent"), sessionEntry.windows.at(j).overrides[QLatin1String("Network/UserAgent")].toString(), true);
			}

			if (sessionEntry.windows.at(j).overrides.value(QLatin1String("Content/PageReloadTime"), -1).toInt() != -1)
			{
				stream << Utils::formatConfigurationEntry(QLatin1String("reloadTime"), QString::number(sessionEntry.windows.at(j).overrides[QLatin1String("Content/PageReloadTime")].toInt()));
			}

			if (sessionEntry.windows.at(j).isAlwaysOnTop)
			{
				stream << QLatin1String("alwaysOnTop=true\n");
			}

			if (sessionEntry.windows.at(j).isPinned)
			{
				stream << QLatin1String("pinned=true\n");
			}

			stream << QLatin1String("history=") << sessionEntry.windows.at(j).history.count() << QLatin1Char('\n');
			stream << QLatin1String("index=") << (sessionEntry.windows.at(j).historyIndex + 1) << QLatin1String("\n\n");

			for (int k = 0; k < sessionEntry.windows.at(j).history.count(); ++k)
			{
				stream << QStringLiteral("[%1/%2/History/%3]\n").arg(i + 1).arg(j + 1).arg(k + 1);
				stream << Utils::formatConfigurationEntry(QLatin1String("url"), sessionEntry.windows.at(j).history.at(k).url, true);
				stream << Utils::formatConfigurationEntry(QLatin1String("title"), sessionEntry.windows.at(j).history.at(k).title, true);
				stream << QLatin1String("position=") << sessionEntry.windows.at(j).history.at(k).position.x() << ',' << sessionEntry.windows.at(j).history.at(k).position.y() << QLatin1Char('\n');
				stream << QLatin1String("zoom=") << sessionEntry.windows.at(j).history.at(k).zoom << QLatin1String("\n\n");
			}
		}
	}

	return file.commit();
}
Example #10
0
void QGenericEngine::doRequestUpdate()
{
#ifndef QT_NO_NETWORKINTERFACE
    QMutexLocker locker(&mutex);

    // Immediately after connecting with a wireless access point
    // QNetworkInterface::allInterfaces() will sometimes return an empty list. Calling it again a
    // second time results in a non-empty list. If we loose interfaces we will end up removing
    // network configurations which will break current sessions.
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    if (interfaces.isEmpty())
        interfaces = QNetworkInterface::allInterfaces();

    QStringList previous = accessPointConfigurations.keys();

    // create configuration for each interface
    while (!interfaces.isEmpty()) {
        QNetworkInterface interface = interfaces.takeFirst();

        if (!interface.isValid())
            continue;

        // ignore loopback interface
        if (interface.flags() & QNetworkInterface::IsLoopBack)
            continue;

        // ignore WLAN interface handled in separate engine
        if (qGetInterfaceType(interface.name()) == QNetworkConfiguration::BearerWLAN)
            continue;

        uint identifier;
        if (interface.index())
            identifier = qHash(QLatin1String("generic:") + QString::number(interface.index()));
        else
            identifier = qHash(QLatin1String("generic:") + interface.hardwareAddress());

        const QString id = QString::number(identifier);

        previous.removeAll(id);

        QString name = interface.humanReadableName();
        if (name.isEmpty())
            name = interface.name();

        QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined;
        if ((interface.flags() & QNetworkInterface::IsRunning) && !interface.addressEntries().isEmpty())
            state |= QNetworkConfiguration::Active;

        if (accessPointConfigurations.contains(id)) {
            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);

            bool changed = false;

            ptr->mutex.lock();

            if (!ptr->isValid) {
                ptr->isValid = true;
                changed = true;
            }

            if (ptr->name != name) {
                ptr->name = name;
                changed = true;
            }

            if (ptr->id != id) {
                ptr->id = id;
                changed = true;
            }

            if (ptr->state != state) {
                ptr->state = state;
                changed = true;
            }

            ptr->mutex.unlock();

            if (changed) {
                locker.unlock();
                emit configurationChanged(ptr);
                locker.relock();
            }
        } else {
            QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate);

            ptr->name = name;
            ptr->isValid = true;
            ptr->id = id;
            ptr->state = state;
            ptr->type = QNetworkConfiguration::InternetAccessPoint;
            ptr->bearerType = qGetInterfaceType(interface.name());

            accessPointConfigurations.insert(id, ptr);
            configurationInterface.insert(id, interface.name());

            locker.unlock();
            emit configurationAdded(ptr);
            locker.relock();
        }
    }

    while (!previous.isEmpty()) {
        QNetworkConfigurationPrivatePointer ptr =
            accessPointConfigurations.take(previous.takeFirst());

        configurationInterface.remove(ptr->id);

        locker.unlock();
        emit configurationRemoved(ptr);
        locker.relock();
    }

    locker.unlock();
#endif

    emit updateCompleted();
}
Example #11
0
bool LeijiCard::targetFilter(const QList<const Player *> &targets, const Player *to_select, const Player *Self) const{
    return targets.isEmpty();
}
Example #12
0
void Renamer::renameMovies(QList<Movie*> movies, const QString &filePattern, const QString &filePatternMulti,
                           const QString &directoryPattern, const bool &renameFiles, const bool &renameDirectories, const bool &dryRun)
{
    if ((renameFiles && filePattern.isEmpty()) || (renameDirectories && directoryPattern.isEmpty()))
        return;

    foreach (Movie *movie, movies) {
        if (movie->files().isEmpty() || (movie->files().count() > 1 && filePatternMulti.isEmpty()) || movie->hasChanged())
            continue;

        qApp->processEvents();
        QFileInfo fi(movie->files().first());
        QString fiCanonicalPath = fi.canonicalPath();
        QDir dir(fi.canonicalPath());
        QString newFolderName = directoryPattern;
        QString newFileName;
        QString nfo = Manager::instance()->mediaCenterInterface()->nfoFilePath(movie);
        QString poster = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MoviePoster);
        QString fanart = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBackdrop);
        QString banner = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBanner);
        QString thumb = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieThumb);
        QString logo = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieLogo);
        QString clearArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieClearArt);
        QString cdArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieCdArt);

        QDir chkDir(fi.canonicalPath());
        chkDir.cdUp();

        bool isBluRay = Helper::instance()->isBluRay(chkDir.path());
        bool isDvd = Helper::instance()->isDvd(chkDir.path());

        if (isBluRay || isDvd)
            dir.cdUp();

        if (!isBluRay && !isDvd && renameFiles) {
            int partNo = 0;
            foreach (const QString &file, movie->files()) {
                newFileName = (movie->files().count() == 1) ? filePattern : filePatternMulti;
                QFileInfo fi(file);
                QString baseName = fi.completeBaseName();
                QDir currentDir = fi.dir();
                Renamer::replace(newFileName, "title", movie->name());
                Renamer::replace(newFileName, "originalTitle", movie->originalName());
                Renamer::replace(newFileName, "sortTitle", movie->sortTitle());
                Renamer::replace(newFileName, "year", movie->released().toString("yyyy"));
                Renamer::replace(newFileName, "extension", fi.suffix());
                Renamer::replace(newFileName, "partNo", QString::number(++partNo));
                Renamer::replace(newFileName, "resolution", Helper::instance()->matchResolution(movie->streamDetails()->videoDetails().value("width").toInt(),
                                                                                                movie->streamDetails()->videoDetails().value("height").toInt()));
                Renamer::replaceCondition(newFileName, "imdbId", movie->id());
                Renamer::replaceCondition(newFileName, "movieset", movie->set());
                Renamer::replaceCondition(newFileName, "3D", movie->streamDetails()->videoDetails().value("stereomode") != "");
                Helper::instance()->sanitizeFileName(newFileName);
                if (fi.fileName() != newFileName) {
                    ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(fi.fileName()).arg(newFileName));
                    if (!dryRun) {
                        if (!rename(file, fi.canonicalPath() + "/" + newFileName))
                            ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                    }

                    foreach (const QString &trailerFile, currentDir.entryList(QStringList() << fi.completeBaseName() + "-trailer.*", QDir::Files | QDir::NoDotAndDotDot)) {
                        QFileInfo trailer(fi.canonicalPath() + "/" + trailerFile);
                        QString newTrailerFileName = newFileName;
                        newTrailerFileName = newTrailerFileName.left(newTrailerFileName.lastIndexOf(".")) + "-trailer." + trailer.suffix();
                        if (trailer.fileName() != newTrailerFileName) {
                            ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(trailer.fileName()).arg(newTrailerFileName));
                            if (!dryRun) {
                                if (!rename(fi.canonicalPath() + "/" + trailerFile, fi.canonicalPath() + "/" + newTrailerFileName))
                                    ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                            }
                        }
                    }

                    QStringList filters;
                    foreach (const QString &extra, m_extraFiles)
                        filters << baseName + extra;
                    foreach (const QString &subFileName, currentDir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot)) {
                        QString subSuffix = subFileName.mid(baseName.length());
                        QString newBaseName = newFileName.left(newFileName.lastIndexOf("."));
                        QString newSubName = newBaseName + subSuffix;
                        ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(subFileName).arg(newSubName));
                        if (!dryRun) {
                            if (!rename(currentDir.canonicalPath() + "/" + subFileName, currentDir.canonicalPath() + "/" + newSubName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename nfo
            if (!nfo.isEmpty()) {
                QString nfoFileName = QFileInfo(nfo).fileName();
                QList<DataFile> nfoFiles = Settings::instance()->dataFiles(DataFileType::MovieNfo);
                if (!nfoFiles.isEmpty()) {
                    QString newNfoFileName = nfoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newNfoFileName);
                    if (newNfoFileName != nfoFileName) {
                        ui->results->append(tr("<b>Rename NFO</b> \"%1\" to \"%2\"").arg(nfoFileName).arg(newNfoFileName));
                        if (!dryRun) {
                            if (!rename(nfo, fiCanonicalPath + "/" + newNfoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Poster
            if (!poster.isEmpty()) {
                QString posterFileName = QFileInfo(poster).fileName();
                QList<DataFile> posterFiles = Settings::instance()->dataFiles(DataFileType::MoviePoster);
                if (!posterFiles.isEmpty()) {
                    QString newPosterFileName = posterFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newPosterFileName);
                    if (newPosterFileName != posterFileName) {
                        ui->results->append(tr("<b>Rename Poster</b> \"%1\" to \"%2\"").arg(posterFileName).arg(newPosterFileName));
                        if (!dryRun) {
                            if (!rename(poster, fiCanonicalPath + "/" + newPosterFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Fanart
            if (!fanart.isEmpty()) {
                QString fanartFileName = QFileInfo(fanart).fileName();
                QList<DataFile> fanartFiles = Settings::instance()->dataFiles(DataFileType::MovieBackdrop);
                if (!fanartFiles.isEmpty()) {
                    QString newFanartFileName = fanartFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newFanartFileName);
                    if (newFanartFileName != fanartFileName) {
                        ui->results->append(tr("<b>Rename Fanart</b> \"%1\" to \"%2\"").arg(fanartFileName).arg(newFanartFileName));
                        if (!dryRun) {
                            if (!rename(fanart, fiCanonicalPath + "/" + newFanartFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Banner
            if (!banner.isEmpty()) {
                QString bannerFileName = QFileInfo(banner).fileName();
                QList<DataFile> bannerFiles = Settings::instance()->dataFiles(DataFileType::MovieBanner);
                if (!bannerFiles.isEmpty()) {
                    QString newBannerFileName = bannerFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newBannerFileName);
                    if (newBannerFileName != bannerFileName) {
                        ui->results->append(tr("<b>Rename Banner</b> \"%1\" to \"%2\"").arg(bannerFileName).arg(newBannerFileName));
                        if (!dryRun) {
                            if (!rename(banner, fiCanonicalPath + "/" + newBannerFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Thumb
            if (!thumb.isEmpty()) {
                QString thumbFileName = QFileInfo(thumb).fileName();
                QList<DataFile> thumbFiles = Settings::instance()->dataFiles(DataFileType::MovieThumb);
                if (!thumbFiles.isEmpty()) {
                    QString newThumbFileName = thumbFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newThumbFileName);
                    if (newThumbFileName != thumbFileName) {
                        ui->results->append(tr("<b>Rename Thumb</b> \"%1\" to \"%2\"").arg(thumbFileName).arg(newThumbFileName));
                        if (!dryRun) {
                            if (!rename(thumb, fiCanonicalPath + "/" + newThumbFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Logo
            if (!logo.isEmpty()) {
                QString logoFileName = QFileInfo(logo).fileName();
                QList<DataFile> logoFiles = Settings::instance()->dataFiles(DataFileType::MovieLogo);
                if (!logoFiles.isEmpty()) {
                    QString newLogoFileName = logoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newLogoFileName);
                    if (newLogoFileName != logoFileName) {
                        ui->results->append(tr("<b>Rename Logo</b> \"%1\" to \"%2\"").arg(logoFileName).arg(newLogoFileName));
                        if (!dryRun) {
                            if (!rename(logo, fiCanonicalPath + "/" + newLogoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename ClearArt
            if (!clearArt.isEmpty()) {
                QString clearArtFileName = QFileInfo(clearArt).fileName();
                QList<DataFile> clearArtFiles = Settings::instance()->dataFiles(DataFileType::MovieClearArt);
                if (!clearArtFiles.isEmpty()) {
                    QString newClearArtFileName = clearArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newClearArtFileName);
                    if (newClearArtFileName != clearArtFileName) {
                        ui->results->append(tr("<b>Rename Clear Art</b> \"%1\" to \"%2\"").arg(clearArtFileName).arg(newClearArtFileName));
                        if (!dryRun) {
                            if (!rename(clearArt, fiCanonicalPath + "/" + newClearArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename CdArt
            if (!cdArt.isEmpty()) {
                QString cdArtFileName = QFileInfo(cdArt).fileName();
                QList<DataFile> cdArtFiles = Settings::instance()->dataFiles(DataFileType::MovieCdArt);
                if (!cdArtFiles.isEmpty()) {
                    QString newCdArtFileName = cdArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newCdArtFileName);
                    if (newCdArtFileName != cdArtFileName) {
                        ui->results->append(tr("<b>Rename CD Art</b> \"%1\" to \"%2\"").arg(cdArtFileName).arg(newCdArtFileName));
                        if (!dryRun) {
                            if (!rename(cdArt, fiCanonicalPath + "/" + newCdArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }
        }
Example #13
0
int CardSet::loadCsv(const CardDisplay& defDisplay, CsvFile& file)
{
    /*
     * This method reads Anki plain text file format:
     *  - plain text, UTF-8, BOM optional;
     *  - ignore lines starting with "#";
     *  - if first uncommented line starts with "tags:", use space-split words
     *    as additional facts;
     *  - recognize any delimiters;
     *  - use double quotes ("\"") as quote char, including quoting newline;
     *  - literal newline in field should be replaced by "<br>";
     *  - fields are interpreted as simplified HTML;
     *
     * Format is extended by following new features:
     *  - comments in format "#FCARD# <attr-name> <attr-value>" are interpreted as
     *    display attributes for following cards. Following attributes are
     *    recognized:
     *
     *      - "background <color-name>"
     *        specifies background color for cards from this set.
     *
     *      - "period <time-ms>"
     *        specifies period (in milliseconds) for which card will be shown.
     *
     *      - "split-{x|y} <width>,..."
     *        specifies horizontal or vertical split distribution.
     *
     *      - "cell <fact-index>,<cell-x>,<cell-y>,<color-name>,<font-family>,<pattern>,<stylesheet>"
     *        specifies display parameters for fact text.
     *
     *      - "protect {on|off},<keyword>,..."
     *        protects or unprotects specified keywords from further changes below that point.
     *
     *      - "include <filename>,<separator>"
     *        includes specified file; path may be relative to this file; separator
     *        may be specified as a literal character or a "#"-prefixed Unicode
     *        codepoint.
     */
    enum Keyword {
        UNKNOWN,
        BACKGROUND,
        PERIOD,
        SPLIT_X,
        SPLIT_Y,
        CELL,
        PROTECT,
        INCLUDE
    };
    static const struct KeywordDesc {
        Keyword     code;
        const char *name;
    } KEYWORD_LIST[] = {
        { BACKGROUND, "background" },
        { PERIOD,     "period"     },
        { SPLIT_X,    "split-x"    },
        { CELL,       "cell"       },
        { INCLUDE,    "include"    },
        { PROTECT,    "protect"    },
        { UNKNOWN,    0            }
    };
    QRegExp fcard("#FCARD#\\s*(\\w+)\\s+(.*)");
    fcard.setPatternSyntax(QRegExp::RegExp2);
    int cardCount = 0;
    QStringList tagSet;
    CardDisplay *display = 0;
    CardDisplay currDisplay(defDisplay);
    for (;;)
    {
        int flags = 0;
        QStringList line = file.readLine(&flags);
        if (line.isEmpty())
        {
            if (!file.lastError().isEmpty())
            {
                qWarning("ERROR: %s", qPrintable(file.lastError()));
                return -1;
            }
            return cardCount;
        }
        if (flags == CsvFile::FLAG_COMMENT)
        {
            if (fcard.exactMatch(line.first()))
            {
                QString aname = fcard.cap(1);
                QString aval = fcard.cap(2);
                QStringList alist;
                int ret;
                if ((ret = TextConv::smartSplit(alist, aval)) != 0)
                {
                    qWarning("ERROR: Field-list syntax error in '%s' near offset %d",
                             qPrintable(aval), ret - 1);
                    continue;
                }
                Keyword code = UNKNOWN;
                for (const KeywordDesc *kwd = KEYWORD_LIST; kwd->name != 0; kwd++)
                    if (aname == kwd->name)
                    {
                        code = kwd->code;
                        break;
                    }
                if (currDisplay.isProtected(code))
                    continue;
                switch (code)
                {
                case UNKNOWN:
                    break;
                case BACKGROUND:
                    {
                        QColor bgd = QColor(aval.trimmed());
                        if (bgd.isValid())
                            currDisplay.setBackground(bgd);
                    }
                    break;
                case PERIOD:
                    {
                        bool ok = false;
                        int period = aval.toInt(&ok);
                        if (ok &&
                                period >= CardDisplay::MIN_PERIOD &&
                                period <= CardDisplay::MAX_PERIOD)
                            currDisplay.setPeriod(period);
                    }
                    break;
                case SPLIT_X:
                case SPLIT_Y:
                    {
                        QList<int> spl;
                        bool ok = TextConv::toIntList(alist, spl);
                        if (ok && !spl.isEmpty())
                        {
                            if (code == SPLIT_X)
                                currDisplay.setSplitX(spl);
                            else
                                currDisplay.setSplitY(spl);
                        }
                    }
                    break;
                case CELL:
                    if (!alist.isEmpty())
                    {
                        QString indVal = alist.takeFirst();
                        bool ok = false;
                        int ind = indVal.toInt(&ok);
                        if (ok && ind >= 0)
                        {
                            CardCell cell;
                            cell.assign(alist);
                            currDisplay.setValue(ind, cell);
                        }
                    }
                    break;
                case PROTECT:
                    if (!alist.isEmpty())
                    {
                        QString bVal = alist.takeFirst();
                        bool value;
                        if (bVal == "on")
                            value = true;
                        else if (bVal == "off")
                            value = false;
                        else
                            break;
                        foreach (QString name, alist)
                        {
                            for (const KeywordDesc *kwd = KEYWORD_LIST; kwd->name != 0; kwd++)
                                if (name == kwd->name && kwd->code != PROTECT)
                                {
                                    currDisplay.setProtected(kwd->code, value);
                                    break;
                                }
                        }
                    }
                    break;
                case INCLUDE:
                    if (!alist.isEmpty())
                    {
                        QChar sep = CsvFile::DEFAULT_SEPARATOR;
                        if (alist.size() > 1)
                            sep = TextConv::toChar(alist[1], sep);
                        CsvFile inclFile(alist[0], sep);
                        int inclCnt = loadCsv(currDisplay, inclFile);
                        if (inclCnt < 0)
                            return inclCnt;
                        cardCount += inclCnt;
                    }
                    break;
                }
            }
            continue;
        }
Example #14
0
void SendCoinsDialog::on_sendButton_clicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate(model->node()))
            {
                recipients.append(entry->getValue());
                recipients[i].fCoinJoin = (ui->checkUseCoinJoin->checkState() == Qt::Checked);
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    QString strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>";
    QString strFee = "";

    if(ui->checkUseCoinJoin->checkState() == Qt::Checked) {
        strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>";
        QString strNearestAmount(
            BitcoinUnits::formatWithUnit(
                model->getOptionsModel()->getDisplayUnit(), COINJOIN_LOW_DENOM));
        strFee = QString(tr(
            "(coinjoin requires this amount to be rounded up to the nearest %1)."
        ).arg(strNearestAmount));
    } else {
        strFunds = tr("using") + " <b>" + tr("any available funds (not anonymous)") + "</b>";
    }

    fNewRecipientAllowed = false;
    // request unlock only if was locked or unlocked for mixing:
    // this way we let users unlock by walletpassphrase or by menu
    // and make many transactions while unlocking through this dialog
    // will call relock
    WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus();
    if(encStatus == model->Locked || encStatus == model->UnlockedForMixingOnly)
    {
        WalletModel::UnlockContext ctx(model->requestUnlock());
        if(!ctx.isValid())
        {
            // Unlock wallet was cancelled
            fNewRecipientAllowed = true;
            return;
        }
        send(recipients, strFee, strFunds);
        return;
    }
    // already unlocked or not encrypted at all
    send(recipients, strFee, strFunds);
}
Example #15
0
void Robot::updateDirection()
{
    //----Magic! Don't touch!---
    //If the detected list is empty, then keep the direction.
    if(m_detectedRobotList.isEmpty())
    {
        //If the robot has a guardian line,
        if(m_hasGuardianLine)
        {
            //Check if the robot reach one side of the line.
            if(m_toP1Distance<=0.9)
            {
                //Move to the guardian line angle.
                m_movingSpeed=1.0;
                m_angle=m_guardianLine.angle();
                return;
            }
            if(m_toP1Distance>=m_guardianLine.length())
            {
                //Move to the opposite angle of the guardian line.
                m_movingSpeed=-1.0;
                m_angle=m_oppositeGuardianLine.angle();
                return;
            }
        }
        //Or else keep the direction.
        return;
    }
    //Now the detected robot list cannot be empty.
    //If the robot has a line to guard.
    if(m_hasGuardianLine)
    {
        //Check if the robot reach one side of the line.
        if(m_toP1Distance<=0.9 || m_toP1Distance>=m_guardianLine.length()-0.9)
        {
            //Move to the different direction.
            if(m_movingSpeed>0)
            {
                m_movingSpeed=-1.0;
                m_angle=m_oppositeGuardianLine.angle();
            }
            else
            {
                m_movingSpeed=1.0;
                m_angle=m_guardianLine.angle();
            }
            return;
        }
        //Or else, we should have move the robot to opposite direction of the
        //nearest robot.
        //The nearest robot have three kind of types:
        //  1. It doesn't have a guardian line.
        //  2. It has a guardian line, but it's not the same as mine.
        //  3. It has the same guardian line.
        //For the first type, ignore it.
        //For the second and third type,  there's one rule: the robot should
        //move to the direction which should leave that robot away.
        QList<RobotStatus> statusList;
        for(Robot *robot : m_detectedRobotList)
        {
            RobotStatus currentStatus;
            currentStatus.robot=robot;
            currentStatus.distance=QLineF(m_pos, robot->pos()).angle();
            statusList.append(currentStatus);
        }
        qSort(statusList);
        //Get the nearest robot, .
        RobotStatus nearestStatus=statusList.takeFirst();
        while(!nearestStatus.robot->hasGuardianLine() && !statusList.isEmpty())
        {
            nearestStatus=statusList.takeFirst();
        }
        //Check the nearest status.
        if(!nearestStatus.robot->hasGuardianLine())
        {
            //All the robot in the detect range don't has a guardian line.
            //They will move away from this point.
            return;
        }
        //So now, we get the nearest point which contains a guardian line.
        Robot *nearestRobot=nearestStatus.robot;
        //If these two robot has the same guardian line, and they are getting
        //closer(have the different speed), move to the other direction.
        //If these two robots have the different speed.
        //For this kinds of type,
        //p1  this
        //|   |
        //+---*><*----------------------
        //       |
        //       nearest
        //
        //Or for this kinds of type,
        //
        //                    this p2
        //                    |    |
        //-----------------*><*----+
        //                 |
        //                 nearest
        //
        //We have to change the direction.
        //
        //So now, there is an ugly thing we have to met.(What the fuck!)
        //The nearest point is not at the same line, but according to the
        //context, this line must be the neighbouring line. Like the following:
        //
        //  --------+
        //          |
        //          |
        //
        //We have change the direction when both of these robots are moving to
        //the same point, and that point is pretty interesting. It's the p1 for
        //the second line and the p2 for the first line. So:
        //
        //    this  p2(for this)
        //       |  |
        //  -----*>-+-p1(for nearest)
        //          |
        //          ^
        //          *
        //          |
        //
        //At this time, the moving speed of this and nearest will be different
        //(this is 1.0 and nearest is -1.0).
        //For another case, it will be like this:
        //
        //      p1(for this)  p1
        //                 |  |
        // p2(for nearest)-+-<*-------
        //                 |
        //                 ^
        //                 *
        //                 |
        //
        //At this time, the moving speed of this and nearest will be different
        //as well(this is -1.0 and nearest is 1.0).
        //We have to change the direction in these two cases.

        if(nearestRobot->movingSpeed()!=m_movingSpeed)
        {
            if(nearestRobot->guardianLine()==m_guardianLine)
            {
                if((m_movingSpeed>0 &&
                    m_toP1Distance<nearestRobot->toP1Distance()) ||
                        (m_movingSpeed<0 &&
                         m_toP1Distance>nearestRobot->toP1Distance()))
                {
                    //Move to the different direction.
                    moveToOppositeDirection();
                    //Ask the robot move to the differect direction as well.
                    nearestRobot->moveToOppositeDirection();
                }
            }
            else
            {
                if((m_movingSpeed>0 &&
                         m_toP1Distance>nearestRobot->toP1Distance()) ||
                   (m_movingSpeed<0 &&
                         m_toP1Distance<nearestRobot->toP1Distance()))
                {
                    //Move to the different direction.
                    moveToOppositeDirection();
                    //Ask the robot move to the differect direction as well.
                    nearestRobot->moveToOppositeDirection();
                }
            }
        }
        //Or else, keep moving.
        return;
    }
    //The prefer direction is to link all the detected robots, calculate the
    //average angle of the robot lists.
    qreal angleSum=0.0;
    for(Robot *robot : m_detectedRobotList)
    {
        angleSum+=QLineF(m_pos, robot->pos()).angle();
    }
    angleSum/=m_detectedRobotList.size();
    //Set the angle to the opposite angle.
    setAngle(angleSum+180.0);
}
Example #16
0
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &context, QgsFeedback *feedback )
{
  // ideally this should not be required, as well behaved callers
  // will NOT fire up a new fetchResults call while an existing one is
  // operating/waiting to be canceled...
  cancelRunningQuery();

  // if no feedback object was passed, create one that is owned by this object
  // to ensure that filters ALWAYS receive a valid feedback
  if ( !feedback )
  {
    mOwnedFeedback.reset( new QgsFeedback() );
    feedback = mOwnedFeedback.get();
  }
  else
  {
    mOwnedFeedback.reset( nullptr );
  }
  mFeedback = feedback;

  QList< QgsLocatorFilter * > activeFilters;
  QString searchString = string;
  if ( searchString.indexOf( ' ' ) > 0 )
  {
    QString prefix = searchString.left( searchString.indexOf( ' ' ) );
    if ( mPrefixedFilters.contains( prefix ) && mPrefixedFilters.value( prefix )->enabled() )
    {
      activeFilters << mPrefixedFilters.value( prefix );
      searchString = searchString.mid( prefix.length() + 1 );
    }
  }
  if ( activeFilters.isEmpty() )
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->useWithoutPrefix() && filter->enabled() )
        activeFilters << filter;
    }
  }

  QList< QgsLocatorFilter *> threadedFilters;
  for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) )
  {
    std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
    connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
    {
      result.filter = filter;
      emit filterSentResult( result );
    } );
    clone->prepare( searchString, context );

    if ( clone->flags() & QgsLocatorFilter::FlagFast )
    {
      // filter is fast enough to fetch results on the main thread
      clone->fetchResults( searchString, context, feedback );
    }
    else
    {
      // run filter in background
      threadedFilters.append( clone.release() );
    }
  }

  mActiveThreads.clear();
  for ( QgsLocatorFilter *filter : qgis::as_const( threadedFilters ) )
  {
    QThread *thread = new QThread();
    mActiveThreads.append( thread );
    filter->moveToThread( thread );
    connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
    {
      if ( !feedback->isCanceled() )
        filter->fetchResults( searchString, context, feedback );
      filter->emit finished();
    }, Qt::QueuedConnection );
    connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
    connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
    connect( thread, &QThread::finished, thread, [this, thread]
    {
      mActiveThreads.removeAll( thread );
      if ( mActiveThreads.empty() )
        emit finished();
    } );
    connect( thread, &QThread::finished, thread, &QThread::deleteLater );
    thread->start();
  }

  if ( mActiveThreads.empty() )
    emit finished();
}
bool ZhiyuanCard::targetFilter(const QList<const Player *> &targets, const Player *to_select, const Player *Self) const{
    return targets.isEmpty() && to_select != Self && to_select->getRoleEnum() == Player::Rebel;
}
Example #18
0
void SendCoinsDialog::on_sendButton_clicked()
{
    if (!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for (int i = 0; i < ui->entries->count(); ++i) {
        SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());

        //UTXO splitter - address should be our own
        const CTxDestination dest = DecodeDestination(entry->getValue().address.toStdString());
        if (!model->isMine(dest) && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
            CoinControlDialog::coinControl->fSplitBlock = false;
            ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
            QMessageBox::warning(this, tr("Send Coins"),
                tr("The split block tool does not work when sending to outside addresses. Try again."),
                QMessageBox::Ok, QMessageBox::Ok);
            return;
        }

        if (entry) {
            if (entry->validate()) {
                recipients.append(entry->getValue());
            } else {
                valid = false;
            }
        }
    }

    if (!valid || recipients.isEmpty()) {
        return;
    }

    //set split block in model
    CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked;

    if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
        CoinControlDialog::coinControl->fSplitBlock = false;
        ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
        QMessageBox::warning(this, tr("Send Coins"),
            tr("The split block tool does not work with multiple addresses. Try again."),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }

    if (CoinControlDialog::coinControl->fSplitBlock)
        CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt());

    QString strFunds = "";
    QString strFee = "";
    recipients[0].inputType = ALL_COINS;

    if (ui->checkSwiftTX->isChecked()) {
        recipients[0].useSwiftTX = true;
        strFunds += " ";
        strFunds += tr("using SwiftX");
    } else {
        recipients[0].useSwiftTX = false;
    }


    // Format confirmation message
    QStringList formatted;
    foreach(const SendCoinsRecipient &rcp, recipients) {
        // generate bold amount string
        QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
        amount.append("</b> ").append(strFunds);

        // generate monospace address string
        QString address = "<span style='font-family: monospace;'>" + rcp.address;
        address.append("</span>");

        QString recipientElement;

        if (!rcp.paymentRequest.IsInitialized()) // normal payment
        {
            if (rcp.label.length() > 0) // label with address
            {
                recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
                recipientElement.append(QString(" (%1)").arg(address));
            } else // just address
            {
                recipientElement = tr("%1 to %2").arg(amount, address);
            }
        } else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
        } else // insecure payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, address);
        }

        if (CoinControlDialog::coinControl->fSplitBlock) {
            recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock));
        }

        formatted.append(recipientElement);
    }
Example #19
0
ErrorList topolTest::checkGaps( double tolerance, QgsVectorLayer *layer1, QgsVectorLayer *layer2, bool isExtent )
{
  Q_UNUSED( tolerance );
  Q_UNUSED( layer2 );

  int i = 0;
  ErrorList errorList;
  GEOSContextHandle_t geosctxt = QgsGeometry::getGEOSHandler();

  // could be enabled for lines and points too
  // so duplicate rule may be removed?

  if ( layer1->geometryType() != QgsWkbTypes::PolygonGeometry )
  {
    return errorList;
  }

  QList<FeatureLayer>::iterator it;
  QgsGeometry g1;

  QList<GEOSGeometry*> geomList;

  qDebug() << mFeatureList1.count() << " features in list!";
  for ( it = mFeatureList1.begin(); it != mFeatureList1.end(); ++it )
  {
    qDebug() << "reading features-" << i;

    if ( !( ++i % 100 ) )
    {
      emit progress( i );
    }

    if ( testCancelled() )
    {
      break;
    }

    g1 = it->feature.geometry();

    if ( g1.isEmpty() )
    {
      continue;
    }

    if ( !_canExportToGeos( g1 ) )
    {
      continue;
    }

    if ( !g1.isGeosValid() )
    {
      qDebug() << "invalid geometry found..skipping.." << it->feature.id();
      continue;
    }

    if ( g1.isMultipart() )
    {
      QgsMultiPolygon polys = g1.asMultiPolygon();
      for ( int m = 0; m < polys.count(); m++ )
      {
        QgsPolygon polygon = polys[m];

        QgsGeometry polyGeom = QgsGeometry::fromPolygon( polygon );

        geomList.push_back( polyGeom.exportToGeos() );
      }

    }
    else
    {
      geomList.push_back( g1.exportToGeos() );
    }
  }

  GEOSGeometry** geomArray = new GEOSGeometry*[geomList.size()];
  for ( int i = 0; i < geomList.size(); ++i )
  {
    //qDebug() << "filling geometry array-" << i;
    geomArray[i] = geomList.at( i );
  }

  qDebug() << "creating geometry collection-";

  if ( geomList.isEmpty() )
  {
    //qDebug() << "geometry list is empty!";
    delete [] geomArray;
    return errorList;
  }

  GEOSGeometry* collection = nullptr;
  collection = GEOSGeom_createCollection_r( geosctxt, GEOS_MULTIPOLYGON, geomArray, geomList.size() );


  qDebug() << "performing cascaded union..might take time..-";
  GEOSGeometry* unionGeom = GEOSUnionCascaded_r( geosctxt, collection );
  //delete[] geomArray;

  QgsGeometry test;
  test.fromGeos( unionGeom );


  //qDebug() << "wktmerged - " << test.exportToWkt();

  QString extentWkt =  test.boundingBox().asWktPolygon();
  QgsGeometry extentGeom = QgsGeometry::fromWkt( extentWkt );
  QgsGeometry bufferExtent = extentGeom.buffer( 2, 3 );

  //qDebug() << "extent wkt - " << bufferExtent->exportToWkt();

  QgsGeometry diffGeoms = bufferExtent.difference( test );
  if ( !diffGeoms )
  {
    qDebug() << "difference result 0-";
    return errorList;
  }

  //qDebug() << "difference gometry - " << diffGeoms->exportToWkt();

  QList<QgsGeometry> geomColl = diffGeoms.asGeometryCollection();

  QgsGeometry canvasExtentPoly = QgsGeometry::fromWkt( theQgsInterface->mapCanvas()->extent().asWktPolygon() );

  for ( int i = 1; i < geomColl.count() ; ++i )
  {
    QgsGeometry conflictGeom = geomColl[i];
    if ( isExtent )
    {
      if ( canvasExtentPoly.disjoint( conflictGeom ) )
      {
        continue;
      }
      if ( canvasExtentPoly.crosses( conflictGeom ) )
      {
        conflictGeom = conflictGeom.intersection( canvasExtentPoly );
      }
    }
    QgsRectangle bBox = conflictGeom.boundingBox();
    FeatureLayer ftrLayer1;
    ftrLayer1.layer = layer1;
    QList<FeatureLayer> errorFtrLayers;
    errorFtrLayers << ftrLayer1 << ftrLayer1;
    TopolErrorGaps* err = new TopolErrorGaps( bBox, conflictGeom, errorFtrLayers );
    errorList << err;
  }

  return errorList;
}
Example #20
0
SSLWidget::SSLWidget(const QUrl &url, const WebSslInfo &info, QWidget *parent)
    : QMenu(parent)
    , m_url(url)
    , m_info(info)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setMinimumWidth(400);

    QList<QSslCertificate> certList = m_info.certificateChain();
    QSslCertificate cert;
    if (!certList.isEmpty())
        cert = certList.first();

    QList<QStringList> certErrorList = SslInfoDialog::errorsFromString(m_info.certificateErrors());
    QStringList firstCertErrorList;
    if (!certErrorList.isEmpty())
        firstCertErrorList = certErrorList.first();

    QGridLayout *layout = new QGridLayout(this);

    QLabel *label;
    QLabel *imageLabel;

    int rows = 0;
    // ------------------------------------------------------------------------------------------------------
    imageLabel = new QLabel(this);
    layout->addWidget(imageLabel, rows , 0, Qt::AlignCenter);

    label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(i18n("Identity"));
    QFont f1 = label->font();
    f1.setBold(true);
    label->setFont(f1);
    layout->addWidget(label, rows++, 1);

    label = new QLabel(this);
    label->setWordWrap(true);
    if (cert.isNull())
    {
        label->setText(i18n("Warning: this site is NOT carrying a certificate."));
        imageLabel->setPixmap(KIcon("security-low").pixmap(32));
        layout->addWidget(label, rows++, 1);
    }
    else
    {
        if (cert.isValid() && firstCertErrorList.isEmpty())
        {
            label->setText(i18n("The certificate for this site is valid and has been verified by:\n%1.",
                                Qt::escape(cert.issuerInfo(QSslCertificate::CommonName))));

            imageLabel->setPixmap(KIcon("security-high").pixmap(32));
        }
        else
        {
            QString c = QL1S("<ul>");
            Q_FOREACH(const QString & s, firstCertErrorList)
            {
                c += QL1S("<li>") + s + QL1S("</li>");
            }
            c += QL1S("</ul>");

            label->setText(i18n("The certificate for this site is NOT valid, for the following reasons:\n%1.", c));
            label->setTextFormat(Qt::RichText);
            imageLabel->setPixmap(KIcon("security-low").pixmap(32));
        }

        layout->addWidget(label, rows++, 1);

        label = new QLabel(this);
        label->setWordWrap(true);
        label->setText(QL1S("<a href=\"moresslinfos\">") + i18n("Certificate Information") + QL1S("</a>"));
        connect(label, SIGNAL(linkActivated(QString)), this, SLOT(showMoreSslInfos(QString)));
        layout->addWidget(label, rows++, 1);
    }
Example #21
0
/**
 * FASTQ format specification: http://maq.sourceforge.net/fastq.shtml
 */
static void load(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& hints, QList<GObject*>& objects, U2OpStatus& os,
                 int gapSize, int predictedSize, QString& writeLockReason, QMap<QString, QString>& skippedLines) {
    DbiOperationsBlock opBlock(dbiRef, os);
    CHECK_OP(os, );
    Q_UNUSED(opBlock);
    writeLockReason.clear();

    bool merge = gapSize!=-1;
    QByteArray sequence;
    QByteArray qualityScores;
    QStringList headers;
    QSet<QString> uniqueNames;

    QVector<U2Region> mergedMapping;
    QByteArray gapSequence((merge ? gapSize : 0), 0);
    sequence.reserve(predictedSize);
    qualityScores.reserve(predictedSize);

    // for lower case annotations
    GObjectReference sequenceRef;
    qint64 sequenceStart = 0;

    U2SequenceImporter seqImporter(hints, true);
    const QString folder = hints.value(DocumentFormat::DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER).toString();
    int seqNumber = 0;
    int progressUpNum = 0;


    const int objectsCountLimit = hints.contains(DocumentReadingMode_MaxObjectsInDoc) ? hints[DocumentReadingMode_MaxObjectsInDoc].toInt() : -1;
    const bool settingsMakeUniqueName = !hints.value(DocumentReadingMode_DontMakeUniqueNames, false).toBool();
    while (!os.isCoR()) {
        U2OpStatus2Log warningOs;

        //read header
        QString sequenceName = readSequenceName(warningOs, io, '@');
        // check for eof while trying to read another FASTQ block
        if (io->isEof()) {
            if (io->hasError()) {
                os.setError(io->errorString());
            }
            break;
        }

        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            continue;
        }

        if(sequenceName.isEmpty()){
            sequenceName = "Sequence";
        }

        if ((merge == false) || (seqNumber == 0)) {
            QString objName = sequenceName;
            if (settingsMakeUniqueName) {
                objName = (merge) ? "Sequence" : TextUtils::variate(sequenceName, "_", uniqueNames);
                objName.squeeze();
                uniqueNames.insert(objName);
            }
            seqImporter.startSequence(warningOs, dbiRef, folder, objName, false);
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        //read sequence
        if (merge && sequence.length() > 0) {
            seqImporter.addDefaultSymbolsBlock(gapSize, warningOs);
            sequenceStart += sequence.length();
            sequenceStart+=gapSize;
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        sequence.clear();
        readSequence(warningOs, io, sequence);
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }
        MemoryLocker lSequence(os, qCeil(sequence.size()/(1000*1000)));
        CHECK_OP_BREAK(os);
        Q_UNUSED(lSequence);

        seqImporter.addBlock(sequence.data(),sequence.length(), warningOs);
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }

        QString qualSequenceName = readSequenceName(warningOs, io, '+');
        if (!qualSequenceName.isEmpty()) {
            if (sequenceName != qualSequenceName){
                warningOs.setError(U2::FastqFormat::tr("Sequence name differs from quality scores name: %1 and %2").arg(sequenceName).arg(qualSequenceName));
            }
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                U2OpStatusImpl seqOs;
                seqImporter.finalizeSequenceAndValidate(seqOs);
                continue;
            }
        }

        // read qualities
        qualityScores.clear();
        readQuality(warningOs, io, qualityScores, sequence.size());
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }

        if(sequence.length() != qualityScores.length()){
            warningOs.setError(U2::FastqFormat::tr("Bad quality scores: inconsistent size."));
        }
        if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
            U2OpStatusImpl seqOs;
            seqImporter.finalizeSequenceAndValidate(seqOs);
            continue;
        }


        seqNumber++;
        progressUpNum++;
        if (merge) {
            headers.append(sequenceName);
            mergedMapping.append(U2Region(sequenceStart, sequence.length() ));
        }
        else {
            if (objectsCountLimit > 0 && objects.size() >= objectsCountLimit) {
                os.setError(FastqFormat::tr("File \"%1\" contains too many sequences to be displayed. "
                    "However, you can process these data using instruments from the menu <i>Tools -> NGS data analysis</i> "
                    "or pipelines built with Workflow Designer.")
                    .arg(io->getURL().getURLString()));
                break;
            }

            U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(warningOs);
            if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){
                continue;
            }
            sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id));

            U2SequenceObject* seqObj = new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id));
            CHECK_EXT_BREAK(seqObj != NULL, os.setError("U2SequenceObject is NULL"));
            seqObj->setQuality(DNAQuality(qualityScores));
            objects << seqObj;

            U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints);
        }
        if (PROGRESS_UPDATE_STEP == progressUpNum) {
            progressUpNum = 0;
            os.setProgress(io->getProgress());
        }
    }

    CHECK_OP_EXT(os, qDeleteAll(objects); objects.clear(), );
    bool emptyObjects = objects.isEmpty();
    CHECK_EXT(!emptyObjects || merge, os.setError(Document::tr("Document is empty.")), );
    SAFE_POINT(headers.size() == mergedMapping.size(), "headers <-> regions mapping failed!", );

    if (!merge) {
        return;
    }
    U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(os);
    CHECK_OP(os,);
    sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id));

    U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints);
    objects << new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id));
    objects << DocumentFormatUtils::addAnnotationsForMergedU2Sequence(sequenceRef, dbiRef, headers, mergedMapping, hints);
    if (headers.size() > 1) {
        writeLockReason = QObject::tr("Document sequences were merged");
    }
}
Example #22
0
void PeerListModel::updatePeers(const google::protobuf::RepeatedPtrField<Protos::GUI::State::Peer>& peers, const QSet<Common::Hash>& peersDownloadingOurData)
{
   Common::SortedArray<Peer*> peersToRemove = this->orderedPeers;
   QList<Peer*> peersToAdd;

   for (int i = 0; i < peers.size(); i++)
   {
      const Common::Hash peerID(peers.Get(i).peer_id().hash());
      const QString& nick = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::nick);
      const QString& coreVersion = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::core_version);
      const quint64 sharingAmount(peers.Get(i).sharing_amount());
      const TransferInformation transferInformation { peers.Get(i).download_rate(), peers.Get(i).upload_rate(),  peersDownloadingOurData.contains(peerID) };
      const QHostAddress ip =
         peers.Get(i).has_ip() ?
            Common::ProtoHelper::getIP(peers.Get(i).ip()) :
            QHostAddress();

      Peer* peer = this->indexedPeers[peerID];
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         peersToRemove.remove(peer);
         if (peer->nick != nick)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_NICK)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->nick = nick;
               peersToAdd << peer;
            }
            else
            {
               peer->nick = nick;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->sharingAmount != sharingAmount)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_SHARING_AMOUNT)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->sharingAmount = sharingAmount;
               peersToAdd << peer;
            }
            else
            {
               peer->sharingAmount = sharingAmount;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->transferInformation != transferInformation)
         {
            peer->transferInformation = transferInformation;
            emit dataChanged(this->createIndex(j, 0), this->createIndex(j, 0));
         }

         peer->ip = ip;
         peer->coreVersion = coreVersion;
      }
      else
      {
         peersToAdd << new Peer(peerID, nick, coreVersion, sharingAmount, ip, transferInformation);
      }
   }

   QList<Common::Hash> peerIDsRemoved;
   for (Common::SortedArray<Peer*>::Iterator i(peersToRemove); i.hasNext();)
   {
      Peer* const peer = i.next();
      peerIDsRemoved << peer->peerID;
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         this->beginRemoveRows(QModelIndex(), j, j);
         this->indexedPeers.remove(peer->peerID);
         this->orderedPeers.remove(peer);
         delete peer;
         this->endRemoveRows();
      }
   }

   if (!peerIDsRemoved.isEmpty())
      emit peersRemoved(peerIDsRemoved);

   for (QListIterator<Peer*> i(peersToAdd); i.hasNext();)
   {
      Peer* const peer = i.next();
      int pos = this->orderedPeers.insert(peer);
      this->beginInsertRows(QModelIndex(), pos, pos);
      this->indexedPeers.insert(peer->peerID, peer);
      this->endInsertRows();
   }
}
Example #23
0
void MsScWriter::note(const QString pitch, const QVector<Bww::BeamType> beamList,
                      const QString type, const int dots,
                      bool tieStart, bool /*TODO tieStop */,
                      StartStop triplet,
                      bool grace)
      {
      qDebug() << "MsScWriter::note()"
               << "type:" << type
               << "dots:" << dots
               << "grace" << grace
      ;

      if (!stepAlterOctMap.contains(pitch)
          || !typeMap.contains(type)) {
            // TODO: error message
            return;
            }
      StepAlterOct sao = stepAlterOctMap.value(pitch);

      int ticks = 4 * Ms::MScore::division / type.toInt();
      if (dots) ticks = 3 * ticks / 2;
      qDebug() << "ticks:" << ticks;
      Ms::TDuration durationType(Ms::TDuration::DurationType::V_INVALID);
      durationType.setVal(ticks);
      qDebug() << "duration:" << durationType.name();
      if (triplet != ST_NONE) ticks = 2 * ticks / 3;

      Ms::Beam::Mode bm  = (beamList.at(0) == Bww::BM_BEGIN) ? Ms::Beam::Mode::BEGIN : Ms::Beam::Mode::AUTO;
      Ms::Direction sd = Ms::Direction::AUTO;

      // create chord
      Ms::Chord* cr = new Ms::Chord(score);
      //ws cr->setTick(tick);
      cr->setBeamMode(bm);
      cr->setTrack(0);
      if (grace) {
            cr->setNoteType(Ms::NoteType::GRACE32);
            cr->setDurationType(Ms::TDuration::DurationType::V_32ND);
            sd = Ms::Direction::UP;
            }
      else {
            if (durationType.type() == Ms::TDuration::DurationType::V_INVALID)
                  durationType.setType(Ms::TDuration::DurationType::V_QUARTER);
            cr->setDurationType(durationType);
            sd = Ms::Direction::DOWN;
            }
      cr->setDuration(durationType.fraction());
      cr->setDots(dots);
      cr->setStemDirection(sd);
      // add note to chord
      Ms::Note* note = new Ms::Note(score);
      note->setTrack(0);
      xmlSetPitch(note, sao.s.toLatin1(), sao.a, sao.o);
      if (tieStart) {
            Ms::Tie* tie = new Ms::Tie(score);
            note->setTieFor(tie);
            tie->setStartNote(note);
            tie->setTrack(0);
            }
      cr->add(note);
      // add chord to measure
      if (!grace) {
            Ms::Segment* s = currentMeasure->getSegment(Ms::Segment::Type::ChordRest, tick);
            s->add(cr);
            if (!currentGraceNotes.isEmpty()) {
                  for (int i = currentGraceNotes.size() - 1; i >=0; i--)
                        cr->add(currentGraceNotes.at(i));
                  currentGraceNotes.clear();
                  }
            doTriplet(cr, triplet);
            int tickBefore = tick;
            tick += ticks;
            Ms::Fraction nl(Ms::Fraction::fromTicks(tick - currentMeasure->tick()));
            currentMeasure->setLen(nl);
            qDebug() << "MsScWriter::note()"
                     << "tickBefore:" << tickBefore
                     << "tick:" << tick
                     << "nl:" << nl.print()
            ;
            }
      else {
            currentGraceNotes.append(cr);
            }
      }
Example #24
0
int main(int argc, char **argv)
{
#if (QT_VERSION < 0x050200)
        #error("You need Qt 5.2.0 or later to compile Actiona Executer");
#endif

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    QtSingleApplication app("actiona-exec", argc, argv);
#else
    ActionTools::NativeEventFilteringApplication app("actiona-exec", argc, argv);
#endif
	app.setQuitOnLastWindowClosed(false);

	qAddPostRoutine(cleanup);

	qsrand(std::time(NULL));

#ifdef Q_OS_LINUX
    notify_init("Actiona executer");
#endif

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif

    QxtCommandOptions preOptions;

    preOptions.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder"));
    preOptions.alias("portable", "p");
    preOptions.parse(QCoreApplication::arguments());

    if(preOptions.count("portable") > 0)
    {
        QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, QApplication::applicationDirPath() + "/userSettings");
        QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, QApplication::applicationDirPath() + "/systemSettings");
        QSettings::setDefaultFormat(QSettings::IniFormat);
    }

    QString locale = Tools::locale();

    Tools::installQtTranslator(locale);
    Tools::installTranslator("tools", locale);
    Tools::installTranslator("actiontools", locale);
    Tools::installTranslator("executer", locale);
    Tools::installTranslator("actexecuter", locale);

    const QStringList &arguments = QCoreApplication::arguments();

    QxtCommandOptions options;
    options.setFlagStyle(QxtCommandOptions::DoubleDash);
    options.setScreenWidth(0);
    options.add("code", QObject::tr("switch to code mode, may not be used with -s"));
    options.alias("code", "c");
    options.add("script", QObject::tr("switch to script mode, may not be used with -c"));
    options.alias("script", "s");
    options.add("nocodeqt", QObject::tr("do not include the Qt library into the code"));
    options.alias("nocodeqt", "Q");
    options.add("portable", QObject::tr("starts in portable mode, storing the settings in the executable folder"));
    options.alias("portable", "p");
    options.add("proxy-mode", QObject::tr("sets the proxy mode, values are \"none\", \"system\" (default) or \"custom\""));
    options.add("proxy-type", QObject::tr("sets the custom proxy type, values are \"http\" or \"socks\" (default)"));
    options.add("proxy-host", QObject::tr("sets the custom proxy host"));
    options.add("proxy-port", QObject::tr("sets the custom proxy port"));
    options.add("proxy-user", QObject::tr("sets the custom proxy user"));
    options.add("proxy-password", QObject::tr("sets the custom proxy password"));
#ifdef Q_OS_WIN
    options.add("console", QObject::tr("create a console to see debug output"));
    options.add("pause-at-end", QObject::tr("wait for user input at the end of the execution, used only with --console"));
#endif
    options.add("version", QObject::tr("show the program version"));
    options.alias("version", "v");
    options.add("help", QObject::tr("show this help text"));
    options.alias("help", "h");
    options.parse(arguments);

#ifdef Q_OS_WIN
    if(options.count("console"))
    {
        createConsole();

        if(options.count("pause-at-end"))
            qAddPostRoutine(pause);
    }
#endif

	qRegisterMetaType<ActionTools::ActionInstance>("ActionInstance");
	qRegisterMetaType<ActionTools::ActionException::Exception>("Exception");
	qRegisterMetaType<ActionTools::Parameter>("Parameter");
	qRegisterMetaType<ActionTools::SubParameter>("SubParameter");
	qRegisterMetaType<Tools::Version>("Version");

	qRegisterMetaTypeStreamOperators<ActionTools::ActionInstance>("ActionInstance");
	qRegisterMetaTypeStreamOperators<ActionTools::Parameter>("Parameter");
	qRegisterMetaTypeStreamOperators<ActionTools::SubParameter>("SubParameter");
	qRegisterMetaTypeStreamOperators<Tools::Version>("Version");

	if(options.count("version"))
	{
		QTextStream stream(stdout);
        stream << "Actiona Executer version " << Global::ACTIONA_VERSION.toString() << ", script version " << Global::SCRIPT_VERSION.toString() << "\n";
		stream.flush();
		return 0;
	}
	if(options.count("help") || options.showUnrecognizedWarning() || options.positional().count() < 1 || (options.count("code") && options.count("script")))
	{
		QTextStream stream(stdout);
		stream << QObject::tr("usage: ") << QCoreApplication::arguments().at(0) << " " << QObject::tr("[parameters]") << " " << QObject::tr("filename") << "\n";
		stream << QObject::tr("Parameters are:") << "\n";
		stream << options.getUsage();
		stream.flush();
		return -1;
	}

	app.addLibraryPath(QApplication::applicationDirPath() + "/actions");
	app.addLibraryPath(QApplication::applicationDirPath() + "/plugins");

	if(!options.count("nocodeqt"))
		app.addLibraryPath(QApplication::applicationDirPath() + "/code");

#ifdef Q_OS_LINUX
	{
#ifdef ACT_PROFILE
		Tools::HighResolutionTimer timer("Load key codes");
#endif
		ActionTools::KeySymHelper::loadKeyCodes();
	}
#endif

	// Proxy settings
	int proxyMode = ActionTools::Settings::PROXY_SYSTEM;
	if(options.value("proxy-mode").toString() == "none")
		proxyMode = ActionTools::Settings::PROXY_NONE;
	else if(options.value("proxy-mode").toString() == "custom")
		proxyMode = ActionTools::Settings::PROXY_CUSTOM;
	else if(options.value("proxy-mode").toString() == "system")
		proxyMode = ActionTools::Settings::PROXY_SYSTEM;
	else if(!options.value("proxy-mode").toString().isEmpty())
	{
		QTextStream stream(stdout);
		stream << QObject::tr("Unknown proxy mode, values are \"none\", \"system\" (default) or \"custom\"") << "\n";
		stream.flush();
		return -1;
	}

	QNetworkProxy proxy;

	switch(proxyMode)
	{
	case ActionTools::Settings::PROXY_NONE:
		proxy.setType(QNetworkProxy::NoProxy);
		break;
	case ActionTools::Settings::PROXY_SYSTEM:
		{
			QUrl url(Global::CONNECTIVITY_URL);
			QNetworkProxyQuery networkProxyQuery(url);
			QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(networkProxyQuery);
			if(!listOfProxies.isEmpty())
				proxy = listOfProxies.first();
			else
				proxy.setType(QNetworkProxy::NoProxy);
		}
		break;
	case ActionTools::Settings::PROXY_CUSTOM:
		{
			int type = ActionTools::Settings::PROXY_TYPE_SOCKS5;
			if(options.value("proxy-type").toString() == "http")
				type = ActionTools::Settings::PROXY_TYPE_HTTP;
			else if(options.value("proxy-type").toString() == "socks")
				type = ActionTools::Settings::PROXY_TYPE_SOCKS5;
			else if(!options.value("proxy-type").toString().isEmpty())
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown proxy type, values are \"http\" or \"socks\" (default)") << "\n";
				stream.flush();
				return -1;
			}

			QNetworkProxy proxy;

			if(type == ActionTools::Settings::PROXY_TYPE_HTTP)
				proxy.setType(QNetworkProxy::HttpProxy);
			else
				proxy.setType(QNetworkProxy::Socks5Proxy);

			proxy.setHostName(options.value("proxy-host").toString());
			proxy.setPort(options.value("proxy-port").toInt());
			proxy.setUser(options.value("proxy-user").toString());
			proxy.setPassword(options.value("proxy-password").toString());
		}
		break;
	}

	QNetworkProxy::setApplicationProxy(proxy);

	QUrl protocolUrl = QUrl::fromEncoded(arguments.at(1).toUtf8());
    if(protocolUrl.isValid() && protocolUrl.scheme() != "actiona")
		protocolUrl = QUrl();

	MainClass::ExecutionMode executionMode = MainClass::Unknown;
	MainClass mainClass;

	if(protocolUrl.isValid())
	{
		QString mode;
        using QStringPair = QPair<QString, QString>;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        for(const QStringPair &queryItem: QUrlQuery(protocolUrl.query()).queryItems())
#else
        for(const QStringPair &queryItem: protocolUrl.queryItems())
#endif
		{
			if(queryItem.first == "mode")
			{
				mode = queryItem.second;
				break;
			}
		}

		if(mode == "code")
			executionMode = MainClass::Code;
		else if(mode == "script")
			executionMode = MainClass::Script;
		else
		{
			if(protocolUrl.path().endsWith(".ascr"))
				executionMode = MainClass::Script;
			else if(protocolUrl.path().endsWith(".acod"))
				executionMode = MainClass::Code;
			else
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown execution mode, please specify mode=script or mode=code") << "\n";
				stream.flush();
				return -1;
			}
		}

		if(!mainClass.start(executionMode, protocolUrl))
			return -1;
	}
	else
	{
		QString filename = options.positional().at(0);

		if(options.count("code"))
			executionMode = MainClass::Code;
		else if(options.count("script"))
			executionMode = MainClass::Script;
		else
		{
			if(filename.endsWith(".ascr"))
				executionMode = MainClass::Script;
			else if(filename.endsWith(".acod"))
				executionMode = MainClass::Code;
			else
			{
				QTextStream stream(stdout);
				stream << QObject::tr("Unknown execution mode, please specify -s (script) or -c (code)") << "\n";
				stream.flush();
				return -1;
			}
		}

		QFile file(filename);
		if(!file.open(QIODevice::ReadOnly))
		{
			QTextStream stream(stdout);
			stream << QObject::tr("Unable to read input file") << "\n";
			stream.flush();
			return -1;
		}

		if(!mainClass.start(executionMode, &file, file.fileName()))
		{
			file.close();

			return -1;
		}
	}

	return app.exec();
}
Example #25
0
void RadialMap::Widget::dropEvent(QDropEvent *e)
{
    QList<QUrl> uriList = KUrlMimeData::urlsFromMimeData(e->mimeData());
    if (!uriList.isEmpty())
        emit giveMeTreeFor(uriList.first());
}
void QgsGraduatedSymbolRendererV2::updateClasses( QgsVectorLayer *vlayer, Mode mode, int nclasses )
{
  if ( mAttrName.isEmpty() )
    return;

  setMode( mode );
  // Custom classes are not recalculated
  if ( mode == Custom )
    return;

  if ( nclasses < 1 )
    nclasses = 1;

  QList<double> values;
  bool valuesLoaded = false;
  double minimum;
  double maximum;

  int attrNum = vlayer->fieldNameIndex( mAttrName );

  bool ok;
  if ( attrNum == -1 )
  {
    values = vlayer->getDoubleValues( mAttrName, ok );
    if ( !ok || values.isEmpty() )
      return;

    qSort( values ); // vmora: is wondering if O( n log(n) ) is really necessary here, min and max are O( n )
    minimum = values.first();
    maximum = values.last();
    valuesLoaded = true;
  }
  else
  {
    minimum = vlayer->minimumValue( attrNum ).toDouble();
    maximum = vlayer->maximumValue( attrNum ).toDouble();
  }

  QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) );
  QList<double> breaks;
  QList<double> labels;
  if ( mode == EqualInterval )
  {
    breaks = _calcEqualIntervalBreaks( minimum, maximum, nclasses );
  }
  else if ( mode == Pretty )
  {
    breaks = QgsSymbolLayerV2Utils::prettyBreaks( minimum, maximum, nclasses );
  }
  else if ( mode == Quantile || mode == Jenks || mode == StdDev )
  {
    // get values from layer
    if ( !valuesLoaded )
    {
      values = vlayer->getDoubleValues( mAttrName, ok );
    }

    // calculate the breaks
    if ( mode == Quantile )
    {
      breaks = _calcQuantileBreaks( values, nclasses );
    }
    else if ( mode == Jenks )
    {
      breaks = _calcJenksBreaks( values, nclasses, minimum, maximum );
    }
    else if ( mode == StdDev )
    {
      breaks = _calcStdDevBreaks( values, nclasses, labels );
    }
  }
  else
  {
    Q_ASSERT( false );
  }

  double lower, upper = minimum;
  QString label;
  deleteAllClasses();

  // "breaks" list contains all values at class breaks plus maximum as last break

  int i = 0;
  for ( QList<double>::iterator it = breaks.begin(); it != breaks.end(); ++it, ++i )
  {
    lower = upper; // upper border from last interval
    upper = *it;

    // Label - either StdDev label or default label for a range
    if ( mode == StdDev )
    {
      if ( i == 0 )
      {
        label = "< " + QString::number( labels[i], 'f', 2 ) + " Std Dev";
      }
      else if ( i == labels.count() - 1 )
      {
        label = ">= " + QString::number( labels[i-1], 'f', 2 ) + " Std Dev";
      }
      else
      {
        label = QString::number( labels[i-1], 'f', 2 ) + " Std Dev" + " - " + QString::number( labels[i], 'f', 2 ) + " Std Dev";
      }
    }
    else
    {
      label = mLabelFormat.labelForRange( lower, upper );
    }
    QgsSymbolV2* newSymbol = mSourceSymbol ? mSourceSymbol->clone() : QgsSymbolV2::defaultSymbol( vlayer->geometryType() );
    addClass( QgsRendererRangeV2( lower, upper, newSymbol, label ) );
  }
  updateColorRamp( 0, mInvertedColorRamp );
}
Example #27
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (ent)
            results.setHostName(QString::fromLatin1(ent->h_name));
#endif

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(aceHostname.constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
#if !defined(Q_OS_VXWORKS)
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
#endif
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
bool Slash::targetsFeasible(const QList<const ClientPlayer *> &targets) const{   
    return !targets.isEmpty();
}
Example #29
0
void PlayQueueView::setMode(ItemView::Mode m)
{
    if (m==mode || (ItemView::Mode_GroupedTree!=m && ItemView::Mode_Table!=m)) {
        return;
    }

    if (ItemView::Mode_Table==mode) {
        treeView->saveHeader();
    }

    switch (m) {
    case ItemView::Mode_GroupedTree:
        if (!groupedView) {
            groupedView=new PlayQueueGroupedView(this);
            groupedView->setContextMenuPolicy(Qt::ActionsContextMenu);
            groupedView->setIndentation(0);
            groupedView->setItemsExpandable(false);
            groupedView->setExpandsOnDoubleClick(false);
            groupedView->installFilter(new KeyEventHandler(groupedView, removeFromAction));
            addWidget(groupedView);
            connect(groupedView, SIGNAL(itemsSelected(bool)), SIGNAL(itemsSelected(bool)));
            connect(groupedView, SIGNAL(doubleClicked(const QModelIndex &)), SIGNAL(doubleClicked(const QModelIndex &)));
            updatePalette();
            #ifdef Q_OS_MAC
            groupedView->setAttribute(Qt::WA_MacShowFocusRect, 0);
            #endif
            groupedView->setProperty(ProxyStyle::constModifyFrameProp, ProxyStyle::VF_Top);
        }
        break;
    case ItemView::Mode_Table:
        if (!treeView) {
            treeView=new PlayQueueTreeView(this);
            treeView->setContextMenuPolicy(Qt::ActionsContextMenu);
            treeView->installFilter(new KeyEventHandler(treeView, removeFromAction));
            treeView->initHeader();
            addWidget(treeView);
            connect(treeView, SIGNAL(itemsSelected(bool)), SIGNAL(itemsSelected(bool)));
            connect(treeView, SIGNAL(doubleClicked(const QModelIndex &)), SIGNAL(doubleClicked(const QModelIndex &)));
            updatePalette();
            #ifdef Q_OS_MAC
            treeView->setAttribute(Qt::WA_MacShowFocusRect, 0);
            #endif
            treeView->setProperty(ProxyStyle::constModifyFrameProp, ProxyStyle::VF_Top);
        }
    default:
        break;
    }

    QAbstractItemModel *model=0;
    QList<QAction *> actions;
    if (ItemView::Mode_Count!=mode) {
        QAbstractItemView *v=view();
        model=v->model();
        v->setModel(0);
        actions=v->actions();
    }

    mode=m;
    QAbstractItemView *v=view();
    v->setModel(model);
    if (!actions.isEmpty() && v->actions().isEmpty()) {
        v->addActions(actions);
    }

    if (ItemView::Mode_Table==mode) {
        treeView->initHeader();
    }

    setCurrentWidget(static_cast<QWidget *>(view()));
    if (spinner) {
        spinner->setWidget(view());
        if (spinner->isActive()) {
            spinner->start();
        }
    }
    if (msgOverlay) {
        msgOverlay->setWidget(view());
    }
}
Example #30
0
void Analeptic::use(Room *room, ServerPlayer *source, const QList<ServerPlayer *> &targets) const{
    BasicCard::use(room, source, targets);
    if(targets.isEmpty())
        room->cardEffect(this, source, source);
}