Enable or disable keywords editor icon when active layer changes.

        :param layer: The layer that is now active.
        :type layer: QgsMapLayer
163761
def layer_changed(self, layer):
        
        if not layer:
            enable_keyword_wizard = False
        elif not hasattr(layer, 'providerType'):
            enable_keyword_wizard = False
        elif layer.providerType() == 'wms':
            enable_keyword_wizard = False
        else:
            enable_keyword_wizard = True

        try:
            if layer:
                if is_raster_layer(layer):
                    enable_field_mapping_tool = False
                else:
                    keywords = KeywordIO().read_keywords(layer)
                    keywords_version = keywords.get('keyword_version')
                    if not keywords_version:
                        supported = False
                    else:
                        supported = (
                            is_keyword_version_supported(keywords_version))
                    if not supported:
                        enable_field_mapping_tool = False
                    else:
                        layer_purpose = keywords.get('layer_purpose')

                        if not layer_purpose:
                            enable_field_mapping_tool = False
                        else:
                            if layer_purpose == layer_purpose_exposure['key']:
                                layer_subcategory = keywords.get('exposure')
                            elif layer_purpose == layer_purpose_hazard['key']:
                                layer_subcategory = keywords.get('hazard')
                            else:
                                layer_subcategory = None
                            field_groups = get_field_groups(
                                layer_purpose, layer_subcategory)
                            if len(field_groups) == 0:
                                # No field group, disable field mapping tool.
                                enable_field_mapping_tool = False
                            else:
                                enable_field_mapping_tool = True
            else:
                enable_field_mapping_tool = False
        except (KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError):
            # No keywords, disable field mapping tool.
            enable_field_mapping_tool = False

        self.action_keywords_wizard.setEnabled(enable_keyword_wizard)
        self.action_field_mapping.setEnabled(enable_field_mapping_tool)
718580
def _add_default_exposure_class(layer):
    
    layer.startEditing()

    field = create_field_from_definition(exposure_class_field)
    layer.keywords['inasafe_fields'][exposure_class_field['key']] = (
        exposure_class_field['field_name'])
    layer.addAttribute(field)

    index = layer.fields().lookupField(exposure_class_field['field_name'])

    exposure = layer.keywords['exposure']

    request = QgsFeatureRequest()
    request.setFlags(QgsFeatureRequest.NoGeometry)
    for feature in layer.getFeatures(request):
        layer.changeAttributeValue(feature.id(), index, exposure)

    layer.commitChanges()
    return
1126584
def prompt_layer_selection(self, node, layers):
        
        valid = {
            "default": "default",
            "def": "default",
            "discard": "discard",
            "dis": "discard",
        }
        question = """Cannot automatically determine layer for node "%s" because there \
are %d layers available in that area, what do you want to do?\n\n""" % (node.name, len(layers))

        available_layers = ""
        for layer in layers:
            available_layers += "%d (%s)\n" % (layer.id, layer.name)
            valid[str(layer.id)] = layer.id

        prompt = """\
choose (enter the number of) one of the following layers:
%s
"default"    use default layer (if no default layer specified in settings node will be discarded)
"discard"    discard node

(default action is to use default layer)\n\n""" % available_layers

        sys.stdout.write(question + prompt)

        while True:
            if self.options.get('noinput') is True:
                answer = 'default'
                break

            answer = raw_input().lower()
            if answer == '':
                answer = "default"

            if answer in valid:
                answer = valid[answer]
                break
            else:
                sys.stdout.write("Please respond with one of the valid answers\n")

        sys.stdout.write("\n")
        return answer
878954
public void setLayer(VectorLayer layer) {
		this.layer = layer;
		if (layer == null) {
			clear();
		} else {
			empty();
			updateFields();
		}
	}
255561
def set_widgets(self):
        """"""
        self.clear()
        self.description_label.setText(
            'In this step you can set some extra keywords for the layer. This '
            'keywords can be used for creating richer reporting or map.')
        subcategory = self.parent.step_kw_subcategory.selected_subcategory()
        extra_keywords = subcategory.get('extra_keywords')
        for extra_keyword in extra_keywords:
            check_box, input_widget = extra_keywords_to_widgets(extra_keyword)
            self.widgets_dict[extra_keyword['key']] = [
                check_box,
                input_widget,
                extra_keyword
            ]

        # Add to layout
        index = 0
        for key, widgets in list(self.widgets_dict.items()):
            self.extra_keywords_layout.addWidget(widgets[0], index, 0)
            self.extra_keywords_layout.addWidget(widgets[1], index, 1)
            index += 1

        self.set_existing_extra_keywords()
