def getLabels(labelsEnabled, layer, folder, sln):
    if (labelsEnabled):
        labelField = layer.customProperty("labeling/fieldName")
        if labelField != "":
            if unicode(layer.customProperty(
                    "labeling/isExpression")).lower() == "true":
                exprFilename = os.path.join(folder, "resources",
                                            "qgis2ol5_expressions.js")
                fieldName = layer.customProperty("labeling/fieldName")
                name = compile_to_file(fieldName, "label_%s" % sln,
                                       "OpenLayers3", exprFilename)
                js = "%s(context)" % (name)
                js = js.strip()
                labelText = js
            else:
                fieldIndex = layer.pendingFields().indexFromName(labelField)
                editFormConfig = layer.editFormConfig()
                editorWidget = editFormConfig.widgetType(fieldIndex)
                if (editorWidget == QgsVectorLayer.Hidden
                        or editorWidget == 'Hidden'):
                    labelField = "q2wHide_" + labelField
                labelText = ('feature.get("%s")' %
                             labelField.replace('"', '\\"'))
        else:
            labelText = '""'
    else:
        labelText = '""'
    return labelText
def getLabels(layer, safeLayerName, outputProjectFileName):
    label_exp = ''
    labeltext = ""
    f = ''
    palyr = QgsPalLayerSettings()
    palyr.readFromLayer(layer)
    if palyr.enabled and palyr.fieldName and palyr.fieldName != "":
        bgColor = palyr.shapeFillColor.name()
        borderWidth = palyr.shapeBorderWidth
        borderColor = palyr.shapeBorderColor.name()
        x = palyr.shapeSize.x()
        y = palyr.shapeSize.y()
        font = palyr.textFont
        fontSize = font.pointSize()
        fontFamily = font.family()
        fontItalic = font.italic()
        fontBold = font.bold()
        fontColor = palyr.textColor.name()
        fontUnderline = font.underline()
        xOffset = palyr.xOffset
        yOffset = palyr.yOffset
        styleStart = "'<div style=\"color: %s; font-size: %dpt; " % (fontColor,
                                                                     fontSize)
        if palyr.shapeDraw:
            styleStart += "background-color: %s; " % bgColor
            styleStart += "border: %dpx solid %s; " % (borderWidth,
                                                       borderColor)
            if palyr.shapeSizeType == 0:
                styleStart += "padding: %dpx %dpx; " % (y, x)
            if palyr.shapeSizeType == 1:
                styleStart += "width: %dpx; " % x
                styleStart += "height: %dpx; " % y
        if fontBold:
            styleStart += "font-weight: bold; "
        if fontItalic:
            styleStart += "font-style: italic; "
        styleStart += "font-family: \\'%s\\', sans-serif;\">' + " % fontFamily
        styleEnd = " + '</div>'"
        if palyr.isExpression and palyr.enabled:
            exprFilename = os.path.join(outputProjectFileName, "js",
                                        "qgis2web_expressions.js")
            name = compile_to_file(palyr.getLabelExpression(),
                                   "label_%s" % safeLayerName, "Leaflet",
                                   exprFilename)
            js = "%s(context)" % (name)
            js = js.strip()
            f = js
        else:
            f = "feature.properties['%s']" % handleHiddenField(
                layer, palyr.fieldName)
        labeltext = ".bindTooltip((" + unicode(f)
        labeltext += " !== null?String(%s%s)%s:'')" % (styleStart, unicode(f),
                                                       styleEnd)
        labeltext += ", {permanent: true, offset: [-0, -16], "
        labeltext += "className: 'css_%s'}" % safeLayerName
        labeltext += ").openTooltip();"
    else:
        labeltext = ""
    return labeltext
def ruleBased(renderer, folder, stylesFolder, layer_alpha, sln, layer):
    cluster = False
    template = """
        function rules_%s(feature, value) {
            var context = {
                feature: feature,
                variables: {}
            };
            // Start of if blocks and style check logic
            %s
            else {
                return %s;
            }
        }
        var style = rules_%s(feature, value);
        """
    elsejs = "[]"
    js = ""
    root_rule = renderer.rootRule()
    rules = root_rule.children()
    expFile = os.path.join(folder, "resources", "qgis2ol5_expressions.js")
    ifelse = "if"
    useAnyMapUnits = False
    for count, rule in enumerate(rules):
        symbol = rule.symbol()
        (styleCode, pattern, setPattern,
         useMapUnits) = getSymbolAsStyle(symbol, stylesFolder, layer_alpha,
                                         renderer, sln, layer)
        name = "".join((sln, "rule", unicode(count)))
        exp = rule.filterExpression()
        if rule.isElse():
            elsejs = styleCode
            continue
        name = compile_to_file(exp, name, "OpenLayers3", expFile)
        js += """
                    %s (%s(context)) {
                      return %s;
                    }
                    """ % (ifelse, name, styleCode)
        js = js.strip()
        ifelse = "else if"
        if useMapUnits:
            useAnyMapUnits = True
    value = ("var value = '';")
    style = template % (sln, js, elsejs, sln)
    return (style, pattern, setPattern, value, useAnyMapUnits)
