Code

Pot and Dutch translation update
[inkscape.git] / src / extension / internal / pdfinput / svg-builder.cpp
index 6e5620236c16220d42e795b6dfa58f6752c8b148..e343dbf338a62d404c7c2f6c12679d7acc532dcb 100644 (file)
@@ -14,6 +14,8 @@
 # include <config.h>
 #endif
 
+#include <string> 
+
 #ifdef HAVE_POPPLER
 
 #include "svg-builder.h"
@@ -33,7 +35,7 @@
 #include "unit-constants.h"
 #include "io/stringstream.h"
 #include "io/base64stream.h"
-#include "libnr/nr-matrix-ops.h"
+#include "display/nr-filter-utils.h"
 #include "libnr/nr-macros.h"
 #include "libnrtype/font-instance.h"
 
@@ -88,6 +90,7 @@ SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref) {
     // Set default preference settings
     _preferences = _xml_doc->createElement("svgbuilder:prefs");
     _preferences->setAttribute("embedImages", "1");
+    _preferences->setAttribute("localFonts", "1");
 }
 
 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
@@ -112,6 +115,15 @@ void SvgBuilder::_init() {
     _current_font = NULL;
     _current_state = NULL;
 
+    // Fill _availableFontNames (Bug LP #179589) (code cfr. FontLister)
+    FamilyToStylesMap familyStyleMap;
+    font_factory::Default()->GetUIFamiliesAndStyles(&familyStyleMap);
+    for (FamilyToStylesMap::iterator iter = familyStyleMap.begin();
+         iter != familyStyleMap.end();
+         iter++) {
+        _availableFontNames.push_back(iter->first.c_str());
+    }
+
     _transp_group_stack = NULL;
     SvgGraphicsState initial_state;
     initial_state.softmask = NULL;
@@ -214,12 +226,13 @@ Inkscape::XML::Node *SvgBuilder::getContainer() {
 }
 
 static gchar *svgConvertRGBToText(double r, double g, double b) {
+    using Inkscape::Filters::clamp;
     static gchar tmp[1023] = {0};
     snprintf(tmp, 1023,
              "#%02x%02x%02x",
-             CLAMP(SP_COLOR_F_TO_U(r), 0, 255),
-             CLAMP(SP_COLOR_F_TO_U(g), 0, 255),
-             CLAMP(SP_COLOR_F_TO_U(b), 0, 255));
+             clamp(SP_COLOR_F_TO_U(r)),
+             clamp(SP_COLOR_F_TO_U(g)),
+             clamp(SP_COLOR_F_TO_U(b)));
     return (gchar *)&tmp;
 }
 
@@ -231,18 +244,13 @@ static gchar *svgConvertGfxRGB(GfxRGB *color) {
 }
 
 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
-                              double c2, double c3, double c4, double c5) {
-    NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
+                            double c2, double c3, double c4, double c5) {
+    Geom::Matrix matrix(c0, c1, c2, c3, c4, c5);
     gchar *transform_text = sp_svg_transform_write(matrix);
     node->setAttribute("transform", transform_text);
     g_free(transform_text);
 }
 
-static void svgSetTransform(Inkscape::XML::Node *node, double *transform) {
-    svgSetTransform(node, transform[0], transform[1], transform[2], transform[3],
-                    transform[4], transform[5]);
-}
-
 /**
  * \brief Generates a SVG path string from poppler's data structure
  */
