-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
366 lines (302 loc) · 8.69 KB
/
main.go
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2023 Ronsor Labs. All rights reserved.
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/pborman/getopt/v2"
"github.com/ronsor/majokko/henshin"
)
var hasError = false
var (
doHelp = false
doVersion = false
doIdentify = false
doConvert = false
doListFormats = false
maxWorkers int = 1
noOutputFileNames = false
identifyFormatString = "%wx%h, hash: %H, comment: %c"
filterArgs FilterArgs
groupParamOpen, groupParamClose *int
)
// FilterArgs is a set of filtering arguments.
// They are listed in the order they will be applied.
type FilterArgs struct {
Strip bool
AddComments []string
SetComments []string
Crop string
Resize string
CompressionLevel int
}
func init() {
getopt.FlagLong(&doHelp, "help", 'h', "Show this help information")
getopt.FlagLong(&doVersion, "version", 'v', "Show version information")
getopt.FlagLong(&doIdentify, "identify", 0, "Print information about the image").SetGroup("action")
getopt.FlagLong(&doConvert, "convert", 0, "Convert or process image (default)").SetGroup("action")
getopt.FlagLong(&doListFormats, "list-formats", 0, "List supported image formats").SetGroup("action")
getopt.FlagLong(&maxWorkers, "workers", 'W', "Maximum concurrent workers")
getopt.FlagLong(&noOutputFileNames, "no-names", 'N', "Don't include file names in output messages")
getopt.FlagLong(&identifyFormatString, "identify-format", 0, "Format string for --identify output")
groupParamOpen = getopt.CounterLong("group", '(', "Open filter parameter group")
groupParamClose = getopt.CounterLong("end-group", ')', "Close filter parameter group")
initFilterArgs(&filterArgs, getopt.CommandLine)
getopt.SetParameters("[images ...] [output path]")
}
func initFilterArgs(filterArgs *FilterArgs, optSet *getopt.Set) {
optSet.FlagLong(&filterArgs.Strip, "strip", 'S', "Strip metadata from image")
optSet.FlagLong(&filterArgs.AddComments, "comment", 'C', "Add comment to image metadata")
optSet.FlagLong(&filterArgs.SetComments, "set-comment", 0, "Set comments for image metadata")
optSet.FlagLong(&filterArgs.Crop, "crop", 'c', "Crop image")
optSet.FlagLong(&filterArgs.Resize, "resize", 'r', "Resize image")
optSet.FlagLong(&filterArgs.CompressionLevel, "compress", 0, "Compression level, if applicable (0-100)")
filterArgs.CompressionLevel = -1 // Set to default
}
func parseFilterArgs(args []string) (ret []*FilterArgs) {
groupStartIdx := -1
groupEndIdx := -1
groupCount := 1
for i, arg := range args {
if arg == "--group" || arg == "-(" {
groupStartIdx = i
} else if arg == "--end-group" || arg == "-)" {
groupEndIdx = i
}
if groupStartIdx != -1 && groupEndIdx != -1 {
if (groupEndIdx - groupStartIdx) == -1 {
groupStartIdx = -1
groupEndIdx = -1
groupCount++
continue
}
optSet := getopt.New()
filterArgs := &FilterArgs{}
initFilterArgs(filterArgs, optSet)
section := args[groupStartIdx:groupEndIdx]
err := optSet.Getopt(section, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Filter group %d: %v\n", groupCount, err)
optSet.SetProgram("majokko -(")
optSet.SetParameters("-)")
optSet.PrintUsage(os.Stderr)
os.Exit(1)
}
ret = append(ret, filterArgs)
groupStartIdx = -1
groupEndIdx = -1
groupCount++
}
}
return
}
func processFilterArgs(wand *henshin.Wand, fa *FilterArgs) {
if fa.Strip {
wand.Strip()
}
if fa.AddComments != nil {
for _, c := range fa.AddComments {
wand.AddComment(wand.FormatString(c))
}
}
if fa.SetComments != nil {
wand.SetComments(fa.SetComments)
}
if fa.Crop != "" {
var (
w = -1
h = -1
xoff = 0
yoff = 0
)
n, _ := fmt.Sscanf(fa.Crop, "%dx%d+%d+%d", &w, &h, &xoff, &yoff)
if n > 0 {
wand.Crop(w, h, xoff, yoff)
}
}
if fa.Resize != "" {
resizeOpt := fa.Resize
shrinkLarger := resizeOpt[len(resizeOpt)-1] == '>'
enlargeSmaller := resizeOpt[len(resizeOpt)-1] == '<'
if (shrinkLarger || enlargeSmaller) && len(resizeOpt) > 1 {
resizeOpt = resizeOpt[:len(resizeOpt)-1]
}
percentScaling := strings.ContainsRune(resizeOpt, '%')
if percentScaling {
resizeOpt = strings.ReplaceAll(resizeOpt, "%", "")
// Special case
if strings.ContainsRune("0123456789", rune(resizeOpt[0])) && !strings.ContainsRune(resizeOpt, 'x') {
// Ensure things like `-resize 50%` work
resizeOpt = resizeOpt + "x"
}
}
if resizeOpt[0] == '@' {
var area int
n, err := fmt.Sscanf(resizeOpt, "@%d", &area)
if n == 1 && err == nil {
currentArea := wand.Width() * wand.Height()
if currentArea < area && shrinkLarger {
goto SKIP
} else if currentArea > area && enlargeSmaller {
goto SKIP
}
wand.ResizeArea(int(area), henshin.BiLinearStrategy)
}
} else if resizeOpt[0] == 'x' {
var h int
n, err := fmt.Sscanf(resizeOpt, "x%d", &h)
if n == 1 && err == nil {
if percentScaling && h != 0 {
h = int((float64(h) / 100) * float64(wand.Height()))
}
if wand.Height() < h && shrinkLarger {
goto SKIP
} else if wand.Height() > h && enlargeSmaller {
goto SKIP
}
wand.Resize(-1, h, henshin.BiLinearStrategy)
}
} else if resizeOpt[len(resizeOpt)-1] == 'x' {
var w int
n, err := fmt.Sscanf(resizeOpt, "%dx", &w)
if n == 1 && err == nil {
if percentScaling && w != 0 {
w = int((float64(w) / 100) * float64(wand.Width()))
}
if wand.Width() < w && shrinkLarger {
goto SKIP
} else if wand.Width() > w && enlargeSmaller {
goto SKIP
}
wand.Resize(w, -1, henshin.BiLinearStrategy)
}
} else {
var w, h int
n, err := fmt.Sscanf(resizeOpt, "%dx%d", &w, &h)
if n == 2 && err == nil {
if percentScaling && w != 0 {
w = int((float64(w) / 100) * float64(wand.Width()))
}
if percentScaling && h != 0 {
h = int((float64(h) / 100) * float64(wand.Height()))
}
area := w * h
currentArea := wand.Width() * wand.Height()
if currentArea < area && shrinkLarger {
goto SKIP
} else if currentArea > area && enlargeSmaller {
goto SKIP
}
wand.Resize(w, h, henshin.BiLinearStrategy)
}
}
SKIP:
}
if fa.CompressionLevel != -1 {
wand.SetCompressionLevel(fa.CompressionLevel)
}
}
func actionIdentify(wand *henshin.Wand, logPrefix string, inFile string) {
fmt.Printf("%s%s\n", logPrefix, wand.FormatString(identifyFormatString))
}
func actionConvert(wand *henshin.Wand, logPrefix string, maxArg int, args []string, inFile string) {
outFile := args[maxArg]
if maxArg > 1 {
outFile = filepath.Join(outFile, filepath.Base(inFile))
}
wand.ForceRGBA()
faGroups := parseFilterArgs(os.Args)
if faGroups == nil {
processFilterArgs(wand, &filterArgs)
} else {
for _, fa := range faGroups {
processFilterArgs(wand, fa)
}
}
err := wand.WriteImage(outFile)
if err != nil {
fmt.Fprintf(os.Stderr, "%sWriteImage (to %s): %v\n", logPrefix, outFile, err)
hasError = true
}
}
func actionVersion(full bool) {
fmt.Printf("Majokko %s (C) 2022-2023 Ronsor Labs. Licensed under the MIT license.\n", VERSION)
fmt.Printf("Supported formats:")
for _, c := range henshin.Codecs() {
fmt.Printf(" %s", c.Name())
}
if !full { fmt.Println(""); return }
fmt.Printf("\nFor more information, use the --list-formats option.\n")
}
func main() {
getopt.Parse()
args := getopt.Args()
if doHelp {
actionVersion(false)
fmt.Println("")
getopt.Usage()
return
}
if doVersion {
actionVersion(true)
if !doListFormats { return }
}
if doListFormats {
fmt.Println("+---- Can decode?")
fmt.Println("|+--- Can encode?")
fmt.Println("||+-- Can handle metadata?")
fmt.Println("||| === Format name ===")
for _, c := range henshin.Codecs() {
_, canDecode := c.(henshin.Decoder)
_, canEncode := c.(henshin.Encoder)
name := c.Name()
fmt.Printf("%s%s%s %s\n",
map[bool]string{true: "D", false: "-"}[canDecode],
map[bool]string{true: "E", false: "-"}[canEncode],
"?",
name)
}
return
}
if *groupParamOpen != *groupParamClose {
fmt.Fprintln(os.Stderr, "Unbalanced filter groups.")
getopt.Usage()
os.Exit(1)
}
if !doConvert {
doConvert = !doIdentify
}
maxArg := len(args)
if doConvert { maxArg = maxArg - 1 }
var wg sync.WaitGroup
n := 0
for i := 0; i < maxArg; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
inFile := args[i]
logPrefix := ""
if !noOutputFileNames {
logPrefix = inFile + ": "
}
wand := henshin.NewWand()
err := wand.ReadImage(args[i])
if err != nil {
fmt.Fprintf(os.Stderr, "%sReadImage: %v\n", logPrefix, err)
hasError = true
return
}
switch {
case doIdentify: actionIdentify(wand, logPrefix, inFile)
case doConvert: actionConvert(wand, logPrefix, maxArg, args, inFile)
}
} (i)
if n == maxWorkers { wg.Wait(); n = 0 }
}
wg.Wait()
if hasError {
os.Exit(1)
}
}