def getLayerStyle(layer, sln, markerFolder, outputProjectFilename):
    markerType = None
    renderer = layer.rendererV2()
    layer_alpha = layer.layerTransparency()
    style = ""
    if isinstance(renderer, QgsSingleSymbolRendererV2):
        symbol = renderer.symbol()
        (styleCode, markerType) = getSymbolAsStyle(symbol, markerFolder,
                                                   layer_alpha, sln)
        style = """
        function style_%s() {
            return %s
        }""" % (sln, styleCode)
    elif isinstance(renderer, QgsCategorizedSymbolRendererV2):
        classAttr = handleHiddenField(layer, renderer.classAttribute())
        style = """
        function style_%s(feature) {
            switch(feature.properties['%s']) {""" % (sln, classAttr)
        for cat in renderer.categories():
            (styleCode, markerType) = getSymbolAsStyle(cat.symbol(),
                                                       markerFolder,
                                                       layer_alpha, sln)
            if cat.value() != "":
                style += """
                case '%s':""" % cat.value()
            else:
                style += """
                default:"""
            style += """
                    return %s
                    break;""" % styleCode
        style += """
            }
        }"""
    elif isinstance(renderer, QgsGraduatedSymbolRendererV2):
        classAttr = handleHiddenField(layer, renderer.classAttribute())
        style = """
        function style_%s(feature) {""" % (sln)
        for ran in renderer.ranges():
            (styleCode, markerType) = getSymbolAsStyle(ran.symbol(),
                                                       markerFolder,
                                                       layer_alpha, sln)
            style += """
            if (feature.properties['%(a)s'] >= %(l)f """
            style += """&& feature.properties['%(a)s'] <= %(u)f ) {
                return %(s)s
            }"""
            style = style % {"a": classAttr, "l": ran.lowerValue(),
                             "u": ran.upperValue(),
                             "s": styleCode}
        style += """
        }"""
    elif isinstance(renderer, QgsRuleBasedRendererV2):
        template = """
        function style_%s(feature) {
            var context = {
                feature: feature,
                variables: {}
            };
            // Start of if blocks and style check logic
            %s
            else {
                return %s;
            }
        }
        """
        elsejs = "{fill: false, stroke: false}"
        js = ""
        root_rule = renderer.rootRule()
        rules = root_rule.children()
        expFile = os.path.join(outputProjectFilename, "js",
                               "qgis2web_expressions.js")
        ifelse = "if"
        for count, rule in enumerate(rules):
            (styleCode, markerType) = getSymbolAsStyle(rule.symbol(),
                                                       markerFolder,
                                                       layer_alpha, sln)
            name = "".join((sln, "rule", unicode(count)))
            exp = rule.filterExpression()
            if rule.isElse():
                elsejs = styleCode
                continue
            name = compile_to_file(exp, name, "Leaflet", expFile)
            js += """
            %s (%s(context)) {
              return %s;
            }
            """ % (ifelse, name, styleCode)
            js = js.strip()
            ifelse = "else if"
        style = template % (sln, js, elsejs)
    else:
        style = ""
    return style, markerType
