Exemplo n.º 1
0
void QgsIdentifyResultsDialog::addFeature( QgsMapToolIdentify::IdentifyResult result )
{
  if ( result.mLayer->type() == QgsMapLayer::VectorLayer )
  {
    addFeature( qobject_cast<QgsVectorLayer *>( result.mLayer ), result.mFeature, result.mDerivedAttributes );
  }
  else if ( result.mLayer->type() == QgsMapLayer::RasterLayer )
  {
    addFeature( qobject_cast<QgsRasterLayer *>( result.mLayer ), result.mLabel, result.mAttributes, result.mDerivedAttributes, result.mFields,  result.mFeature, result.mParams );
  }
}
Exemplo n.º 2
0
	static void parseShaderFeatures( bool* pShaderEnabled, List< ShaderFeature >* pShaderFeatures, const char** pShaderTypes, uint typeCount, const string& featuresLine )
	{
		for (uint i = 0u; i < typeCount; ++i)
		{
			const string search = formatString( "%s-features=", pShaderTypes[ i ] );

			const int index = featuresLine.indexOf( search );
			pShaderEnabled[ i ] = ( index >= 0 );

			if ( index != -1 )
			{
				const int baseIndex = int( index + search.getLength() );
				const int length = featuresLine.indexOf( ' ', baseIndex ) - baseIndex;
				const string featuresString = featuresLine.subString( baseIndex, length );

				Array< string > featuresList;
				featuresString.trim().split( featuresList, "," );

				for (uint j = 0u; j < featuresList.getCount(); ++j)
				{
					string name = featuresList[ j ];
					uint32 maxValue = 1u;

					int arrayIndex = name.indexOf( '[' );
					if ( arrayIndex != -1 )
					{
						arrayIndex++;
						const int arrayLength = name.indexOf( ']' ) - arrayIndex;
						if ( arrayLength < 0u )
						{
							TIKI_TRACE_ERROR( "invalid shader feature name: %s. feature will be ignored.\n", name.cStr() );
							continue;
						}

						const string maxValueString = name.subString( arrayIndex, arrayLength );
						maxValue	= ParseString::parseUInt32( maxValueString.cStr() ) - 1u;
						name		= name.subString( 0u, arrayIndex - 1 );
					}

					if ( i == 0u ) // fx feature will be applied to all shaders in file
					{
						for (uint k = 1u; k < typeCount; ++k)
						{
							addFeature( pShaderFeatures[ i ], name, maxValue );
						}
					}

					addFeature( pShaderFeatures[ i ], name, maxValue );
				}

				featuresList.dispose();
			}
		}
	}
Exemplo n.º 3
0
void ADC::HubUser::addFeatures(char* feats) {
	if (!feats) return;

	char* it = &feats[0];
	while (strlen(it) > 4) {
		addFeature(strndup(it, 4));
		it = &it[5];
	}
	
	if (strlen(it) > 0) {
		addFeature(strdup(it));
	}
}
Exemplo n.º 4
0
SessionImpl::SessionImpl(const std::string& init):
	_init(init),
	_f(false),
	_connected(true)
{
	addFeature("f1", &SessionImpl::setF, &SessionImpl::getF);
	addFeature("f2", 0, &SessionImpl::getF);
	addFeature("f3", &SessionImpl::setF, 0);
	addFeature("connected", &SessionImpl::setConnected, &SessionImpl::getConnected);
	addProperty("p1", &SessionImpl::setP, &SessionImpl::getP);
	addProperty("p2", 0, &SessionImpl::getP);
	addProperty("p3", &SessionImpl::setP, &SessionImpl::getP);
}
Exemplo n.º 5
0
  void HandTask::updateTransAndThetaU(vpHomogeneousMatrix& hmdMhm)
  {
    if ( _trans.get() == NULL )
    {
      _trans.reset( new vpFeatureTranslation(hmdMhm, vpFeatureTranslation::cdMc) );
      _thetaU.reset( new vpFeatureThetaU(hmdMhm, vpFeatureThetaU::cdRc) );

      addFeature(*_trans);
      addFeature(*_thetaU);
    }
    else
    {
      _trans->buildFrom(hmdMhm);
      _thetaU->buildFrom(hmdMhm);
    }
  }