@@ -534,7 +542,7 @@ void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
  * \return true on success; false on invalid transformation
  */
 bool SvgBuilder::getTransform(double *transform) {
-    NR::Matrix svd;
+    Geom::Matrix svd;
     gchar const *tr = _container->attribute("transform");
     bool valid = sp_svg_transform_read(tr, &svd);
     if (valid) {
@@ -553,11 +561,15 @@ bool SvgBuilder::getTransform(double *transform) {
 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
                               double c4, double c5) {
 
+    // Avoid transforming a group with an already set clip-path
+    if ( _container->attribute("clip-path") != NULL ) {
+        pushGroup();
+    }
     TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
     svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
 }
 
-void SvgBuilder::setTransform(double *transform) {
+void SvgBuilder::setTransform(double const *transform) {
     setTransform(transform[0], transform[1], transform[2], transform[3],
                  transform[4], transform[5]);
 }
@@ -596,7 +608,8 @@ gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_
         if ( pattern->getType() == 2 ) {  // Shading pattern
             GfxShadingPattern *shading_pattern = (GfxShadingPattern*)pattern;
             id = _createGradient(shading_pattern->getShading(),
-                                 shading_pattern->getMatrix());
+                                 shading_pattern->getMatrix(),
+                                 !is_stroke);
         } else if ( pattern->getType() == 1 ) {   // Tiling pattern
             id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
         }
@@ -619,7 +632,7 @@ gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
     Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
     // Set pattern transform matrix
     double *p2u = tiling_pattern->getMatrix();
-    NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
+    Geom::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
     gchar *transform_text = sp_svg_transform_write(pat_matrix);
     pattern_node->setAttribute("patternTransform", transform_text);
     g_free(transform_text);
@@ -717,10 +730,10 @@ gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for
     gradient->setAttribute("gradientUnits", "userSpaceOnUse");
     // If needed, flip the gradient transform around the y axis
     if (matrix) {
-        NR::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
+        Geom::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
                               matrix[4], matrix[5]);
         if ( !for_shading && _is_top_level ) {
-            NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
+            Geom::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
             pat_matrix *= flip;
         }
         gchar *transform_text = sp_svg_transform_write(pat_matrix);
@@ -759,7 +772,7 @@ void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset
         double gray = (double)color->r / 65535.0;
         gray = CLAMP(gray, 0.0, 1.0);
         os_opacity << gray;
-        color_text = "#ffffff";
+        color_text = (char*) "#ffffff";
     } else {
         os_opacity << opacity;
         color_text = svgConvertGfxRGB(color);
@@ -850,26 +863,87 @@ void SvgBuilder::updateStyle(GfxState *state) {
     }
 }
 
+/*
+    MatchingChars
+    Count for how many characters s1 matches sp taking into account 
+    that a space in sp may be removed or replaced by some other tokens
+    specified in the code. (Bug LP #179589)
+*/
+static int MatchingChars(std::string s1, std::string sp)
+{
+    unsigned int is = 0;
+    unsigned int ip = 0;
+
+    while(is < s1.length() && ip < sp.length()) {
+        if (s1[is] == sp[ip]) {
+            is++; ip++;
+        } else if (sp[ip] == ' ') {
+            ip++;
+            if (s1[is] == '_') { // Valid matches to spaces in sp.
+                is++;
+            }
+        } else {
+            break;
+        }
+    }
+    return(ip);
+}
+
+/*
+    SvgBuilder::_BestMatchingFont
+    Scan the available fonts to find the font name that best matches PDFname.
+    (Bug LP #179589)
+*/
+std::string SvgBuilder::_BestMatchingFont(std::string PDFname)
+{
+    double bestMatch = 0;
+    std::string bestFontname = "Arial";
+    
+    for (guint i = 0; i < _availableFontNames.size(); i++) {
+        std::string fontname = _availableFontNames[i];
+        
+        // At least the first word of the font name should match.
+        guint minMatch = fontname.find(" ");
+        if (minMatch == std::string::npos) {
+           minMatch = fontname.length();
+        }
+        
+        int Match = MatchingChars(PDFname, fontname);
+        if (Match >= minMatch) {
+            double relMatch = (float)Match / (fontname.length() + PDFname.length());
+            if (relMatch > bestMatch) {
+                bestMatch = relMatch;
+                bestFontname = fontname;
+            }
+        }
+    }
+
+    if (bestMatch == 0)
+        return PDFname;
+    else
+        return bestFontname;
+}
+
 /**
  * This array holds info about translating font weight names to more or less CSS equivalents
  */
 static char *font_weight_translator[][2] = {
-    {"bold", "bold"},
-    {"light", "300"},
-    {"black", "900"},
-    {"heavy", "900"},
-    {"ultrabold", "800"},
-    {"extrabold", "800"},
-    {"demibold", "600"},
-    {"semibold", "600"},
-    {"medium", "500"},
-    {"book", "normal"},
-    {"regular", "normal"},
-    {"roman", "normal"},
-    {"normal", "normal"},
-    {"ultralight", "200"},
-    {"extralight", "200"},
-    {"thin", "100"}
+    {(char*) "bold",        (char*) "bold"},
+    {(char*) "light",       (char*) "300"},
+    {(char*) "black",       (char*) "900"},
+    {(char*) "heavy",       (char*) "900"},
+    {(char*) "ultrabold",   (char*) "800"},
+    {(char*) "extrabold",   (char*) "800"},
+    {(char*) "demibold",    (char*) "600"},
+    {(char*) "semibold",    (char*) "600"},
+    {(char*) "medium",      (char*) "500"},
+    {(char*) "book",        (char*) "normal"},
+    {(char*) "regular",     (char*) "normal"},
+    {(char*) "roman",       (char*) "normal"},
+    {(char*) "normal",      (char*) "normal"},
+    {(char*) "ultralight",  (char*) "200"},
+    {(char*) "extralight",  (char*) "200"},
+    {(char*) "thin",        (char*) "100"}
 };
 
 /**
@@ -892,7 +966,7 @@ void SvgBuilder::updateFont(GfxState *state) {
     } else if (font->getName()) {
         _font_specification = font->getName()->getCString();
     } else {
-        _font_specification = "Arial";
+        _font_specification = (char*) "Arial";
     }
 
     // Prune the font name to get the correct font family name
@@ -916,10 +990,17 @@ void SvgBuilder::updateFont(GfxState *state) {
     }
 
     // Font family
-    if (font->getFamily()) {
+    if (font->getFamily()) { // if font family is explicitly given use it.
         sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
-    } else {
-        sp_repr_css_set_property(_font_style, "font-family", font_family);
+    } else { 
+        int attr_value = 1;
+        sp_repr_get_int(_preferences, "localFonts", &attr_value);
+        if (attr_value != 0) {
+            // Find the font that best matches the stripped down (orig)name (Bug LP #179589).
+            sp_repr_css_set_property(_font_style, "font-family", _BestMatchingFont(font_family).c_str());
+        } else {
+            sp_repr_css_set_property(_font_style, "font-family", font_family);
+        }
     }
 
     // Font style
@@ -942,9 +1023,9 @@ void SvgBuilder::updateFont(GfxState *state) {
     char *css_font_weight = NULL;
     if ( font_weight != GfxFont::WeightNotDefined ) {
         if ( font_weight == GfxFont::W400 ) {
-            css_font_weight = "normal";
+            css_font_weight = (char*) "normal";
         } else if ( font_weight == GfxFont::W700 ) {
-            css_font_weight = "bold";
+            css_font_weight = (char*) "bold";
         } else {
             gchar weight_num[4] = "100";
             weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
@@ -959,7 +1040,7 @@ void SvgBuilder::updateFont(GfxState *state) {
             }
         }
     } else {
-        css_font_weight = "normal";
+        css_font_weight = (char*) "normal";
     }
     if (css_font_weight) {
         sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
@@ -974,31 +1055,31 @@ void SvgBuilder::updateFont(GfxState *state) {
     gchar *stretch_value = NULL;
     switch (font_stretch) {
         case GfxFont::UltraCondensed:
-            stretch_value = "ultra-condensed";
+            stretch_value = (char*) "ultra-condensed";
             break;
         case GfxFont::ExtraCondensed:
-            stretch_value = "extra-condensed";
+            stretch_value = (char*) "extra-condensed";
             break;
         case GfxFont::Condensed:
-            stretch_value = "condensed";
+            stretch_value = (char*) "condensed";
             break;
         case GfxFont::SemiCondensed:
-            stretch_value = "semi-condensed";
+            stretch_value = (char*) "semi-condensed";
             break;
         case GfxFont::Normal:
-            stretch_value = "normal";
+            stretch_value = (char*) "normal";
             break;
         case GfxFont::SemiExpanded:
-            stretch_value = "semi-expanded";
+            stretch_value = (char*) "semi-expanded";
             break;
         case GfxFont::Expanded:
-            stretch_value = "expanded";
+            stretch_value = (char*) "expanded";
             break;
         case GfxFont::ExtraExpanded:
-            stretch_value = "extra-expanded";
+            stretch_value = (char*) "extra-expanded";
             break;
         case GfxFont::UltraExpanded:
-            stretch_value = "ultra-expanded";
+            stretch_value = (char*) "ultra-expanded";
             break;
         default:
             break;
@@ -1046,7 +1127,7 @@ void SvgBuilder::updateTextShift(GfxState *state, double shift) {
  * \brief Updates current text position
  */
 void SvgBuilder::updateTextPosition(double tx, double ty) {
-    NR::Point new_position(tx, ty);
+    Geom::Point new_position(tx, ty);
     _text_position = new_position;
 }
 
@@ -1066,7 +1147,7 @@ void SvgBuilder::updateTextMatrix(GfxState *state) {
         max_scale = h_scale;
     }
     // Calculate new text matrix
-    NR::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
+    Geom::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
                                text_matrix[1] * state->getHorizScaling(),
                                -text_matrix[2], -text_matrix[3],
                                0.0, 0.0);