def getLayerStyle(layer, sln, markerFolder, outputProjectFilename, useShapes):
    markerType = None
    renderer = layer.rendererV2()
    layer_alpha = layer.layerTransparency()
    style = ""
    if isinstance(renderer, QgsSingleSymbolRendererV2):
        symbol = renderer.symbol()
        for sl in xrange(symbol.symbolLayerCount()):
            (styleCode, markerType) = getSymbolAsStyle(symbol, markerFolder,
                                                       layer_alpha, sln, sl)
            style += """
        function style_%s_%s() {
            return %s
        }""" % (sln, sl, styleCode)
    elif isinstance(renderer, QgsCategorizedSymbolRendererV2):
        classAttr = handleHiddenField(layer, renderer.classAttribute())
        symbol = renderer.categories()[0].symbol()
        for sl in xrange(symbol.symbolLayerCount()):
            style += """
        function style_%s_%s(feature) {
            switch(feature.properties['%s'].toString()) {""" % (sln, sl,
                                                                classAttr)
            for cat in renderer.categories():
                (styleCode,
                 markerType) = getSymbolAsStyle(cat.symbol(), markerFolder,
                                                layer_alpha, sln, sl)
                if (cat.value() is not None and cat.value() != ""
                        and not isinstance(cat.value(), QPyNullVariant)):
                    style += """
                case '%s':""" % unicode(cat.value()).replace("'", "\\'")
                else:
                    style += """
                default:"""
                style += """
                    return %s
                    break;""" % styleCode
            style += """
            }
        }"""
    elif isinstance(renderer, QgsGraduatedSymbolRendererV2):
        classAttr = handleHiddenField(layer, renderer.classAttribute())
        symbol = renderer.ranges()[0].symbol()
        for sl in xrange(symbol.symbolLayerCount()):
            style += """
        function style_%s_%s(feature) {""" % (sln, sl)
            for ran in renderer.ranges():
                (styleCode,
                 markerType) = getSymbolAsStyle(ran.symbol(), markerFolder,
                                                layer_alpha, sln, sl)
                style += """
            if (feature.properties['%(a)s'] >= %(l)f """
                style += """&& feature.properties['%(a)s'] <= %(u)f ) {
                return %(s)s
            }"""
                style = style % {
                    "a": classAttr,
                    "l": ran.lowerValue(),
                    "u": ran.upperValue(),
                    "s": styleCode
                }
            style += """
        }"""
    elif isinstance(renderer, QgsRuleBasedRendererV2):
        symbol = renderer.rootRule().children()[0].symbol()
        for sl in xrange(symbol.symbolLayerCount()):
            template = """
        function style_%s_{sl}(feature) {{
            var context = {{
                feature: feature,
                variables: {{}}
            }};
            // Start of if blocks and style check logic
            %s
            else {{
                return %s;
            }}
        }}
        """.format(sl=sl)
            elsejs = "{fill: false, stroke: false}"
            js = ""
            root_rule = renderer.rootRule()
            rules = root_rule.children()
            expFile = os.path.join(outputProjectFilename, "js",
                                   "qgis2web_expressions.js")
            ifelse = "if"
            for count, rule in enumerate(rules):
                if rule.symbol().symbolLayer(sl) is not None:
                    (styleCode,
                     markerType) = getSymbolAsStyle(rule.symbol(),
                                                    markerFolder, layer_alpha,
                                                    sln, sl)
                    name = "".join((sln, "rule", unicode(count)))
                    exp = rule.filterExpression()
                    if rule.isElse():
                        elsejs = styleCode
                        continue
                    name = compile_to_file(exp, name, "Leaflet", expFile)
                    js += """
                %s (%s(context)) {
                  return %s;
                }
                """ % (ifelse, name, styleCode)
                    js = js.strip()
                    ifelse = "else if"
            style += template % (sln, js, elsejs)
    else:
        style = ""
    if markerType == "shapeMarker":
        useShapes = True
    return style, markerType, useShapes
