github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/src/cmd/pprof/internal/svg/svg.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package svg provides tools related to handling of SVG files
     6  package svg
     7  
     8  import (
     9  	"bytes"
    10  	"regexp"
    11  	"strings"
    12  )
    13  
    14  var (
    15  	viewBox  = regexp.MustCompile(`<svg\s*width="[^"]+"\s*height="[^"]+"\s*viewBox="[^"]+"`)
    16  	graphId  = regexp.MustCompile(`<g id="graph\d"`)
    17  	svgClose = regexp.MustCompile(`</svg>`)
    18  )
    19  
    20  // Massage enhances the SVG output from DOT to provide bettern
    21  // panning inside a web browser. It uses the SVGPan library, which is
    22  // accessed through the svgPan URL.
    23  func Massage(in bytes.Buffer, svgPan string) string {
    24  	svg := string(in.Bytes())
    25  
    26  	// Work around for dot bug which misses quoting some ampersands,
    27  	// resulting on unparsable SVG.
    28  	svg = strings.Replace(svg, "&;", "&amp;;", -1)
    29  	if svgPan == "" {
    30  		return svg
    31  	}
    32  
    33  	//Dot's SVG output is
    34  	//
    35  	//    <svg width="___" height="___"
    36  	//     viewBox="___" xmlns=...>
    37  	//    <g id="graph0" transform="...">
    38  	//    ...
    39  	//    </g>
    40  	//    </svg>
    41  	//
    42  	// Change it to
    43  	//
    44  	//    <svg width="100%" height="100%"
    45  	//     xmlns=...>
    46  	//    <script xlink:href=" ...$svgpan.. "/>
    47  
    48  	//    <g id="viewport" transform="translate(0,0)">
    49  	//    <g id="graph0" transform="...">
    50  	//    ...
    51  	//    </g>
    52  	//    </g>
    53  	//    </svg>
    54  
    55  	if loc := viewBox.FindStringIndex(svg); loc != nil {
    56  		svg = svg[:loc[0]] +
    57  			`<svg width="100%" height="100%"` +
    58  			svg[loc[1]:]
    59  	}
    60  
    61  	if loc := graphId.FindStringIndex(svg); loc != nil {
    62  		svg = svg[:loc[0]] +
    63  			`<script xlink:href="` + svgPan + `"/>` +
    64  			`<g id="viewport" transform="scale(0.5,0.5) translate(0,0)">` +
    65  			svg[loc[0]:]
    66  	}
    67  
    68  	if loc := svgClose.FindStringIndex(svg); loc != nil {
    69  		svg = svg[:loc[0]] +
    70  			`</g>` +
    71  			svg[loc[0]:]
    72  	}
    73  
    74  	return svg
    75  }