Exemplo n.º 6
0
void QgsMapToolAddFeature::digitized( QgsFeature &f )
{
  QgsVectorLayer *vlayer = currentVectorLayer();
  bool res = addFeature( vlayer, &f, false );

  if ( res && ( mode() == CaptureLine || mode() == CapturePolygon ) )
  {
    //add points to other features to keep topology up-to-date
    bool topologicalEditing = QgsProject::instance()->topologicalEditing();

    //use always topological editing for avoidIntersection.
    //Otherwise, no way to guarantee the geometries don't have a small gap in between.
    QList<QgsVectorLayer *> intersectionLayers = QgsProject::instance()->avoidIntersectionsLayers();
    bool avoidIntersection = !intersectionLayers.isEmpty();
    if ( avoidIntersection ) //try to add topological points also to background layers
    {
      const auto constIntersectionLayers = intersectionLayers;
      for ( QgsVectorLayer *vl : constIntersectionLayers )
      {
        //can only add topological points if background layer is editable...
        if ( vl->geometryType() == QgsWkbTypes::PolygonGeometry && vl->isEditable() )
        {
          vl->addTopologicalPoints( f.geometry() );
        }
      }
    }
    else if ( topologicalEditing )
    {
      vlayer->addTopologicalPoints( f.geometry() );
    }
  }
}
Exemplo n.º 7
0
double MaxEntModel::getObsCounts(EventSet& events, vector<double>& obsCounts)
{
  vector<double> probs;
  obsCounts.clear();
  obsCounts.assign(_lambda.size(), 0);
  double maxFtSum = 0;
  for (unsigned int i = 0; i<events.size(); i++) {
    MaxEntEvent& e = *events[i];
    unsigned long c = e.classId();
    double count = e.count();
    double ftSum = 0;
    for (unsigned long j=0; j<e.size(); j++) {
      FtMap::iterator it = _index.find(e[j]);
      if (it!=_index.end()) 
	obsCounts[it->second+c] += count;
      else { // new feature, need to expand obsCounts and _lambda
	for (unsigned int k = 0; k<_classes; k++) 
	  obsCounts.push_back(0);
	obsCounts[_lambda.size()+c] += count;
	addFeature(e[j]);
      }
      ftSum++;
    }
    if (ftSum>maxFtSum)
      maxFtSum = ftSum;
  }
  return maxFtSum;
}
Exemplo n.º 8
0
void FeatureSet::addFeatures(const std::vector<Feature>& features)
{
    for (size_t i = 0; i < features.size(); ++i)
    {
        addFeature(features[i]);
    }
}
Tile Tile::createTile(std::vector<ProjectedFeature>& features,
                      uint32_t z2,
                      uint32_t tx,
                      uint32_t ty,
                      double tolerance,
                      bool noSimplify) {
    Tile tile;

    tile.z2 = z2;
    tile.tx = tx;
    tile.ty = ty;

    for (const auto& feature : features) {
        tile.numFeatures++;
        addFeature(tile, feature, tolerance, noSimplify);

        const auto& min = feature.min;
        const auto& max = feature.max;

        if (min.x < tile.min.x)
            tile.min.x = min.x;
        if (min.y < tile.min.y)
            tile.min.y = min.y;
        if (max.x > tile.max.x)
            tile.max.x = max.x;
        if (max.y > tile.max.y)
            tile.max.y = max.y;
    }

    return std::move(tile);
}
Exemplo n.º 10
0
void VisionRequestItem::setFeatures(const std::vector<Feature>& features)
{
    _json["features"].clear();

    for (auto& feature: features)
    {
        addFeature(feature);
    }
}
Exemplo n.º 11
0
bool QgsVectorLayerExporter::addFeatures( QgsFeatureList &features, Flags flags )
{
  QgsFeatureList::iterator fIt = features.begin();
  bool result = true;
  for ( ; fIt != features.end(); ++fIt )
  {
    result = result && addFeature( *fIt, flags );
  }
  return result;
}
Exemplo n.º 12
0
void QgsMapToolAddFeature::activate()
{
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );
  if ( vlayer && vlayer->geometryType() == QGis::NoGeometry )
  {
    QgsFeature f;
    addFeature( vlayer, &f, false );
    return;
  }

  QgsMapToolCapture::activate();
}
Exemplo n.º 13
0
bool QgsVectorLayerEditBuffer::addFeatures( QgsFeatureList& features )
{
  if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures ) )
    return false;

  for ( QgsFeatureList::iterator iter = features.begin(); iter != features.end(); ++iter )
  {
    addFeature( *iter );
  }

  L->updateExtents();
  return true;
}
Exemplo n.º 14
0
States::States ( const cv::Mat& kx ) :
    X(cv::Vec3d( kx.at<double>(0,0), kx.at<double>(1,0), kx.at<double>(2,0)) ),
    V( cv::Vec3d( kx.at<double>(3,0), kx.at<double>(4,0), kx.at<double>(5,0)) ),
    b( cv::Vec3d( kx.at<double>(6,0), kx.at<double>(7,0), kx.at<double>(8,0) ) )
{
    int nf;
    nf = (kx.rows-9)/3;
    for( int i=0; i<nf; ++i )
    {
        addFeature(Feature( cv::Vec3d( kx.at<double>(9+3*i,0), 
            kx.at<double>(10+3*i,0), kx.at<double>(11+3*i,0) ), 0 )); 
    }
    return ;
}		/* -----  end of method States::States  ----- */
Exemplo n.º 15
0
void FeatureIndex::query(
        std::unordered_map<std::string, std::vector<Feature>>& result,
        const GeometryCollection& queryGeometry,
        const float bearing,
        const double tileSize,
        const double scale,
        const optional<std::vector<std::string>>& filterLayerIDs,
        const GeometryTile& geometryTile,
        const CanonicalTileID& tileID,
        const style::Style& style) const {

    mapbox::geometry::box<int16_t> box = mapbox::geometry::envelope(queryGeometry);

    const float pixelsToTileUnits = util::EXTENT / tileSize / scale;
    const int16_t additionalRadius = std::min<int16_t>(util::EXTENT, std::ceil(style.getQueryRadius() * pixelsToTileUnits));
    std::vector<IndexedSubfeature> features = grid.query({ box.min - additionalRadius, box.max + additionalRadius });

    std::sort(features.begin(), features.end(), topDown);
    size_t previousSortIndex = std::numeric_limits<size_t>::max();
    for (const auto& indexedFeature : features) {

        // If this feature is the same as the previous feature, skip it.
        if (indexedFeature.sortIndex == previousSortIndex) continue;
        previousSortIndex = indexedFeature.sortIndex;

        addFeature(result, indexedFeature, queryGeometry, filterLayerIDs, geometryTile, tileID, style, bearing, pixelsToTileUnits);
    }

    // query symbol features
    assert(collisionTile);
    std::vector<IndexedSubfeature> symbolFeatures = collisionTile->queryRenderedSymbols(box, scale);
    std::sort(symbolFeatures.begin(), symbolFeatures.end(), topDownSymbols);
    for (const auto& symbolFeature : symbolFeatures) {
        addFeature(result, symbolFeature, queryGeometry, filterLayerIDs, geometryTile, tileID, style, bearing, pixelsToTileUnits);
    }
}
template <typename PointFeature> void
pcl::PyramidFeatureHistogram<PointFeature>::compute ()
{
  if (!initializeHistogram ())
    return;

  for (size_t feature_i = 0; feature_i < input_->points.size (); ++feature_i)
  {
    std::vector<float> feature_vector;
    convertFeatureToVector (input_->points[feature_i], feature_vector);
    addFeature (feature_vector);
  }

  is_computed_ = true;
}
Exemplo n.º 17
0
void FeatureSet::merge( const FeatureSet &features )
{
   PROFILE_SCOPE( FeatureSet_Merge );

   if ( mFeatures.empty() )
   {
      mFeatures.merge( features.mFeatures );
      mDescription = features.mDescription;
      return;
   }

   for ( U32 i=0; i < features.mFeatures.size(); i++ )
      addFeature( *features.mFeatures[i].type, 
                  features.mFeatures[i].index );
}
Exemplo n.º 18
0
SessionImpl::SessionImpl(const std::string& fileName, std::size_t loginTimeout):
	Poco::Data::AbstractSessionImpl<SessionImpl>(fileName, loginTimeout),
	_connector(Connector::KEY),
	_pDB(0),
	_connected(false),
	_isTransaction(false)
{
	open();
	setConnectionTimeout(CONNECTION_TIMEOUT_DEFAULT);
	setProperty("handle", _pDB);
	addFeature("autoCommit", 
		&SessionImpl::autoCommit, 
		&SessionImpl::isAutoCommit);
	addProperty("connectionTimeout", &SessionImpl::setConnectionTimeout, &SessionImpl::getConnectionTimeout);
}
Exemplo n.º 19
0
  // ---- Disco ----
  Disco::Disco( ClientBase* parent )
    : m_parent( parent ), m_form( 0 )
  {
    addFeature( XMLNS_VERSION );
//     addFeature( XMLNS_DISCO_INFO ); //handled by Disco::Info now
//     addFeature( XMLNS_DISCO_ITEMS ); //handled by Disco::Info now
    if( m_parent )
    {
      m_parent->registerIqHandler( this, ExtDiscoInfo );
      m_parent->registerIqHandler( this, ExtDiscoItems );
      m_parent->registerIqHandler( this, ExtVersion );
      m_parent->registerStanzaExtension( new Disco::Info() );
      m_parent->registerStanzaExtension( new Disco::Items() );
      m_parent->registerStanzaExtension( new SoftwareVersion() );
    }
  }
