v / cmd / tools
Raw file | 556 loc (500 sloc) | 18.95 KB | Latest commit hash 017ace6ea
1// Copyright (c) 2021 Lars Pontoppidan. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4//
5// vgret (V Graphics REgression Tool) aids in generating screenshots of various graphical `gg`
6// based V applications, in a structured directory hierarchy, with the intent of either:
7// * Generate a directory structure of screenshots/images to test against
8// (which, as an example, could later be pushed to a remote git repository)
9// * Test for *visual* differences between two, structurally equal, directories
10//
11// vgret uses features and applications that is currently only available on Linux based distros:
12// idiff - to programmatically find *visual* differences between two images:
13// - Ubuntu: `sudo apt install openimageio-tools`
14// - Arch: `sudo pacman -S openimageio`
15// Xvfb - to start a virtual X server framebuffer:
16// - Ubuntu: `sudo apt install xvfb`
17// - Arch: `sudo pacman -S xorg-server-xvfb`
18//
19// For developers:
20// For a quick overview of the generated images you can use `montage` from imagemagick to generate a "Contact Sheet":
21// montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#000000' -fill 'gray' -define jpeg:size=200x200 -geometry 200x200+2+2 -auto-orient $(fd -t f . /path/to/vgret/out/dir) /tmp/montage.jpg
22// - Ubuntu: `sudo apt install imagemagick`
23// - Arch: `sudo pacman -S imagemagick`
24//
25// To generate the reference images locally - or for uploading to a remote repo like `gg-regression-images`
26// You can do the following:
27// 1. `export DISPLAY=:99` # Start all graphical apps on DISPLAY 99
28// 2. `Xvfb $DISPLAY -screen 0 1280x1024x24 &` # Starts a virtual X11 screen buffer
29// 3. `v gret -v /tmp/gg-regression-images` # Generate reference images to /tmp/gg-regression-images
30// 4. `v gret -v /tmp/test /tmp/gg-regression-images` # Test if the tests can pass locally by comparing to a fresh imageset
31// 5. Visually check the images (you can get an overview by running the `montage` command above)
32// 6. Upload to GitHub or keep locally for more testing/tweaking
33//
34// It's a known factor that the images generated on a local machine won't match the images generated on a remote machine by 100%.
35// They will most likely differ by a small percentage - the comparison tool can be tweaked to accept these subtle changes,
36// at the expense of slightly more inaccurate test results. For non-animated apps the percentage should be > 0.01.
37// You can emulate or test these inaccuracies to some extend locally by simply running the test from a terminal using
38// your physical X11 session display (Usually DISPLAY=:0).
39//
40// Read more about the options of `idiff` here: https://openimageio.readthedocs.io/en/latest/idiff.html
41//
42import os
43import flag
44import time
45import toml
46
47const (
48 tool_name = 'vgret'
49 tool_version = '0.0.2'
50 tool_description = '\n Dump and/or compare rendered frames of graphical apps
51 both external and `gg` based apps is supported.
52
53Examples:
54 Generate screenshots to `/tmp/test`
55 v gret /tmp/test
56 Generate and compare screenshots in `/tmp/src` to existing screenshots in `/tmp/dst`
57 v gret /tmp/src /tmp/dst
58 Compare screenshots in `/tmp/src` to existing screenshots in `/tmp/dst`
59 v gret --compare-only /tmp/src /tmp/dst
60'
61 tmp_dir = os.join_path(os.vtmp_dir(), 'v', tool_name)
62 runtime_os = os.user_os()
63 v_root = os.real_path(@VMODROOT)
64)
65
66const (
67 supported_hosts = ['linux']
68 supported_capture_methods = ['gg_record', 'generic_screenshot']
69 // External tool executables
70 v_exe = os.getenv('VEXE')
71 idiff_exe = os.find_abs_path_of_executable('idiff') or { '' }
72)
73
74const (
75 embedded_toml = $embed_file('vgret.defaults.toml', .zlib)
76 default_toml = embedded_toml.to_string()
77 empty_toml_array = []toml.Any{}
78 empty_toml_map = map[string]toml.Any{}
79)
80
81struct Config {
82 path string
83mut:
84 apps []AppConfig
85}
86
87struct CompareOptions {
88mut:
89 method string = 'idiff'
90 flags []string
91}
92
93struct CaptureRegion {
94mut:
95 x int
96 y int
97 width int
98 height int
99}
100
101fn (cr CaptureRegion) is_empty() bool {
102 return cr.width == 0 && cr.height == 0
103}
104
105struct CaptureOptions {
106mut:
107 method string = 'gg_record'
108 wait_ms int // used by "generic_screenshot" to wait X milliseconds *after* execution of the app
109 flags []string
110 regions []CaptureRegion
111 env map[string]string
112}
113
114fn (co CaptureOptions) validate() ! {
115 if co.method !in supported_capture_methods {
116 return error('capture method "${co.method}" is not supported. Supported methods are: ${supported_capture_methods}')
117 }
118}
119
120struct AppConfig {
121 compare CompareOptions
122 capture CaptureOptions
123 path string
124 abs_path string
125mut:
126 screenshots_path string
127 screenshots []string
128}
129
130struct Options {
131 verbose bool
132 compare_only bool
133 root_path string
134mut:
135 config Config
136}
137
138fn (opt Options) verbose_execute(cmd string) os.Result {
139 opt.verbose_eprintln('Running `${cmd}`')
140 return os.execute(cmd)
141}
142
143fn (opt Options) verbose_eprintln(msg string) {
144 if opt.verbose {
145 eprintln(msg)
146 }
147}
148
149fn main() {
150 if runtime_os !in supported_hosts {
151 eprintln('${tool_name} is currently only supported on ${supported_hosts} hosts')
152 exit(1)
153 }
154 if os.args.len == 1 {
155 eprintln('Usage: ${tool_name} PATH \n${tool_description}\n${tool_name} -h for more help...')
156 exit(1)
157 }
158
159 mut fp := flag.new_flag_parser(os.args[1..])
160 fp.application(tool_name)
161 fp.version(tool_version)
162 fp.description(tool_description)
163 fp.arguments_description('PATH [PATH]')
164 fp.skip_executable()
165
166 show_help := fp.bool('help', `h`, false, 'Show this help text.')
167
168 // Collect tool options
169 mut opt := Options{
170 verbose: fp.bool('verbose', `v`, false, "Be verbose about the tool's progress.")
171 compare_only: fp.bool('compare-only', `c`, false, "Don't generate screenshots - only compare input directories")
172 root_path: fp.string('root-path', `r`, v_root, 'Root path of the comparison')
173 }
174
175 toml_conf := fp.string('toml-config', `t`, default_toml, 'Path or string with TOML configuration')
176 arg_paths := fp.finalize()!
177 if show_help {
178 println(fp.usage())
179 exit(0)
180 }
181
182 if arg_paths.len == 0 {
183 println(fp.usage())
184 println('\nError missing arguments')
185 exit(1)
186 }
187
188 if !os.exists(tmp_dir) {
189 os.mkdir_all(tmp_dir)!
190 }
191
192 opt.config = new_config(opt.root_path, toml_conf) or { panic(err) }
193
194 gen_in_path := arg_paths[0]
195 if arg_paths.len >= 1 {
196 generate_screenshots(mut opt, gen_in_path) or { panic(err) }
197 }
198 if arg_paths.len > 1 {
199 target_path := arg_paths[1]
200 path := opt.config.path
201 all_paths_in_use := [path, gen_in_path, target_path]
202 for path_in_use in all_paths_in_use {
203 if !os.is_dir(path_in_use) {
204 eprintln('`${path_in_use}` is not a directory')
205 exit(1)
206 }
207 }
208 if path == target_path || gen_in_path == target_path || gen_in_path == path {
209 eprintln('Compare paths can not be the same directory `${path}`/`${target_path}`/`${gen_in_path}`')
210 exit(1)
211 }
212 compare_screenshots(opt, gen_in_path, target_path)!
213 }
214}
215
216fn generate_screenshots(mut opt Options, output_path string) ! {
217 path := opt.config.path
218
219 dst_path := output_path.trim_right('/')
220
221 if !os.is_dir(path) {
222 return error('`${path}` is not a directory')
223 }
224
225 for mut app_config in opt.config.apps {
226 file := app_config.path
227 app_path := app_config.abs_path
228
229 mut rel_out_path := ''
230 if os.is_file(app_path) {
231 rel_out_path = os.dir(file)
232 } else {
233 rel_out_path = file
234 }
235
236 if app_config.capture.method == 'gg_record' {
237 opt.verbose_eprintln('Compiling shaders (if needed) for `${file}`')
238 sh_result := opt.verbose_execute('${os.quoted_path(v_exe)} shader ${os.quoted_path(app_path)}')
239 if sh_result.exit_code != 0 {
240 opt.verbose_eprintln('Skipping shader compile for `${file}` v shader failed with:\n${sh_result.output}')
241 continue
242 }
243 }
244
245 if !os.exists(dst_path) {
246 opt.verbose_eprintln('Creating output path `${dst_path}`')
247 os.mkdir_all(dst_path) or { return error('Failed making directory `${dst_path}`') }
248 }
249
250 screenshot_path := os.join_path(dst_path, rel_out_path)
251 if !os.exists(screenshot_path) {
252 os.mkdir_all(screenshot_path) or {
253 return error('Failed making screenshot path `${screenshot_path}`')
254 }
255 }
256
257 app_config.screenshots_path = screenshot_path
258 app_config.screenshots = take_screenshots(opt, app_config) or {
259 return error('Failed taking screenshots of `${app_path}`:\n${err.msg()}')
260 }
261 }
262}
263
264fn compare_screenshots(opt Options, output_path string, target_path string) ! {
265 mut fails := map[string]string{}
266 mut warns := map[string]string{}
267 for app_config in opt.config.apps {
268 screenshots := app_config.screenshots
269 opt.verbose_eprintln('Comparing ${screenshots.len} screenshots in `${output_path}` with `${target_path}`')
270 for screenshot in screenshots {
271 relative_screenshot := screenshot.all_after(output_path + os.path_separator)
272
273 src := screenshot
274 target := os.join_path(target_path, relative_screenshot)
275 opt.verbose_eprintln('Comparing `${src}` with `${target}` with ${app_config.compare.method}')
276
277 if app_config.compare.method == 'idiff' {
278 if idiff_exe == '' {
279 return error('${tool_name} need the `idiff` tool installed. It can be installed on Ubuntu with `sudo apt install openimageio-tools`')
280 }
281 diff_file := os.join_path(os.vtmp_dir(), os.file_name(src).all_before_last('.') +
282 '.diff.tif')
283 flags := app_config.compare.flags.join(' ')
284 diff_cmd := '${os.quoted_path(idiff_exe)} ${flags} -abs -od -o ${os.quoted_path(diff_file)} -abs ${os.quoted_path(src)} ${os.quoted_path(target)}'
285 result := opt.verbose_execute(diff_cmd)
286 if result.exit_code == 0 {
287 opt.verbose_eprintln('OUTPUT: \n${result.output}')
288 }
289 if result.exit_code != 0 {
290 eprintln('OUTPUT: \n${result.output}')
291 if result.exit_code == 1 {
292 warns[src] = target
293 } else {
294 fails[src] = target
295 }
296 }
297 }
298 }
299 }
300
301 if warns.len > 0 {
302 eprintln('--- WARNINGS ---')
303 eprintln('The following files had warnings when compared to their targets')
304 for warn_src, warn_target in warns {
305 eprintln('${warn_src} ~= ${warn_target}')
306 }
307 }
308 if fails.len > 0 {
309 eprintln('--- ERRORS ---')
310 eprintln('The following files did not match their targets')
311 for fail_src, fail_target in fails {
312 eprintln('${fail_src} != ${fail_target}')
313 }
314 first := fails.keys()[0]
315 fail_copy := os.join_path(os.vtmp_dir(), 'fail.' + first.all_after_last('.'))
316 os.cp(first, fail_copy)!
317 eprintln('First failed file `${first}` is copied to `${fail_copy}`')
318
319 diff_file := os.join_path(os.vtmp_dir(), os.file_name(first).all_before_last('.') +
320 '.diff.tif')
321 diff_copy := os.join_path(os.vtmp_dir(), 'diff.tif')
322 if os.is_file(diff_file) {
323 os.cp(diff_file, diff_copy)!
324 eprintln('First failed diff file `${diff_file}` is copied to `${diff_copy}`')
325 eprintln('Removing alpha channel from ${diff_copy} ...')
326 final_fail_result_file := os.join_path(os.vtmp_dir(), 'diff.png')
327 opt.verbose_execute('convert ${os.quoted_path(diff_copy)} -alpha off ${os.quoted_path(final_fail_result_file)}')
328 eprintln('Final diff file: `${final_fail_result_file}`')
329 }
330 exit(1)
331 }
332}
333
334fn take_screenshots(opt Options, app AppConfig) ![]string {
335 out_path := app.screenshots_path
336 if !opt.compare_only {
337 opt.verbose_eprintln('Taking screenshot(s) of `${app.path}` to `${out_path}`')
338 match app.capture.method {
339 'gg_record' {
340 for k, v in app.capture.env {
341 rv := v.replace('\$OUT_PATH', out_path)
342 opt.verbose_eprintln('Setting ENV `${k}` = ${rv} ...')
343 os.setenv('${k}', rv, true)
344 }
345
346 flags := app.capture.flags.join(' ')
347 result := opt.verbose_execute('${os.quoted_path(v_exe)} ${flags} -d gg_record run ${os.quoted_path(app.abs_path)}')
348 if result.exit_code != 0 {
349 return error('Failed taking screenshot of `${app.abs_path}`:\n${result.output}')
350 }
351 }
352 'generic_screenshot' {
353 for k, v in app.capture.env {
354 rv := v.replace('\$OUT_PATH', out_path)
355 opt.verbose_eprintln('Setting ENV `${k}` = ${rv} ...')
356 os.setenv('${k}', rv, true)
357 }
358
359 existing_screenshots := get_app_screenshots(out_path, app)!
360
361 flags := app.capture.flags
362
363 if !os.exists(app.abs_path) {
364 return error('Failed starting app `${app.abs_path}`, the path does not exist')
365 }
366 opt.verbose_eprintln('Running ${app.abs_path} ${flags}')
367 mut p_app := os.new_process(app.abs_path)
368 p_app.set_args(flags)
369 p_app.set_redirect_stdio()
370 p_app.run()
371
372 if !p_app.is_alive() {
373 output := p_app.stdout_read() + '\n' + p_app.stderr_read()
374 return error('Failed starting app `${app.abs_path}` (before screenshot):\n${output}')
375 }
376 if app.capture.wait_ms > 0 {
377 opt.verbose_eprintln('Waiting ${app.capture.wait_ms} before capturing')
378 time.sleep(app.capture.wait_ms * time.millisecond)
379 }
380 if !p_app.is_alive() {
381 output := p_app.stdout_slurp() + '\n' + p_app.stderr_slurp()
382 return error('App `${app.abs_path}` exited (${p_app.code}) before a screenshot could be captured:\n${output}')
383 }
384 // Use ImageMagick's `import` tool to take the screenshot
385 out_file := os.join_path(out_path, os.file_name(app.path) +
386 '_screenshot_${existing_screenshots.len:02}.png')
387 result := opt.verbose_execute('import -window root "${out_file}"')
388 if result.exit_code != 0 {
389 p_app.signal_kill()
390 return error('Failed taking screenshot of `${app.abs_path}` to "${out_file}":\n${result.output}')
391 }
392
393 // When using regions the capture is split up into regions.len
394 // And name the output based on each region's properties
395 if app.capture.regions.len > 0 {
396 for region in app.capture.regions {
397 region_id := 'x${region.x}y${region.y}w${region.width}h${region.height}'
398 region_out_file := os.join_path(out_path, os.file_name(app.path) +
399 '_screenshot_${existing_screenshots.len:02}_region_${region_id}.png')
400 // If the region is empty (w, h == 0, 0) infer a full screenshot,
401 // This allows for capturing both regions *and* the complete screen
402 if region.is_empty() {
403 os.cp(out_file, region_out_file) or {
404 return error('Failed copying original screenshot "${out_file}" to region file "${region_out_file}"')
405 }
406 continue
407 }
408 extract_result := opt.verbose_execute('convert -extract ${region.width}x${region.height}+${region.x}+${region.y} "${out_file}" "${region_out_file}"')
409 if extract_result.exit_code != 0 {
410 p_app.signal_kill()
411 return error('Failed extracting region ${region_id} from screenshot of `${app.abs_path}` to "${region_out_file}":\n${result.output}')
412 }
413 }
414 // When done, remove the original file that was split into regions.
415 opt.verbose_eprintln('Removing "${out_file}" (region mode)')
416 os.rm(out_file) or {
417 return error('Failed removing original screenshot "${out_file}"')
418 }
419 }
420 p_app.signal_kill()
421 }
422 else {
423 return error('Unsupported capture method "${app.capture.method}"')
424 }
425 }
426 }
427 return get_app_screenshots(out_path, app)!
428}
429
430fn get_app_screenshots(path string, app AppConfig) ![]string {
431 mut screenshots := []string{}
432 shots := os.ls(path) or { return error('Failed listing dir `${path}`') }
433 for shot in shots {
434 if shot.starts_with(os.file_name(app.path).all_before_last('.')) {
435 screenshots << os.join_path(path, shot)
436 }
437 }
438 return screenshots
439}
440
441fn new_config(root_path string, toml_config string) !Config {
442 doc := if os.is_file(toml_config) {
443 toml.parse_file(toml_config) or { return error(err.msg()) }
444 } else {
445 toml.parse_text(toml_config) or { return error(err.msg()) }
446 }
447
448 path := os.real_path(root_path).trim_right('/')
449
450 compare_method := doc.value('compare.method').default_to('idiff').string()
451 compare_flags := doc.value('compare.flags').default_to(empty_toml_array).array().as_strings()
452 default_compare := CompareOptions{
453 method: compare_method
454 flags: compare_flags
455 }
456 capture_method := doc.value('capture.method').default_to('gg_record').string()
457 capture_flags := doc.value('capture.flags').default_to(empty_toml_array).array().as_strings()
458 capture_regions_any := doc.value('capture.regions').default_to(empty_toml_array).array()
459 mut capture_regions := []CaptureRegion{}
460 for capture_region_any in capture_regions_any {
461 region := CaptureRegion{
462 x: capture_region_any.value('x').default_to(0).int()
463 y: capture_region_any.value('y').default_to(0).int()
464 width: capture_region_any.value('width').default_to(0).int()
465 height: capture_region_any.value('height').default_to(0).int()
466 }
467 capture_regions << region
468 }
469 capture_wait_ms := doc.value('capture.wait_ms').default_to(0).int()
470 capture_env := doc.value('capture.env').default_to(empty_toml_map).as_map()
471 mut env_map := map[string]string{}
472 for k, v in capture_env {
473 env_map[k] = v.string()
474 }
475 default_capture := CaptureOptions{
476 method: capture_method
477 wait_ms: capture_wait_ms
478 flags: capture_flags
479 regions: capture_regions
480 env: env_map
481 }
482
483 apps_any := doc.value('apps').default_to(empty_toml_array).array()
484 mut apps := []AppConfig{cap: apps_any.len}
485 for app_any in apps_any {
486 rel_path := app_any.value('path').string().trim_right('/')
487
488 // Merge, per app, overwrites
489 mut merged_compare := CompareOptions{}
490 merged_compare.method = app_any.value('compare.method').default_to(default_compare.method).string()
491 merged_compare_flags := app_any.value('compare.flags').default_to(empty_toml_array).array().as_strings()
492 if merged_compare_flags.len > 0 {
493 merged_compare.flags = merged_compare_flags
494 } else {
495 merged_compare.flags = default_compare.flags
496 }
497
498 mut merged_capture := CaptureOptions{}
499 merged_capture.method = app_any.value('capture.method').default_to(default_capture.method).string()
500 merged_capture_flags := app_any.value('capture.flags').default_to(empty_toml_array).array().as_strings()
501 if merged_capture_flags.len > 0 {
502 merged_capture.flags = merged_capture_flags
503 } else {
504 merged_capture.flags = default_capture.flags
505 }
506
507 app_capture_regions_any := app_any.value('capture.regions').default_to(empty_toml_array).array()
508 mut app_capture_regions := []CaptureRegion{}
509 for capture_region_any in app_capture_regions_any {
510 region := CaptureRegion{
511 x: capture_region_any.value('x').default_to(0).int()
512 y: capture_region_any.value('y').default_to(0).int()
513 width: capture_region_any.value('width').default_to(0).int()
514 height: capture_region_any.value('height').default_to(0).int()
515 }
516 app_capture_regions << region
517 }
518 mut merged_capture_regions := []CaptureRegion{}
519 for default_capture_region in default_capture.regions {
520 if default_capture_region !in app_capture_regions {
521 merged_capture_regions << default_capture_region
522 }
523 }
524 for app_capture_region in app_capture_regions {
525 if app_capture_region !in default_capture.regions {
526 merged_capture_regions << app_capture_region
527 }
528 }
529 merged_capture.regions = merged_capture_regions
530
531 merged_capture.wait_ms = app_any.value('capture.wait_ms').default_to(default_capture.wait_ms).int()
532 merge_capture_env := app_any.value('capture.env').default_to(empty_toml_map).as_map()
533 mut merge_env_map := default_capture.env.clone()
534 for k, v in merge_capture_env {
535 merge_env_map[k] = v.string()
536 }
537 for k, v in merge_env_map {
538 merged_capture.env[k] = v
539 }
540
541 merged_capture.validate()!
542
543 app_config := AppConfig{
544 compare: merged_compare
545 capture: merged_capture
546 path: rel_path
547 abs_path: os.join_path(path, rel_path).trim_right('/')
548 }
549 apps << app_config
550 }
551
552 return Config{
553 apps: apps
554 path: path
555 }
556}