Ejemplo n.º 1
0
void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    bool hadTransform = hasTransform();
    bool hadLayer = hasLayer();
    bool layerWasSelfPainting = hadLayer && layer()->isSelfPaintingLayer();

    RenderObject::styleDidChange(diff, oldStyle);
    updateFromStyle();

    if (requiresLayer()) {
        if (!layer() && layerCreationAllowedForSubtree()) {
            if (s_wasFloating && isFloating())
                setChildNeedsLayout();
            createLayer();
            if (parent() && !needsLayout() && containingBlock()) {
                layer()->repainter().setRepaintStatus(NeedsFullRepaint);
                // There is only one layer to update, it is not worth using |cachedOffset| since
                // we are not sure the value will be used.
                layer()->updateLayerPositions(0);
            }
        }
    } else if (layer() && layer()->parent()) {
        setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
        setHasReflection(false);
        layer()->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
        if (s_wasFloating && isFloating())
            setChildNeedsLayout();
        if (hadTransform)
            setNeedsLayoutAndPrefWidthsRecalc();
    }

    if (layer()) {
        layer()->styleChanged(diff, oldStyle);
        if (hadLayer && layer()->isSelfPaintingLayer() != layerWasSelfPainting)
            setChildNeedsLayout();
    }

    if (FrameView *frameView = view()->frameView()) {
        bool newStyleIsViewportConstained = style()->hasViewportConstrainedPosition();
        bool oldStyleIsViewportConstrained = oldStyle && oldStyle->hasViewportConstrainedPosition();
        if (newStyleIsViewportConstained != oldStyleIsViewportConstrained) {
            if (newStyleIsViewportConstained && layer())
                frameView->addViewportConstrainedObject(this);
            else
                frameView->removeViewportConstrainedObject(this);
        }
    }
}
Ejemplo n.º 2
0
bool WKCACFLayer::isTransformLayer() const
{
    return CACFLayerGetClass(layer()) == kCACFTransformLayer();
}
Ejemplo n.º 3
0
void WKCACFLayer::setContentsGravity(ContentsGravityType type)
{
    CACFLayerSetContentsGravity(layer(), toCACFContentsGravityType(type));
    setNeedsCommit();
}
Ejemplo n.º 4
0
void QgsLegendLayer::addToPopupMenu( QMenu& theMenu )
{
  QgsMapLayer *lyr = layer();
  QAction *toggleEditingAction = QgisApp::instance()->actionToggleEditing();

  // zoom to layer extent
  theMenu.addAction( QgsApplication::getThemeIcon( "/mActionZoomToLayer.png" ),
                     tr( "&Zoom to Layer Extent" ), legend(), SLOT( legendLayerZoom() ) );
  if ( lyr->type() == QgsMapLayer::RasterLayer )
  {
    theMenu.addAction( tr( "&Zoom to Best Scale (100%)" ), legend(), SLOT( legendLayerZoomNative() ) );

    QgsRasterLayer *rasterLayer =  qobject_cast<QgsRasterLayer *>( lyr );
    if ( rasterLayer && rasterLayer->rasterType() != QgsRasterLayer::Palette )
    {
      theMenu.addAction( tr( "&Stretch Using Current Extent" ), legend(), SLOT( legendLayerStretchUsingCurrentExtent() ) );
    }
  }

  // show in overview
  QAction* showInOverviewAction = theMenu.addAction( tr( "&Show in Overview" ), this, SLOT( showInOverview() ) );
  showInOverviewAction->setCheckable( true );
  showInOverviewAction->blockSignals( true );
  showInOverviewAction->setChecked( mLyr.isInOverview() );
  showInOverviewAction->blockSignals( false );

  // remove from canvas
  theMenu.addAction( QgsApplication::getThemeIcon( "/mActionRemoveLayer.png" ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) );

  // set layer crs
  theMenu.addAction( QgsApplication::getThemeIcon( "/mActionSetCRS.png" ), tr( "&Set Layer CRS" ), QgisApp::instance(), SLOT( setLayerCRS() ) );

  // assign layer crs to project
  theMenu.addAction( QgsApplication::getThemeIcon( "/mActionSetProjectCRS.png" ), tr( "Set &Project CRS from Layer" ), QgisApp::instance(), SLOT( setProjectCRSFromLayer() ) );

  theMenu.addSeparator();

  if ( lyr->type() == QgsMapLayer::VectorLayer )
  {
    QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer *>( lyr );

    // attribute table
    theMenu.addAction( QgsApplication::getThemeIcon( "/mActionOpenTable.png" ), tr( "&Open Attribute Table" ),
                       QgisApp::instance(), SLOT( attributeTable() ) );

    // allow editing
    int cap = vlayer->dataProvider()->capabilities();
    if ( cap & QgsVectorDataProvider::EditingCapabilities )
    {
      if ( toggleEditingAction )
      {
        theMenu.addAction( toggleEditingAction );
        toggleEditingAction->setChecked( vlayer->isEditable() );
      }
    }

    // save as vector file
    theMenu.addAction( tr( "Save As..." ), QgisApp::instance(), SLOT( saveAsFile() ) );

    // save selection as vector file
    QAction* saveSelectionAsAction = theMenu.addAction( tr( "Save Selection As..." ), QgisApp::instance(), SLOT( saveSelectionAsVectorFile() ) );
    if ( vlayer->selectedFeatureCount() == 0 )
    {
      saveSelectionAsAction->setEnabled( false );
    }

    if ( !vlayer->isEditable() && vlayer->dataProvider()->supportsSubsetString() && vlayer->vectorJoins().isEmpty() )
      theMenu.addAction( tr( "&Query..." ), QgisApp::instance(), SLOT( layerSubsetString() ) );

    //show number of features in legend if requested
    QAction* showNFeaturesAction = new QAction( tr( "Show Feature Count" ), &theMenu );
    showNFeaturesAction->setCheckable( true );
    showNFeaturesAction->setChecked( mShowFeatureCount );
    QObject::connect( showNFeaturesAction, SIGNAL( toggled( bool ) ), this, SLOT( setShowFeatureCount( bool ) ) );
    theMenu.addAction( showNFeaturesAction );
    theMenu.addSeparator();
  }
Ejemplo n.º 5
0
void List::createItem(const char* value, ItemID ID)
{
  Item* item = new Item(layer(), value, ID);
  addItem(*item);
}
Ejemplo n.º 6
0
void QgsAttributeFormEditorWidget::createSearchWidgetWrappers( const QString &widgetId, int fieldIdx, const QVariantMap &config,  const QgsAttributeEditorContext &context )
{
  QgsSearchWidgetWrapper *sww = QgsGui::editorWidgetRegistry()->createSearchWidget( widgetId, layer(), fieldIdx, config,
                                mSearchFrame, context );
  setSearchWidgetWrapper( sww );
  if ( sww->supportedFlags() & QgsSearchWidgetWrapper::Between ||
       sww->supportedFlags() & QgsSearchWidgetWrapper::IsNotBetween )
  {
    // create secondary widget for between type searches
    QgsSearchWidgetWrapper *sww2 = QgsGui::editorWidgetRegistry()->createSearchWidget( widgetId, layer(), fieldIdx, config,
                                   mSearchFrame, context );
    mSearchWidgets << sww2;
    mSearchFrame->layout()->addWidget( sww2->widget() );
    sww2->widget()->hide();
  }
}
Ejemplo n.º 7
0
TYPED_TEST(MemoryDataLayerTest, TestSetBatchSize) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter param;
  MemoryDataParameter* memory_data_param = param.mutable_memory_data_param();
  memory_data_param->set_batch_size(this->batch_size_);
  memory_data_param->set_channels(this->channels_);
  memory_data_param->set_height(this->height_);
  memory_data_param->set_width(this->width_);
  MemoryDataLayer<Dtype> layer(param);
  layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
  // first add data as usual
  int num_iter = 5;
  vector<cv::Mat> mat_vector(this->batch_size_ * num_iter);
  vector<int> label_vector(this->batch_size_ * num_iter);
  for (int i = 0; i < this->batch_size_*num_iter; ++i) {
    mat_vector[i] = cv::Mat(this->height_, this->width_, CV_8UC4);
    label_vector[i] = i;
    cv::randu(mat_vector[i], cv::Scalar::all(0), cv::Scalar::all(255));
  }
  layer.AddMatVector(mat_vector, label_vector);
  // then consume the data
  int data_index;
  const size_t count = this->channels_ * this->height_ * this->width_;
  for (int iter = 0; iter < num_iter; ++iter) {
    int offset = this->batch_size_ * iter;
    layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    const Dtype* data = this->data_blob_->cpu_data();
    for (int i = 0; i < this->batch_size_; ++i) {
      EXPECT_EQ(offset + i, this->label_blob_->cpu_data()[i]);
      for (int h = 0; h < this->height_; ++h) {
        const unsigned char* ptr_mat = mat_vector[offset + i].ptr<uchar>(h);
        int index = 0;
        for (int w = 0; w < this->width_; ++w) {
          for (int c = 0; c < this->channels_; ++c) {
            data_index = (i*count) + (c * this->height_ + h) * this->width_ + w;
            Dtype pixel = static_cast<Dtype>(ptr_mat[index++]);
            EXPECT_EQ(static_cast<int>(pixel), data[data_index]);
          }
        }
      }
    }
  }
  // and then add new data with different batch_size
  int new_batch_size = 16;
  layer.set_batch_size(new_batch_size);
  mat_vector.clear();
  mat_vector.resize(new_batch_size * num_iter);
  label_vector.clear();
  label_vector.resize(new_batch_size * num_iter);
  for (int i = 0; i < new_batch_size*num_iter; ++i) {
    mat_vector[i] = cv::Mat(this->height_, this->width_, CV_8UC4);
    label_vector[i] = i;
    cv::randu(mat_vector[i], cv::Scalar::all(0), cv::Scalar::all(255));
  }
  layer.AddMatVector(mat_vector, label_vector);

  // finally consume new data and check if everything is fine
  for (int iter = 0; iter < num_iter; ++iter) {
    int offset = new_batch_size * iter;
    layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    EXPECT_EQ(new_batch_size, this->blob_top_vec_[0]->num());
    EXPECT_EQ(new_batch_size, this->blob_top_vec_[1]->num());
    const Dtype* data = this->data_blob_->cpu_data();
    for (int i = 0; i < new_batch_size; ++i) {
      EXPECT_EQ(offset + i, this->label_blob_->cpu_data()[i]);
      for (int h = 0; h < this->height_; ++h) {
        const unsigned char* ptr_mat = mat_vector[offset + i].ptr<uchar>(h);
        int index = 0;
        for (int w = 0; w < this->width_; ++w) {
          for (int c = 0; c < this->channels_; ++c) {
            data_index = (i*count) + (c * this->height_ + h) * this->width_ + w;
            Dtype pixel = static_cast<Dtype>(ptr_mat[index++]);
            EXPECT_EQ(static_cast<int>(pixel), data[data_index]);
          }
        }
      }
    }
  }
}
Ejemplo n.º 8
0
void SetLayerName::onUndo()
{
  layer()->setName(m_oldName);
  layer()->incrementVersion();
}
Ejemplo n.º 9
0
TYPED_TEST(ConvolutionLayerTest, TestNDAgainst2D) {
  typedef typename TypeParam::Dtype Dtype;
  const int kernel_h = 11;
  const int kernel_w = 13;
  vector<int> bottom_shape(4);
  bottom_shape[0] = 15;
  bottom_shape[1] = 18;
  bottom_shape[2] = kernel_h * 2;
  bottom_shape[3] = kernel_w * 2;
  FillerParameter filler_param;
  GaussianFiller<Dtype> filler(filler_param);
  for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) {
    this->blob_bottom_vec_[i]->Reshape(bottom_shape);
    filler.Fill(this->blob_bottom_vec_[i]);
  }
  LayerParameter layer_param;
  ConvolutionParameter* convolution_param =
      layer_param.mutable_convolution_param();
  convolution_param->set_num_output(12);
  convolution_param->set_bias_term(false);
  convolution_param->set_group(6);
  convolution_param->set_kernel_h(kernel_h);
  convolution_param->set_kernel_w(kernel_w);
  convolution_param->mutable_weight_filler()->set_type("gaussian");
  Blob<Dtype> weights;
  Blob<Dtype> top_diff;
  // Shape and fill weights and top_diff.
  bool copy_diff;
  bool reshape;
  {
    ConvolutionLayer<Dtype> layer(layer_param);
    layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
    top_diff.ReshapeLike(*this->blob_top_);
    filler.Fill(&top_diff);
    ASSERT_EQ(1, layer.blobs().size());
    copy_diff = false; reshape = true;
    weights.CopyFrom(*layer.blobs()[0], copy_diff, reshape);
  }
  vector<bool> propagate_down(1, true);
  Blob<Dtype> result_2d;
  Blob<Dtype> backward_result_2d;
  Blob<Dtype> backward_weight_result_2d;
  // Test with 2D im2col
  {
    caffe_set(this->blob_top_->count(), Dtype(0),
              this->blob_top_->mutable_cpu_data());
    caffe_set(this->blob_bottom_->count(), Dtype(0),
              this->blob_bottom_->mutable_cpu_diff());
    caffe_set(weights.count(), Dtype(0), weights.mutable_cpu_diff());
    // Do SetUp and Forward; save Forward result in result_2d.
    convolution_param->set_force_nd_im2col(false);
    ConvolutionLayer<Dtype> layer_2d(layer_param);
    layer_2d.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
    ASSERT_EQ(1, layer_2d.blobs().size());
    copy_diff = false; reshape = false;
    layer_2d.blobs()[0]->CopyFrom(weights, copy_diff, reshape);
    layer_2d.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    copy_diff = false; reshape = true;
    result_2d.CopyFrom(*this->blob_top_, copy_diff, reshape);
    // Copy pre-generated top diff into actual top diff;
    // do Backward and save result in backward_result_2d.
    ASSERT_EQ(this->blob_top_->shape(), top_diff.shape());
    caffe_copy(top_diff.count(), top_diff.cpu_data(),
               this->blob_top_->mutable_cpu_diff());
    layer_2d.Backward(this->blob_top_vec_, propagate_down,
                      this->blob_bottom_vec_);
    copy_diff = true; reshape = true;
    backward_result_2d.CopyFrom(*this->blob_bottom_, copy_diff, reshape);
    backward_weight_result_2d.CopyFrom(weights, copy_diff, reshape);
  }
  Blob<Dtype> result_nd;
  Blob<Dtype> backward_result_nd;
  Blob<Dtype> backward_weight_result_nd;
  // Test with ND im2col
  {
    caffe_set(this->blob_top_->count(), Dtype(0),
              this->blob_top_->mutable_cpu_data());
    caffe_set(this->blob_bottom_->count(), Dtype(0),
              this->blob_bottom_->mutable_cpu_diff());
    caffe_set(weights.count(), Dtype(0), weights.mutable_cpu_diff());
    // Do SetUp and Forward; save Forward result in result_nd.
    convolution_param->set_force_nd_im2col(true);
    ConvolutionLayer<Dtype> layer_nd(layer_param);
    layer_nd.SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
    ASSERT_EQ(1, layer_nd.blobs().size());
    copy_diff = false; reshape = false;
    layer_nd.blobs()[0]->CopyFrom(weights, copy_diff, reshape);
    layer_nd.Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    copy_diff = false; reshape = true;
    result_nd.CopyFrom(*this->blob_top_, copy_diff, reshape);
    // Copy pre-generated top diff into actual top diff;
    // do Backward and save result in backward_result_nd.
    ASSERT_EQ(this->blob_top_->shape(), top_diff.shape());
    caffe_copy(top_diff.count(), top_diff.cpu_data(),
               this->blob_top_->mutable_cpu_diff());
    layer_nd.Backward(this->blob_top_vec_, propagate_down,
                      this->blob_bottom_vec_);
    copy_diff = true; reshape = true;
    backward_result_nd.CopyFrom(*this->blob_bottom_, copy_diff, reshape);
    backward_weight_result_nd.CopyFrom(weights, copy_diff, reshape);
  }
  ASSERT_EQ(result_nd.count(), result_2d.count());
  for (int i = 0; i < result_2d.count(); ++i)  {
    EXPECT_EQ(result_2d.cpu_data()[i], result_nd.cpu_data()[i]);
  }
  ASSERT_EQ(backward_result_nd.count(), backward_result_2d.count());
  for (int i = 0; i < backward_result_2d.count(); ++i) {
    EXPECT_EQ(backward_result_2d.cpu_diff()[i],
              backward_result_nd.cpu_diff()[i]);
  }
  ASSERT_EQ(backward_weight_result_nd.count(),
            backward_weight_result_2d.count());
  for (int i = 0; i < backward_weight_result_2d.count(); ++i) {
    EXPECT_EQ(backward_weight_result_2d.cpu_diff()[i],
              backward_weight_result_nd.cpu_diff()[i]);
  }
}
Ejemplo n.º 10
0
bool MapMode::LoadMap()
{
  std::string script_name = "data/maps/" + map_name + "-map.lua";

  if (!read_script)
    read_script = new rpg_script::ReadScript();

  if (read_script->IsOpen())
    read_script->CloseFile();

  if (!read_script->OpenFile(script_name))
  {
    PRINT_ERROR << "Failed to open tilemap script: " << script_name << endl;
    return false;
  }

  // cout << "---------- Tilemap Information ----------" << endl;
  // cout << "| File: " << _lua_filepath << endl;

  read_script->OpenTable("map_data");

  string script_path = read_script->ReadData<string>("script_path", "");

  int map_width = read_script->ReadData<int>("num_cols", -1);
  int map_height = read_script->ReadData<int>("num_rows", -1);
  if (map_width < 0 || map_height < 0)
  {
    PRINT_ERROR << "Invalid map dimensions in map script." << endl;
    return false;
  }

  // string name = read_script->ReadData<string>("name", "");
  // cout << "| Name: " << name << endl;
  // cout << "|" << endl;
  //
  // cout << "| Dimensions: " << map_width << " x " << map_height << endl;
  // cout << "|\n---------- Tileset Information ----------" << endl;

  if (!tile_supervisor)
    tile_supervisor = new private_map_mode::TileSupervisor();

  read_script->OpenTable("tilesets");
  int num_tilesets = read_script->ReadData<int>("count", -1);

  // cout << "| Tileset Count: " << num_tilesets << endl;

  if (num_tilesets < 0)
  {
    PRINT_ERROR << "No tilesets found in map script." << endl;
    return false;
  }

  for (int i = 0; i < num_tilesets; ++i)
  {
    string path = read_script->ReadData<string>(i, "");
    // cout << "| " << i << ". " << path << endl;
    if (path.empty() || !LoadTileset(path))
    {
      PRINT_ERROR << "Failed to load tileset" << endl;
      return false;
    }
  }
  read_script->CloseTable();

  // cout << "|\n----------- Layer Information -----------" << endl;

  // Load in the layer data
  read_script->OpenTable("layers");
  int num_layers = read_script->ReadData<int>("num_layers", -1);

  // cout << "| Layer Count: " << num_layers << endl;
  if (num_layers < 0)
  {
    PRINT_ERROR << "No layers found in map script." << endl;
    return false;
  }

  if (read_script->HasError())
  {
    read_script->PrintErrors();
    return false;
  }

  for (int l = 0; l < num_layers; ++l)
  {
    read_script->OpenTableIntegers(l);

    MapLayerType type;
    string str_type = read_script->ReadData<string>("type", "");

    if (str_type == "ground")
      type = MapLayerType::GROUND;
    else if (str_type == "wall")
      type = MapLayerType::WALL;
    else if (str_type == "sky")
      type = MapLayerType::SKY;
    else
    {
      PRINT_WARNING << "Unknown type for layer" << endl;
      continue;
    }

    // cout << "| " << l << ". " << str_type << endl;

    private_map_mode::MapLayer layer(type);
    for (int row = 0; row < map_height; ++row)
    {
      read_script->OpenTableIntegers(row + 1);
      // cout << "|\t";
      vector<int> temp;
      for (int col = 0; col < map_width; ++col)
      {
        int id = read_script->ReadData<int>(col + 1, -1);
        // cout << setw(3) << id << " ";
        temp.push_back(id);
      }
      // cout << endl;
      layer.tiles.push_back(temp);
      read_script->CloseTable();
    }

    tile_supervisor->layers.push_back(layer);

    read_script->CloseTable();
  }
  read_script->CloseTable();

  // cout << "|\n--------- Collision Information ---------" << endl;
  // Load object data
  if (!object_supervisor)
    object_supervisor = new private_map_mode::ObjectSupervisor();

  // cout << "| " << "Static Collision Matrix" << endl;

  read_script->OpenTable("collision");

  if (read_script->HasError())
  {
    read_script->PrintErrors();
    return false;
  }

  for (int i = 0; i < map_height; ++i)
  {
    read_script->OpenTableIntegers(i + 1);
    // cout << "|\t";
    vector<int> temp;
    for (int j = 0; j < map_width; ++j)
    {
      int value = read_script->ReadData<int>(j + 1, -1);
      // cout << setw(2) << value << " ";
      temp.push_back(value);
    }
    object_supervisor->collision_grid.push_back(temp);
    // cout << endl;
    read_script->CloseTable();
  }

  if (read_script->HasError())
  {
      read_script->PrintErrors();
      return false;
  }

  read_script->CloseTable();
  read_script->CloseFile();

  // cout << "-----------------------------------------" << endl;

  if (script_path.empty())
    return false;

  if (!read_script->OpenFile(script_path))
  {
    PRINT_ERROR << "Failed to open tilemap script: " << script_path << endl;
    return false;
  }

  IF_PRINT_DEBUG(MAP_MODE_DEBUG) << "Loading tilemap functionality script" << endl;

  read_script->CallFunction("Load");
  if (read_script->HasError())
  {
      read_script->PrintErrors();
      return false;
  }

  // read_script->CloseFile();

  return true;
}
Ejemplo n.º 11
0
void SetLayerName::onExecute()
{
  layer()->setName(m_newName);
  layer()->incrementVersion();
}
Ejemplo n.º 12
0
bool RenderView::hitTest(const HitTestRequest& request, HitTestResult& result)
{
    return layer()->hitTest(request, result);
}
Ejemplo n.º 13
0
void QgsRangeWidgetWrapper::initWidget( QWidget* editor )
{
  mDoubleSpinBox = qobject_cast<QDoubleSpinBox*>( editor );
  mIntSpinBox = qobject_cast<QSpinBox*>( editor );
  mDial = qobject_cast<QDial*>( editor );
  mSlider = qobject_cast<QSlider*>( editor );
  mQgsDial = qobject_cast<QgsDial*>( editor );
  mQgsSlider = qobject_cast<QgsSlider*>( editor );

  bool allowNull = config( "AllowNull" ).toBool();

  QVariant min( config( "Min" ) );
  QVariant max( config( "Max" ) );
  QVariant step( config( "Step" ) );

  if ( mDoubleSpinBox )
  {
    // set the precision if field is integer
    int precision = layer()->fields()[fieldIdx()].precision();
    if ( precision > 0 )
    {
      mDoubleSpinBox->setDecimals( layer()->fields()[fieldIdx()].precision() );
    }

    double minval = min.toDouble();
    double stepval = step.toDouble();
    QgsDoubleSpinBox* qgsWidget = dynamic_cast<QgsDoubleSpinBox*>( mDoubleSpinBox );
    if ( qgsWidget )
      qgsWidget->setShowClearButton( allowNull );
    if ( allowNull )
    {
      if ( precision > 0 )
      {
        minval -= 10 ^ -precision;
      }
      else
      {
        minval -= stepval;
      }
      mDoubleSpinBox->setValue( minval );
      mDoubleSpinBox->setSpecialValueText( QSettings().value( "qgis/nullValue", "NULL" ).toString() );
    }
    if ( min.isValid() )
      mDoubleSpinBox->setMinimum( min.toDouble() );
    if ( max.isValid() )
      mDoubleSpinBox->setMaximum( max.toDouble() );
    if ( step.isValid() )
      mDoubleSpinBox->setSingleStep( step.toDouble() );
    if ( config( "Suffix" ).isValid() )
      mDoubleSpinBox->setSuffix( config( "Suffix" ).toString() );

    connect( mDoubleSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( valueChanged( double ) ) );
  }

  if ( mIntSpinBox )
  {
    int minval = min.toInt();
    int stepval = step.toInt();
    QgsSpinBox* qgsWidget = dynamic_cast<QgsSpinBox*>( mIntSpinBox );
    if ( qgsWidget )
      qgsWidget->setShowClearButton( allowNull );
    if ( allowNull )
    {
      minval -= stepval;
      mIntSpinBox->setValue( minval );
      mIntSpinBox->setSpecialValueText( QSettings().value( "qgis/nullValue", "NULL" ).toString() );
    }
    if ( min.isValid() )
      mIntSpinBox->setMinimum( min.toInt() );
    if ( max.isValid() )
      mIntSpinBox->setMaximum( max.toInt() );
    if ( step.isValid() )
      mIntSpinBox->setSingleStep( step.toInt() );
    if ( config( "Suffix" ).isValid() )
      mIntSpinBox->setSuffix( config( "Suffix" ).toString() );
    connect( mIntSpinBox, SIGNAL( valueChanged( int ) ), this, SLOT( valueChanged( int ) ) );
  }


  if ( mQgsDial || mQgsSlider )
  {
    field().convertCompatible( min );
    field().convertCompatible( max );
    field().convertCompatible( step );

    if ( mQgsSlider )
    {
      if ( min.isValid() )
        mQgsSlider->setMinimum( min );
      if ( max.isValid() )
        mQgsSlider->setMaximum( max );
      if ( step.isValid() )
        mQgsSlider->setSingleStep( step );
    }

    if ( mQgsDial )
    {
      if ( min.isValid() )
        mQgsDial->setMinimum( min );
      if ( max.isValid() )
        mQgsDial->setMaximum( max );
      if ( step.isValid() )
        mQgsDial->setSingleStep( step );
    }

    connect( editor, SIGNAL( valueChanged( QVariant ) ), this, SLOT( valueChanged( QVariant ) ) );
  }
  else if ( mDial )
  {
    if ( min.isValid() )
      mDial->setMinimum( min.toInt() );
    if ( max.isValid() )
      mDial->setMaximum( max.toInt() );
    if ( step.isValid() )
      mDial->setSingleStep( step.toInt() );
    connect( mDial, SIGNAL( valueChanged( int ) ), this, SLOT( valueChanged( int ) ) );
  }
  else if ( mSlider )
QgsMapLayer* QgsMapLayerComboBox::currentLayer() const
{
    return layer( currentIndex() );
}
Ejemplo n.º 15
0
bool QgsFieldExpressionWidget::isValidExpression( QString *expressionError )
{
  QString temp;
  return QgsExpression::isValid( currentText(), layer()->pendingFields(), expressionError ? *expressionError : temp );
}
Ejemplo n.º 16
0
TYPED_TEST(CuDNNConvolutionLayerTest, TestSobelConvolutionCuDNN) {
  // Test separable convolution by computing the Sobel operator
  // as a single filter then comparing the result
  // as the convolution of two rectangular filters.

  // Fill bottoms with identical Gaussian noise.
  shared_ptr<GaussianFiller<TypeParam> > filler;
  FillerParameter filler_param;
  filler_param.set_value(1.);
  filler.reset(new GaussianFiller<TypeParam>(filler_param));
  filler->Fill(this->blob_bottom_);
  this->blob_bottom_2_->CopyFrom(*this->blob_bottom_);
  // Compute Sobel G_x operator as 3 x 3 convolution.
  LayerParameter layer_param;
  ConvolutionParameter* convolution_param =
      layer_param.mutable_convolution_param();
  convolution_param->add_kernel_size(3);
  convolution_param->add_stride(2);
  convolution_param->set_num_output(1);
  convolution_param->set_bias_term(false);
  shared_ptr<Layer<TypeParam> > layer(
      new CuDNNConvolutionLayer<TypeParam>(layer_param));
  layer->blobs().resize(1);
  layer->blobs()[0].reset(new Blob<TypeParam>(1, 3, 3, 3));
  TypeParam* weights = layer->blobs()[0]->mutable_cpu_data();
  for (int c = 0; c < 3; ++c) {
    int i = c * 9;  // 3 x 3 filter
    weights[i +  0] = -1;
    weights[i +  1] =  0;
    weights[i +  2] =  1;
    weights[i +  3] = -2;
    weights[i +  4] =  0;
    weights[i +  5] =  2;
    weights[i +  6] = -1;
    weights[i +  7] =  0;
    weights[i +  8] =  1;
  }
  layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
  layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);
  // Compute Sobel G_x operator as separable 3 x 1 and 1 x 3 convolutions.
  // (1) the [1 2 1] column filter
  vector<Blob<TypeParam>*> sep_blob_bottom_vec;
  vector<Blob<TypeParam>*> sep_blob_top_vec;
  shared_ptr<Blob<TypeParam> > blob_sep(new Blob<TypeParam>());
  sep_blob_bottom_vec.push_back(this->blob_bottom_2_);
  sep_blob_top_vec.push_back(this->blob_top_2_);
  convolution_param->clear_kernel_size();
  convolution_param->clear_stride();
  convolution_param->set_kernel_h(3);
  convolution_param->set_kernel_w(1);
  convolution_param->set_stride_h(2);
  convolution_param->set_stride_w(1);
  convolution_param->set_num_output(1);
  convolution_param->set_bias_term(false);
  layer.reset(new CuDNNConvolutionLayer<TypeParam>(layer_param));
  layer->blobs().resize(1);
  layer->blobs()[0].reset(new Blob<TypeParam>(1, 3, 3, 1));
  TypeParam* weights_1 = layer->blobs()[0]->mutable_cpu_data();
  for (int c = 0; c < 3; ++c) {
    int i = c * 3;  // 3 x 1 filter
    weights_1[i +  0] = 1;
    weights_1[i +  1] = 2;
    weights_1[i +  2] = 1;
  }
  layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec);
  layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec);
  // (2) the [-1 0 1] row filter
  blob_sep->CopyFrom(*this->blob_top_2_, false, true);
  sep_blob_bottom_vec.clear();
  sep_blob_bottom_vec.push_back(blob_sep.get());
  convolution_param->set_kernel_h(1);
  convolution_param->set_kernel_w(3);
  convolution_param->set_stride_h(1);
  convolution_param->set_stride_w(2);
  convolution_param->set_num_output(1);
  convolution_param->set_bias_term(false);
  layer.reset(new CuDNNConvolutionLayer<TypeParam>(layer_param));
  layer->blobs().resize(1);
  layer->blobs()[0].reset(new Blob<TypeParam>(1, 1, 1, 3));
  TypeParam* weights_2 = layer->blobs()[0]->mutable_cpu_data();
  weights_2[0] = -1;
  weights_2[1] =  0;
  weights_2[2] =  1;
  layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec);
  layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec);
  // Test equivalence of full and separable filters.
  const TypeParam* top_data = this->blob_top_->cpu_data();
  const TypeParam* sep_top_data = this->blob_top_2_->cpu_data();
  for (int i = 0; i < this->blob_top_->count(); ++i) {
    EXPECT_NEAR(top_data[i], sep_top_data[i], 1e-4);
  }
}
Ejemplo n.º 17
0
void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    RenderElement::styleDidChange(diff, oldStyle);
    updateFromStyle();

    if (requiresLayer()) {
        if (!layer() && layerCreationAllowedForSubtree()) {
            if (s_wasFloating && isFloating())
                setChildNeedsLayout();
            createLayer();
            if (parent() && !needsLayout() && containingBlock()) {
                layer()->setRepaintStatus(NeedsFullRepaint);
                // There is only one layer to update, it is not worth using |cachedOffset| since
                // we are not sure the value will be used.
                layer()->updateLayerPositions(0);
            }
        }
    } else if (layer() && layer()->parent()) {
#if ENABLE(CSS_COMPOSITING)
        if (oldStyle->hasBlendMode())
            layer()->parent()->dirtyAncestorChainHasBlendingDescendants();
#endif
        setHasTransformRelatedProperty(false); // All transform-related propeties force layers, so we know we don't have one or the object doesn't support them.
        setHasReflection(false);
        // Repaint the about to be destroyed self-painting layer when style change also triggers repaint.
        if (layer()->isSelfPaintingLayer() && layer()->repaintStatus() == NeedsFullRepaint)
            repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
        layer()->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
        if (s_wasFloating && isFloating())
            setChildNeedsLayout();
        if (s_hadTransform)
            setNeedsLayoutAndPrefWidthsRecalc();
    }

    if (layer()) {
        layer()->styleChanged(diff, oldStyle);
        if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
            setChildNeedsLayout();
    }

    bool newStyleIsViewportConstrained = style().hasViewportConstrainedPosition();
    bool oldStyleIsViewportConstrained = oldStyle && oldStyle->hasViewportConstrainedPosition();
    if (newStyleIsViewportConstrained != oldStyleIsViewportConstrained) {
        if (newStyleIsViewportConstrained && layer())
            view().frameView().addViewportConstrainedObject(this);
        else
            view().frameView().removeViewportConstrainedObject(this);
    }

