~mendelmaleh/dummy

ref: b7992e7049cbea825edd717ffdc3e89122e1a0d4 dummy/cmd/dummyserver/options.go -rw-r--r-- 1.8 KiB
b7992e70Mendel E Normalize in server package 1 year, 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main

import (
	"net/url"
	"strconv"

	"git.sr.ht/~mendelmaleh/dummy"
)

type Options struct {
	dummy.Options
}

// FromForm gets values from the form (which includes the url encoded query)
// and applies them to our Options. To ne used with r.Form after r.ParseForm().
func (opt *Options) FromForm(form url.Values) error {
	// image
	if v, ok := form["width"]; ok {
		i, err := strconv.Atoi(v[0])
		if err != nil {
			return err
		}

		opt.Width = i
		opt.Height = i
	}

	if v, ok := form["height"]; ok {
		i, err := strconv.Atoi(v[0])
		if err != nil {
			return err
		}

		opt.Height = i
	}

	if v, ok := form["mask"]; ok {
		opt.Mask = v[0]
	}

	if colors, ok := form["color"]; ok {
		for i, h := range colors {
			c, err := dummy.Hex(h)
			if err != nil {
				return err
			}

			opt.Colors[i] = c
		}
	}

	// text
	if v, ok := form["text"]; ok {
		opt.Text = v[0]
	}

	if v, ok := form["font"]; ok {
		// TODO: less strict font matching
		if f, ok := fonts[v[0]]; ok {
			opt.Font = f
		}
	}

	if v, ok := form["size"]; ok {
		f, err := strconv.ParseFloat(v[0], 64)
		if err != nil {
			return err
		}

		opt.Size = f
	}

	if v, ok := form["dpi"]; ok {
		f, err := strconv.ParseFloat(v[0], 64)
		if err != nil {
			return err
		}

		opt.DPI = f
	}

	// web
	if v, ok := form["desc"]; ok {
		opt.Desc = v[0]
	}

	// apply limits and hacks
	opt.Normalize()

	return nil
}

// Normalize our Options, implement limits and workarounds.
func (opt *Options) Normalize() {
	limit := &dummy.Options{
		Width:  4096,
		Height: 4096,

		Size: 240,
		DPI:  2880,
	}

	opt.Width = min(opt.Width, limit.Width)
	opt.Height = min(opt.Height, limit.Height)

	opt.Size = minFloat64(opt.Size, limit.Size)
	opt.DPI = minFloat64(opt.DPI, limit.DPI)
}

func min(a, b int) int {
	if a < b {
		return a
	}

	return b
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	}

	return b
}