@@ -1101,7 +1182,7 @@ void SvgBuilder::_flushText() {
 
     Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
     // Set text matrix
-    NR::Matrix text_transform(_text_matrix);
+    Geom::Matrix text_transform(_text_matrix);
     text_transform[4] = first_glyph.position[0];
     text_transform[5] = first_glyph.position[1];
     gchar *transform = sp_svg_transform_write(text_transform);
@@ -1110,13 +1191,12 @@ void SvgBuilder::_flushText() {
 
     bool new_tspan = true;
     bool same_coords[2] = {true, true};
-    NR::Point last_delta_pos;
+    Geom::Point last_delta_pos;
     unsigned int glyphs_in_a_row = 0;
     Inkscape::XML::Node *tspan_node = NULL;
     Glib::ustring x_coords;
     Glib::ustring y_coords;
     Glib::ustring text_buffer;
-    bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb");  // FIXME
 
     // Output all buffered glyphs
     while (1) {
@@ -1170,7 +1250,14 @@ void SvgBuilder::_flushText() {
                 break;
             } else {
                 tspan_node = _xml_doc->createElement("svg:tspan");
-                tspan_node->setAttribute("inkscape:font-specification", glyph.font_specification);
+                
+                ///////
+                // Create a font specification string and save the attribute in the style
+                PangoFontDescription *descr = pango_font_description_from_string(glyph.font_specification);
+                Glib::ustring properFontSpec = font_factory::Default()->ConstructFontSpecification(descr);
+                pango_font_description_free(descr);
+                sp_repr_css_set_property(glyph.style, "-inkscape-font-specification", properFontSpec.c_str());
+
                 // Set style and unref SPCSSAttr if it won't be needed anymore
                 sp_repr_css_change(tspan_node, glyph.style, "style");
                 if ( glyph.style_changed && i != _glyphs.begin() ) {    // Free previous style
@@ -1191,7 +1278,7 @@ void SvgBuilder::_flushText() {
             }
         }
         // Append the coordinates to their respective strings
-        NR::Point delta_pos( glyph.text_position - first_glyph.text_position );
+        Geom::Point delta_pos( glyph.text_position - first_glyph.text_position );
         delta_pos[1] += glyph.rise;
         delta_pos[1] *= -1.0;   // flip it
         delta_pos *= _font_scaling;
@@ -1204,7 +1291,9 @@ void SvgBuilder::_flushText() {
         last_delta_pos = delta_pos;
 
         // Append the character to the text buffer
-        text_buffer.append((char *)&glyph.code, 1);
+       if ( !glyph.code.empty() ) {
+            text_buffer.append(1, glyph.code[0]);
+       }
 
         glyphs_in_a_row++;
         i++;
@@ -1239,40 +1328,43 @@ void SvgBuilder::addChar(GfxState *state, double x, double y,
     bool is_space = ( uLen == 1 && u[0] == 32 );
     // Skip beginning space
     if ( is_space && _glyphs.size() < 1 ) {
-        NR::Point delta(dx, dy);
+        Geom::Point delta(dx, dy);
          _text_position += delta;
          return;
     }
     // Allow only one space in a row
-    if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
-         _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
-        NR::Point delta(dx, dy);
+    if ( is_space && (_glyphs[_glyphs.size() - 1].code.size() == 1) &&
+         (_glyphs[_glyphs.size() - 1].code[0] == 32) ) {
+        Geom::Point delta(dx, dy);
         _text_position += delta;
         return;
     }
 
     SvgGlyph new_glyph;
     new_glyph.is_space = is_space;
-    new_glyph.position = NR::Point( x - originX, y - originY );
+    new_glyph.position = Geom::Point( x - originX, y - originY );
     new_glyph.text_position = _text_position;
     new_glyph.dx = dx;
     new_glyph.dy = dy;
-    NR::Point delta(dx, dy);
+    Geom::Point delta(dx, dy);
     _text_position += delta;
 
     // Convert the character to UTF-8 since that's our SVG document's encoding
-    static UnicodeMap *u_map = NULL;
-    if ( u_map == NULL ) {
-        GooString *enc = new GooString("UTF-8");
-        u_map = globalParams->getUnicodeMap(enc);
-        u_map->incRefCnt();
-        delete enc;
-    }
-    int code_size = 0;
-    for ( int i = 0 ; i < uLen ; i++ ) {
-        code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
+    {
+        gunichar2 uu[8] = {0};
+
+        for (int i = 0; i < uLen; i++) {
+            uu[i] = u[i];
+        }
+
+        gchar *tmp = g_utf16_to_utf8(uu, uLen, NULL, NULL, NULL);
+        if ( tmp && *tmp ) {
+            new_glyph.code = tmp;
+        } else {
+            new_glyph.code.clear();
+        }
+        g_free(tmp);
     }
-    new_glyph.code_size = code_size;
 
     // Copy current style if it has changed since the previous glyph
     if (_invalidated_style || _glyphs.size() == 0 ) {
@@ -1356,14 +1448,14 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
         return NULL;
     }
     // Decide whether we should embed this image
-    double attr_value = 1.0;
-    sp_repr_get_double(_preferences, "embedImages", &attr_value);
-    bool embed_image = ( attr_value != 0.0 );
+    int attr_value = 1;
+    sp_repr_get_int(_preferences, "embedImages", &attr_value);
+    bool embed_image = ( attr_value != 0 );
     // Set read/write functions
     Inkscape::IO::StringOutputStream base64_string;
     Inkscape::IO::Base64OutputStream base64_stream(base64_string);
-    FILE *fp;
-    gchar *file_name;
+    FILE *fp = NULL;
+    gchar *file_name = NULL;
     if (embed_image) {
         base64_stream.setColumnWidth(0);   // Disable line breaks
         png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
@@ -1447,7 +1539,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
             }
             png_write_row(png_ptr, (png_bytep)buffer);
         }
-        delete buffer;
+        delete [] buffer;
     } else if (color_map) {
         image_stream = new ImageStream(str, width,
                                        color_map->getNumPixelComps(),
@@ -1486,7 +1578,7 @@ Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height
                 png_write_row(png_ptr, (png_bytep)buffer);
             }
         }
-        delete buffer;
+        delete [] buffer;
 
     } else {    // A colormap must be provided, so quit
         png_destroy_write_struct(&png_ptr, &info_ptr);
@@ -1547,7 +1639,6 @@ Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
     } else {    // Work around for renderer bug when mask isn't defined in pattern
         static int mask_count = 0;
         Inkscape::XML::Node *defs = _root->firstChild();
-        Inkscape::XML::Node *result = NULL;
         if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
             // Create <defs> node
             defs = _xml_doc->createElement("svg:defs");
@@ -1626,7 +1717,7 @@ void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int hei
         mask_image_node->setAttribute("transform", NULL);
         mask_node->appendChild(mask_image_node);
         // Scale the mask to the size of the image
-        NR::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
+        Geom::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
         gchar *transform_text = sp_svg_transform_write(mask_transform);
         mask_node->setAttribute("maskTransform", transform_text);
         g_free(transform_text);