#if ENABLE(CSS_SCROLL_SNAP)
    const RenderStyle& newStyle = style();
    if (oldStyle && scrollSnapContainerRequiresUpdateForStyleUpdate(*oldStyle, newStyle)) {
        if (RenderLayer* renderLayer = layer()) {
            renderLayer->updateSnapOffsets();
            renderLayer->updateScrollSnapState();
        } else if (isBody() || isDocumentElementRenderer()) {
            FrameView& frameView = view().frameView();
            frameView.updateSnapOffsets();
            frameView.updateScrollSnapState();
            frameView.updateScrollingCoordinatorScrollSnapProperties();
        }
    }
    if (oldStyle && oldStyle->scrollSnapCoordinates() != newStyle.scrollSnapCoordinates()) {
        const RenderBox* scrollSnapBox = enclosingBox().findEnclosingScrollableContainer();
        if (scrollSnapBox && scrollSnapBox->layer()) {
            const RenderStyle& style = scrollSnapBox->style();
            if (style.scrollSnapType() != ScrollSnapType::None) {
                scrollSnapBox->layer()->updateSnapOffsets();
                scrollSnapBox->layer()->updateScrollSnapState();
                if (scrollSnapBox->isBody() || scrollSnapBox->isDocumentElementRenderer())
                    scrollSnapBox->view().frameView().updateScrollingCoordinatorScrollSnapProperties();
            }
        }
    }