948374
def ok_button_status(self):
        """"""
        if not self.layer.currentLayer():
            self.button_box.button(
                QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
        elif (self.hazard_class_form.count() > 0
              and self.layer.currentLayer().name()
              and len(self.output_form.text()) >= 0):
            self.button_box.button(
                QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
        else:
            self.button_box.button(
                QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
195296
@Override
	public void onVisibleChange(LayerShownEvent event) {
		if (!themeChange && getActiveViewConfig() != null && !event.isScaleChange()) {
			activateViewConfig(null);
		}
	}
1286912
def set_keywords_creation_mode(self, layer=None, keywords=None):
        
        self.layer = layer or self.iface.mapCanvas().currentLayer()

        if keywords is not None:
            self.existing_keywords = keywords
        else:
            # Always read from metadata file.
            try:
                self.existing_keywords = self.keyword_io.read_keywords(
                    self.layer)
            except (HashNotFoundError,
                    OperationalError,
                    NoKeywordsFoundError,
                    KeywordNotFoundError,
                    InvalidParameterError,
                    UnsupportedProviderError,
                    MetadataReadError):
                self.existing_keywords = {}
        self.set_mode_label_to_keywords_creation()

        step = self.step_kw_purpose
        step.set_widgets()
        self.go_to_step(step)
952997
private void init() {
		view.setLayerTitle(layer.getTitle());
		view.setLayerVisible(layer.isMarkedAsVisible());

		updateVisibilityToggle();

		mapPresenter.getEventBus().addViewPortChangedHandler(new ViewPortChangedHandler() {
			@Override
			public void onViewPortChanged(ViewPortChangedEvent event) {
				updateVisibilityToggle();
			}
		});

		// React to layer visibility events:
		mapPresenter.getEventBus().addLayerVisibilityHandler(new LayerVisibilityHandler() {

			@Override
			public void onShow(LayerShowEvent event) {
			}

			@Override
			public void onHide(LayerHideEvent event) {
			}

			@Override
			public void onVisibilityMarked(LayerVisibilityMarkedEvent event) {
				view.setLayerVisible(layer.isMarkedAsVisible());

			}
		}, this.layer);
	}
653848
public void setLayer(VectorLayer layer) {
		this.layer = layer;
		Object value = layerSelect.getValue();
		if (value == null || !value.equals(layer.getLabel())) {
			layerSelect.setValue(layer.getLabel());
		}
		empty();
	}
332670
def set_layer_visible(layer, visible):
        
        if layer is None:
            return

        QgsProject.instance().layerTreeRoot().findLayer(
            layer.id()).setItemVisibilityChecked(visible)
280114
def accept(self):
        
        # set parameter from dialog
        input_layer = self.layer.currentLayer()
        output_path = self.output_form.text()
        radius = self.get_classification()
        # monkey patch keywords so layer works on multi buffering function
        input_layer.keywords = {'inasafe_fields': {}}

        # run multi buffering
        self.output_layer = multi_buffering(input_layer, radius)

        # save output layer to data store and check whether user
        # provide the output path.
        if output_path:
            self.output_directory, self.output_filename = (
                os.path.split(output_path))
            self.output_filename, self.output_extension = (
                os.path.splitext(self.output_filename))

        # if user do not provide the output path, create a temporary file.
        else:
            self.output_directory = temp_dir(sub_dir='work')
            self.output_filename = (
                unique_filename(
                    prefix='hazard_layer',
                    suffix='.geojson',
                    dir=self.output_directory))
            self.output_filename = os.path.split(self.output_filename)[1]
            self.output_filename, self.output_extension = (
                os.path.splitext(self.output_filename))

        self.data_store = Folder(self.output_directory)
        if self.output_extension == '.shp':
            self.data_store.default_vector_format = 'shp'
        elif self.output_extension == '.geojson':
            self.data_store.default_vector_format = 'geojson'
        self.data_store.add_layer(self.output_layer, self.output_filename)

        # add output layer to map canvas
        self.output_layer = self.data_store.layer(self.output_filename)

        QgsProject.instance().addMapLayers(
            [self.output_layer])
        self.iface.setActiveLayer(self.output_layer)
        self.iface.zoomToActiveLayer()
        self.done(QtWidgets.QDialog.Accepted)

        if self.keyword_wizard_checkbox.isChecked():
            self.launch_keyword_wizard()
894325
def isEnabled(self):
        
        if self._disableWithLayer and self._layer:
            lenabled = self._layer.isEnabled()
        elif self._inputNode and self._outputNode:
            lenabled = self._inputNode.isEnabled() and self._outputNode.isEnabled()
        else:
            lenabled = True

        return self._enabled and lenabled
166882
protected void fireLayerMovedDownEvent(MapLayer layer, int newIndex) {
		fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent(this, layer,
				Type.MOVE_CHILD_DOWN, newIndex, layer.isTemporaryLayer()));
	}
1305829
function (layers) {
		var id, layer;

		for (id in layers) {
			layer = layers[id];

			// Make sure we do not override markers that do not belong to THIS group.
			if (this.hasLayer(layer)) {
				// Need to re-create the icon first, then re-draw the marker.
				layer.setIcon(this._overrideMarkerIcon(layer));
			}
		}
	}
517884
function(layer, attributes) {
    if(attributes === undefined) {
      attributes = layer;
      layer = 0;
    }

    if(layer >= this.getLayerCount() && layer < 0) {
      throw new Error("layer does not exist");
    }

    if(typeof(attributes) == 'string') {
      attributes = attributes.split(',');
    }

    for(var i = 0; i < attributes.length; ++i) {
      attributes[i] = attributes[i].replace(/ /g, '');
    }

    this.layers[layer].options.interactivity = attributes;
    this._definitionUpdated();
    return this;
  }
1086284
def on_lstLayerModes_itemSelectionChanged(self):
        
        self.clear_further_steps()
        # Set widgets
        layer_mode = self.selected_layermode()
        # Exit if no selection
        if not layer_mode:
            self.lblDescribeLayerMode.setText('')
            return
        # Set description label
        self.lblDescribeLayerMode.setText(layer_mode['description'])
        # Enable the next button
        self.parent.pbnNext.setEnabled(True)