void hgSeqRange(char *db, char *chrom, int chromStart, int chromEnd, char strand,
                char *name)
/* Print out dna sequence for the given range. */
{
    int count = 0;
    unsigned starts[1];
    unsigned sizes[1];
    boolean exonFlags[1];
    boolean cdsFlags[1];
    int chromSize = hgSeqChromSize(db, chrom);
    maxStartsOffset = 0;
    addFeature(&count, starts, sizes, exonFlags, cdsFlags,
               chromStart, chromEnd - chromStart, FALSE, FALSE, chromSize);

    hgSeqRegionsDb(db, chrom, chromSize, strand, name, FALSE, count, starts, sizes, exonFlags,
                   cdsFlags);
}
Exemplo n.º 21
0
void QgsMapToolAddFeature::activate()
{
  if ( !mCanvas || mCanvas->isDrawing() )
  {
    return;
  }

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );
  if ( vlayer && vlayer->geometryType() == QGis::NoGeometry )
  {
    QgsFeature f;
    addFeature( vlayer, &f );
    return;
  }

  QgsMapTool::activate();
}
Exemplo n.º 22
0
FeatureSet::FeatureSet(FeatureSet* pOther)
{
    if (pOther == NULL)
    {
        return;
    }
    m_nDescriptorLength = pOther->m_nDescriptorLength;
    m_nFrameLength = pOther->m_nFrameLength;
    m_nNumFeatures = 0;
    for (int nFeature = 0; nFeature < pOther->m_nNumFeatures; nFeature++)
    {
        float* pDescCopy = new float[m_nDescriptorLength];
        float* pFrameCopy = new float[m_nFrameLength];
        memcpy(pDescCopy, pOther->m_vDescriptors[nFeature], m_nDescriptorLength * sizeof(float));
        memcpy(pFrameCopy, pOther->m_vFrames[nFeature], m_nFrameLength * sizeof(float));
        addFeature(pDescCopy, pFrameCopy);
    } // nFeature
}
Exemplo n.º 23
0
bool QgsGPXProvider::addFeatures( QgsFeatureList & flist )
{

  // add all the features
  for ( QgsFeatureList::iterator iter = flist.begin();
        iter != flist.end(); ++iter )
  {
    if ( !addFeature( *iter ) )
      return false;
  }

  // write back to file
  QFile file( mFileName );
  if ( !file.open( QIODevice::WriteOnly ) )
    return false;
  QTextStream ostr( &file );
  data->writeXML( ostr );
  return true;
}
Exemplo n.º 24
0
    void Keyframe::deserialize( XMLNode* node )
    {
        // TODO:
        if( node->name() != "Keyframe" ){
            throw CVTException( "this is not a Keyframe node" );
        }

        _id = node->childByName( "id" )->value().toInteger();

        XMLNode * n;
        n = node->childByName( "Pose" );
        if( n != NULL ){
            Matrix4d m = Matrix4d::fromString( n->child( 0 )->value() );
            Eigen::Matrix4d eM;
            EigenBridge::toEigen( eM, m );
            _pose.set( eM );
        }

        n = node->childByName( "Image" );
        if( n ){
            _img = new Image();
            String fileName = n->childByName( "file" )->value();
            std::cout << "Loading file: " << fileName << std::endl;
            _img->load( fileName );
        }

        // the measurements:
        n = node->childByName( "Measurements" );
        size_t numMeas = n->childSize();
        MapMeasurement mm;
        _featMeas.clear();
        for( size_t i = 0; i < numMeas; i++ ){
            XMLNode* mapMeasNode = n->child( i );
            size_t measId = mapMeasNode->childByName( "featureId" )->value().toInteger();

            XMLNode* measNode = mapMeasNode->childByName( "PointMeasurement" );
            mm.deserialize( measNode );

            addFeature( mm, measId );
        }
    }