#endif
}
Ejemplo n.º 18
0
void RenderView::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
{
    rects.append(pixelSnappedIntRect(accumulatedOffset, layer()->size()));
}
Ejemplo n.º 19
0
PsdStatus PsdFile::readLayers(const uint8_t *&ptr, const uint8_t *end)
{
    if (ptr > mMapped.get().getEndAddress())
        return PsdStatusFileOutOfRange;

    PsdStatus status;
    deque<PsdLayerGroup *> groups;
    PsdLayerGroup *group = NULL;
    PsdLayers allLayers(new vector<shared_ptr<PsdLayer> >());
    allLayers->reserve(mLayersCount);
    mLayers.reset(new vector<shared_ptr<PsdLayer> >);
    mLayers->reserve(mLayersCount / 2 + 1);

    // read the header of each layer and construct the layer group tree
    for (uint16_t i = 0; i < mLayersCount && ptr < end; i++) {
        shared_ptr<PsdLayer> layer(new PsdLayer(this));

        status = layer->readMeta(ptr, end);
        if (status != PsdStatusOK)
            return status;

        allLayers->push_back(layer);

        LOG_DEBUG("layer: %s\n", layer->getName());
        if (layer->getType() == PsdLayer::LayerTypeGroup) {
            if (layer->mIsEndOfGroup) {
                group = new PsdLayerGroup(this);
                groups.push_back(group);
            } else if (group) {
                group->mName = layer->mName;
                groups.pop_back();

                if (groups.empty()) {
                    // No group in the stack, push to the root group
                    mLayers->push_back(shared_ptr<PsdLayer>(group));
                    group = NULL;
                } else {
                    // Otherwise, push to the top group on the stack
                    groups.back()->mLayers->push_back(shared_ptr<PsdLayer>(group));
                    group = groups.back();
                }
            } else {
                LOG_ALWAYS("A group layer is found but no end-of-group layer exists. Ignoring this layer.");
            }
        } else {
            if (group)
                group->mLayers->push_back(layer);
            else
                mLayers->push_back(layer);
        }
        ptr = layer->mAdditionalInfoBlock.getEndAddress();
    }
    if (!groups.empty())
        return PsdStatusLayerGroupNotComplete;

    LOG_DEBUG("Layer image data start: %u\n", uint32_t(ptr - mMapped.get().mAddress));

    // loop over all layers to obtain the address and length of per-layer image data
    vector<shared_ptr<PsdLayer> >::iterator iter = allLayers->begin(), layersEnd = allLayers->end();
    for (; iter != layersEnd; iter++) {
        PsdLayer *layer = iter->get();

        if (ptr + layer->mImageDataBlock.mLength > end)
            return PsdStatusFileOutOfRange;
        LOG_DEBUG("Layer image data: %u\n", uint32_t(ptr - mMapped.get().mAddress));
        layer->mImageDataBlock.mAddress = ptr;
        ptr += layer->mImageDataBlock.mLength;
    }

    LOG_DEBUG("Layer image data end: %u\n", uint32_t(ptr - mMapped.get().mAddress));

    return PsdStatusOK;
}
Ejemplo n.º 20
0
void RenderView::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
{
    if (wasFixed)
        *wasFixed = false;
    quads.append(FloatRect(FloatPoint(), layer()->size()));
}
void QgsRangeWidgetWrapper::initWidget( QWidget *editor )
{
  mDoubleSpinBox = qobject_cast<QDoubleSpinBox *>( editor );
  mIntSpinBox = qobject_cast<QSpinBox *>( editor );

  mDial = qobject_cast<QDial *>( editor );
  mSlider = qobject_cast<QSlider *>( editor );
  mQgsDial = qobject_cast<QgsDial *>( editor );
  mQgsSlider = qobject_cast<QgsSlider *>( editor );

  bool allowNull = config( QStringLiteral( "AllowNull" ), true ).toBool();

  QVariant min( config( QStringLiteral( "Min" ) ) );
  QVariant max( config( QStringLiteral( "Max" ) ) );
  QVariant step( config( QStringLiteral( "Step" ) ) );
  QVariant precision( config( QStringLiteral( "Precision" ) ) );

  if ( mDoubleSpinBox )
  {
    double stepval = step.isValid() ? step.toDouble() : 1.0;
    double minval = min.isValid() ? min.toDouble() : std::numeric_limits<double>::lowest();
    double maxval  = max.isValid() ? max.toDouble() : std::numeric_limits<double>::max();
    int precisionval = precision.isValid() ? precision.toInt() : layer()->fields().at( fieldIdx() ).precision();

    mDoubleSpinBox->setDecimals( precisionval );

    QgsDoubleSpinBox *qgsWidget = qobject_cast<QgsDoubleSpinBox *>( mDoubleSpinBox );


    if ( qgsWidget )
      qgsWidget->setShowClearButton( allowNull );
    // Make room for null value: lower the minimum to allow for NULL special values
    if ( allowNull )
    {
      double decr;
      if ( precisionval > 0 )
      {
        decr = std::pow( 10, -precisionval );
      }
      else
      {
        decr = stepval;
      }
      minval -= decr;
      // Note: call setMinimum here or setValue won't work
      mDoubleSpinBox->setMinimum( minval );
      mDoubleSpinBox->setValue( minval );
      QgsDoubleSpinBox *doubleSpinBox( qobject_cast<QgsDoubleSpinBox *>( mDoubleSpinBox ) );
      if ( doubleSpinBox )
        doubleSpinBox->setSpecialValueText( QgsApplication::nullRepresentation() );
      else
        mDoubleSpinBox->setSpecialValueText( QgsApplication::nullRepresentation() );
    }
    mDoubleSpinBox->setMinimum( minval );
    mDoubleSpinBox->setMaximum( maxval );
    mDoubleSpinBox->setSingleStep( stepval );
    if ( config( QStringLiteral( "Suffix" ) ).isValid() )
      mDoubleSpinBox->setSuffix( config( QStringLiteral( "Suffix" ) ).toString() );

    connect( mDoubleSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ),
    this, [ = ]( double ) { emitValueChanged(); } );
  }
  else if ( mIntSpinBox )
  {
    QgsSpinBox *qgsWidget = qobject_cast<QgsSpinBox *>( mIntSpinBox );
    if ( qgsWidget )
      qgsWidget->setShowClearButton( allowNull );
    int minval = min.toInt();
    if ( allowNull )
    {
      int stepval = step.isValid() ? step.toInt() : 1;
      minval -= stepval;
      mIntSpinBox->setValue( minval );
      QgsSpinBox *intSpinBox( qobject_cast<QgsSpinBox *>( mIntSpinBox ) );
      if ( intSpinBox )
        intSpinBox->setSpecialValueText( QgsApplication::nullRepresentation() );
      else
        mIntSpinBox->setSpecialValueText( QgsApplication::nullRepresentation() );
    }
    setupIntEditor( minval, max, step, mIntSpinBox, this );
    if ( config( QStringLiteral( "Suffix" ) ).isValid() )
      mIntSpinBox->setSuffix( config( QStringLiteral( "Suffix" ) ).toString() );
  }
  else
  {
    ( void )field().convertCompatible( min );
    ( void )field().convertCompatible( max );
    ( void )field().convertCompatible( step );
    if ( mQgsDial )
      setupIntEditor( min, max, step, mQgsDial, this );
    else if ( mQgsSlider )
      setupIntEditor( min, max, step, mQgsSlider, this );
    else if ( mDial )
      setupIntEditor( min, max, step, mDial, this );
    else if ( mSlider )
      setupIntEditor( min, max, step, mSlider, this );
  }
}
Ejemplo n.º 22
0
void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
{
    // Make sure both our start and end objects are defined.
    // Check www.msnbc.com and try clicking around to find the case where this happened.
    if ((start && !end) || (end && !start))
        return;

    // Just return if the selection hasn't changed.
    if (m_selectionStart == start && m_selectionStartPos == startPos &&
        m_selectionEnd == end && m_selectionEndPos == endPos)
        return;

    // Record the old selected objects.  These will be used later
    // when we compare against the new selected objects.
    int oldStartPos = m_selectionStartPos;
    int oldEndPos = m_selectionEndPos;

    // Objects each have a single selection rect to examine.
    typedef HashMap<RenderObject*, OwnPtr<RenderSelectionInfo> > SelectedObjectMap;
    SelectedObjectMap oldSelectedObjects;
    SelectedObjectMap newSelectedObjects;

    // Blocks contain selected objects and fill gaps between them, either on the left, right, or in between lines and blocks.
    // In order to get the repaint rect right, we have to examine left, middle, and right rects individually, since otherwise
    // the union of those rects might remain the same even when changes have occurred.
    typedef HashMap<RenderBlock*, OwnPtr<RenderBlockSelectionInfo> > SelectedBlockMap;
    SelectedBlockMap oldSelectedBlocks;
    SelectedBlockMap newSelectedBlocks;

    RenderObject* os = m_selectionStart;
    RenderObject* stop = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
    while (os && os != stop) {
        if ((os->canBeSelectionLeaf() || os == m_selectionStart || os == m_selectionEnd) && os->selectionState() != SelectionNone) {
            // Blocks are responsible for painting line gaps and margin gaps.  They must be examined as well.
            oldSelectedObjects.set(os, adoptPtr(new RenderSelectionInfo(os, true)));
            if (blockRepaintMode == RepaintNewXOROld) {
                RenderBlock* cb = os->containingBlock();
                while (cb && !cb->isRenderView()) {
                    OwnPtr<RenderBlockSelectionInfo>& blockInfo = oldSelectedBlocks.add(cb, nullptr).iterator->value;
                    if (blockInfo)
                        break;
                    blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
                    cb = cb->containingBlock();
                }
            }
        }

        os = os->nextInPreOrder();
    }

    // Now clear the selection.
    SelectedObjectMap::iterator oldObjectsEnd = oldSelectedObjects.end();
    for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i)
        i->key->setSelectionStateIfNeeded(SelectionNone);

    // set selection start and end
    m_selectionStart = start;
    m_selectionStartPos = startPos;
    m_selectionEnd = end;
    m_selectionEndPos = endPos;

    // Update the selection status of all objects between m_selectionStart and m_selectionEnd
    if (start && start == end)
        start->setSelectionStateIfNeeded(SelectionBoth);
    else {
        if (start)
            start->setSelectionStateIfNeeded(SelectionStart);
        if (end)
            end->setSelectionStateIfNeeded(SelectionEnd);
    }

    RenderObject* o = start;
    stop = rendererAfterPosition(end, endPos);

    while (o && o != stop) {
        if (o != start && o != end && o->canBeSelectionLeaf())
            o->setSelectionStateIfNeeded(SelectionInside);
        o = o->nextInPreOrder();
    }

    if (blockRepaintMode != RepaintNothing)
        layer()->clearBlockSelectionGapsBounds();

    // Now that the selection state has been updated for the new objects, walk them again and
    // put them in the new objects list.
    o = start;
    while (o && o != stop) {
        if ((o->canBeSelectionLeaf() || o == start || o == end) && o->selectionState() != SelectionNone) {
            newSelectedObjects.set(o, adoptPtr(new RenderSelectionInfo(o, true)));
            RenderBlock* cb = o->containingBlock();
            while (cb && !cb->isRenderView()) {
                OwnPtr<RenderBlockSelectionInfo>& blockInfo = newSelectedBlocks.add(cb, nullptr).iterator->value;
                if (blockInfo)
                    break;
                blockInfo = adoptPtr(new RenderBlockSelectionInfo(cb));
                cb = cb->containingBlock();
            }
        }

        o = o->nextInPreOrder();
    }

    if (!m_frameView || blockRepaintMode == RepaintNothing)
        return;

    m_frameView->beginDeferredRepaints();

    // Have any of the old selected objects changed compared to the new selection?
    for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i) {
        RenderObject* obj = i->key;
        RenderSelectionInfo* newInfo = newSelectedObjects.get(obj);
        RenderSelectionInfo* oldInfo = i->value.get();
        if (!newInfo || oldInfo->rect() != newInfo->rect() || oldInfo->state() != newInfo->state() ||
            (m_selectionStart == obj && oldStartPos != m_selectionStartPos) ||
            (m_selectionEnd == obj && oldEndPos != m_selectionEndPos)) {
            oldInfo->repaint();
            if (newInfo) {
                newInfo->repaint();
                newSelectedObjects.remove(obj);
            }
        }
    }

    // Any new objects that remain were not found in the old objects dict, and so they need to be updated.
    SelectedObjectMap::iterator newObjectsEnd = newSelectedObjects.end();
    for (SelectedObjectMap::iterator i = newSelectedObjects.begin(); i != newObjectsEnd; ++i)
        i->value->repaint();

    // Have any of the old blocks changed?
    SelectedBlockMap::iterator oldBlocksEnd = oldSelectedBlocks.end();
    for (SelectedBlockMap::iterator i = oldSelectedBlocks.begin(); i != oldBlocksEnd; ++i) {
        RenderBlock* block = i->key;
        RenderBlockSelectionInfo* newInfo = newSelectedBlocks.get(block);
        RenderBlockSelectionInfo* oldInfo = i->value.get();
        if (!newInfo || oldInfo->rects() != newInfo->rects() || oldInfo->state() != newInfo->state()) {
            oldInfo->repaint();
            if (newInfo) {
                newInfo->repaint();
                newSelectedBlocks.remove(block);
            }
        }
    }

    // Any new blocks that remain were not found in the old blocks dict, and so they need to be updated.
    SelectedBlockMap::iterator newBlocksEnd = newSelectedBlocks.end();
    for (SelectedBlockMap::iterator i = newSelectedBlocks.begin(); i != newBlocksEnd; ++i)
        i->value->repaint();

    m_frameView->endDeferredRepaints();
}
void ScrollingStateStickyNode::syncLayerPositionForViewportRect(const LayoutRect& viewportRect)
{
    FloatPoint position = m_constraints.layerPositionForConstrainingRect(viewportRect);
    if (layer().representsGraphicsLayer())
        static_cast<GraphicsLayer*>(layer())->syncPosition(position);
}
Ejemplo n.º 24
0
void RenderView::clearSelection()
{
    layer()->repaintBlockSelectionGaps();
    setSelection(0, -1, 0, -1, RepaintNewMinusOld);
}
Ejemplo n.º 25
0
void WKCACFLayer::becomeRootLayerForContext(CACFContextRef context)
{
    CACFContextSetLayer(context, layer());
    setNeedsCommit();
}
TYPED_TEST(LSTMLayerTest, TestForward) {
  typedef typename TypeParam::Dtype Dtype;
  const int kNumTimesteps = 3;
  const int num = this->blob_bottom_.shape(1);
  this->ReshapeBlobs(kNumTimesteps, num);

  // Fill the flush blob with <0, 1, 1, ..., 1>,
  // indicating a sequence that begins at the first timestep
  // then continues for the rest of the sequence.
  for (int t = 0; t < kNumTimesteps; ++t) {
    for (int n = 0; n < num; ++n) {
      this->blob_bottom_flush_.mutable_cpu_data()[t * num + n] = t > 0;
    }
  }

  // Process the full sequence in a single batch.
  FillerParameter filler_param;
  filler_param.set_mean(0);
  filler_param.set_std(1);
  GaussianFiller<Dtype> sequence_filler(filler_param);
  sequence_filler.Fill(&this->blob_bottom_);
  shared_ptr<LSTMLayer<Dtype> > layer(new LSTMLayer<Dtype>(this->layer_param_));
  Caffe::set_random_seed(1701);
  layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
  LOG(INFO) << "Calling forward for full sequence LSTM";
  layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);

  // Copy the inputs and outputs to reuse/check them later.
  Blob<Dtype> bottom_copy(this->blob_bottom_.shape());
  bottom_copy.CopyFrom(this->blob_bottom_);
  Blob<Dtype> top_copy(this->blob_top_.shape());
  top_copy.CopyFrom(this->blob_top_);

  // Process the batch one timestep at a time;
  // check that we get the same result.
  this->ReshapeBlobs(1, num);
  layer.reset(new LSTMLayer<Dtype>(this->layer_param_));
  Caffe::set_random_seed(1701);
  layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
  const int bottom_count = this->blob_bottom_.count();
  const int top_count = this->blob_top_.count();
  const Dtype kEpsilon = 1e-5;
  for (int t = 0; t < kNumTimesteps; ++t) {
    caffe_copy(bottom_count, bottom_copy.cpu_data() + t * bottom_count,
               this->blob_bottom_.mutable_cpu_data());
    for (int n = 0; n < num; ++n) {
      this->blob_bottom_flush_.mutable_cpu_data()[n] = t > 0;
    }
    LOG(INFO) << "Calling forward for LSTM timestep " << t;
    layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    for (int i = 0; i < top_count; ++i) {
      ASSERT_LT(t * top_count + i, top_copy.count());
      EXPECT_NEAR(this->blob_top_.cpu_data()[i],
                  top_copy.cpu_data()[t * top_count + i], kEpsilon)
         << "t = " << t << "; i = " << i;
    }
  }

  // Process the batch one timestep at a time with all flush blobs set to 0.
  // Check that we get a different result, except in the first timestep.
  Caffe::set_random_seed(1701);
  layer.reset(new LSTMLayer<Dtype>(this->layer_param_));
  layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
  for (int t = 0; t < kNumTimesteps; ++t) {
    caffe_copy(bottom_count, bottom_copy.cpu_data() + t * bottom_count,
               this->blob_bottom_.mutable_cpu_data());
    for (int n = 0; n < num; ++n) {
      this->blob_bottom_flush_.mutable_cpu_data()[n] = 0;
    }
    LOG(INFO) << "Calling forward for LSTM timestep " << t;
    layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);
    for (int i = 0; i < top_count; ++i) {
      if (t == 0) {
        EXPECT_NEAR(this->blob_top_.cpu_data()[i],
                    top_copy.cpu_data()[t * top_count + i], kEpsilon)
           << "t = " << t << "; i = " << i;
      } else {
        EXPECT_NE(this->blob_top_.cpu_data()[i],
                  top_copy.cpu_data()[t * top_count + i])
           << "t = " << t << "; i = " << i;
      }
    }
  }
}
Ejemplo n.º 27
0
void WKCACFLayer::insertSublayer(PassRefPtr<WKCACFLayer> sublayer, size_t index)
{
    index = min(index, numSublayers());
    CACFLayerInsertSublayer(layer(), sublayer->layer(), index);
    setNeedsCommit();
}
Ejemplo n.º 28
0
int CDVDOverlayCodecSSA::Decode(DemuxPacket *pPacket)
{
  if(!pPacket)
    return OC_ERROR;
  
  double pts = pPacket->dts != DVD_NOPTS_VALUE ? pPacket->dts : pPacket->pts;
  if (pts == DVD_NOPTS_VALUE)
    pts = 0;
  uint8_t *data = pPacket->pData;
  int size = pPacket->iSize;
  double duration = pPacket->duration;
  if(duration == DVD_NOPTS_VALUE)
    duration = 0.0;

  if(strncmp((const char*)data, "Dialogue:", 9) == 0)
  {
    int    sh, sm, ss, sc, eh, em, es, ec;
    double beg, end;
    size_t pos;
    std::string      line, line2;
    std::vector<std::string> lines;
    StringUtils::Tokenize((const char*)data, lines, "\r\n");
    for(size_t i=0; i<lines.size(); i++)
    {
      line = lines[i];
      StringUtils::Trim(line);
      std::unique_ptr<char[]> layer(new char[line.length() + 1]);

      if(sscanf(line.c_str(), "%*[^:]:%[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d"
                            , layer.get(), &sh, &sm, &ss, &sc, &eh,&em, &es, &ec) != 9)
        continue;

      end = 10000 * ((eh*360000.0)+(em*6000.0)+(es*100.0)+ec);
      beg = 10000 * ((sh*360000.0)+(sm*6000.0)+(ss*100.0)+sc);

      pos = line.find_first_of(",", 0);
      pos = line.find_first_of(",", pos+1);
      pos = line.find_first_of(",", pos+1);
      if(pos == std::string::npos)
        continue;

      line2 = StringUtils::Format("%d,%s,%s", m_order++, layer.get(), line.substr(pos+1).c_str());

      m_libass->DecodeDemuxPkt((char*)line2.c_str(), line2.length(), beg, end - beg);

      /* setup time spanning all dialogs */
      if(pts == DVD_NOPTS_VALUE || beg < pts)
        pts = beg;
      if(end - pts > duration)
        duration = end - pts;
    }
  }
  else
    m_libass->DecodeDemuxPkt((char*)data, size, pts, duration);

  if (m_pOverlay && m_pOverlay->iPTSStartTime == pts)
  {
    if (m_pOverlay->iPTSStopTime < pts + duration)
      m_pOverlay->iPTSStopTime = pts + duration;
    return 0;
  }

  if(m_pOverlay)
  {
    /* there will only ever be one active, so we 
     * must always make sure any new one overlap
     * include the full duration of the old one */
    if(m_pOverlay->iPTSStopTime > pts + duration)
      duration = m_pOverlay->iPTSStopTime - pts;
    SAFE_RELEASE(m_pOverlay);
  }

  m_pOverlay = new CDVDOverlaySSA(m_libass);
  m_pOverlay->iPTSStartTime = pts;
  m_pOverlay->iPTSStopTime  = pts + duration;
  m_output = true;
  return OC_OVERLAY;
}
Ejemplo n.º 29
0
WKCACFLayer::ContentsGravityType WKCACFLayer::contentsGravity() const
{
    return fromCACFContentsGravityType(CACFLayerGetContentsGravity(layer()));
}
void QgsAttributeTableFilterModel::generateListOfVisibleFeatures()
{
  if ( !layer() )
    return;

  bool filter = false;
  QgsRectangle rect = mCanvas->mapSettings().mapToLayerCoordinates( layer(), mCanvas->extent() );
  QgsRenderContext renderContext;
  renderContext.expressionContext() << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope()
  << QgsExpressionContextUtils::layerScope( layer() );
  QgsFeatureRendererV2* renderer = layer()->rendererV2();

  mFilteredFeatures.clear();

  if ( !renderer )
  {
    QgsDebugMsg( "Cannot get renderer" );
    return;
  }

  const QgsMapSettings& ms = mCanvas->mapSettings();
  if ( layer()->hasScaleBasedVisibility() &&
       ( layer()->minimumScale() > ms.scale() ||
         layer()->maximumScale() <= ms.scale() ) )
  {
    QgsDebugMsg( "Out of scale limits" );
  }
  else
  {
    if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
    {
      // setup scale
      // mapRenderer()->renderContext()->scale is not automaticaly updated when
      // render extent changes (because it's scale is used to identify if changed
      // since last render) -> use local context
      renderContext.setExtent( ms.visibleExtent() );
      renderContext.setMapToPixel( ms.mapToPixel() );
      renderContext.setRendererScale( ms.scale() );
    }

    filter = renderer && renderer->capabilities() & QgsFeatureRendererV2::Filter;
  }

  renderer->startRender( renderContext, layer()->fields() );

  QgsFeatureRequest r( masterModel()->request() );
  if ( !r.filterRect().isNull() )
  {
    r.setFilterRect( r.filterRect().intersect( &rect ) );
  }
  else
  {
    r.setFilterRect( rect );
  }
  QgsFeatureIterator features = masterModel()->layerCache()->getFeatures( r );

  QgsFeature f;

  while ( features.nextFeature( f ) )
  {
    renderContext.expressionContext().setFeature( f );
    if ( !filter || renderer->willRenderFeature( f, renderContext ) )
    {
      mFilteredFeatures << f.id();
    }
#if 0
    if ( t.elapsed() > 5000 )
    {
      bool cancel = false;
      emit progress( i, cancel );
      if ( cancel )
        break;

      t.restart();
    }
#endif
  }

  features.close();

  if ( renderer && renderer->capabilities() & QgsFeatureRendererV2::ScaleDependent )
  {
    renderer->stopRender( renderContext );
  }
}