Exemple #6
0
def exportStyles(layers, folder, clustered):
    stylesFolder = os.path.join(folder, "styles")
    QDir().mkpath(stylesFolder)
    for count, (layer, cluster) in enumerate(zip(layers, clustered)):
        sln = safeName(layer.name()) + unicode(count)
        if layer.type() != layer.VectorLayer:
            continue
        labelsEnabled = unicode(
            layer.customProperty("labeling/enabled")).lower() == "true"
        if (labelsEnabled):
            labelField = layer.customProperty("labeling/fieldName")
            if labelField != "":
                if unicode(layer.customProperty(
                        "labeling/isExpression")).lower() == "true":
                    exprFilename = os.path.join(folder, "resources",
                                                "qgis2web_expressions.js")
                    fieldName = layer.customProperty("labeling/fieldName")
                    name = compile_to_file(fieldName, "label_%s" % sln,
                                           "OpenLayers3", exprFilename)
                    js = "%s(context)" % (name)
                    js = js.strip()
                    labelText = js
                else:
                    fieldIndex = layer.pendingFields().indexFromName(
                        labelField)
                    try:
                        editFormConfig = layer.editFormConfig()
                        editorWidget = editFormConfig.widgetType(fieldIndex)
                    except:
                        editorWidget = layer.editorWidgetV2(fieldIndex)
                    if (editorWidget == QgsVectorLayer.Hidden
                            or editorWidget == 'Hidden'):
                        labelField = "q2wHide_" + labelField
                    labelText = ('feature.get("%s")' %
                                 labelField.replace('"', '\\"'))
            else:
                labelText = '""'
        else:
            labelText = '""'
        defs = "var size = 0;\n"
        try:
            renderer = layer.rendererV2()
            layer_alpha = layer.layerTransparency()
            if isinstance(renderer, QgsSingleSymbolRendererV2):
                symbol = renderer.symbol()
                if cluster:
                    style = "var size = feature.get('features').length;\n"
                else:
                    style = "var size = 0;\n"
                style += "    var style = " + getSymbolAsStyle(
                    symbol, stylesFolder, layer_alpha)
                value = 'var value = ""'
            elif isinstance(renderer, QgsCategorizedSymbolRendererV2):
                defs += """function categories_%s(feature, value) {
                switch(value) {""" % sln
                cats = []
                for cat in renderer.categories():
                    if (cat.value() is not None and cat.value() != ""
                            and not isinstance(cat.value(), QPyNullVariant)):
                        categoryStr = "case '%s':" % unicode(
                            cat.value()).replace("'", "\\'")
                    else:
                        categoryStr = "default:"
                    categoryStr += '''
                    return %s;
                    break;''' % (getSymbolAsStyle(cat.symbol(), stylesFolder,
                                                  layer_alpha))
                    cats.append(categoryStr)
                defs += "\n".join(cats) + "}};"
                classAttr = renderer.classAttribute()
                fieldIndex = layer.pendingFields().indexFromName(classAttr)
                try:
                    editFormConfig = layer.editFormConfig()
                    editorWidget = editFormConfig.widgetType(fieldIndex)
                except:
                    editorWidget = layer.editorWidgetV2(fieldIndex)
                if (editorWidget == QgsVectorLayer.Hidden
                        or editorWidget == 'Hidden'):
                    classAttr = "q2wHide_" + classAttr
                value = ('var value = feature.get("%s");' % classAttr)
                style = ('''var style = categories_%s(feature, value)''' %
                         (sln))
            elif isinstance(renderer, QgsGraduatedSymbolRendererV2):
                varName = "ranges_" + sln
                defs += "var %s = [" % varName
                ranges = []
                for ran in renderer.ranges():
                    symbolstyle = getSymbolAsStyle(ran.symbol(), stylesFolder,
                                                   layer_alpha)
                    ranges.append(
                        '[%f, %f, %s]' %
                        (ran.lowerValue(), ran.upperValue(), symbolstyle))
                defs += ",\n".join(ranges) + "];"
                classAttr = renderer.classAttribute()
                fieldIndex = layer.pendingFields().indexFromName(classAttr)
                try:
                    editFormConfig = layer.editFormConfig()
                    editorWidget = editFormConfig.widgetType(fieldIndex)
                except:
                    editorWidget = layer.editorWidgetV2(fieldIndex)
                if (editorWidget == QgsVectorLayer.Hidden
                        or editorWidget == 'Hidden'):
                    classAttr = "q2wHide_" + classAttr
                value = ('var value = feature.get("%s");' % classAttr)
                style = '''var style = %(v)s[0][2];
    for (i = 0; i < %(v)s.length; i++){
        var range = %(v)s[i];
        if (value > range[0] && value<=range[1]){
            style =  range[2];
        }
    }''' % {
                    "v": varName
                }
            elif isinstance(renderer, QgsRuleBasedRendererV2):
                template = """
        function rules_%s(feature, value) {
            var context = {
                feature: feature,
                variables: {}
            };
            // Start of if blocks and style check logic
            %s
            else {
                return %s;
            }
        }
        var style = rules_%s(feature, value);
        """
                elsejs = "[]"
                js = ""
                root_rule = renderer.rootRule()
                rules = root_rule.children()
                expFile = os.path.join(folder, "resources",
                                       "qgis2web_expressions.js")
                ifelse = "if"
                for count, rule in enumerate(rules):
                    symbol = rule.symbol()
                    styleCode = getSymbolAsStyle(symbol, stylesFolder,
                                                 layer_alpha)
                    name = "".join((sln, "rule", unicode(count)))
                    exp = rule.filterExpression()
                    if rule.isElse():
                        elsejs = styleCode
                        continue
                    name = compile_to_file(exp, name, "OpenLayers3", expFile)
                    js += """
                    %s (%s(context)) {
                      return %s;
                    }
                    """ % (ifelse, name, styleCode)
                    js = js.strip()
                    ifelse = "else if"
                value = ("var value = '';")
                style = template % (sln, js, elsejs, sln)
            else:
                style = ""
            if layer.customProperty("labeling/fontSize"):
                size = float(layer.customProperty("labeling/fontSize")) * 1.3
            else:
                size = 10
            italic = layer.customProperty("labeling/fontItalic")
            bold = layer.customProperty("labeling/fontWeight")
            r = layer.customProperty("labeling/textColorR")
            g = layer.customProperty("labeling/textColorG")
            b = layer.customProperty("labeling/textColorB")
            color = "rgba(%s, %s, %s, 255)" % (r, g, b)
            face = layer.customProperty("labeling/fontFamily")
            palyr = QgsPalLayerSettings()
            palyr.readFromLayer(layer)
            sv = palyr.scaleVisibility
            if sv:
                min = float(palyr.scaleMin)
                max = float(palyr.scaleMax)
                min = 1 / ((1 / min) * 39.37 * 90.7)
                max = 1 / ((1 / max) * 39.37 * 90.7)
                labelRes = " && resolution > %(min)d " % {"min": min}
                labelRes += "&& resolution < %(max)d" % {"max": max}
            else:
                labelRes = ""
            buffer = palyr.bufferDraw
            if buffer:
                bufferColor = palyr.bufferColor.name()
                bufferWidth = palyr.bufferSize
                stroke = """
              stroke: new ol.style.Stroke({
                color: "%s",
                width: %d
              }),""" % (bufferColor, bufferWidth)
            else:
                stroke = ""
            if style != "":
                style = '''function(feature, resolution){
    var context = {
        feature: feature,
        variables: {}
    };
    %(value)s
    %(style)s;
    if (%(label)s !== null%(labelRes)s) {
        var labelText = String(%(label)s);
    } else {
        var labelText = ""
    }
    var key = value + "_" + labelText

    if (!%(cache)s[key]){
        var text = new ol.style.Text({
              font: '%(size)spx \\'%(face)s\\', sans-serif',
              text: labelText,
              textBaseline: "center",
              textAlign: "left",
              offsetX: 5,
              offsetY: 3,
              fill: new ol.style.Fill({
                color: '%(color)s'
              }),%(stroke)s
            });
        %(cache)s[key] = new ol.style.Style({"text": text})
    }
    var allStyles = [%(cache)s[key]];
    allStyles.push.apply(allStyles, style);
    return allStyles;
}''' % {
                    "style": style,
                    "labelRes": labelRes,
                    "label": labelText,
                    "cache": "styleCache_" + sln,
                    "size": size,
                    "face": face,
                    "color": color,
                    "stroke": stroke,
                    "value": value
                }
            else:
                style = "''"
        except Exception, e:
            style = """{
            /* """ + traceback.format_exc() + " */}"
            QgsMessageLog.logMessage(traceback.format_exc(),
                                     "qgis2web",
                                     level=QgsMessageLog.CRITICAL)

        path = os.path.join(stylesFolder, sln + "_style.js")

        with codecs.open(path, "w", "utf-8") as f:
            f.write('''%(defs)s
var styleCache_%(name)s={}
var style_%(name)s = %(style)s;''' % {
                "defs": defs,
                "name": sln,
                "style": style
            })
