expander.go 1.52 KB
package main

import (
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"

	"github.com/antchfx/xmlquery"
)

func main() {
	var input *os.File

	if len(os.Args) > 1 {
		var err error

		input, err = os.Open(os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
		defer input.Close()
	} else {
		input = os.Stdin
	}

	x, err := xmlquery.Parse(input)
	if err != nil {
		log.Fatal(err)
	}

	for _, v := range xmlquery.Find(x, "//rect | //size") {
		expand(v.SelectElement("x"))
		expand(v.SelectElement("y"))
		expand(v.SelectElement("width"))
		expand(v.SelectElement("height"))
	}

	for _, v := range xmlquery.Find(x, "//pointsize") {
		expand(v)
	}

	for _, v := range xmlquery.Find(x, "//string") {
		expandCSS(v)
	}

	output := x.OutputXML(false)

	if len(os.Args) > 2 {
		if err := os.WriteFile(os.Args[2], []byte(output), 0664); err != nil {
			log.Fatal(err)
		}
	} else {
		if _, err := os.Stdout.Write([]byte(output)); err != nil {
			log.Fatal(err)
		}
	}
}

func expand(n *xmlquery.Node) {
	if n == nil {
		return
	}

	i, err := strconv.Atoi(n.FirstChild.Data)
	if err != nil {
		log.Fatal(err)
	}

	n.FirstChild.Data = fmt.Sprintf("%v", int(float32(i)*1.2))
}

func expandCSS(n *xmlquery.Node) {
	if n == nil || n.FirstChild == nil {
		return
	}

	re := regexp.MustCompile(`[0-9]+px`)

	for _, v := range re.FindAllString(n.FirstChild.Data, -1) {
		var px int
		if _, err := fmt.Sscanf(v, "%d", &px); err != nil {
			log.Fatal(err)
		}

		n.FirstChild.Data = strings.ReplaceAll(n.FirstChild.Data, v, fmt.Sprintf("%vpx", int(float32(px)*1.2)))
	}
}