Exemplo n.º 25
0
std::unordered_map<std::string, std::vector<Feature>>
FeatureIndex::lookupSymbolFeatures(const std::vector<IndexedSubfeature>& symbolFeatures,
                                   const RenderedQueryOptions& queryOptions,
                                   const std::vector<const RenderLayer*>& layers,
                                   const OverscaledTileID& tileID,
                                   const std::shared_ptr<std::vector<size_t>>& featureSortOrder) const {
    std::unordered_map<std::string, std::vector<Feature>> result;
    if (!tileData) {
        return result;
    }
    std::vector<IndexedSubfeature> sortedFeatures(symbolFeatures.begin(), symbolFeatures.end());

    std::sort(sortedFeatures.begin(), sortedFeatures.end(), [featureSortOrder](const IndexedSubfeature& a, const IndexedSubfeature& b) {
        // Same idea as the non-symbol sort order, but symbol features may have changed their sort order
        // since their corresponding IndexedSubfeature was added to the CollisionIndex
        // The 'featureSortOrder' is relatively inefficient for querying but cheap to build on every bucket sort
        if (featureSortOrder) {
            // queryRenderedSymbols documentation says we'll return features in
            // "top-to-bottom" rendering order (aka last-to-first).
            // Actually there can be multiple symbol instances per feature, so
            // we sort each feature based on the first matching symbol instance.
            auto sortedA = std::find(featureSortOrder->begin(), featureSortOrder->end(), a.index);
            auto sortedB = std::find(featureSortOrder->begin(), featureSortOrder->end(), b.index);
            assert(sortedA != featureSortOrder->end());
            assert(sortedB != featureSortOrder->end());
            return sortedA > sortedB;
        } else {
            // Bucket hasn't been re-sorted based on angle, so use same "reverse of appearance in source data"
            // logic as non-symboles
            return a.sortIndex > b.sortIndex;
        }
    });

    for (const auto& symbolFeature : sortedFeatures) {
        mat4 unusedMatrix;
        addFeature(result, symbolFeature, queryOptions, tileID.canonical, layers, GeometryCoordinates(), {}, 0, unusedMatrix);
    }
    return result;
}
Exemplo n.º 26
0
void FeatureIndex::query(
        std::unordered_map<std::string, std::vector<Feature>>& result,
        const GeometryCoordinates& queryGeometry,
        const TransformState& transformState,
        const mat4& posMatrix,
        const double tileSize,
        const double scale,
        const RenderedQueryOptions& queryOptions,
        const UnwrappedTileID& tileID,
        const std::vector<const RenderLayer*>& layers,
        const float additionalQueryPadding) const {
    
    if (!tileData) {
        return;
    }

    // Determine query radius
    const float pixelsToTileUnits = util::EXTENT / tileSize / scale;
    const int16_t additionalPadding = std::min<int16_t>(util::EXTENT, additionalQueryPadding * pixelsToTileUnits);

    // Query the grid index
    mapbox::geometry::box<int16_t> box = mapbox::geometry::envelope(queryGeometry);
    std::vector<IndexedSubfeature> features = grid.query({ convertPoint<float>(box.min - additionalPadding),
                                                           convertPoint<float>(box.max + additionalPadding) });


    std::sort(features.begin(), features.end(), [](const IndexedSubfeature& a, const IndexedSubfeature& b) {
        return a.sortIndex > b.sortIndex;
    });
    size_t previousSortIndex = std::numeric_limits<size_t>::max();
    for (const auto& indexedFeature : features) {

        // If this feature is the same as the previous feature, skip it.
        if (indexedFeature.sortIndex == previousSortIndex) continue;
        previousSortIndex = indexedFeature.sortIndex;

        addFeature(result, indexedFeature, queryOptions, tileID.canonical, layers, queryGeometry, transformState, pixelsToTileUnits, posMatrix);
    }
}
Exemplo n.º 27
0
Mat EkfSlam::step(Mat u)
{
	Mat observations;
	Mat n = (Mat_<double>(2,1) << 0, 0);
	Mat v = (Mat_<double>(2,1) << 0, 0);
	Mat Y;

	// motion prediction updates covariance and state vector
	move(mState(Rect(0,0,1,3)), u, n);

	// landmark correction
	for(int i=0; i < (mState.rows-3)/2; i++) {
		v.at<double>(0) = s.at<double>(0)*r->gaussian(.5);
		v.at<double>(1) = s.at<double>(1)*r->gaussian(.5);

		Mat yi = scan(i);
		if(yi.rows) {
			observations.push_back(yi);
			yi+=v;
			correct(scan(i), v, i);
		}
	}

	// initialize any new landmarks discovered
	for(int i=(mState.rows-3)/2;;i++) { 
		Mat f = scan(i);
		if(f.rows == 2) {
			addFeature(f,i);
			observations.push_back(f);
		}
		else
			break;
	}

	// return raw sensor data for simple navigation tasks
	return observations;
}
Exemplo n.º 28
0
QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWidget *parent, Qt::WindowFlags flags )
    : QDialog( parent, flags ), mDock( NULL )
{
  mLayer = theLayer;

  setupUi( this );

  setAttribute( Qt::WA_DeleteOnClose );

  QSettings settings;
  restoreGeometry( settings.value( "/Windows/BetterAttributeTable/geometry" ).toByteArray() );

  mView->setLayer( mLayer );
  mFilterModel = ( QgsAttributeTableFilterModel * ) mView->model();
  mModel = ( QgsAttributeTableModel * )(( QgsAttributeTableFilterModel * )mView->model() )->sourceModel();

  mQuery = query;
  mColumnBox = columnBox;
  columnBoxInit();

  bool myDockFlag = settings.value( "/qgis/dockAttributeTable", false ).toBool();
  if ( myDockFlag )
  {
    mDock = new QgsAttributeTableDock( tr( "Attribute table - %1 (%n Feature(s))", "feature count", mModel->rowCount() ).arg( mLayer->name() ), QgisApp::instance() );
    mDock->setAllowedAreas( Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea );
    mDock->setWidget( this );
    connect( this, SIGNAL( destroyed() ), mDock, SLOT( close() ) );
    QgisApp::instance()->addDockWidget( Qt::BottomDockWidgetArea, mDock );
  }

  updateTitle();

  mRemoveSelectionButton->setIcon( QgisApp::getThemeIcon( "/mActionUnselectAttributes.png" ) );
  mSelectedToTopButton->setIcon( QgisApp::getThemeIcon( "/mActionSelectedToTop.png" ) );
  mCopySelectedRowsButton->setIcon( QgisApp::getThemeIcon( "/mActionCopySelected.png" ) );
  mZoomMapToSelectedRowsButton->setIcon( QgisApp::getThemeIcon( "/mActionZoomToSelected.png" ) );
  mInvertSelectionButton->setIcon( QgisApp::getThemeIcon( "/mActionInvertSelection.png" ) );
  mToggleEditingButton->setIcon( QgisApp::getThemeIcon( "/mActionToggleEditing.png" ) );
  mSaveEditsButton->setIcon( QgisApp::getThemeIcon( "/mActionSaveEdits.png" ) );
  mDeleteSelectedButton->setIcon( QgisApp::getThemeIcon( "/mActionDeleteSelected.png" ) );
  mOpenFieldCalculator->setIcon( QgisApp::getThemeIcon( "/mActionCalculateField.png" ) );
  mAddAttribute->setIcon( QgisApp::getThemeIcon( "/mActionNewAttribute.png" ) );
  mRemoveAttribute->setIcon( QgisApp::getThemeIcon( "/mActionDeleteAttribute.png" ) );

  // toggle editing
  bool canChangeAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues;
  bool canDeleteFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteFeatures;
  bool canAddAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddAttributes;
  bool canDeleteAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::DeleteAttributes;
  bool canAddFeatures = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures;

  mToggleEditingButton->setCheckable( true );
  mToggleEditingButton->setChecked( mLayer->isEditable() );
  mToggleEditingButton->setEnabled( canChangeAttributes && !mLayer->isReadOnly() );

  mSaveEditsButton->setEnabled( canChangeAttributes && mLayer->isEditable() );
  mOpenFieldCalculator->setEnabled( canChangeAttributes && mLayer->isEditable() );
  mDeleteSelectedButton->setEnabled( canDeleteFeatures && mLayer->isEditable() );
  mAddAttribute->setEnabled( canAddAttributes && mLayer->isEditable() );
  mRemoveAttribute->setEnabled( canDeleteAttributes && mLayer->isEditable() );
  mAddFeature->setEnabled( canAddFeatures && mLayer->isEditable() && mLayer->geometryType() == QGis::NoGeometry );
  mAddFeature->setHidden( !canAddFeatures || mLayer->geometryType() != QGis::NoGeometry );

  // info from table to application
  connect( this, SIGNAL( editingToggled( QgsMapLayer * ) ), QgisApp::instance(), SLOT( toggleEditing( QgsMapLayer * ) ) );
  connect( this, SIGNAL( saveEdits( QgsMapLayer * ) ), QgisApp::instance(), SLOT( saveEdits( QgsMapLayer * ) ) );

  // info from layer to table
  connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( editingToggled() ) );
  connect( mLayer, SIGNAL( editingStopped() ), this, SLOT( editingToggled() ) );

  connect( searchButton, SIGNAL( clicked() ), this, SLOT( search() ) );
  connect( mAddFeature, SIGNAL( clicked() ), this, SLOT( addFeature() ) );

  connect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( updateSelectionFromLayer() ) );
  connect( mLayer, SIGNAL( layerDeleted() ), this, SLOT( close() ) );
  connect( mView->verticalHeader(), SIGNAL( sectionClicked( int ) ), this, SLOT( updateRowSelection( int ) ) );
  connect( mView->verticalHeader(), SIGNAL( sectionPressed( int ) ), this, SLOT( updateRowPressed( int ) ) );
  connect( mModel, SIGNAL( modelChanged() ), this, SLOT( updateSelection() ) );

  if ( settings.value( "/qgis/attributeTableBehaviour", 0 ).toInt() == 2 )
  {
    connect( QgisApp::instance()->mapCanvas(), SIGNAL( extentsChanged() ), mModel, SLOT( layerModified() ) );
  }

  mLastClickedHeaderIndex = 0;
  mSelectionModel = new QItemSelectionModel( mFilterModel );
  updateSelectionFromLayer();

  //make sure to show all recs on first load
  on_cbxShowSelectedOnly_toggled( false );
}
Exemplo n.º 29
0
Library::Library(
        QObject* parent,
        UserSettingsPointer pConfig,
        mixxx::DbConnectionPoolPtr pDbConnectionPool,
        PlayerManagerInterface* pPlayerManager,
        RecordingManager* pRecordingManager)
    : m_pConfig(pConfig),
      m_pDbConnectionPool(pDbConnectionPool),
      m_pSidebarModel(new SidebarModel(parent)),
      m_pTrackCollection(new TrackCollection(pConfig)),
      m_pLibraryControl(new LibraryControl(this)),
      m_pMixxxLibraryFeature(nullptr),
      m_pPlaylistFeature(nullptr),
      m_pCrateFeature(nullptr),
      m_pAnalysisFeature(nullptr),
      m_scanner(pDbConnectionPool, m_pTrackCollection, pConfig) {

    QSqlDatabase dbConnection = mixxx::DbConnectionPooled(m_pDbConnectionPool);

    // TODO(XXX): Add a checkbox in the library preferences for checking
    // and repairing the database on the next restart of the application.
    if (pConfig->getValue(kConfigKeyRepairDatabaseOnNextRestart, false)) {
        kLogger.info() << "Checking and repairing database (if necessary)";
        m_pTrackCollection->repairDatabase(dbConnection);
        // Reset config value
        pConfig->setValue(kConfigKeyRepairDatabaseOnNextRestart, false);
    }

    kLogger.info() << "Connecting database";
    m_pTrackCollection->connectDatabase(dbConnection);

    qRegisterMetaType<Library::RemovalType>("Library::RemovalType");

    m_pKeyNotation.reset(new ControlObject(ConfigKey(kConfigGroup, "key_notation")));

    connect(&m_scanner, SIGNAL(scanStarted()),
            this, SIGNAL(scanStarted()));
    connect(&m_scanner, SIGNAL(scanFinished()),
            this, SIGNAL(scanFinished()));
    // Refresh the library models when the library (re)scan is finished.
    connect(&m_scanner, SIGNAL(scanFinished()),
            this, SLOT(slotRefreshLibraryModels()));

    // TODO(rryan) -- turn this construction / adding of features into a static
    // method or something -- CreateDefaultLibrary
    m_pMixxxLibraryFeature = new MixxxLibraryFeature(this, m_pTrackCollection,m_pConfig);
    addFeature(m_pMixxxLibraryFeature);

    addFeature(new AutoDJFeature(this, pConfig, pPlayerManager, m_pTrackCollection));
    m_pPlaylistFeature = new PlaylistFeature(this, m_pTrackCollection, m_pConfig);
    addFeature(m_pPlaylistFeature);
    m_pCrateFeature = new CrateFeature(this, m_pTrackCollection, m_pConfig);
    addFeature(m_pCrateFeature);
    BrowseFeature* browseFeature = new BrowseFeature(
        this, pConfig, m_pTrackCollection, pRecordingManager);
    connect(browseFeature, SIGNAL(scanLibrary()),
            &m_scanner, SLOT(scan()));
    connect(&m_scanner, SIGNAL(scanStarted()),
            browseFeature, SLOT(slotLibraryScanStarted()));
    connect(&m_scanner, SIGNAL(scanFinished()),
            browseFeature, SLOT(slotLibraryScanFinished()));

    addFeature(browseFeature);
    addFeature(new RecordingFeature(this, pConfig, m_pTrackCollection, pRecordingManager));
    addFeature(new SetlogFeature(this, pConfig, m_pTrackCollection));
    m_pAnalysisFeature = new AnalysisFeature(this, pConfig, m_pTrackCollection);
    connect(m_pPlaylistFeature, SIGNAL(analyzeTracks(QList<TrackId>)),
            m_pAnalysisFeature, SLOT(analyzeTracks(QList<TrackId>)));
    connect(m_pCrateFeature, SIGNAL(analyzeTracks(QList<TrackId>)),
            m_pAnalysisFeature, SLOT(analyzeTracks(QList<TrackId>)));
    addFeature(m_pAnalysisFeature);
    //iTunes and Rhythmbox should be last until we no longer have an obnoxious
    //messagebox popup when you select them. (This forces you to reach for your
    //mouse or keyboard if you're using MIDI control and you scroll through them...)
    if (RhythmboxFeature::isSupported() &&
        pConfig->getValue(ConfigKey(kConfigGroup,"ShowRhythmboxLibrary"), true)) {
        addFeature(new RhythmboxFeature(this, m_pTrackCollection));
    }
    if (pConfig->getValue(ConfigKey(kConfigGroup,"ShowBansheeLibrary"), true)) {
        BansheeFeature::prepareDbPath(pConfig);
        if (BansheeFeature::isSupported()) {
            addFeature(new BansheeFeature(this, m_pTrackCollection, pConfig));
        }
    }
    if (ITunesFeature::isSupported() &&
        pConfig->getValue(ConfigKey(kConfigGroup,"ShowITunesLibrary"), true)) {
        addFeature(new ITunesFeature(this, m_pTrackCollection));
    }
    if (TraktorFeature::isSupported() &&
        pConfig->getValue(ConfigKey(kConfigGroup,"ShowTraktorLibrary"), true)) {
        addFeature(new TraktorFeature(this, m_pTrackCollection));
    }

    // On startup we need to check if all of the user's library folders are
    // accessible to us. If the user is using a database from <1.12.0 with
    // sandboxing then we will need them to give us permission.
    QStringList directories = m_pTrackCollection->getDirectoryDAO().getDirs();

    qDebug() << "Checking for access to user's library directories:";
    foreach (QString directoryPath, directories) {
        QFileInfo directory(directoryPath);
        bool hasAccess = Sandbox::askForAccess(directory.canonicalFilePath());
        qDebug() << "Checking for access to" << directoryPath << ":" << hasAccess;
    }
Exemplo n.º 30
0
void QgsMapToolAddFeature::canvasReleaseEvent( QMouseEvent * e )
{
  QgsDebugMsg( "entered." );

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  QGis::WkbType layerWKBType = vlayer->wkbType();

  QgsVectorDataProvider* provider = vlayer->dataProvider();

  if ( !( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) )
  {
    QMessageBox::information( 0, tr( "Layer cannot be added to" ),
                              tr( "The data provider for this layer does not support the addition of features." ) );
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  // POINT CAPTURING
  if ( mode() == CapturePoint )
  {
    //check we only use this tool for point/multipoint layers
    if ( vlayer->geometryType() != QGis::Point )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture point' tool on this vector layer" ) );
      return;
    }


    QgsPoint idPoint; //point in map coordinates
    QList<QgsSnappingResult> snapResults;
    QgsPoint savePoint; //point in layer coordinates

    if ( mSnapper.snapToBackgroundLayers( e->pos(), snapResults ) == 0 )
    {
      idPoint = snapPointFromResults( snapResults, e->pos() );
      try
      {
        savePoint = toLayerCoordinates( vlayer, idPoint );
        QgsDebugMsg( "savePoint = " + savePoint.toString() );
      }
      catch ( QgsCsException &cse )
      {
        Q_UNUSED( cse );
        QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                  tr( "Cannot transform the point to the layers coordinate system" ) );
        return;
      }
    }

    //only do the rest for provider with feature addition support
    //note that for the grass provider, this will return false since
    //grass provider has its own mechanism of feature addition
    if ( provider->capabilities() & QgsVectorDataProvider::AddFeatures )
    {
      QgsFeature* f = new QgsFeature( 0, "WKBPoint" );

      QgsGeometry *g = 0;
      if ( layerWKBType == QGis::WKBPoint || layerWKBType == QGis::WKBPoint25D )
      {
        g = QgsGeometry::fromPoint( savePoint );
      }
      else if ( layerWKBType == QGis::WKBMultiPoint || layerWKBType == QGis::WKBMultiPoint25D )
      {
        g = QgsGeometry::fromMultiPoint( QgsMultiPoint() << savePoint );
      }

      f->setGeometry( g );

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      mCanvas->refresh();
    }
  }
  else if ( mode() == CaptureLine || mode() == CapturePolygon )
  {
    //check we only use the line tool for line/multiline layers
    if ( mode() == CaptureLine && vlayer->geometryType() != QGis::Line )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture line' tool on this vector layer" ) );
      return;
    }

    //check we only use the polygon tool for polygon/multipolygon layers
    if ( mode() == CapturePolygon && vlayer->geometryType() != QGis::Polygon )
    {
      QMessageBox::information( 0, tr( "Wrong editing tool" ),
                                tr( "Cannot apply the 'capture polygon' tool on this vector layer" ) );
      return;
    }

    //add point to list and to rubber band
    int error = addVertex( e->pos() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      QMessageBox::information( 0, tr( "Coordinate transform error" ),
                                tr( "Cannot transform the point to the layers coordinate system" ) );
      return;
    }

    if ( e->button() == Qt::LeftButton )
    {
      startCapturing();
    }
    else if ( e->button() == Qt::RightButton )
    {
      // End of string

      //lines: bail out if there are not at least two vertices
      if ( mode() == CaptureLine && size() < 2 )
      {
        stopCapturing();
        return;
      }

      //polygons: bail out if there are not at least two vertices
      if ( mode() == CapturePolygon && size() < 3 )
      {
        stopCapturing();
        return;
      }

      //create QgsFeature with wkb representation
      QgsFeature* f = new QgsFeature( 0, "WKBLineString" );

      QgsGeometry *g;

      if ( mode() == CaptureLine )
      {
        if ( layerWKBType == QGis::WKBLineString || layerWKBType == QGis::WKBLineString25D )
        {
          g = QgsGeometry::fromPolyline( points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiLineString || layerWKBType == QGis::WKBMultiLineString25D )
        {
          g = QgsGeometry::fromMultiPolyline( QgsMultiPolyline() << points().toVector() );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        f->setGeometry( g );
      }
      else // polygon
      {
        if ( layerWKBType == QGis::WKBPolygon ||  layerWKBType == QGis::WKBPolygon25D )
        {
          g = QgsGeometry::fromPolygon( QgsPolygon() << points().toVector() );
        }
        else if ( layerWKBType == QGis::WKBMultiPolygon ||  layerWKBType == QGis::WKBMultiPolygon25D )
        {
          g = QgsGeometry::fromMultiPolygon( QgsMultiPolygon() << ( QgsPolygon() << points().toVector() ) );
        }
        else
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "Cannot add feature. Unknown WKB type" ) );
          stopCapturing();
          return; //unknown wkbtype
        }

        if ( !g )
        {
          stopCapturing();
          delete f;
          return; // invalid geometry; one possibility is from duplicate points
        }
        f->setGeometry( g );

        int avoidIntersectionsReturn = f->geometry()->avoidIntersections();
        if ( avoidIntersectionsReturn == 1 )
        {
          //not a polygon type. Impossible to get there
        }
#if 0
        else if ( avoidIntersectionsReturn == 2 ) //MH120131: disable this error message until there is a better way to cope with the single type / multi type problem
        {
          //bail out...
          QMessageBox::critical( 0, tr( "Error" ), tr( "The feature could not be added because removing the polygon intersections would change the geometry type" ) );
          delete f;
          stopCapturing();
          return;
        }
#endif
        else if ( avoidIntersectionsReturn == 3 )
        {
          QMessageBox::critical( 0, tr( "Error" ), tr( "An error was reported during intersection removal" ) );
        }
      }

      vlayer->beginEditCommand( tr( "Feature added" ) );

      if ( addFeature( vlayer, f ) )
      {
        //add points to other features to keep topology up-to-date
        int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );
        if ( topologicalEditing )
        {
          vlayer->addTopologicalPoints( f->geometry() );
        }

        vlayer->endEditCommand();
      }
      else
      {
        delete f;
        vlayer->destroyEditCommand();
      }

      stopCapturing();
    }
  }
}