def labelsAndPopups(layer, safeLayerName, highlight, popupsOnHover, popup,
                    outputProjectFileName):
    fields = layer.pendingFields()
    field_names = popup.keys()
    field_vals = popup.values()
    html_prov = False
    label_exp = ''
    labeltext = ""
    f = ''
    palyr = QgsPalLayerSettings()
    palyr.readFromLayer(layer)
    bgColor = palyr.shapeFillColor.name()
    borderWidth = palyr.shapeBorderWidth
    borderColor = palyr.shapeBorderColor.name()
    x = palyr.shapeSize.x()
    y = palyr.shapeSize.y()
    font = palyr.textFont
    fontSize = font.pointSize()
    fontFamily = font.family()
    fontItalic = font.italic()
    fontBold = font.bold()
    fontColor = palyr.textColor.name()
    fontUnderline = font.underline()
    xOffset = palyr.xOffset
    yOffset = palyr.yOffset
    styleStart = "'<div style=\"color: %s; font-size: %dpt; " % (fontColor,
                                                                 fontSize)
    if palyr.shapeDraw:
        styleStart += "background-color: %s; " % bgColor
        styleStart += "border: %dpx solid %s; " % (borderWidth, borderColor)
        if palyr.shapeSizeType == 0:
            styleStart += "padding: %dpx %dpx; " % (y, x)
        if palyr.shapeSizeType == 1:
            styleStart += "width: %dpx; " % x
            styleStart += "height: %dpx; " % y
    if fontBold:
        styleStart += "font-weight: bold; "
    if fontItalic:
        styleStart += "font-style: italic; "
    styleStart += "font-family: \\'%s\\', sans-serif;\">' + " % fontFamily
    styleEnd = " + '</div>'"
    if palyr.isExpression and palyr.enabled:
        exprFilename = os.path.join(outputProjectFileName, "js",
                                    "qgis2web_expressions.js")
        name = compile_to_file(palyr.getLabelExpression(),
                               "label_%s" % safeLayerName, "Leaflet",
                               exprFilename)
        js = "%s(context)" % (name)
        js = js.strip()
        f = js
    else:
        f = "feature.properties['%s']" % handleHiddenField(
            layer, palyr.fieldName)
    label_exp = False
    labeltext = ".bindTooltip((" + unicode(f)
    labeltext += " !== null?String(%s%s)%s:'')" % (styleStart, unicode(f),
                                                   styleEnd)
    labeltext += ", {permanent: true, offset: [-0, -16], "
    labeltext += "className: 'css_%s'}" % safeLayerName
    labeltext += ").openTooltip();"
    f = palyr.fieldName
    table = ""
    for field in popup:
        if unicode(field) == 'html_exp':
            html_prov = True
            table = 'feature.properties.html_exp'
        if (unicode(f) != "" and f and palyr.enabled):
            label_exp = True
        if not html_prov:
            tablestart = "'<table>\\"
            row = ""
            for field, val in zip(field_names, field_vals):
                fieldIndex = fields.indexFromName(unicode(field))
                try:
                    formCfg = layer.editFormConfig()
                    editorWidget = formCfg.widgetType(fieldIndex)
                except:
                    editorWidget = layer.editorWidgetV2(fieldIndex)
                if (editorWidget == QgsVectorLayer.Hidden
                        or editorWidget == 'Hidden'):
                    continue

                row += """
                    <tr>\\"""
                if val == 'inline label':
                    row += """
                        <th scope="row">"""
                    row += layer.attributeDisplayName(fieldIndex)
                    row += """</th>\\
                        <td>"""
                else:
                    row += """
                        <td colspan="2">"""
                if val == "header label":
                    row += '<strong>'
                    row += layer.attributeDisplayName(fieldIndex)
                    row += '</strong><br />'
                row += "' + "
                row += "(feature.properties[\'" + unicode(field) + "\'] "
                row += "!== null ? "

                if (editorWidget == QgsVectorLayer.Photo
                        or editorWidget == 'Photo'):
                    row += "'<img src=\"images/' + "
                    row += "String(feature.properties['" + unicode(field)
                    row += "']).replace(/[\\\/:]/g, '_').trim()"
                    row += " + '\">' : '') + '"
                else:
                    row += "Autolinker.link("
                    row += "String(feature.properties['" + unicode(field)
                    row += "'])) : '') + '"

                row += """</td>\\
                    </tr>\\"""
            tableend = """
                </table>'"""
            table = tablestart + row + tableend
    if not label_exp:
        labeltext = ""
    if popup != 0 and table != "":
        popFuncs = popFuncsScript(table)
    else:
        popFuncs = ""
    new_pop = popupScript(safeLayerName, popFuncs, highlight, popupsOnHover)
    return new_pop, labeltext, popFuncs
def labelsAndPopups(layer, safeLayerName, highlight, popupsOnHover, popup,
                    outputProjectFileName):
    fields = layer.pendingFields()
    field_names = popup.keys()
    field_vals = popup.values()
    html_prov = False
    label_exp = ''
    labeltext = ""
    f = ''
    palyr = QgsPalLayerSettings()
    palyr.readFromLayer(layer)
    bgColor = palyr.shapeFillColor.name()
    borderWidth = palyr.shapeBorderWidth
    borderColor = palyr.shapeBorderColor.name()
    x = palyr.shapeSize.x()
    y = palyr.shapeSize.y()
    font = palyr.textFont
    fontSize = font.pointSize()
    fontFamily = font.family()
    fontItalic = font.italic()
    fontBold = font.bold()
    fontColor = palyr.textColor.name()
    fontUnderline = font.underline()
    xOffset = palyr.xOffset
    yOffset = palyr.yOffset
    styleStart = "'<div style=\"color: %s; font-size: %dpt; " % (
            fontColor, fontSize)
    if palyr.shapeDraw:
        styleStart += "background-color: %s; " % bgColor
        styleStart += "border: %dpx solid %s; " % (borderWidth, borderColor)
        if palyr.shapeSizeType == 0:
            styleStart += "padding: %dpx %dpx; " % (y, x)
        if palyr.shapeSizeType == 1:
            styleStart += "width: %dpx; " % x
            styleStart += "height: %dpx; " % y
    if fontBold:
        styleStart += "font-weight: bold; "
    if fontItalic:
        styleStart += "font-style: italic; "
    styleStart += "font-family: \\'%s\\', sans-serif;\">' + " % fontFamily
    styleEnd = " + '</div>'"
    if palyr.isExpression and palyr.enabled:
        exprFilename = os.path.join(outputProjectFileName, "js",
                                    "qgis2web_expressions.js")
        name = compile_to_file(palyr.getLabelExpression(),
                               "label_%s" % safeLayerName, "Leaflet",
                               exprFilename)
        js = "%s(context)" % (name)
        js = js.strip()
        f = js
    else:
        f = "feature.properties['%s']" % handleHiddenField(layer,
                                                           palyr.fieldName)
    label_exp = False
    labeltext = ".bindTooltip((" + unicode(f)
    labeltext += " !== null?String(%s%s)%s:'')" % (
            styleStart, unicode(f), styleEnd)
    labeltext += ", {permanent: true, offset: [-0, -16], "
    labeltext += "className: 'css_%s'}" % safeLayerName
    labeltext += ").openTooltip();"
    f = palyr.fieldName
    table = ""
    for field in popup:
        if unicode(field) == 'html_exp':
            html_prov = True
            table = 'feature.properties.html_exp'
        if (unicode(f) != "" and
                f and palyr.enabled):
            label_exp = True
        if not html_prov:
            tablestart = "'<table>\\"
            row = ""
            for field, val in zip(field_names, field_vals):
                fieldIndex = fields.indexFromName(unicode(field))
                try:
                    formCfg = layer.editFormConfig()
                    editorWidget = formCfg.widgetType(fieldIndex)
                except:
                    editorWidget = layer.editorWidgetV2(fieldIndex)
                if (editorWidget == QgsVectorLayer.Hidden or
                        editorWidget == 'Hidden'):
                    continue

                row += """
                    <tr>\\"""
                if val == 'inline label':
                    row += """
                        <th scope="row">"""
                    row += layer.attributeDisplayName(fieldIndex)
                    row += """</th>\\
                        <td>"""
                else:
                    row += """
                        <td colspan="2">"""
                if val == "header label":
                    row += '<strong>'
                    row += layer.attributeDisplayName(fieldIndex)
                    row += '</strong><br />'
                row += "' + "
                row += "(feature.properties[\'" + unicode(field) + "\'] "
                row += "!== null ? "

                if (editorWidget == QgsVectorLayer.Photo or
                        editorWidget == 'Photo'):
                    row += "'<img src=\"images/' + "
                    row += "String(feature.properties['" + unicode(field)
                    row += "']).replace(/[\\\/:]/g, '_').trim()"
                    row += " + '\">' : '') + '"
                else:
                    row += "Autolinker.link("
                    row += "String(feature.properties['" + unicode(field)
                    row += "'])) : '') + '"

                row += """</td>\\
                    </tr>\\"""
            tableend = """
                </table>'"""
            table = tablestart + row + tableend
    if not label_exp:
        labeltext = ""
    if popup != 0 and table != "":
        popFuncs = popFuncsScript(table)
    else:
        popFuncs = ""
    new_pop = popupScript(safeLayerName, popFuncs, highlight, popupsOnHover)
    return new_pop, labeltext, popFuncs